Add figma.js

This commit is contained in:
vladislav 2026-08-24 12:03:20 +00:00
parent 17fe1e6544
commit 048b9680d1

210
figma.js Normal file
View File

@ -0,0 +1,210 @@
// MIT License
// Copyright (c) 2026 vladislav
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
m1 = figma.currentPage.children[0]
HTML_TAGS = new Set(['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr']);
function isHtmlTag(name) {
return typeof name === 'string' && HTML_TAGS.has(name.toLowerCase());
}
function randomString5() { const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let s = ''; for (let i = 0; i < 5; i++) s += chars.charAt(Math.floor(Math.random() * chars.length)); return s; }
pc = m1.children[0]
tablet = m1.children[1]
mob = m1.children[2]
console.log(pc.name, tablet.name, mob.name)
// helpers (примерные реализации, если у вас другие — замените)
function randomString5() {
return Math.random().toString(36).slice(2, 7);
}
function isHtmlTag(name) {
return typeof name === 'string' && /^[a-zA-Z][\w-]*$/.test(name);
}
function cssObjectToString(obj) {
return Object.entries(obj || {})
.map(([k, v]) => `${k.replace(/[A-Z]/g, m => '-' + m.toLowerCase())}: ${v};`)
.join(' ');
}
// helper: конвертирует объект CSS в строку
function cssObjectToString(obj = {}) {
return Object.entries(obj)
.map(([k, v]) => `${k}: ${v};`)
.join(' ');
}
async function element_create(pc_node, tablet_node, mob_node) {
const cssRules = [];
const randomString5 = () => Math.random().toString(36).substring(2, 5);
function nodeExists(node, idx) {
return node && Array.isArray(node.children) && node.children[idx];
}
async function getStyle(node) {
if (!node) return {};
if (typeof node.getCSSAsync === 'function') {
return await node.getCSSAsync();
}
return node.style || {};
}
function cssObjectToString(cssObj) {
if (!cssObj || typeof cssObj !== 'object') return '';
return Object.entries(cssObj)
.map(([prop, value]) => `${prop}: ${value};`)
.sort()
.join(' ');
}
function findExistingClass(pcBody, tableBody, mobBody) {
for (const r of cssRules) {
if (r.pcBody === pcBody &&
r.tableBody === tableBody &&
r.mobBody === mobBody) {
return r.cls;
}
}
return null;
}
async function build(pcN, tabN, mobN) {
if (!pcN?.name) return document.createElement('div');
const tagName = pcN.name.replace(/Desktop|desktop/gi, 'section').toLowerCase();
const el = document.createElement(tagName);
if (pcN.characters != null) {
el.textContent = pcN.characters;
}
// Рекурсия по детям
if (Array.isArray(pcN.children) && pcN.children.length) {
for (let i = 0; i < pcN.children.length; i++) {
const pcChild = pcN.children[i];
const tabChild = nodeExists(tabN, i) ? tabN.children[i] : pcChild;
const mobChild = nodeExists(mobN, i) ? mobN.children[i] : pcChild;
if (typeof isHtmlTag === 'function' && isHtmlTag(pcChild.name)) {
const childEl = await build(pcChild, tabChild, mobChild);
el.appendChild(childEl);
}
}
}
const pcCss = await getStyle(pcN);
const tabCss = await getStyle(tabN);
const mobCss = await getStyle(mobN);
const pcBody = cssObjectToString(pcCss);
const tableBody = cssObjectToString(tabCss);
const mobBody = cssObjectToString(mobCss);
let cls = findExistingClass(pcBody, tableBody, mobBody);
if (!cls) {
cls = 'c_' + randomString5();
const baseCls = 'b_' + randomString5();
cssRules.push({
cls,
baseCls,
pcBody,
tableBody,
mobBody,
baseStyle: '' // заполним ниже
});
}
// Добавляем оба класса к элементу
el.classList.add(cls);
// base-класс добавим только если есть общие стили (позже)
return el;
}
const rootEl = await build(pc_node, tablet_node, mob_node);
// === Определяем общие стили и различия ===
const baseBlockParts = [];
for (const rule of cssRules) {
const { cls, baseCls, pcBody, tableBody, mobBody } = rule;
let baseStyle = '';
// Определяем, есть ли общие стили
if (pcBody && pcBody === tableBody && tableBody === mobBody) {
baseStyle = pcBody;
} else if (pcBody && pcBody === tableBody) {
baseStyle = pcBody; // desktop + tablet одинаковые
} else if (pcBody && pcBody === mobBody) {
baseStyle = pcBody;
} else if (tableBody && tableBody === mobBody) {
baseStyle = tableBody;
}
rule.baseStyle = baseStyle;
// Добавляем base-класс только если есть общие стили
if (baseStyle) {
baseBlockParts.push(`.${baseCls} { ${baseStyle} }`);
// Находим все элементы с этим cls и добавляем им baseCls
// (поскольку build уже завершён, делаем это через DOM)
rootEl.querySelectorAll(`.${cls}`).forEach(el => {
el.classList.add(baseCls);
});
}
// Различия для медиа-запросов (только то, что отличается от base)
rule.mobDiff = (mobBody && mobBody !== baseStyle) ? `.${cls} { ${mobBody} }` : '';
rule.tableDiff = (tableBody && tableBody !== baseStyle) ? `.${cls} { ${tableBody} }` : '';
rule.pcDiff = (pcBody && pcBody !== baseStyle) ? `.${cls} { ${pcBody} }` : '';
}
const baseBlock = baseBlockParts.join('\n');
const mobBlock = cssRules.map(r => r.mobDiff).filter(Boolean).join('\n');
const tableBlock = cssRules.map(r => r.tableDiff).filter(Boolean).join('\n');
const pcBlock = cssRules.map(r => r.pcDiff).filter(Boolean).join('\n');
// === Создаём <style> ===
const styleEl = document.createElement('style');
styleEl.type = 'text/css';
styleEl.textContent = `
/* Base (common) styles */
${baseBlock}
/* Mobile */
@media (max-width: 699px) {
${mobBlock}
}
/* Tablet */
@media (min-width: 700px) and (max-width: 900px) {
${tableBlock}
}
/* Desktop */
@media (min-width: 901px) {
${pcBlock}
}
`.trim();
const ret = document.createElement('div');
ret.appendChild(rootEl);
ret.appendChild(styleEl);
return ret;
}
sss = await element_create(pc, tablet, mob)
sss.innerHTML