Skip to content

Commit

Permalink
Make plugin dynamic-page compatible
Browse files Browse the repository at this point in the history
  • Loading branch information
origami-z committed Mar 1, 2024
1 parent f7de960 commit 3d89988
Show file tree
Hide file tree
Showing 24 changed files with 89 additions and 73 deletions.
10 changes: 10 additions & 0 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,15 @@ module.exports = {
],
rules: {
"@typescript-eslint/no-explicit-any": 1,
"@typescript-eslint/no-floating-promises": ["error"],
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": [
"warn", // or "error"
{
argsIgnorePattern: "^_",
varsIgnorePattern: "^_",
caughtErrorsIgnorePattern: "^_",
},
],
},
};
3 changes: 2 additions & 1 deletion packages/copy-manager/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@
"https://fonts.gstatic.com",
"https://fonts.googleapis.com"
]
}
},
"documentAccess": "dynamic-page"
}
16 changes: 8 additions & 8 deletions packages/copy-manager/plugin-src/code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ figma.ui.onmessage = async (msg: PostToFigmaMessage) => {
persistDataInFigma();
}
} else if (msg.type === "focus-node") {
focusNode(msg.id);
await focusNode(msg.id);
} else if (msg.type === "scan-text-node-info") {
const nodesInfo = await scanTextNodesInfo(msg.autoTrigger);
// console.log({ nodesInfo });
Expand Down Expand Up @@ -133,7 +133,7 @@ async function updateWithLang(lang: string) {

const totalTopLvlNodes = topLvlNodes.length;

const { data, meta } = parsedCsv;
const { data } = parsedCsv;

let notificationHandle: NotificationHandler = figma.notify("Update start...");

Expand All @@ -159,8 +159,8 @@ async function updateWithLang(lang: string) {
})) || 0;

if (nodes.length > 1) {
setTimeout(() => {
processFirstNode(nodes.slice(1));
setTimeout(async () => {
await processFirstNode(nodes.slice(1));
}, 20);
} else {
notificationHandle?.cancel();
Expand All @@ -175,7 +175,7 @@ async function updateWithLang(lang: string) {
}
}

processFirstNode(topLvlNodes);
await processFirstNode(topLvlNodes);
}

async function parseCsvAndDetectRevision(csvString: string) {
Expand Down Expand Up @@ -241,8 +241,8 @@ async function exportCsvFile() {
processedInfo.push(processResult);

if (nodes.length > 1) {
setTimeout(() => {
processFirstNode(nodes.slice(1));
setTimeout(async () => {
await processFirstNode(nodes.slice(1));
}, 20);
} else {
notificationHandle?.cancel();
Expand All @@ -264,5 +264,5 @@ async function exportCsvFile() {
}, 20);
}
}
processFirstNode(topLvlNodes);
await processFirstNode(topLvlNodes);
}
10 changes: 5 additions & 5 deletions packages/copy-manager/plugin-src/processors/csvProcessor.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { parse } from "papaparse";
import { convertToCsvDataUri } from "../../shared-src/export-utils";
import {
CsvNodeInfo,
CsvNodeInfoWithProperId,
} from "../../shared-src/messages";
import {
DEFAULT_HEADING_SETTINGS,
getHeadingLevelNumber,
HeadingSettings,
getHeadingLevelNumber,
loadAllFonts,
replaceTextInTextNode,
setRelaunchButton,
Expand All @@ -14,12 +16,10 @@ import {
import {
CsvExportSettings,
CsvNodeInfoMap,
UpdaterSettings,
iterate,
iterateUpdate,
UpdaterSettings,
} from "./iterate";
import { unparse, parse } from "papaparse";
import { convertToCsvDataUri } from "../../shared-src/export-utils";

const getListOption = (node: TextNode): string => {
const fullListOption = node.getRangeListOptions(0, node.characters.length);
Expand Down Expand Up @@ -125,7 +125,7 @@ export const parseCsvString = <T extends CsvNodeInfo>(input: string) => {
export const getNodeInfoMap = <T extends CsvNodeInfo>(
nodeInfos: T[]
): CsvNodeInfoMap => {
let map: CsvNodeInfoMap = {};
const map: CsvNodeInfoMap = {};
nodeInfos.forEach((x) => {
const nodeInfoWithNormalId = {
...x,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export async function scanTextNodesInfo(autoTrigger: boolean) {

export const textNodeInfoTextNodeProcess = (
node: TextNode,
settings: any
_settings: any
): SelectableTextNodeInfo[] => {
if (!node.visible || node.characters.length === 0) {
return [];
Expand Down
4 changes: 3 additions & 1 deletion packages/copy-manager/plugin-src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,9 @@ export function sendTextNodesInfoToUI(nodesInfo: SelectableTextNodeInfo[]) {
} satisfies PostToUIMessage);
}

export function focusNode(id: string) {
export async function focusNode(id: string) {
await figma.loadAllPagesAsync();
// eslint-disable-next-line @figma/figma-plugins/dynamic-page-find-method-advice
const nodeToFocus = figma.root.findOne((x) => x.id === id);
if (nodeToFocus !== null) {
// TODO: Switch current page first
Expand Down
2 changes: 1 addition & 1 deletion packages/copy-manager/shared-src/export-utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { unparse, parse } from "papaparse";
import { unparse } from "papaparse";

export const convertToCsvDataUri = <T extends unknown[]>(data: T): string => {
const rowsString = unparse(data, { header: true });
Expand Down
5 changes: 0 additions & 5 deletions packages/copy-manager/shared-src/messages.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
type Id = string;

type StoredCopyVersion = {
name: string;
characters: string;
};

// We need to keep an array so that additional headers being added by the user can be detected
export const CSV_HEADER_FIELDS = [
"id",
Expand Down
6 changes: 3 additions & 3 deletions packages/copy-manager/ui-src/components/NodeKeyInput.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import React, { useCallback, useEffect, useState } from "react";
import { Input } from "@salt-ds/lab";
import { SelectableTextNodeInfo } from "../../shared-src";
import { Button } from "@salt-ds/core";
import { CloseSmallIcon, WarningIcon } from "@salt-ds/icons";
import { Input } from "@salt-ds/lab";
import React from "react";
import { SelectableTextNodeInfo } from "../../shared-src";

export const NodeKeyInput = ({
nodeInfo,
Expand Down
2 changes: 1 addition & 1 deletion packages/copy-manager/ui-src/view/AdvancedView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ export const AdvancedView = () => {
const checkedRows = textNodesInfo.filter((x) => x.checked);
// Every checked row should have key filled in
const exportButtonDisabled =
checkedRows.length == 0 || checkedRows.some((x) => !!!x.key);
checkedRows.length == 0 || checkedRows.some((x) => !x.key);

const onExportButtonClicked = () => {
const exportContent = textNodesInfo
Expand Down
5 changes: 3 additions & 2 deletions packages/copy-manager/ui-src/view/SimpleView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export const SimpleView = () => {
case "available-lang-from-csv": {
const { langs } = pluginMessage;
setCsvLangs(langs);
break;
}
default:
}
Expand Down Expand Up @@ -86,7 +87,7 @@ export const SimpleView = () => {
if (files.length && files[0] !== null) {
const csv = files[0];
setCsvFile(csv);
var reader = new FileReader();
const reader = new FileReader();
reader.readAsText(csv, "UTF-8");
reader.onload = function (evt) {
const fileReadString = evt.target?.result as any;
Expand All @@ -101,7 +102,7 @@ export const SimpleView = () => {
"*"
);
};
reader.onerror = function (evt) {
reader.onerror = function () {
console.error("error reading file");
setCsvFile(null);
};
Expand Down
3 changes: 2 additions & 1 deletion packages/export-styles/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,6 @@
"https://fonts.gstatic.com",
"https://fonts.googleapis.com"
]
}
},
"documentAccess": "dynamic-page"
}
41 changes: 23 additions & 18 deletions packages/export-styles/plugin-src/code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ figma.showUI(__html__, {
: "Export Variable To JSON",
});

figma.ui.onmessage = (msg: PostToFigmaMessage) => {
figma.ui.onmessage = async (msg: PostToFigmaMessage) => {
if (msg.type === "ui-ready") {
const command = figma.command as PluginCommandType;
figma.ui.resize(
Expand All @@ -45,10 +45,12 @@ figma.ui.onmessage = (msg: PostToFigmaMessage) => {
command: command,
} satisfies PostToUIMessage);
} else if (msg.type === "export-css") {
const solidPaints = figma.getLocalPaintStyles().filter((paintStyle) => {
let color = paintStyle.paints[0];
return color.type === "SOLID";
});
const solidPaints = (await figma.getLocalPaintStylesAsync()).filter(
(paintStyle) => {
const color = paintStyle.paints[0];
return color.type === "SOLID";
}
);

// Alpha channel is ignored in certain format
const colorConvertFn = getColorConvertFn(msg.format);
Expand Down Expand Up @@ -112,10 +114,12 @@ figma.ui.onmessage = (msg: PostToFigmaMessage) => {
data: outputText.join("\n"),
} satisfies PostToUIMessage);
} else if (msg.type === "export-json") {
const solidPaints = figma.getLocalPaintStyles().filter((paintStyle) => {
let color = paintStyle.paints[0];
return color.type === "SOLID";
});
const solidPaints = (await figma.getLocalPaintStylesAsync()).filter(
(paintStyle) => {
const color = paintStyle.paints[0];
return color.type === "SOLID";
}
);

// Alpha channel is ignored in certain format
const colorConvertFn = getColorConvertFn(msg.format);
Expand All @@ -131,6 +135,7 @@ figma.ui.onmessage = (msg: PostToFigmaMessage) => {
while (parts.length > 1) {
const part = parts.shift();

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
target = target[part!] = target[part!] || {};
}
Expand Down Expand Up @@ -158,20 +163,20 @@ figma.ui.onmessage = (msg: PostToFigmaMessage) => {
Math.max(height, JSON_VIEW_HEIGHT)
);
} else if (msg.type === "get-variable-collections") {
const localCollections = figma.variables
.getLocalVariableCollections()
.map((c) => ({
name: c.name,
id: c.id,
}));
const localCollections = (
await figma.variables.getLocalVariableCollectionsAsync()
).map((c) => ({
name: c.name,
id: c.id,
}));
figma.ui.postMessage({
type: "get-variable-collections-result",
collections: localCollections,
} satisfies PostToUIMessage);
} else if (msg.type === "get-variable-modes") {
const { collectionId } = msg;
const variableCollection =
figma.variables.getVariableCollectionById(collectionId);
await figma.variables.getVariableCollectionByIdAsync(collectionId);
if (variableCollection) {
figma.ui.postMessage({
type: "get-variable-modes-result",
Expand All @@ -185,9 +190,9 @@ figma.ui.onmessage = (msg: PostToFigmaMessage) => {
const { collectionId, modeId } = msg;

const variableCollection =
figma.variables.getVariableCollectionById(collectionId);
await figma.variables.getVariableCollectionByIdAsync(collectionId);
if (variableCollection) {
const exportResult = exportVariables(variableCollection, modeId);
const exportResult = await exportVariables(variableCollection, modeId);
if (exportResult) {
figma.ui.postMessage({
type: "export-variable-to-json-result",
Expand Down
17 changes: 9 additions & 8 deletions packages/export-styles/plugin-src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export function getRgbStringFromFigmaColor(rgb: RGB, opacity?: number) {
}

function componentToHex(c: number) {
var hex = c.toString(16).toUpperCase();
const hex = c.toString(16).toUpperCase();
return hex.length == 1 ? "0" + hex : hex;
}

Expand Down Expand Up @@ -95,7 +95,7 @@ export function getColorConvertFn(format: ExportColorFormat) {
}
}

export function exportVariables(
export async function exportVariables(
{ name, modes, variableIds }: VariableCollection,
modeId: string
) {
Expand All @@ -105,9 +105,10 @@ export function exportVariables(
}

const file = { fileName: `${name}.${mode.name}.tokens.json`, body: {} };
variableIds.forEach((variableId) => {

for (const variableId of variableIds) {
const { name, resolvedType, valuesByMode } =
figma.variables.getVariableById(variableId)!;
(await figma.variables.getVariableByIdAsync(variableId))!;
const value = valuesByMode[mode.modeId];
if (value !== undefined && ["COLOR", "FLOAT"].includes(resolvedType)) {
let obj = file.body as any;
Expand All @@ -121,14 +122,14 @@ export function exportVariables(
"type" in value &&
value.type === "VARIABLE_ALIAS"
) {
obj.$value = `{${figma.variables
.getVariableById(value.id)!
.name.replace(/\//g, ".")}}`;
obj.$value = `{${(await figma.variables.getVariableByIdAsync(
value.id
))!.name.replace(/\//g, ".")}}`;
} else {
obj.$value = resolvedType === "COLOR" ? rgbToHex(value as RGBA) : value;
}
}
});
}

return file;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/export-styles/ui-src/views/VariableJsonView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ export const VariableJsonView = () => {
}, []);

const onDownload = () => {
var blob = new Blob([text], { type: "application/json" });
const blob = new Blob([text], { type: "application/json" });
// Use blob instead of plain text downloadDataUri, as Safari wipes out new line
downloadBlob(blob, fileName);
};
Expand Down
3 changes: 2 additions & 1 deletion packages/table-generator/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@
"https://fonts.gstatic.com",
"https://fonts.googleapis.com"
]
}
},
"documentAccess": "dynamic-page"
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, test } from "vitest";
import { getPreferredTextInChild } from "../../utils/data-interface";
import { vi, test, expect, describe } from "vitest";

describe("getPreferredTextInChild", () => {
test("returns empty string when no nested TextNode", () => {
Expand Down
Loading

0 comments on commit 3d89988

Please sign in to comment.