@pairdraw/core 0.16.2 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/canvas/outline-stroke.d.ts.map +1 -1
- package/dist/canvas/outline-stroke.js.map +1 -1
- package/dist/canvas/overlays/prototype.d.ts +2 -5
- package/dist/canvas/overlays/prototype.d.ts.map +1 -1
- package/dist/canvas/overlays/prototype.js +3 -19
- package/dist/canvas/overlays/prototype.js.map +1 -1
- package/dist/canvas/renderer/fonts.js +2 -1
- package/dist/canvas/renderer/fonts.js.map +1 -1
- package/dist/canvas/renderer.d.ts +4 -0
- package/dist/canvas/renderer.d.ts.map +1 -1
- package/dist/canvas/renderer.js +4 -0
- package/dist/canvas/renderer.js.map +1 -1
- package/dist/canvas/rulers.js +1 -1
- package/dist/canvas/rulers.js.map +1 -1
- package/dist/canvas/scene.d.ts.map +1 -1
- package/dist/canvas/scene.js +61 -37
- package/dist/canvas/scene.js.map +1 -1
- package/dist/canvas/text/font-families.d.ts +4 -3
- package/dist/canvas/text/font-families.d.ts.map +1 -1
- package/dist/canvas/text/font-families.js +8 -7
- package/dist/canvas/text/font-families.js.map +1 -1
- package/dist/canvas/text/index.d.ts.map +1 -1
- package/dist/canvas/text/index.js +1 -1
- package/dist/canvas/text/index.js.map +1 -1
- package/dist/canvas/text/paragraph/index.js +2 -2
- package/dist/canvas/text/paragraph/index.js.map +1 -1
- package/dist/canvas/text/placed.js +2 -2
- package/dist/canvas/text/placed.js.map +1 -1
- package/dist/canvas/text/renderer.d.ts +2 -0
- package/dist/canvas/text/renderer.d.ts.map +1 -1
- package/dist/clipboard/pairdraw.d.ts.map +1 -1
- package/dist/clipboard/pairdraw.js +53 -7
- package/dist/clipboard/pairdraw.js.map +1 -1
- package/dist/design-jsx/preview/picture.js +6 -1
- package/dist/design-jsx/preview/picture.js.map +1 -1
- package/dist/design-jsx/renderer.d.ts.map +1 -1
- package/dist/editor/alignment.d.ts.map +1 -1
- package/dist/editor/alignment.js +35 -27
- package/dist/editor/alignment.js.map +1 -1
- package/dist/editor/bridges/undo.d.ts +1 -1
- package/dist/editor/clipboard/detach.d.ts.map +1 -1
- package/dist/editor/clipboard/detach.js +3 -3
- package/dist/editor/clipboard/detach.js.map +1 -1
- package/dist/editor/clipboard/paste/properties.d.ts.map +1 -1
- package/dist/editor/clipboard/paste/properties.js +3 -1
- package/dist/editor/clipboard/paste/properties.js.map +1 -1
- package/dist/editor/create.d.ts +1 -1
- package/dist/editor/structure.d.ts.map +1 -1
- package/dist/editor/structure.js +3 -1
- package/dist/editor/structure.js.map +1 -1
- package/dist/editor/viewport.js +2 -2
- package/dist/editor/viewport.js.map +1 -1
- package/dist/figma-api/index.d.ts +43 -8
- package/dist/figma-api/index.d.ts.map +1 -1
- package/dist/figma-api/index.js +48 -6
- package/dist/figma-api/index.js.map +1 -1
- package/dist/figma-api/serialization.js +10 -0
- package/dist/figma-api/serialization.js.map +1 -1
- package/dist/figma-api/text/bindings.d.ts.map +1 -1
- package/dist/figma-api/text/bindings.js +20 -8
- package/dist/figma-api/text/bindings.js.map +1 -1
- package/dist/figma-api/text/index.js +1 -1
- package/dist/geometry/connectors.js +2 -14
- package/dist/geometry/connectors.js.map +1 -1
- package/dist/geometry/index.d.ts +2 -2
- package/dist/geometry/scene.d.ts +3 -1
- package/dist/geometry/scene.d.ts.map +1 -1
- package/dist/geometry/scene.js +16 -1
- package/dist/geometry/scene.js.map +1 -1
- package/dist/geometry/types.d.ts +7 -1
- package/dist/geometry/types.d.ts.map +1 -1
- package/dist/io/formats/drawio/export.d.ts.map +1 -1
- package/dist/io/formats/drawio/export.js +10 -0
- package/dist/io/formats/drawio/export.js.map +1 -1
- package/dist/io/formats/drawio/index.d.ts.map +1 -1
- package/dist/io/formats/drawio/index.js +32 -1
- package/dist/io/formats/drawio/index.js.map +1 -1
- package/dist/io/formats/drawio/shapes.d.ts +10 -5
- package/dist/io/formats/drawio/shapes.d.ts.map +1 -1
- package/dist/io/formats/drawio/shapes.js +10 -6
- package/dist/io/formats/drawio/shapes.js.map +1 -1
- package/dist/io/formats/drawio/warnings.d.ts +11 -0
- package/dist/io/formats/drawio/warnings.d.ts.map +1 -0
- package/dist/io/formats/drawio/warnings.js +23 -0
- package/dist/io/formats/drawio/warnings.js.map +1 -0
- package/dist/io/formats/pdf/dom.d.ts +10 -1
- package/dist/io/formats/pdf/dom.d.ts.map +1 -1
- package/dist/io/formats/pdf/dom.js +31 -1
- package/dist/io/formats/pdf/dom.js.map +1 -1
- package/dist/io/formats/pdf/export.js +3 -2
- package/dist/io/formats/pdf/export.js.map +1 -1
- package/dist/io/formats/raster/headless.d.ts +2 -2
- package/dist/io/formats/raster/headless.d.ts.map +1 -1
- package/dist/io/formats/raster/headless.js +2 -2
- package/dist/io/formats/raster/headless.js.map +1 -1
- package/dist/io/formats/raster/render.d.ts +1 -1
- package/dist/io/formats/raster/render.d.ts.map +1 -1
- package/dist/io/formats/raster/render.js +2 -2
- package/dist/io/formats/raster/render.js.map +1 -1
- package/dist/io/formats.d.ts.map +1 -1
- package/dist/io/formats.js +6 -6
- package/dist/io/formats.js.map +1 -1
- package/dist/io/registry.d.ts +2 -0
- package/dist/io/registry.d.ts.map +1 -1
- package/dist/io/registry.js +5 -0
- package/dist/io/registry.js.map +1 -1
- package/dist/io/types.d.ts +2 -0
- package/dist/io/types.d.ts.map +1 -1
- package/dist/library/snapshot.d.ts.map +1 -1
- package/dist/library/snapshot.js +1 -0
- package/dist/library/snapshot.js.map +1 -1
- package/dist/lint/linter.d.ts.map +1 -1
- package/dist/lint/linter.js +11 -2
- package/dist/lint/linter.js.map +1 -1
- package/dist/rpc/variables-command.d.ts.map +1 -1
- package/dist/rpc/variables-command.js +4 -2
- package/dist/rpc/variables-command.js.map +1 -1
- package/dist/text/character-style.d.ts.map +1 -1
- package/dist/text/character-style.js +2 -1
- package/dist/text/character-style.js.map +1 -1
- package/dist/text/coverage.d.ts.map +1 -1
- package/dist/text/coverage.js +6 -3
- package/dist/text/coverage.js.map +1 -1
- package/dist/text/fallbacks.d.ts +8 -2
- package/dist/text/fallbacks.d.ts.map +1 -1
- package/dist/text/fallbacks.js +73 -7
- package/dist/text/fallbacks.js.map +1 -1
- package/dist/text/font/manager.d.ts +14 -6
- package/dist/text/font/manager.d.ts.map +1 -1
- package/dist/text/font/manager.js +40 -14
- package/dist/text/font/manager.js.map +1 -1
- package/dist/text/index.d.ts +2 -2
- package/dist/text/index.js +3 -3
- package/dist/text/outlines.js +1 -1
- package/dist/text/outlines.js.map +1 -1
- package/dist/text/path/caret.d.ts +2 -4
- package/dist/text/path/caret.d.ts.map +1 -1
- package/dist/text/path/caret.js.map +1 -1
- package/dist/text/prepare.d.ts +5 -1
- package/dist/text/prepare.d.ts.map +1 -1
- package/dist/text/prepare.js +19 -2
- package/dist/text/prepare.js.map +1 -1
- package/dist/text/web-font/assets.d.ts.map +1 -1
- package/dist/text/web-font/assets.js +13 -21
- package/dist/text/web-font/assets.js.map +1 -1
- package/dist/text/web-font/resolver.d.ts.map +1 -1
- package/dist/text/web-font/resolver.js +4 -1
- package/dist/text/web-font/resolver.js.map +1 -1
- package/dist/tools/create/components.d.ts +2 -1
- package/dist/tools/create/components.d.ts.map +1 -1
- package/dist/tools/create/components.js +27 -1
- package/dist/tools/create/components.js.map +1 -1
- package/dist/tools/create/icons.d.ts.map +1 -1
- package/dist/tools/create/icons.js +11 -5
- package/dist/tools/create/icons.js.map +1 -1
- package/dist/tools/create/vector.d.ts.map +1 -1
- package/dist/tools/create/vector.js +9 -6
- package/dist/tools/create/vector.js.map +1 -1
- package/dist/tools/create.d.ts +2 -2
- package/dist/tools/create.js +2 -2
- package/dist/tools/modify/effects.d.ts.map +1 -1
- package/dist/tools/modify/effects.js +5 -3
- package/dist/tools/modify/effects.js.map +1 -1
- package/dist/tools/modify/matching.d.ts.map +1 -1
- package/dist/tools/modify/matching.js +9 -6
- package/dist/tools/modify/matching.js.map +1 -1
- package/dist/tools/modify/paint.d.ts.map +1 -1
- package/dist/tools/modify/paint.js +7 -5
- package/dist/tools/modify/paint.js.map +1 -1
- package/dist/tools/modify/text.d.ts.map +1 -1
- package/dist/tools/modify/text.js +28 -8
- package/dist/tools/modify/text.js.map +1 -1
- package/dist/tools/read/libraries.d.ts.map +1 -1
- package/dist/tools/read/libraries.js +20 -8
- package/dist/tools/read/libraries.js.map +1 -1
- package/dist/tools/read/pages.d.ts.map +1 -1
- package/dist/tools/read/pages.js.map +1 -1
- package/dist/tools/registry/extended.d.ts.map +1 -1
- package/dist/tools/registry/extended.js +2 -1
- package/dist/tools/registry/extended.js.map +1 -1
- package/dist/tools/schema.d.ts +24 -5
- package/dist/tools/schema.d.ts.map +1 -1
- package/dist/tools/schema.js +80 -6
- package/dist/tools/schema.js.map +1 -1
- package/dist/tools/structure/batch.d.ts.map +1 -1
- package/dist/tools/structure/batch.js +4 -3
- package/dist/tools/structure/batch.js.map +1 -1
- package/dist/tools/variables/values.d.ts.map +1 -1
- package/dist/tools/variables/values.js +4 -2
- package/dist/tools/variables/values.js.map +1 -1
- package/dist/tools/vector/export.d.ts.map +1 -1
- package/dist/tools/vector/export.js +5 -2
- package/dist/tools/vector/export.js.map +1 -1
- package/package.json +9 -9
- package/src/canvas/outline-stroke.ts +2 -6
- package/src/canvas/overlays/prototype.ts +5 -27
- package/src/canvas/renderer/fonts.ts +2 -1
- package/src/canvas/renderer.ts +4 -0
- package/src/canvas/rulers.ts +1 -1
- package/src/canvas/scene.ts +92 -63
- package/src/canvas/text/font-families.ts +8 -7
- package/src/canvas/text/index.ts +3 -1
- package/src/canvas/text/paragraph/index.ts +2 -2
- package/src/canvas/text/placed.ts +2 -2
- package/src/canvas/text/renderer.ts +2 -0
- package/src/clipboard/pairdraw.ts +51 -7
- package/src/design-jsx/preview/picture.ts +8 -2
- package/src/editor/alignment.ts +33 -29
- package/src/editor/clipboard/detach.ts +9 -3
- package/src/editor/clipboard/paste/properties.ts +3 -1
- package/src/editor/structure.ts +3 -1
- package/src/editor/viewport.ts +2 -2
- package/src/figma-api/index.ts +90 -9
- package/src/figma-api/serialization.ts +14 -0
- package/src/figma-api/text/bindings.ts +26 -8
- package/src/geometry/connectors.ts +2 -12
- package/src/geometry/index.ts +1 -1
- package/src/geometry/scene.ts +19 -0
- package/src/geometry/types.ts +8 -0
- package/src/io/formats/drawio/export.ts +11 -0
- package/src/io/formats/drawio/index.ts +36 -1
- package/src/io/formats/drawio/shapes.ts +13 -9
- package/src/io/formats/drawio/warnings.ts +27 -0
- package/src/io/formats/pdf/dom.ts +29 -0
- package/src/io/formats/pdf/export.ts +3 -2
- package/src/io/formats/raster/headless.ts +10 -3
- package/src/io/formats/raster/render.ts +4 -2
- package/src/io/formats.ts +8 -10
- package/src/io/registry.ts +12 -0
- package/src/io/types.ts +2 -0
- package/src/library/snapshot.ts +1 -0
- package/src/lint/linter.ts +12 -2
- package/src/rpc/variables-command.ts +6 -5
- package/src/text/character-style.ts +8 -4
- package/src/text/coverage.ts +17 -2
- package/src/text/fallbacks.ts +81 -7
- package/src/text/font/manager.ts +50 -17
- package/src/text/outlines.ts +1 -1
- package/src/text/path/caret.ts +3 -4
- package/src/text/prepare.ts +34 -2
- package/src/text/web-font/assets.ts +11 -15
- package/src/text/web-font/resolver.ts +7 -1
- package/src/tools/create/components.ts +33 -0
- package/src/tools/create/icons.ts +13 -5
- package/src/tools/create/vector.ts +16 -6
- package/src/tools/create.ts +1 -0
- package/src/tools/modify/effects.ts +11 -4
- package/src/tools/modify/matching.ts +10 -6
- package/src/tools/modify/paint.ts +13 -5
- package/src/tools/modify/text.ts +53 -20
- package/src/tools/read/libraries.ts +35 -11
- package/src/tools/read/pages.ts +1 -0
- package/src/tools/registry/extended.ts +2 -0
- package/src/tools/schema.ts +109 -5
- package/src/tools/structure/batch.ts +10 -5
- package/src/tools/variables/values.ts +6 -3
- package/src/tools/vector/export.ts +5 -1
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { placeIcon } from "../../icons/render.js";
|
|
2
|
-
import { defineTool, toolNumber } from "../schema.js";
|
|
3
|
-
import { parseColor } from "@pairdraw/scene-graph/color";
|
|
2
|
+
import { defineTool, parseToolColor, toolNumber } from "../schema.js";
|
|
4
3
|
import { iconOptionsSchema } from "@pairdraw/scene-graph/icons";
|
|
5
4
|
import * as v from "valibot";
|
|
6
5
|
//#region src/tools/create/icons.ts
|
|
@@ -68,14 +67,16 @@ const insertIcon = defineTool({
|
|
|
68
67
|
size: v.optional(toolNumber(v.pipe(v.number(), v.description("Icon size in pixels (default: 24)")))),
|
|
69
68
|
color: v.optional(v.pipe(v.string(), v.description("Icon color hex (replaces currentColor). Default: #000000"))),
|
|
70
69
|
parent_id: v.optional(v.pipe(v.string(), v.description("Parent node ID for all icons"))),
|
|
70
|
+
x: v.optional(toolNumber(v.pipe(v.number(), v.description("X position in the parent")))),
|
|
71
|
+
y: v.optional(toolNumber(v.pipe(v.number(), v.description("Y position in the parent")))),
|
|
71
72
|
...iconOptionInputs
|
|
72
73
|
}),
|
|
73
74
|
execute: async (figma, args) => {
|
|
74
75
|
const names = args.names ?? (args.name ? [args.name] : []);
|
|
75
76
|
if (names.length === 0) return { error: "Provide \"names\" (array) or \"name\" (string)" };
|
|
76
77
|
const size = args.size ?? 24;
|
|
77
|
-
const
|
|
78
|
-
|
|
78
|
+
const parsedColor = parseToolColor(args.color ?? "#000000");
|
|
79
|
+
if ("error" in parsedColor) return parsedColor;
|
|
79
80
|
const options = iconOptions(args);
|
|
80
81
|
let icons;
|
|
81
82
|
try {
|
|
@@ -92,9 +93,14 @@ const insertIcon = defineTool({
|
|
|
92
93
|
continue;
|
|
93
94
|
}
|
|
94
95
|
const parentId = args.parent_id ?? figma.currentPage.id;
|
|
96
|
+
const overrides = args.x === void 0 && args.y === void 0 ? {} : {
|
|
97
|
+
x: args.x ?? 0,
|
|
98
|
+
y: args.y ?? 0
|
|
99
|
+
};
|
|
95
100
|
const frame = placeIcon(figma.graph, parentId, icon, {
|
|
96
101
|
size,
|
|
97
|
-
color: parsedColor
|
|
102
|
+
color: parsedColor,
|
|
103
|
+
overrides
|
|
98
104
|
});
|
|
99
105
|
inserted.push({
|
|
100
106
|
id: frame.id,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"icons.js","names":[],"sources":["../../../src/tools/create/icons.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport { parseColor } from '@pairdraw/scene-graph/color'\nimport { iconOptionsSchema, type IconOptions } from '@pairdraw/scene-graph/icons'\n\nimport { placeIcon } from '#core/icons'\nimport { toolNumber, defineTool } from '#core/tools/schema'\n\nexport const fetchIconsTool = defineTool({\n name: 'fetch_icons',\n exposure: { webmcp: false },\n description:\n 'Pre-fetch icons from Iconify into cache. Batches by prefix (one HTTP request per set). Call this once with all needed icons, then use insert_icon to place them instantly. Popular sets: lucide (outline), mdi (filled), heroicons, tabler, solar, mingcute, ri (remix).',\n execution: { kind: 'async', mutation: 'none' },\n capabilities: ['network:access'],\n input: v.strictObject({\n names: v.pipe(\n v.array(v.string()),\n v.minLength(1),\n v.description('Icon names as prefix:name (e.g. [\"lucide:heart\", \"lucide:home\", \"mdi:star\"])')\n ),\n size: v.optional(\n toolNumber(v.pipe(v.number(), v.description('Icon size in pixels (default: 24)')))\n )\n }),\n execute: async (figma, args) => {\n const size = args.size ?? 24\n try {\n const icons = await figma.icons.icons(args.names, size)\n const fetched = [...icons.keys()]\n const notFound = args.names.filter((name) => !icons.has(name))\n const result: Record<string, unknown> = { fetched, count: fetched.length }\n if (notFound.length > 0) result.not_found = notFound\n return result\n } catch (e) {\n return { error: (e as Error).message }\n }\n }\n})\n\n/**\n * How a set with options draws its icons, as Material Symbols' variable axes. Sets without\n * options ignore them; a value outside an axis is clamped to it.\n */\nconst iconOptionInputs = {\n weight: v.optional(\n toolNumber(\n v.pipe(\n v.number(),\n v.description('Stroke weight, 100 to 700 (Material Symbols; default: 400)')\n )\n )\n ),\n fill: v.optional(\n v.pipe(v.boolean(), v.description('Filled rather than outlined (Material Symbols)'))\n ),\n grade: v.optional(\n toolNumber(\n v.pipe(\n v.number(),\n v.description('Grade, -50 to 200: thickness without resizing (Material Symbols)')\n )\n )\n ),\n optical_size: v.optional(\n toolNumber(\n v.pipe(v.number(), v.description('Optical size, 20 to 48 (Material Symbols; default: 24)'))\n )\n ),\n options: v.optional(\n v.pipe(\n iconOptionsSchema,\n v.description(\n 'Other options of a set that has them, by key, such as an SF Symbols weight or scale'\n )\n )\n )\n}\n\n/** The named options as the axes a set reads, over any given by key. */\nfunction iconOptions(args: {\n weight?: number\n fill?: boolean\n grade?: number\n optical_size?: number\n options?: IconOptions\n}): IconOptions | undefined {\n const options: IconOptions = { ...args.options }\n if (args.optical_size !== undefined) options.opsz = args.optical_size\n if (args.weight !== undefined) options.wght = args.weight\n if (args.fill !== undefined) options.FILL = args.fill ? 1 : 0\n if (args.grade !== undefined) options.GRAD = args.grade\n return Object.keys(options).length > 0 ? options : undefined\n}\n\nexport const insertIcon = defineTool({\n name: 'insert_icon',\n\n description:\n 'Insert one or more vector icons onto the canvas. Pass a single name or multiple names to batch-insert into the same parent. If already cached by fetch_icons — instant, no network request. Material Symbols icons (material-symbols-outlined, -rounded, -sharp) take weight, fill, grade, and optical_size; the icon keeps them when swapped.',\n execution: { kind: 'async', mutation: 'document' },\n capabilities: ['document:write', 'network:access'],\n input: v.strictObject({\n names: v.optional(\n v.pipe(\n v.array(v.string()),\n v.minLength(1),\n v.description(\n 'Icon names as prefix:name (e.g. [\"lucide:heart\"] or [\"lucide:heart\",\"lucide:home\",\"lucide:star\"])'\n )\n )\n ),\n name: v.optional(\n v.pipe(v.string(), v.description('Single icon name (shorthand for names with one icon)'))\n ),\n size: v.optional(\n toolNumber(v.pipe(v.number(), v.description('Icon size in pixels (default: 24)')))\n ),\n color: v.optional(\n v.pipe(v.string(), v.description('Icon color hex (replaces currentColor). Default: #000000'))\n ),\n parent_id: v.optional(v.pipe(v.string(), v.description('Parent node ID for all icons'))),\n ...iconOptionInputs\n }),\n execute: async (figma, args) => {\n const names = args.names ?? (args.name ? [args.name] : [])\n if (names.length === 0) return { error: 'Provide \"names\" (array) or \"name\" (string)' }\n\n const size = args.size ?? 24\n const color = args.color ?? '#000000'\n const parsedColor = parseColor(color)\n const options = iconOptions(args)\n\n let icons\n try {\n icons = await figma.icons.icons(names, size, options)\n } catch (e) {\n return { error: (e as Error).message }\n }\n\n const inserted: { id: string; name: string; icon: string }[] = []\n const notFound: string[] = []\n\n for (const name of names) {\n const icon = icons.get(name)\n if (!icon || icon.paths.length === 0) {\n notFound.push(name)\n continue\n }\n const parentId = args.parent_id ?? figma.currentPage.id\n const frame = placeIcon(figma.graph, parentId, icon, { size, color: parsedColor })\n inserted.push({ id: frame.id, name: frame.name, icon: name })\n }\n\n if (args.name && inserted.length === 1) {\n return { id: inserted[0].id, name: inserted[0].name, type: 'FRAME' as const }\n }\n\n const result: Record<string, unknown> = { inserted }\n if (notFound.length > 0) result.not_found = notFound\n return result\n }\n})\n\nexport const searchIconsTool = defineTool({\n name: 'search_icons',\n exposure: { webmcp: false },\n description:\n 'Search Iconify for icons by keyword. Accepts multiple queries — all searched in parallel. Returns results keyed by query.',\n execution: { kind: 'async', mutation: 'none' },\n capabilities: ['network:access'],\n input: v.strictObject({\n queries: v.pipe(\n v.array(v.string()),\n v.minLength(1),\n v.description('Search keywords (e.g. [\"heart\", \"arrow\", \"settings\"])')\n ),\n limit: v.optional(\n toolNumber(v.pipe(v.number(), v.description('Max results per query (default: 5)')))\n ),\n prefix: v.optional(\n v.pipe(v.string(), v.description('Filter by icon set prefix (e.g. \"lucide\", \"mdi\")'))\n )\n }),\n execute: async (figma, args) => {\n try {\n const options = { limit: args.limit ?? 5, prefix: args.prefix }\n const results = await Promise.all(\n args.queries.map(\n async (query) => [query, await figma.icons.search(query, options)] as const\n )\n )\n return Object.fromEntries(\n results.map(([query, result]) => [query, { icons: result.icons, total: result.total }])\n )\n } catch (e) {\n return { error: (e as Error).message }\n }\n }\n})\n"],"mappings":";;;;;;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KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,oCAAoC,CAAC,CAAC,CACpF;EACA,QAAQ,EAAE,SACR,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,sDAAkD,CAAC,CACtF;CACF,CAAC;CACD,SAAS,OAAO,OAAO,SAAS;EAC9B,IAAI;GACF,MAAM,UAAU;IAAE,OAAO,KAAK,SAAS;IAAG,QAAQ,KAAK;GAAO;GAC9D,MAAM,UAAU,MAAM,QAAQ,IAC5B,KAAK,QAAQ,IACX,OAAO,UAAU,CAAC,OAAO,MAAM,MAAM,MAAM,OAAO,OAAO,OAAO,CAAC,CACnE,CACF;GACA,OAAO,OAAO,YACZ,QAAQ,KAAK,CAAC,OAAO,YAAY,CAAC,OAAO;IAAE,OAAO,OAAO;IAAO,OAAO,OAAO;GAAM,CAAC,CAAC,CACxF;EACF,SAAS,GAAG;GACV,OAAO,EAAE,OAAQ,EAAY,QAAQ;EACvC;CACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"icons.js","names":[],"sources":["../../../src/tools/create/icons.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport { iconOptionsSchema, type IconOptions } from '@pairdraw/scene-graph/icons'\n\nimport { placeIcon } from '#core/icons'\nimport { defineTool, parseToolColor, toolNumber } from '#core/tools/schema'\n\nexport const fetchIconsTool = defineTool({\n name: 'fetch_icons',\n exposure: { webmcp: false },\n description:\n 'Pre-fetch icons from Iconify into cache. Batches by prefix (one HTTP request per set). Call this once with all needed icons, then use insert_icon to place them instantly. Popular sets: lucide (outline), mdi (filled), heroicons, tabler, solar, mingcute, ri (remix).',\n execution: { kind: 'async', mutation: 'none' },\n capabilities: ['network:access'],\n input: v.strictObject({\n names: v.pipe(\n v.array(v.string()),\n v.minLength(1),\n v.description('Icon names as prefix:name (e.g. [\"lucide:heart\", \"lucide:home\", \"mdi:star\"])')\n ),\n size: v.optional(\n toolNumber(v.pipe(v.number(), v.description('Icon size in pixels (default: 24)')))\n )\n }),\n execute: async (figma, args) => {\n const size = args.size ?? 24\n try {\n const icons = await figma.icons.icons(args.names, size)\n const fetched = [...icons.keys()]\n const notFound = args.names.filter((name) => !icons.has(name))\n const result: Record<string, unknown> = { fetched, count: fetched.length }\n if (notFound.length > 0) result.not_found = notFound\n return result\n } catch (e) {\n return { error: (e as Error).message }\n }\n }\n})\n\n/**\n * How a set with options draws its icons, as Material Symbols' variable axes. Sets without\n * options ignore them; a value outside an axis is clamped to it.\n */\nconst iconOptionInputs = {\n weight: v.optional(\n toolNumber(\n v.pipe(\n v.number(),\n v.description('Stroke weight, 100 to 700 (Material Symbols; default: 400)')\n )\n )\n ),\n fill: v.optional(\n v.pipe(v.boolean(), v.description('Filled rather than outlined (Material Symbols)'))\n ),\n grade: v.optional(\n toolNumber(\n v.pipe(\n v.number(),\n v.description('Grade, -50 to 200: thickness without resizing (Material Symbols)')\n )\n )\n ),\n optical_size: v.optional(\n toolNumber(\n v.pipe(v.number(), v.description('Optical size, 20 to 48 (Material Symbols; default: 24)'))\n )\n ),\n options: v.optional(\n v.pipe(\n iconOptionsSchema,\n v.description(\n 'Other options of a set that has them, by key, such as an SF Symbols weight or scale'\n )\n )\n )\n}\n\n/** The named options as the axes a set reads, over any given by key. */\nfunction iconOptions(args: {\n weight?: number\n fill?: boolean\n grade?: number\n optical_size?: number\n options?: IconOptions\n}): IconOptions | undefined {\n const options: IconOptions = { ...args.options }\n if (args.optical_size !== undefined) options.opsz = args.optical_size\n if (args.weight !== undefined) options.wght = args.weight\n if (args.fill !== undefined) options.FILL = args.fill ? 1 : 0\n if (args.grade !== undefined) options.GRAD = args.grade\n return Object.keys(options).length > 0 ? options : undefined\n}\n\nexport const insertIcon = defineTool({\n name: 'insert_icon',\n\n description:\n 'Insert one or more vector icons onto the canvas. Pass a single name or multiple names to batch-insert into the same parent. If already cached by fetch_icons — instant, no network request. Material Symbols icons (material-symbols-outlined, -rounded, -sharp) take weight, fill, grade, and optical_size; the icon keeps them when swapped.',\n execution: { kind: 'async', mutation: 'document' },\n capabilities: ['document:write', 'network:access'],\n input: v.strictObject({\n names: v.optional(\n v.pipe(\n v.array(v.string()),\n v.minLength(1),\n v.description(\n 'Icon names as prefix:name (e.g. [\"lucide:heart\"] or [\"lucide:heart\",\"lucide:home\",\"lucide:star\"])'\n )\n )\n ),\n name: v.optional(\n v.pipe(v.string(), v.description('Single icon name (shorthand for names with one icon)'))\n ),\n size: v.optional(\n toolNumber(v.pipe(v.number(), v.description('Icon size in pixels (default: 24)')))\n ),\n color: v.optional(\n v.pipe(v.string(), v.description('Icon color hex (replaces currentColor). Default: #000000'))\n ),\n parent_id: v.optional(v.pipe(v.string(), v.description('Parent node ID for all icons'))),\n x: v.optional(toolNumber(v.pipe(v.number(), v.description('X position in the parent')))),\n y: v.optional(toolNumber(v.pipe(v.number(), v.description('Y position in the parent')))),\n ...iconOptionInputs\n }),\n execute: async (figma, args) => {\n const names = args.names ?? (args.name ? [args.name] : [])\n if (names.length === 0) return { error: 'Provide \"names\" (array) or \"name\" (string)' }\n\n const size = args.size ?? 24\n const parsedColor = parseToolColor(args.color ?? '#000000')\n if ('error' in parsedColor) return parsedColor\n const options = iconOptions(args)\n\n let icons\n try {\n icons = await figma.icons.icons(names, size, options)\n } catch (e) {\n return { error: (e as Error).message }\n }\n\n const inserted: { id: string; name: string; icon: string }[] = []\n const notFound: string[] = []\n\n for (const name of names) {\n const icon = icons.get(name)\n if (!icon || icon.paths.length === 0) {\n notFound.push(name)\n continue\n }\n const parentId = args.parent_id ?? figma.currentPage.id\n // A position puts the icon there; without one, its parent's layout places it.\n const overrides =\n args.x === undefined && args.y === undefined ? {} : { x: args.x ?? 0, y: args.y ?? 0 }\n const frame = placeIcon(figma.graph, parentId, icon, {\n size,\n color: parsedColor,\n overrides\n })\n inserted.push({ id: frame.id, name: frame.name, icon: name })\n }\n\n if (args.name && inserted.length === 1) {\n return { id: inserted[0].id, name: inserted[0].name, type: 'FRAME' as const }\n }\n\n const result: Record<string, unknown> = { inserted }\n if (notFound.length > 0) result.not_found = notFound\n return result\n }\n})\n\nexport const searchIconsTool = defineTool({\n name: 'search_icons',\n exposure: { webmcp: false },\n description:\n 'Search Iconify for icons by keyword. Accepts multiple queries — all searched in parallel. Returns results keyed by query.',\n execution: { kind: 'async', mutation: 'none' },\n capabilities: ['network:access'],\n input: v.strictObject({\n queries: v.pipe(\n v.array(v.string()),\n v.minLength(1),\n v.description('Search keywords (e.g. [\"heart\", \"arrow\", \"settings\"])')\n ),\n limit: v.optional(\n toolNumber(v.pipe(v.number(), v.description('Max results per query (default: 5)')))\n ),\n prefix: v.optional(\n v.pipe(v.string(), v.description('Filter by icon set prefix (e.g. \"lucide\", \"mdi\")'))\n )\n }),\n execute: async (figma, args) => {\n try {\n const options = { limit: args.limit ?? 5, prefix: args.prefix }\n const results = await Promise.all(\n args.queries.map(\n async (query) => [query, await figma.icons.search(query, options)] as const\n )\n )\n return Object.fromEntries(\n results.map(([query, result]) => [query, { icons: result.icons, total: result.total }])\n )\n } catch (e) {\n return { error: (e as Error).message }\n }\n }\n})\n"],"mappings":";;;;;AAOA,MAAa,iBAAiB,WAAW;CACvC,MAAM;CACN,UAAU,EAAE,QAAQ,MAAM;CAC1B,aACE;CACF,WAAW;EAAE,MAAM;EAAS,UAAU;CAAO;CAC7C,cAAc,CAAC,gBAAgB;CAC/B,OAAO,EAAE,aAAa;EACpB,OAAO,EAAE,KACP,EAAE,MAAM,EAAE,OAAO,CAAC,GAClB,EAAE,UAAU,CAAC,GACb,EAAE,YAAY,oFAA8E,CAC9F;EACA,MAAM,EAAE,SACN,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,mCAAmC,CAAC,CAAC,CACnF;CACF,CAAC;CACD,SAAS,OAAO,OAAO,SAAS;EAC9B,MAAM,OAAO,KAAK,QAAQ;EAC1B,IAAI;GACF,MAAM,QAAQ,MAAM,MAAM,MAAM,MAAM,KAAK,OAAO,IAAI;GACtD,MAAM,UAAU,CAAC,GAAG,MAAM,K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E,OAAO,KAAK,SAAS;IAAG,QAAQ,KAAK;GAAO;GAC9D,MAAM,UAAU,MAAM,QAAQ,IAC5B,KAAK,QAAQ,IACX,OAAO,UAAU,CAAC,OAAO,MAAM,MAAM,MAAM,OAAO,OAAO,OAAO,CAAC,CACnE,CACF;GACA,OAAO,OAAO,YACZ,QAAQ,KAAK,CAAC,OAAO,YAAY,CAAC,OAAO;IAAE,OAAO,OAAO;IAAO,OAAO,OAAO;GAAM,CAAC,CAAC,CACxF;EACF,SAAS,GAAG;GACV,OAAO,EAAE,OAAQ,EAAY,QAAQ;EACvC;CACF;AACF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vector.d.ts","names":[],"sources":["../../../src/tools/create/vector.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"vector.d.ts","names":[],"sources":["../../../src/tools/create/vector.ts"],"mappings":";;cA+Ca,cAAA"}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { computeAccurateBounds } from "../../vector/curve-math.js";
|
|
2
|
-
import { defineTool, nodeSummary, positionInputs, toolNumber } from "../schema.js";
|
|
2
|
+
import { defineTool, nodeSummary, parseOptionalToolColor, positionInputs, toolNumber } from "../schema.js";
|
|
3
3
|
import { parseVectorNetworkJSON } from "../vector/network.js";
|
|
4
4
|
import { parseSVGPath } from "@pairdraw/scene-graph/parse-path";
|
|
5
|
-
import { parseColor } from "@pairdraw/scene-graph/color";
|
|
6
5
|
import { transformVectorNetwork } from "@pairdraw/scene-graph/vector-network";
|
|
7
6
|
import * as v from "valibot";
|
|
8
7
|
//#region src/tools/create/vector.ts
|
|
@@ -61,6 +60,10 @@ const createVector = defineTool({
|
|
|
61
60
|
if ("error" in parsed) return parsed;
|
|
62
61
|
parsedPath = parsed;
|
|
63
62
|
}
|
|
63
|
+
const fill = parseOptionalToolColor(args.fill);
|
|
64
|
+
if ("error" in fill) return fill;
|
|
65
|
+
const stroke = parseOptionalToolColor(args.stroke);
|
|
66
|
+
if ("error" in stroke) return stroke;
|
|
64
67
|
const node = figma.createVector();
|
|
65
68
|
node.x = args.x;
|
|
66
69
|
node.y = args.y;
|
|
@@ -69,13 +72,13 @@ const createVector = defineTool({
|
|
|
69
72
|
if (parsedPath.size) node.resize(parsedPath.size.width, parsedPath.size.height);
|
|
70
73
|
figma.graph.updateNode(node.id, { vectorNetwork: parsedPath.network });
|
|
71
74
|
}
|
|
72
|
-
if (
|
|
75
|
+
if (fill.color) node.fills = [{
|
|
73
76
|
type: "SOLID",
|
|
74
|
-
color:
|
|
77
|
+
color: fill.color
|
|
75
78
|
}];
|
|
76
|
-
if (
|
|
79
|
+
if (stroke.color) figma.graph.updateNode(node.id, { strokes: [{
|
|
77
80
|
type: "SOLID",
|
|
78
|
-
color:
|
|
81
|
+
color: stroke.color,
|
|
79
82
|
weight: args.stroke_weight ?? 1,
|
|
80
83
|
opacity: 1,
|
|
81
84
|
visible: true,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vector.js","names":[],"sources":["../../../src/tools/create/vector.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport type { VectorNetwork } from '@pairdraw/scene-graph'\nimport {
|
|
1
|
+
{"version":3,"file":"vector.js","names":[],"sources":["../../../src/tools/create/vector.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport type { VectorNetwork } from '@pairdraw/scene-graph'\nimport { parseSVGPath } from '@pairdraw/scene-graph/parse-path'\nimport { transformVectorNetwork } from '@pairdraw/scene-graph/vector-network'\n\nimport {\n defineTool,\n nodeSummary,\n parseOptionalToolColor,\n positionInputs,\n toolNumber\n} from '#core/tools/schema'\nimport { parseVectorNetworkJSON } from '#core/tools/vector/network'\nimport { computeAccurateBounds } from '#core/vector/curve-math'\n\ninterface ParsedVectorPath {\n network: VectorNetwork\n size: { width: number; height: number } | null\n}\n\ntype VectorPathResult = ParsedVectorPath | { error: string }\n\nfunction parseSVGVectorPath(path: string): VectorPathResult {\n const network = parseSVGPath(path)\n if (network.segments.length === 0) {\n return { error: 'SVG path data must contain at least one drawable segment' }\n }\n\n const bounds = computeAccurateBounds(network)\n // Figma's vectors cannot be 0×0, so a path that never leaves its start is not one.\n if (bounds.width === 0 && bounds.height === 0) {\n return { error: 'SVG path data must span some width or height' }\n }\n return {\n network: transformVectorNetwork([1, 0, -bounds.x, 0, 1, -bounds.y, 0, 0, 1], network),\n size: { width: bounds.width, height: bounds.height }\n }\n}\n\nfunction parseVectorPath(path: string): VectorPathResult {\n const trimmed = path.trim()\n if (/^[Mm]/.test(trimmed)) return parseSVGVectorPath(trimmed)\n const parsed = parseVectorNetworkJSON(trimmed)\n return 'error' in parsed ? parsed : { network: parsed.network, size: null }\n}\n\nexport const createVector = defineTool({\n name: 'create_vector',\n\n description: 'Create a vector node from SVG path data or a VectorNetwork.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n ...positionInputs,\n name: v.optional(v.pipe(v.string(), v.description('Node name'))),\n path: v.optional(\n v.pipe(\n v.string(),\n v.description(\n 'SVG path data (preferred, e.g. \"M0 0 L100 0 L50 80 Z\") or VectorNetwork JSON, e.g. {\"vertices\":[{\"x\":0,\"y\":0},{\"x\":10,\"y\":0}],\"segments\":[{\"start\":0,\"end\":1}],\"regions\":[]}'\n )\n )\n ),\n fill: v.optional(v.pipe(v.string(), v.description('Fill color (hex)'))),\n stroke: v.optional(v.pipe(v.string(), v.description('Stroke color (hex)'))),\n stroke_weight: v.optional(toolNumber(v.pipe(v.number(), v.description('Stroke weight')))),\n parent_id: v.optional(v.pipe(v.string(), v.description('Parent node ID')))\n }),\n execute: (figma, args) => {\n let parsedPath: ParsedVectorPath | null = null\n if (args.path !== undefined) {\n const parsed = parseVectorPath(args.path)\n if ('error' in parsed) return parsed\n parsedPath = parsed\n }\n // Both colours are read before the node exists, so a bad one creates nothing.\n const fill = parseOptionalToolColor(args.fill)\n if ('error' in fill) return fill\n const stroke = parseOptionalToolColor(args.stroke)\n if ('error' in stroke) return stroke\n\n const node = figma.createVector()\n node.x = args.x\n node.y = args.y\n if (args.name) node.name = args.name\n if (parsedPath) {\n if (parsedPath.size) node.resize(parsedPath.size.width, parsedPath.size.height)\n figma.graph.updateNode(node.id, { vectorNetwork: parsedPath.network })\n }\n if (fill.color) {\n node.fills = [{ type: 'SOLID', color: fill.color }]\n }\n if (stroke.color) {\n figma.graph.updateNode(node.id, {\n strokes: [\n {\n type: 'SOLID',\n color: stroke.color,\n weight: args.stroke_weight ?? 1,\n opacity: 1,\n visible: true,\n align: 'CENTER'\n }\n ]\n })\n }\n if (args.parent_id) {\n const parent = figma.getNodeById(args.parent_id)\n if (parent) parent.appendChild(node)\n }\n return nodeSummary(node)\n }\n})\n"],"mappings":";;;;;;;AAuBA,SAAS,mBAAmB,MAAgC;CAC1D,MAAM,UAAU,aAAa,IAAI;CACjC,IAAI,QAAQ,SAAS,WAAW,GAC9B,OAAO,EAAE,OAAO,2DAA2D;CAG7E,MAAM,SAAS,sBAAsB,OAAO;CAE5C,IAAI,OAAO,UAAU,KAAK,OAAO,WAAW,GAC1C,OAAO,EAAE,OAAO,+CAA+C;CAEjE,OAAO;EACL,SAAS,uBAAuB;GAAC;GAAG;GAAG,CAAC,OAAO;GAAG;GAAG;GAAG,CAAC,OAAO;GAAG;GAAG;GAAG;EAAC,GAAG,OAAO;EACpF,MAAM;GAAE,OAAO,OAAO;GAAO,QAAQ,OAAO;EAAO;CACrD;AACF;AAEA,SAAS,gBAAgB,MAAgC;CACvD,MAAM,UAAU,KAAK,KAAK;CAC1B,IAAI,QAAQ,KAAK,OAAO,GAAG,OAAO,mBAAmB,OAAO;CAC5D,MAAM,SAAS,uBAAuB,OAAO;CAC7C,OAAO,WAAW,SAAS,SAAS;EAAE,SAAS,OAAO;EAAS,MAAM;CAAK;AAC5E;AAEA,MAAa,eAAe,WAAW;CACrC,MAAM;CAEN,aAAa;CACb,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAW;CAChD,OAAO,EAAE,aAAa;EACpB,GAAG;EACH,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MAAM,WAAW,KAAK,IAAI,EAC9B,SAAS,CACP;GACE,MAAM;GACN,OAAO,OAAO;GACd,QAAQ,KAAK,iBAAiB;GAC9B,SAAS;GACT,SAAS;GACT,OAAO;EACT,CACF,EACF,CAAC;EAEH,IAAI,KAAK,WAAW;GAClB,MAAM,SAAS,MAAM,YAAY,KAAK,SAAS;GAC/C,IAAI,QAAQ,OAAO,YAAY,IAAI;EACrC;EACA,OAAO,YAAY,IAAI;CACzB;AACF,CAAC"}
|
package/dist/tools/create.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createPage, createShape, createSlice } from "./create/basic.js";
|
|
2
2
|
import { createSlot, getBehaviour, setBehaviour } from "./create/behaviours.js";
|
|
3
|
-
import { combineAsVariants, createComponent, createInstance, exposeInstanceSwap } from "./create/components.js";
|
|
3
|
+
import { combineAsVariants, createComponent, createInstance, detachInstance, exposeInstanceSwap } from "./create/components.js";
|
|
4
4
|
import { fetchIconsTool, insertIcon, searchIconsTool } from "./create/icons.js";
|
|
5
5
|
import { render } from "./create/render.js";
|
|
6
6
|
import { script } from "./create/script.js";
|
|
@@ -9,4 +9,4 @@ import { importSVG } from "./create/svg.js";
|
|
|
9
9
|
import { importHTML } from "./create/html.js";
|
|
10
10
|
import { createVector } from "./create/vector.js";
|
|
11
11
|
import { createConnectorTool } from "./create/connector.js";
|
|
12
|
-
export { combineAsVariants, createComponent, createConnectorTool, createInstance, createPage, createShape, createSlice, createSlot, createVector, exposeInstanceSwap, fetchIconsTool, getBehaviour, importHTML, importMermaid, importSVG, insertIcon, render, script, searchIconsTool, setBehaviour };
|
|
12
|
+
export { combineAsVariants, createComponent, createConnectorTool, createInstance, createPage, createShape, createSlice, createSlot, createVector, detachInstance, exposeInstanceSwap, fetchIconsTool, getBehaviour, importHTML, importMermaid, importSVG, insertIcon, render, script, searchIconsTool, setBehaviour };
|
package/dist/tools/create.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createPage, createShape, createSlice } from "./create/basic.js";
|
|
2
2
|
import { createSlot, getBehaviour, setBehaviour } from "./create/behaviours.js";
|
|
3
|
-
import { combineAsVariants, createComponent, createInstance, exposeInstanceSwap } from "./create/components.js";
|
|
3
|
+
import { combineAsVariants, createComponent, createInstance, detachInstance, exposeInstanceSwap } from "./create/components.js";
|
|
4
4
|
import { fetchIconsTool, insertIcon, searchIconsTool } from "./create/icons.js";
|
|
5
5
|
import { render } from "./create/render.js";
|
|
6
6
|
import { script } from "./create/script.js";
|
|
@@ -9,4 +9,4 @@ import { importSVG } from "./create/svg.js";
|
|
|
9
9
|
import { importHTML } from "./create/html.js";
|
|
10
10
|
import { createVector } from "./create/vector.js";
|
|
11
11
|
import { createConnectorTool } from "./create/connector.js";
|
|
12
|
-
export { combineAsVariants, createComponent, createConnectorTool, createInstance, createPage, createShape, createSlice, createSlot, createVector, exposeInstanceSwap, fetchIconsTool, getBehaviour, importHTML, importMermaid, importSVG, insertIcon, render, script, searchIconsTool, setBehaviour };
|
|
12
|
+
export { combineAsVariants, createComponent, createConnectorTool, createInstance, createPage, createShape, createSlice, createSlot, createVector, detachInstance, exposeInstanceSwap, fetchIconsTool, getBehaviour, importHTML, importMermaid, importSVG, insertIcon, render, script, searchIconsTool, setBehaviour };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"effects.d.ts","names":[],"sources":["../../../src/tools/modify/effects.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"effects.d.ts","names":[],"sources":["../../../src/tools/modify/effects.ts"],"mappings":";;cAYa,YAAA"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { DEFAULT_SHADOW_COLOR } from "../../constants.js";
|
|
2
|
-
import { defineTool, nodeIdInputSchema, nodeNotFound, toolNumber } from "../schema.js";
|
|
3
|
-
import { parseColor } from "@pairdraw/scene-graph/color";
|
|
2
|
+
import { defineTool, nodeIdInputSchema, nodeNotFound, parseOptionalToolColor, toolNumber } from "../schema.js";
|
|
4
3
|
import * as v from "valibot";
|
|
5
4
|
//#region src/tools/modify/effects.ts
|
|
6
5
|
const setEffects = defineTool({
|
|
@@ -27,6 +26,9 @@ const setEffects = defineTool({
|
|
|
27
26
|
execute: (figma, args) => {
|
|
28
27
|
const node = figma.getNodeById(args.id);
|
|
29
28
|
if (!node) return nodeNotFound(args.id);
|
|
29
|
+
const parsedColor = parseOptionalToolColor(args.color);
|
|
30
|
+
if ("error" in parsedColor) return parsedColor;
|
|
31
|
+
const shadowColor = parsedColor.color ?? { ...DEFAULT_SHADOW_COLOR };
|
|
30
32
|
const effect = args.type === "FOREGROUND_BLUR" || args.type === "BACKGROUND_BLUR" ? {
|
|
31
33
|
type: args.type === "BACKGROUND_BLUR" ? "BACKGROUND_BLUR" : "LAYER_BLUR",
|
|
32
34
|
radius: args.radius,
|
|
@@ -34,7 +36,7 @@ const setEffects = defineTool({
|
|
|
34
36
|
blurType: "NORMAL"
|
|
35
37
|
} : {
|
|
36
38
|
type: args.type,
|
|
37
|
-
color:
|
|
39
|
+
color: shadowColor,
|
|
38
40
|
offset: {
|
|
39
41
|
x: args.offset_x,
|
|
40
42
|
y: args.offset_y
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"effects.js","names":[],"sources":["../../../src/tools/modify/effects.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport {
|
|
1
|
+
{"version":3,"file":"effects.js","names":[],"sources":["../../../src/tools/modify/effects.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport { DEFAULT_SHADOW_COLOR } from '#core/constants'\nimport type { FigmaEffect } from '#core/figma-api/effects'\nimport {\n defineTool,\n nodeIdInputSchema,\n nodeNotFound,\n parseOptionalToolColor,\n toolNumber\n} from '#core/tools/schema'\n\nexport const setEffects = defineTool({\n name: 'set_effects',\n\n description:\n 'Set effects on a node (drop shadow, inner shadow, blur). Pass an array or a single effect.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n type: v.pipe(\n v.picklist(['DROP_SHADOW', 'INNER_SHADOW', 'FOREGROUND_BLUR', 'BACKGROUND_BLUR']),\n v.description('Effect type')\n ),\n color: v.optional(v.pipe(v.string(), v.description('Shadow color (hex). Ignored for blur.'))),\n offset_x: v.optional(toolNumber(v.pipe(v.number(), v.description('Shadow X offset'))), 0),\n offset_y: v.optional(toolNumber(v.pipe(v.number(), v.description('Shadow Y offset'))), 4),\n radius: v.optional(\n toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Blur radius'))),\n 4\n ),\n spread: v.optional(toolNumber(v.pipe(v.number(), v.description('Shadow spread'))), 0)\n }),\n execute: (figma, args) => {\n const node = figma.getNodeById(args.id)\n if (!node) return nodeNotFound(args.id)\n const parsedColor = parseOptionalToolColor(args.color)\n if ('error' in parsedColor) return parsedColor\n const shadowColor = parsedColor.color ?? { ...DEFAULT_SHADOW_COLOR }\n\n const effect: FigmaEffect =\n args.type === 'FOREGROUND_BLUR' || args.type === 'BACKGROUND_BLUR'\n ? {\n type: args.type === 'BACKGROUND_BLUR' ? 'BACKGROUND_BLUR' : 'LAYER_BLUR',\n radius: args.radius,\n visible: true,\n blurType: 'NORMAL'\n }\n : {\n type: args.type,\n color: shadowColor,\n offset: { x: args.offset_x, y: args.offset_y },\n radius: args.radius,\n spread: args.spread,\n visible: true,\n blendMode: 'NORMAL'\n }\n\n node.effects = [...node.effects, effect]\n return { id: args.id, effects: node.effects.length }\n }\n})\n"],"mappings":";;;;AAYA,MAAa,aAAa,WAAW;CACnC,MAAM;CAEN,aACE;CACF,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAa;CAClD,OAAO,EAAE,aAAa;EACpB,IAAI;EACJ,MAAM,EAAE,KACN,EAAE,SAAS;GAAC;GAAe;GAAgB;GAAmB;EAAiB,CAAC,GAChF,EAAE,YAAY,aAAa,CAC7B;EACA,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,uCAAuC,CAAC,CAAC;EAC5F,U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ts","names":[],"sources":["../../../src/tools/modify/matching.ts"],"mappings":";;cAoNa,2BAAA"}
|
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import { collectNodeFontFaces } from "../../text/requirements/collect.js";
|
|
2
2
|
import { getNodeEditCapability } from "../../editor/capabilities.js";
|
|
3
3
|
import { getStyledTextSegments } from "../../figma-api/text/style.js";
|
|
4
|
-
import { defineTool, toolFailure, toolNumber } from "../schema.js";
|
|
4
|
+
import { defineTool, parseToolColor, toolFailure, toolNumber } from "../schema.js";
|
|
5
5
|
import { editNode } from "../../figma-api/accessor-utils.js";
|
|
6
6
|
import { textFonts } from "./text.js";
|
|
7
7
|
import { copyStroke } from "@pairdraw/scene-graph/copy";
|
|
8
8
|
import { mapValues, pick } from "es-toolkit";
|
|
9
|
-
import { tryParseColor } from "@pairdraw/scene-graph/color";
|
|
10
9
|
import * as v from "valibot";
|
|
11
10
|
//#region src/tools/modify/matching.ts
|
|
12
11
|
const colorPairSchema = v.strictObject({
|
|
@@ -59,12 +58,16 @@ function channels(color) {
|
|
|
59
58
|
color.b
|
|
60
59
|
].map((value) => Math.round(value * 255)).join(",");
|
|
61
60
|
}
|
|
61
|
+
/** A colour as a tool reads it, so a bad value fails with the message other tools give. */
|
|
62
|
+
function colorOf(value) {
|
|
63
|
+
const parsed = parseToolColor(value);
|
|
64
|
+
if ("error" in parsed) throw new Error(parsed.error);
|
|
65
|
+
return parsed;
|
|
66
|
+
}
|
|
62
67
|
/** The swap a colour pair makes; throws on a value that is not a colour. */
|
|
63
68
|
function colorSwap(pair) {
|
|
64
|
-
const from =
|
|
65
|
-
const to =
|
|
66
|
-
if (!from) throw new Error(`"${pair.from}" is not a color`);
|
|
67
|
-
if (!to) throw new Error(`"${pair.to}" is not a color`);
|
|
69
|
+
const from = colorOf(pair.from);
|
|
70
|
+
const to = colorOf(pair.to);
|
|
68
71
|
const key = channels(from);
|
|
69
72
|
const percent = (value) => Math.round(value * 100);
|
|
70
73
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"matching.js","names":[],"sources":["../../../src/tools/modify/matching.ts"],"sourcesContent":["import { mapValues, pick } from 'es-toolkit'\nimport * as v from 'valibot'\n\nimport type { Fill, NodeType, SceneNode } from '@pairdraw/scene-graph'\nimport { tryParseColor } from '@pairdraw/scene-graph/color'\nimport { copyStroke } from '@pairdraw/scene-graph/copy'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport { getNodeEditCapability } from '#core/editor/capabilities'\nimport type { FigmaAPI } from '#core/figma-api'\nimport { editNode } from '#core/figma-api/accessor-utils'\nimport type { FigmaFontNameInput } from '#core/figma-api/fonts/names'\nimport { getStyledTextSegments } from '#core/figma-api/text/style'\nimport { collectNodeFontFaces } from '#core/text/requirements/collect'\nimport { defineTool, toolFailure, toolNumber } from '#core/tools/schema'\n\nimport { textFonts } from './text'\n\nconst colorPairSchema = v.strictObject({\n from: v.pipe(v.string(), v.description('Color to find (hex); with alpha, only that opacity')),\n to: v.pipe(v.string(), v.description('Color to use instead (hex); with alpha, its opacity'))\n})\nconst numberPairSchema = v.strictObject({\n from: toolNumber(v.pipe(v.number(), v.description('Value to find'))),\n to: toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Value to use instead')))\n})\nconst textPairSchema = v.strictObject({\n from: v.pipe(v.string(), v.nonEmpty(), v.description('Value to find (case-insensitive)')),\n to: v.pipe(v.string(), v.nonEmpty(), v.description('Value to use instead'))\n})\nconst fontNameSchema = v.object({ family: v.string(), style: v.string() })\n\nconst pairs = <S extends v.GenericSchema>(schema: S, description: string) =>\n v.optional(v.pipe(v.array(schema), v.minLength(1), v.description(description)))\n\nconst replacementInputs = {\n fill_color: pairs(colorPairSchema, 'Solid fill colors of layers other than text'),\n text_color: pairs(colorPairSchema, 'Text colors, including colored ranges'),\n stroke_color: pairs(colorPairSchema, 'Solid stroke colors'),\n stroke_weight: pairs(numberPairSchema, 'Stroke weights of layers that have strokes'),\n corner_radius: pairs(\n numberPairSchema,\n 'Corner radii: a layer’s radius, or each corner on its own where they are set separately'\n ),\n font_family: pairs(textPairSchema, 'Font families, keeping each range’s style'),\n font_style: pairs(textPairSchema, 'Font styles such as Regular or Bold, keeping the family'),\n font_size: pairs(numberPairSchema, 'Font sizes')\n}\n\ntype ReplacementKind = keyof typeof replacementInputs\ntype ColorPair = v.InferOutput<typeof colorPairSchema>\ntype NumberPair = v.InferOutput<typeof numberPairSchema>\ntype TextPair = v.InferOutput<typeof textPairSchema>\ntype Replacements = {\n fill_color?: ColorPair[]\n text_color?: ColorPair[]\n stroke_color?: ColorPair[]\n stroke_weight?: NumberPair[]\n corner_radius?: NumberPair[]\n font_family?: TextPair[]\n font_style?: TextPair[]\n font_size?: NumberPair[]\n}\ntype Scope = { ids?: string[]; within: 'page' | 'selection' }\n\nconst CORNERS = [\n 'topLeftRadius',\n 'topRightRadius',\n 'bottomRightRadius',\n 'bottomLeftRadius'\n] as const\n/** Layers that draw their corners rounded; a radius on any other is not shown. */\nconst ROUNDED_TYPES: ReadonlySet<NodeType> = new Set([\n 'FRAME',\n 'RECTANGLE',\n 'ROUNDED_RECTANGLE',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'INSTANCE'\n])\n\n/** Channels as 0–255 integers, so a hex written by hand matches the colour it names. */\nfunction channels(color: Color): string {\n return [color.r, color.g, color.b].map((value) => Math.round(value * 255)).join(',')\n}\n\ninterface ColorSwap {\n match: (paint: Fill) => boolean\n apply: (paint: Fill) => Fill\n}\n\n/** The swap a colour pair makes; throws on a value that is not a colour. */\nfunction colorSwap(pair: ColorPair): ColorSwap {\n const from = tryParseColor(pair.from)\n const to = tryParseColor(pair.to)\n if (!from) throw new Error(`\"${pair.from}\" is not a color`)\n if (!to) throw new Error(`\"${pair.to}\" is not a color`)\n const key = channels(from)\n const percent = (value: number) => Math.round(value * 100)\n return {\n match: (paint) =>\n paint.type === 'SOLID' &&\n channels(paint.color) === key &&\n (from.a >= 1 || percent(paint.opacity * paint.color.a) === percent(from.a)),\n // A colour's alpha is the paint's opacity, as Figma takes it; without one the paint keeps its own.\n apply: (paint) => ({\n ...paint,\n color: { ...to, a: 1 },\n opacity: to.a < 1 ? to.a : paint.opacity * paint.color.a\n })\n }\n}\n\n/** `paints` with every listed colour swapped, or null when none matched. */\nfunction swapPaints<T extends Fill>(\n paints: readonly T[],\n swaps: readonly ColorSwap[],\n bound: (index: number) => boolean\n): T[] | null {\n const next = paints.map((paint, index) => {\n if (bound(index)) return paint\n const swap = swaps.find((candidate) => candidate.match(paint))\n return swap ? { ...paint, ...swap.apply(paint) } : paint\n })\n return next.some((paint, index) => paint !== paints[index]) ? next : null\n}\n\nfunction swapNumber(value: number, swaps: readonly NumberPair[] | undefined): number | null {\n const swap = swaps?.find((pair) => pair.from === value)\n return swap && swap.to !== value ? swap.to : null\n}\n\nfunction swapText(value: string, swaps: readonly TextPair[] | undefined): string | null {\n const swap = swaps?.find((pair) => pair.from.toLowerCase() === value.toLowerCase())\n return swap && swap.to !== value ? swap.to : null\n}\n\n/** The layers a call searches: the given ones, the selection, or the page's, with descendants. */\nfunction searchedNodes(figma: FigmaAPI, scope: Scope): SceneNode[] | string {\n const graph = figma.graph\n let roots: string[]\n if (scope.ids && scope.ids.length > 0) {\n const missing = scope.ids.find((id) => !graph.getNode(id))\n if (missing) return `Node \"${missing}\" not found`\n roots = scope.ids\n } else if (scope.within === 'selection') {\n roots = figma.currentPage.selection.map((node) => node.id)\n if (roots.length === 0) return 'Nothing is selected'\n } else {\n roots = graph.getNode(figma.currentPage.id)?.childIds ?? []\n }\n const nodes: SceneNode[] = []\n const seen = new Set<string>()\n const walk = (id: string) => {\n const node = seen.has(id) ? undefined : graph.getNode(id)\n if (!node) return\n seen.add(id)\n nodes.push(node)\n for (const childId of node.childIds) walk(childId)\n }\n for (const id of roots) walk(id)\n return nodes\n}\n\ninterface TextEdit {\n start: number\n end: number\n fontName?: { family: string; style: string }\n fontSize?: number\n family: boolean\n style: boolean\n}\n\n/** The font and size changes one text layer takes, range by range. */\nfunction textEdits(node: SceneNode, replacements: Replacements): TextEdit[] {\n if (node.type !== 'TEXT') return []\n const { font_family, font_style, font_size } = replacements\n if (!font_family && !font_style && !font_size) return []\n const edit = (start: number, end: number, font: unknown, size: unknown): TextEdit | null => {\n if (!v.is(fontNameSchema, font)) return null\n const family = swapText(font.family, font_family)\n const style = swapText(font.style, font_style)\n const fontSize = typeof size === 'number' ? swapNumber(size, font_size) : null\n if (!family && !style && fontSize === null) return null\n const textEdit: TextEdit = { start, end, family: family !== null, style: style !== null }\n if (family || style) {\n textEdit.fontName = { family: family ?? font.family, style: style ?? font.style }\n }\n if (fontSize !== null) textEdit.fontSize = fontSize\n return textEdit\n }\n if (node.text.length === 0) {\n // An empty text has no ranges to read; its own face is the first one it lists.\n const face = collectNodeFontFaces(node).at(0)\n const whole = face && edit(0, 0, face, node.fontSize)\n return whole ? [whole] : []\n }\n return getStyledTextSegments(node, ['fontName', 'fontSize']).flatMap(\n (segment) => edit(segment.start, segment.end, segment.fontName, segment.fontSize) ?? []\n )\n}\n\nconst REPLACEMENT_KINDS = Object.keys(replacementInputs) as ReplacementKind[]\n\nfunction colorSwaps(pairs: readonly ColorPair[] | undefined): ColorSwap[] {\n return (pairs ?? []).map(colorSwap)\n}\n\nexport const replaceMatchingProperties = defineTool({\n name: 'replace_matching_properties',\n description:\n 'Swap one value for another on every layer that uses it, across the current page (default), the selection, or the given layers with their descendants: fill, text, and stroke colors, stroke weights, corner radii, font families, font styles, and font sizes. Each property takes a list of { from, to } pairs; colors match by hex, ignoring opacity unless from has alpha, and colors bound to variables are left alone. Layers of read-only library components are not changed and come back in read_only. Returns how many values changed per property and the layers changed.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n ids: v.optional(\n v.pipe(\n v.array(v.string()),\n v.description('Layers to search with their descendants (default: see within)')\n )\n ),\n within: v.optional(\n v.pipe(\n v.picklist(['page', 'selection']),\n v.description('Without ids: the current page (default) or the selection')\n ),\n 'page'\n ),\n ...replacementInputs\n }),\n fonts: (figma, args) => {\n const nodes = searchedNodes(figma, args)\n if (typeof nodes === 'string') return []\n const fonts: FigmaFontNameInput[] = []\n for (const node of nodes) {\n const edits = textEdits(node, args)\n if (edits.length === 0) continue\n fonts.push(...textFonts(figma, node.id))\n for (const edit of edits) if (edit.fontName) fonts.push(edit.fontName)\n }\n return fonts\n },\n execute: (figma, args) => {\n const kinds = REPLACEMENT_KINDS.filter((kind) => args[kind] !== undefined)\n if (kinds.length === 0) return { error: 'Name at least one property to replace' }\n const nodes = searchedNodes(figma, args)\n if (typeof nodes === 'string') return { error: nodes }\n const counts = mapValues(replacementInputs, () => 0)\n const changed = new Set<string>()\n const readOnly: string[] = []\n try {\n const swaps = {\n fill: colorSwaps(args.fill_color),\n text: colorSwaps(args.text_color),\n stroke: colorSwaps(args.stroke_color)\n }\n for (const node of nodes) {\n const paint = paintAndGeometryChanges(node, args, swaps)\n const edits = textEdits(node, args)\n if (!paint && edits.length === 0) continue\n // A library's components change in that library, so their layers are reported instead.\n if (!getNodeEditCapability(figma.graph, node.id).editable) {\n readOnly.push(node.id)\n continue\n }\n if (paint) {\n // As the node setters write, so styles detach and instances keep the change.\n editNode(figma.graph, node.id, paint.changes, figma.groupFitOptions)\n for (const kind of REPLACEMENT_KINDS) counts[kind] += paint.counts[kind] ?? 0\n }\n if (edits.length > 0) changeText(figma, node, edits, counts)\n changed.add(node.id)\n }\n } catch (error) {\n return toolFailure(error)\n }\n return {\n replaced: pick(counts, kinds),\n changed: changed.size,\n ids: [...changed],\n ...(readOnly.length > 0 ? { read_only: readOnly } : {})\n }\n }\n})\n\ntype Counts = Record<ReplacementKind, number>\n\n/** What one layer's paints, stroke weight, and corners change to, with the values it changes. */\nfunction paintAndGeometryChanges(\n node: SceneNode,\n replacements: Replacements,\n swaps: { fill: ColorSwap[]; text: ColorSwap[]; stroke: ColorSwap[] }\n): { changes: Partial<SceneNode>; counts: Partial<Counts> } | null {\n const changes: Partial<SceneNode> = {}\n const counts: Partial<Counts> = {}\n const count = (kind: ReplacementKind, amount = 1) => {\n counts[kind] = (counts[kind] ?? 0) + amount\n }\n const isText = node.type === 'TEXT'\n const fillSwaps = isText ? swaps.text : swaps.fill\n const fillKind = isText ? 'text_color' : 'fill_color'\n const bound = (kind: 'fills' | 'strokes') => (index: number) =>\n !!node.boundVariables[`${kind}/${index}/color`]\n if (fillSwaps.length > 0) {\n const fills = swapPaints(node.fills, fillSwaps, bound('fills'))\n if (fills) {\n changes.fills = fills\n count(fillKind, fills.filter((paint, index) => paint !== node.fills[index]).length)\n }\n if (isText) {\n let runs = 0\n const styleRuns = node.styleRuns.map((run) => {\n const runFills = run.style.fills && swapPaints(run.style.fills, fillSwaps, () => false)\n if (!runFills) return run\n runs++\n return { ...run, style: { ...run.style, fills: runFills } }\n })\n if (runs > 0) {\n changes.styleRuns = styleRuns\n count('text_color', runs)\n }\n }\n }\n if (swaps.stroke.length > 0) {\n const strokes = swapPaints(node.strokes, swaps.stroke, bound('strokes'))\n if (strokes) {\n changes.strokes = strokes\n count('stroke_color', strokes.filter((paint, index) => paint !== node.strokes[index]).length)\n }\n }\n const weight =\n node.strokes.length > 0 ? swapNumber(node.strokeWeight, replacements.stroke_weight) : null\n if (weight !== null) {\n // Each stroke draws at its own weight, so they all take it, as the strokeWeight setter does.\n changes.strokeWeight = weight\n changes.strokes = (changes.strokes ?? node.strokes).map((stroke) => ({\n ...copyStroke(stroke),\n weight\n }))\n count('stroke_weight')\n }\n if (replacements.corner_radius && ROUNDED_TYPES.has(node.type)) {\n Object.assign(changes, cornerChanges(node, replacements.corner_radius, count))\n }\n return Object.keys(changes).length > 0 ? { changes, counts } : null\n}\n\n/**\n * The corner radii `swaps` give a layer. Corners set together draw `cornerRadius`, whatever the\n * corner fields hold, so only corners set one by one are matched each on its own.\n */\nfunction cornerChanges(\n node: SceneNode,\n swaps: readonly NumberPair[],\n count: (kind: ReplacementKind) => void\n): Partial<SceneNode> {\n if (!node.independentCorners) {\n const radius = swapNumber(node.cornerRadius, swaps)\n if (radius === null) return {}\n count('corner_radius')\n return {\n cornerRadius: radius,\n ...Object.fromEntries(CORNERS.map((corner) => [corner, radius])),\n independentCorners: false\n }\n }\n const changes: Partial<SceneNode> = {}\n for (const corner of CORNERS) {\n const radius = swapNumber(node[corner], swaps)\n if (radius === null) continue\n changes[corner] = radius\n count('corner_radius')\n }\n const radii = CORNERS.map((corner) => changes[corner] ?? node[corner])\n if (radii.every((radius, index) => radius === node[CORNERS[index]])) return {}\n const uniform = radii.every((radius) => radius === radii[0])\n changes.cornerRadius = uniform ? radii[0] : node.cornerRadius\n changes.independentCorners = !uniform\n return changes\n}\n\nfunction changeText(\n figma: FigmaAPI,\n node: SceneNode,\n edits: readonly TextEdit[],\n counts: Record<ReplacementKind, number>\n): void {\n const text = figma.getNodeById(node.id)\n if (!text) return\n for (const edit of edits) {\n // A range over all of the text sets the text's own font, as set_font does, not a style run.\n const ranged = edit.start > 0 || edit.end < node.text.length\n if (edit.fontName) {\n if (ranged) text.setRangeFontName(edit.start, edit.end, edit.fontName)\n else text.fontName = edit.fontName\n }\n // The size comes after the font, so it lays the text out in the font it ends up in.\n if (edit.fontSize !== undefined) {\n if (ranged) text.setRangeFontSize(edit.start, edit.end, edit.fontSize)\n else text.fontSize = edit.fontSize\n counts.font_size++\n }\n if (edit.family) counts.font_family++\n if (edit.style) counts.font_style++\n }\n}\n"],"mappings":";;;;;;;;;;;AAkBA,MAAM,kBAAkB,EAAE,aAAa;CACrC,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,oDAAoD,CAAC;CAC5F,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,qDAAqD,CAAC;AAC7F,CAAC;AACD,MAAM,mBAAmB,EAAE,aAAa;CACtC,MAAM,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,eAAe,CAAC,CAAC;CACnE,IAAI,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,SAAS,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T;AAEA,SAAS,WACP,OACA,MACA,OACA,QACM;CACN,MAAM,OAAO,MAAM,YAAY,KAAK,EAAE;CACtC,IAAI,CAAC,MAAM;CACX,KAAK,MAAM,QAAQ,OAAO;EAExB,MAAM,SAAS,KAAK,QAAQ,KAAK,KAAK,MAAM,KAAK,KAAK;EACtD,IAAI,KAAK,UAAU;GACjB,IAAI,QAAQ,KAAK,iBAAiB,KAAK,OAAO,KAAK,KAAK,KAAK,QAAQ;QAChE,KAAK,WAAW,KAAK;EAC5B;EAEA,IAAI,KAAK,aAAa,KAAA,GAAW;GAC/B,IAAI,QAAQ,KAAK,iBAAiB,KAAK,OAAO,KAAK,KAAK,KAAK,QAAQ;QAChE,KAAK,WAAW,KAAK;GAC1B,OAAO;EACT;EACA,IAAI,KAAK,QAAQ,OAAO;EACxB,IAAI,KAAK,OAAO,OAAO;CACzB;AACF"}
|
|
1
|
+
{"version":3,"file":"matching.js","names":[],"sources":["../../../src/tools/modify/matching.ts"],"sourcesContent":["import { mapValues, pick } from 'es-toolkit'\nimport * as v from 'valibot'\n\nimport type { Fill, NodeType, SceneNode } from '@pairdraw/scene-graph'\nimport { copyStroke } from '@pairdraw/scene-graph/copy'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport { getNodeEditCapability } from '#core/editor/capabilities'\nimport type { FigmaAPI } from '#core/figma-api'\nimport { editNode } from '#core/figma-api/accessor-utils'\nimport type { FigmaFontNameInput } from '#core/figma-api/fonts/names'\nimport { getStyledTextSegments } from '#core/figma-api/text/style'\nimport { collectNodeFontFaces } from '#core/text/requirements/collect'\nimport { defineTool, parseToolColor, toolFailure, toolNumber } from '#core/tools/schema'\n\nimport { textFonts } from './text'\n\nconst colorPairSchema = v.strictObject({\n from: v.pipe(v.string(), v.description('Color to find (hex); with alpha, only that opacity')),\n to: v.pipe(v.string(), v.description('Color to use instead (hex); with alpha, its opacity'))\n})\nconst numberPairSchema = v.strictObject({\n from: toolNumber(v.pipe(v.number(), v.description('Value to find'))),\n to: toolNumber(v.pipe(v.number(), v.minValue(0), v.description('Value to use instead')))\n})\nconst textPairSchema = v.strictObject({\n from: v.pipe(v.string(), v.nonEmpty(), v.description('Value to find (case-insensitive)')),\n to: v.pipe(v.string(), v.nonEmpty(), v.description('Value to use instead'))\n})\nconst fontNameSchema = v.object({ family: v.string(), style: v.string() })\n\nconst pairs = <S extends v.GenericSchema>(schema: S, description: string) =>\n v.optional(v.pipe(v.array(schema), v.minLength(1), v.description(description)))\n\nconst replacementInputs = {\n fill_color: pairs(colorPairSchema, 'Solid fill colors of layers other than text'),\n text_color: pairs(colorPairSchema, 'Text colors, including colored ranges'),\n stroke_color: pairs(colorPairSchema, 'Solid stroke colors'),\n stroke_weight: pairs(numberPairSchema, 'Stroke weights of layers that have strokes'),\n corner_radius: pairs(\n numberPairSchema,\n 'Corner radii: a layer’s radius, or each corner on its own where they are set separately'\n ),\n font_family: pairs(textPairSchema, 'Font families, keeping each range’s style'),\n font_style: pairs(textPairSchema, 'Font styles such as Regular or Bold, keeping the family'),\n font_size: pairs(numberPairSchema, 'Font sizes')\n}\n\ntype ReplacementKind = keyof typeof replacementInputs\ntype ColorPair = v.InferOutput<typeof colorPairSchema>\ntype NumberPair = v.InferOutput<typeof numberPairSchema>\ntype TextPair = v.InferOutput<typeof textPairSchema>\ntype Replacements = {\n fill_color?: ColorPair[]\n text_color?: ColorPair[]\n stroke_color?: ColorPair[]\n stroke_weight?: NumberPair[]\n corner_radius?: NumberPair[]\n font_family?: TextPair[]\n font_style?: TextPair[]\n font_size?: NumberPair[]\n}\ntype Scope = { ids?: string[]; within: 'page' | 'selection' }\n\nconst CORNERS = [\n 'topLeftRadius',\n 'topRightRadius',\n 'bottomRightRadius',\n 'bottomLeftRadius'\n] as const\n/** Layers that draw their corners rounded; a radius on any other is not shown. */\nconst ROUNDED_TYPES: ReadonlySet<NodeType> = new Set([\n 'FRAME',\n 'RECTANGLE',\n 'ROUNDED_RECTANGLE',\n 'COMPONENT',\n 'COMPONENT_SET',\n 'INSTANCE'\n])\n\n/** Channels as 0–255 integers, so a hex written by hand matches the colour it names. */\nfunction channels(color: Color): string {\n return [color.r, color.g, color.b].map((value) => Math.round(value * 255)).join(',')\n}\n\n/** A colour as a tool reads it, so a bad value fails with the message other tools give. */\nfunction colorOf(value: string): Color {\n const parsed = parseToolColor(value)\n if ('error' in parsed) throw new Error(parsed.error)\n return parsed\n}\n\ninterface ColorSwap {\n match: (paint: Fill) => boolean\n apply: (paint: Fill) => Fill\n}\n\n/** The swap a colour pair makes; throws on a value that is not a colour. */\nfunction colorSwap(pair: ColorPair): ColorSwap {\n const from = colorOf(pair.from)\n const to = colorOf(pair.to)\n const key = channels(from)\n const percent = (value: number) => Math.round(value * 100)\n return {\n match: (paint) =>\n paint.type === 'SOLID' &&\n channels(paint.color) === key &&\n (from.a >= 1 || percent(paint.opacity * paint.color.a) === percent(from.a)),\n // A colour's alpha is the paint's opacity, as Figma takes it; without one the paint keeps its own.\n apply: (paint) => ({\n ...paint,\n color: { ...to, a: 1 },\n opacity: to.a < 1 ? to.a : paint.opacity * paint.color.a\n })\n }\n}\n\n/** `paints` with every listed colour swapped, or null when none matched. */\nfunction swapPaints<T extends Fill>(\n paints: readonly T[],\n swaps: readonly ColorSwap[],\n bound: (index: number) => boolean\n): T[] | null {\n const next = paints.map((paint, index) => {\n if (bound(index)) return paint\n const swap = swaps.find((candidate) => candidate.match(paint))\n return swap ? { ...paint, ...swap.apply(paint) } : paint\n })\n return next.some((paint, index) => paint !== paints[index]) ? next : null\n}\n\nfunction swapNumber(value: number, swaps: readonly NumberPair[] | undefined): number | null {\n const swap = swaps?.find((pair) => pair.from === value)\n return swap && swap.to !== value ? swap.to : null\n}\n\nfunction swapText(value: string, swaps: readonly TextPair[] | undefined): string | null {\n const swap = swaps?.find((pair) => pair.from.toLowerCase() === value.toLowerCase())\n return swap && swap.to !== value ? swap.to : null\n}\n\n/** The layers a call searches: the given ones, the selection, or the page's, with descendants. */\nfunction searchedNodes(figma: FigmaAPI, scope: Scope): SceneNode[] | string {\n const graph = figma.graph\n let roots: string[]\n if (scope.ids && scope.ids.length > 0) {\n const missing = scope.ids.find((id) => !graph.getNode(id))\n if (missing) return `Node \"${missing}\" not found`\n roots = scope.ids\n } else if (scope.within === 'selection') {\n roots = figma.currentPage.selection.map((node) => node.id)\n if (roots.length === 0) return 'Nothing is selected'\n } else {\n roots = graph.getNode(figma.currentPage.id)?.childIds ?? []\n }\n const nodes: SceneNode[] = []\n const seen = new Set<string>()\n const walk = (id: string) => {\n const node = seen.has(id) ? undefined : graph.getNode(id)\n if (!node) return\n seen.add(id)\n nodes.push(node)\n for (const childId of node.childIds) walk(childId)\n }\n for (const id of roots) walk(id)\n return nodes\n}\n\ninterface TextEdit {\n start: number\n end: number\n fontName?: { family: string; style: string }\n fontSize?: number\n family: boolean\n style: boolean\n}\n\n/** The font and size changes one text layer takes, range by range. */\nfunction textEdits(node: SceneNode, replacements: Replacements): TextEdit[] {\n if (node.type !== 'TEXT') return []\n const { font_family, font_style, font_size } = replacements\n if (!font_family && !font_style && !font_size) return []\n const edit = (start: number, end: number, font: unknown, size: unknown): TextEdit | null => {\n if (!v.is(fontNameSchema, font)) return null\n const family = swapText(font.family, font_family)\n const style = swapText(font.style, font_style)\n const fontSize = typeof size === 'number' ? swapNumber(size, font_size) : null\n if (!family && !style && fontSize === null) return null\n const textEdit: TextEdit = { start, end, family: family !== null, style: style !== null }\n if (family || style) {\n textEdit.fontName = { family: family ?? font.family, style: style ?? font.style }\n }\n if (fontSize !== null) textEdit.fontSize = fontSize\n return textEdit\n }\n if (node.text.length === 0) {\n // An empty text has no ranges to read; its own face is the first one it lists.\n const face = collectNodeFontFaces(node).at(0)\n const whole = face && edit(0, 0, face, node.fontSize)\n return whole ? [whole] : []\n }\n return getStyledTextSegments(node, ['fontName', 'fontSize']).flatMap(\n (segment) => edit(segment.start, segment.end, segment.fontName, segment.fontSize) ?? []\n )\n}\n\nconst REPLACEMENT_KINDS = Object.keys(replacementInputs) as ReplacementKind[]\n\nfunction colorSwaps(pairs: readonly ColorPair[] | undefined): ColorSwap[] {\n return (pairs ?? []).map(colorSwap)\n}\n\nexport const replaceMatchingProperties = defineTool({\n name: 'replace_matching_properties',\n description:\n 'Swap one value for another on every layer that uses it, across the current page (default), the selection, or the given layers with their descendants: fill, text, and stroke colors, stroke weights, corner radii, font families, font styles, and font sizes. Each property takes a list of { from, to } pairs; colors match by hex, ignoring opacity unless from has alpha, and colors bound to variables are left alone. Layers of read-only library components are not changed and come back in read_only. Returns how many values changed per property and the layers changed.',\n execution: { kind: 'sync', mutation: 'document' },\n input: v.strictObject({\n ids: v.optional(\n v.pipe(\n v.array(v.string()),\n v.description('Layers to search with their descendants (default: see within)')\n )\n ),\n within: v.optional(\n v.pipe(\n v.picklist(['page', 'selection']),\n v.description('Without ids: the current page (default) or the selection')\n ),\n 'page'\n ),\n ...replacementInputs\n }),\n fonts: (figma, args) => {\n const nodes = searchedNodes(figma, args)\n if (typeof nodes === 'string') return []\n const fonts: FigmaFontNameInput[] = []\n for (const node of nodes) {\n const edits = textEdits(node, args)\n if (edits.length === 0) continue\n fonts.push(...textFonts(figma, node.id))\n for (const edit of edits) if (edit.fontName) fonts.push(edit.fontName)\n }\n return fonts\n },\n execute: (figma, args) => {\n const kinds = REPLACEMENT_KINDS.filter((kind) => args[kind] !== undefined)\n if (kinds.length === 0) return { error: 'Name at least one property to replace' }\n const nodes = searchedNodes(figma, args)\n if (typeof nodes === 'string') return { error: nodes }\n const counts = mapValues(replacementInputs, () => 0)\n const changed = new Set<string>()\n const readOnly: string[] = []\n try {\n const swaps = {\n fill: colorSwaps(args.fill_color),\n text: colorSwaps(args.text_color),\n stroke: colorSwaps(args.stroke_color)\n }\n for (const node of nodes) {\n const paint = paintAndGeometryChanges(node, args, swaps)\n const edits = textEdits(node, args)\n if (!paint && edits.length === 0) continue\n // A library's components change in that library, so their layers are reported instead.\n if (!getNodeEditCapability(figma.graph, node.id).editable) {\n readOnly.push(node.id)\n continue\n }\n if (paint) {\n // As the node setters write, so styles detach and instances keep the change.\n editNode(figma.graph, node.id, paint.changes, figma.groupFitOptions)\n for (const kind of REPLACEMENT_KINDS) counts[kind] += paint.counts[kind] ?? 0\n }\n if (edits.length > 0) changeText(figma, node, edits, counts)\n changed.add(node.id)\n }\n } catch (error) {\n return toolFailure(error)\n }\n return {\n replaced: pick(counts, kinds),\n changed: changed.size,\n ids: [...changed],\n ...(readOnly.length > 0 ? { read_only: readOnly } : {})\n }\n }\n})\n\ntype Counts = Record<ReplacementKind, number>\n\n/** What one layer's paints, stroke weight, and corners change to, with the values it changes. */\nfunction paintAndGeometryChanges(\n node: SceneNode,\n replacements: Replacements,\n swaps: { fill: ColorSwap[]; text: ColorSwap[]; stroke: ColorSwap[] }\n): { changes: Partial<SceneNode>; counts: Partial<Counts> } | null {\n const changes: Partial<SceneNode> = {}\n const counts: Partial<Counts> = {}\n const count = (kind: ReplacementKind, amount = 1) => {\n counts[kind] = (counts[kind] ?? 0) + amount\n }\n const isText = node.type === 'TEXT'\n const fillSwaps = isText ? swaps.text : swaps.fill\n const fillKind = isText ? 'text_color' : 'fill_color'\n const bound = (kind: 'fills' | 'strokes') => (index: number) =>\n !!node.boundVariables[`${kind}/${index}/color`]\n if (fillSwaps.length > 0) {\n const fills = swapPaints(node.fills, fillSwaps, bound('fills'))\n if (fills) {\n changes.fills = fills\n count(fillKind, fills.filter((paint, index) => paint !== node.fills[index]).length)\n }\n if (isText) {\n let runs = 0\n const styleRuns = node.styleRuns.map((run) => {\n const runFills = run.style.fills && swapPaints(run.style.fills, fillSwaps, () => false)\n if (!runFills) return run\n runs++\n return { ...run, style: { ...run.style, fills: runFills } }\n })\n if (runs > 0) {\n changes.styleRuns = styleRuns\n count('text_color', runs)\n }\n }\n }\n if (swaps.stroke.length > 0) {\n const strokes = swapPaints(node.strokes, swaps.stroke, bound('strokes'))\n if (strokes) {\n changes.strokes = strokes\n count('stroke_color', strokes.filter((paint, index) => paint !== node.strokes[index]).length)\n }\n }\n const weight =\n node.strokes.length > 0 ? swapNumber(node.strokeWeight, replacements.stroke_weight) : null\n if (weight !== null) {\n // Each stroke draws at its own weight, so they all take it, as the strokeWeight setter does.\n changes.strokeWeight = weight\n changes.strokes = (changes.strokes ?? node.strokes).map((stroke) => ({\n ...copyStroke(stroke),\n weight\n }))\n count('stroke_weight')\n }\n if (replacements.corner_radius && ROUNDED_TYPES.has(node.type)) {\n Object.assign(changes, cornerChanges(node, replacements.corner_radius, count))\n }\n return Object.keys(changes).length > 0 ? { changes, counts } : null\n}\n\n/**\n * The corner radii `swaps` give a layer. Corners set together draw `cornerRadius`, whatever the\n * corner fields hold, so only corners set one by one are matched each on its own.\n */\nfunction cornerChanges(\n node: SceneNode,\n swaps: readonly NumberPair[],\n count: (kind: ReplacementKind) => void\n): Partial<SceneNode> {\n if (!node.independentCorners) {\n const radius = swapNumber(node.cornerRadius, swaps)\n if (radius === null) return {}\n count('corner_radius')\n return {\n cornerRadius: radius,\n ...Object.fromEntries(CORNERS.map((corner) => [corner, radius])),\n independentCorners: false\n }\n }\n const changes: Partial<SceneNode> = {}\n for (const corner of CORNERS) {\n const radius = swapNumber(node[corner], swaps)\n if (radius === null) continue\n changes[corner] = radius\n count('corner_radius')\n }\n const radii = CORNERS.map((corner) => changes[corner] ?? node[corner])\n if (radii.every((radius, index) => radius === node[CORNERS[index]])) return {}\n const uniform = radii.every((radius) => radius === radii[0])\n changes.cornerRadius = uniform ? radii[0] : node.cornerRadius\n changes.independentCorners = !uniform\n return changes\n}\n\nfunction changeText(\n figma: FigmaAPI,\n node: SceneNode,\n edits: readonly TextEdit[],\n counts: Record<ReplacementKind, number>\n): void {\n const text = figma.getNodeById(node.id)\n if (!text) return\n for (const edit of edits) {\n // A range over all of the text sets the text's own font, as set_font does, not a style run.\n const ranged = edit.start > 0 || edit.end < node.text.length\n if (edit.fontName) {\n if (ranged) text.setRangeFontName(edit.start, edit.end, edit.fontName)\n else text.fontName = edit.fontName\n }\n // The size comes after the font, so it lays the text out in the font it ends up in.\n if (edit.fontSize !== undefined) {\n if (ranged) text.setRangeFontSize(edit.start, edit.end, edit.fontSize)\n else text.fontSize = edit.fontSize\n counts.font_size++\n }\n if (edit.family) counts.font_family++\n if (edit.style) counts.font_style++\n }\n}\n"],"mappings":";;;;;;;;;;AAiBA,MAAM,kBAAkB,EAAE,aAAa;CACrC,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,oDAAoD,CAAC;CAC5F,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,qDAAqD,CAAC;AAC7F,CAAC;AACD,MAAM,mBAAmB,EAAE,aAAa;CACtC,MAAM,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,eAAe,CAAC,CAAC;CACnE,IAAI,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,SAAS,CAAC,GAAG,EAAE,YAAY,sBAAsB,CAAC,CAAC;AACzF,CAAC;AACD,MAAM,iBAAiB,EAAE,aAAa;CACpC,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,SAAS,GAAG,EAAE,YAAY,kCAAkC,CAAC;CACxF,IAAI,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,SAAS,GAAG,EAAE,YAAY,sBAAsB,CAAC;AAC5E,CAAC;AACD,MAAM,iBAAiB,EAAE,OAAO;CAAE,QAAQ,EAAE,OAAO;CAAG,OAAO,EAAE,OAAO;AAAE,CAAC;AAEzE,MAAM,SAAoC,QAAW,gBACnD,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,MAAM,GAAG,EAAE,UAAU,CAAC,GAAG,EAAE,YAAY,WAAW,CAAC,CAAC;AAEhF,MAAM,oBAAoB;CACxB,YAAY,MAAM,iBAAiB,6CAA6C;CAChF,YAAY,MAAM,iBAAiB,uCAAuC;CAC1E,cAAc,MAAM,iBAAiB,qBAAqB;CAC1D,eAAe,MAAM,kBAAkB,4CAA4C;CACnF,eAAe,M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ources":["../../../src/tools/modify/paint.ts"],"mappings":";;cAwBa,SAAA;cAoEA,WAAA;cA8BA,cAAA"}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import { defineTool, nodeIdInputSchema, toolFailure, toolNumber } from "../schema.js";
|
|
1
|
+
import { defineTool, nodeIdInputSchema, parseToolColor, toolFailure, toolNumber } from "../schema.js";
|
|
2
2
|
import { storeImage } from "../../figma-api/images.js";
|
|
3
3
|
import { isValid, toUint8Array } from "js-base64";
|
|
4
4
|
import { gradientTransformRows, linearGradientTransform } from "@pairdraw/scene-graph/gradient";
|
|
5
|
-
import { parseColor } from "@pairdraw/scene-graph/color";
|
|
6
5
|
import * as v from "valibot";
|
|
7
6
|
//#region src/tools/modify/paint.ts
|
|
8
7
|
/**
|
|
@@ -39,9 +38,11 @@ const setFill = defineTool({
|
|
|
39
38
|
execute: (figma, { id, color, color_end, gradient }) => {
|
|
40
39
|
const node = figma.getNodeById(id);
|
|
41
40
|
if (!node) return { error: `Node "${id}" not found` };
|
|
42
|
-
const c =
|
|
41
|
+
const c = parseToolColor(color);
|
|
42
|
+
if ("error" in c) return c;
|
|
43
43
|
if (gradient && color_end) {
|
|
44
|
-
const cEnd =
|
|
44
|
+
const cEnd = parseToolColor(color_end);
|
|
45
|
+
if ("error" in cEnd) return cEnd;
|
|
45
46
|
const ends = {
|
|
46
47
|
"top-bottom": [{
|
|
47
48
|
x: .5,
|
|
@@ -121,7 +122,8 @@ const setStroke = defineTool({
|
|
|
121
122
|
execute: (figma, { id, color, weight, align }) => {
|
|
122
123
|
const node = figma.getNodeById(id);
|
|
123
124
|
if (!node) return { error: `Node "${id}" not found` };
|
|
124
|
-
const c =
|
|
125
|
+
const c = parseToolColor(color);
|
|
126
|
+
if ("error" in c) return c;
|
|
125
127
|
node.strokes = [{
|
|
126
128
|
type: "SOLID",
|
|
127
129
|
color: c
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"paint.js","names":[],"sources":["../../../src/tools/modify/paint.ts"],"sourcesContent":["import { isValid, toUint8Array } from 'js-base64'\nimport * as v from 'valibot'\n\nimport {
|
|
1
|
+
{"version":3,"file":"paint.js","names":[],"sources":["../../../src/tools/modify/paint.ts"],"sourcesContent":["import { isValid, toUint8Array } from 'js-base64'\nimport * as v from 'valibot'\n\nimport { gradientTransformRows, linearGradientTransform } from '@pairdraw/scene-graph/gradient'\nimport type { Vector } from '@pairdraw/scene-graph/primitives'\n\nimport { storeImage } from '#core/figma-api/images'\nimport {\n defineTool,\n nodeIdInputSchema,\n parseToolColor,\n toolFailure,\n toolNumber\n} from '#core/tools/schema'\n\n/**\n * Stretch as Figma's API writes it: a crop whose window is the whole image, which the image fill\n * panel's Stretch and `.pen`'s `stretch` also store.\n */\nconst STRETCH_IMAGE_TRANSFORM: [[number, number, number], [number, number, number]] = [\n [1, 0, 0],\n [0, 1, 0]\n]\n\nexport const setFill = defineTool({\n name: 'set_fill',\n\n description:\n 'Set fill on a node. Solid: color=\"#ff0000\". Linear gradient: gradient=\"top-bottom\" or \"left-right\" with color (start) and color_end (end).',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n color: v.pipe(v.string(), v.description('Color (hex). For gradient: start color.')),\n color_end: v.optional(\n v.pipe(v.string(), v.description('End color for gradient (if omitted, solid fill)'))\n ),\n gradient: v.optional(\n v.pipe(\n v.picklist(['top-bottom', 'bottom-top', 'left-right', 'right-left']),\n v.description('Gradient direction')\n )\n )\n }),\n execute: (figma, { id, color, color_end, gradient }) => {\n const node = figma.getNodeById(id)\n if (!node) return { error: `Node \"${id}\" not found` }\n\n const c = parseToolColor(color)\n if ('error' in c) return c\n\n if (gradient && color_end) {\n const cEnd = parseToolColor(color_end)\n if ('error' in cEnd) return cEnd\n // Edge middles of the layer's unit square that each direction runs between.\n const ends: Record<string, [Vector, Vector]> = {\n 'top-bottom': [\n { x: 0.5, y: 0 },\n { x: 0.5, y: 1 }\n ],\n 'bottom-top': [\n { x: 0.5, y: 1 },\n { x: 0.5, y: 0 }\n ],\n 'left-right': [\n { x: 0, y: 0.5 },\n { x: 1, y: 0.5 }\n ],\n 'right-left': [\n { x: 1, y: 0.5 },\n { x: 0, y: 0.5 }\n ]\n }\n const [start, end] = ends[gradient] ?? ends['top-bottom']\n node.fills = [\n {\n type: 'GRADIENT_LINEAR',\n gradientStops: [\n { position: 0, color: c },\n { position: 1, color: cEnd }\n ],\n gradientTransform: gradientTransformRows(linearGradientTransform(start, end))\n }\n ]\n return { id, gradient, start: c, end: cEnd }\n }\n\n // A colour's alpha becomes the paint's opacity, as Figma takes it.\n node.fills = [{ type: 'SOLID', color: c }]\n return { id, color: c }\n }\n})\n\nexport const setStroke = defineTool({\n name: 'set_stroke',\n\n description: 'Set the stroke (border) of a node.',\n execution: { kind: 'sync', mutation: 'properties' },\n input: v.strictObject({\n id: nodeIdInputSchema,\n color: v.pipe(v.string(), v.description('Stroke color (hex)')),\n weight: v.optional(\n toolNumber(v.pipe(v.number(), v.minValue(0.1), v.description('Stroke weight'))),\n 1\n ),\n align: v.optional(\n v.pipe(v.picklist(['INSIDE', 'CENTER', 'OUTSIDE']), v.description('Stroke alignment')),\n 'INSIDE'\n )\n }),\n execute: (figma, { id, color, weight, align }) => {\n const node = figma.getNodeById(id)\n if (!node) return { error: `Node \"${id}\" not found` }\n\n const c = parseToolColor(color)\n if ('error' in c) return c\n node.strokes = [{ type: 'SOLID', color: c }]\n node.strokeWeight = weight\n node.strokeAlign = align\n return { id, color: c, weight: weight }\n }\n})\n\nexport const setImageFill = defineTool({\n name: 'set_image_fill',\n\n description:\n 'Set an image fill on a node from base64-encoded image data or an image URL (http, https, or data). A URL is fetched as figma.createImageAsync fetches it, up to 64 MB.',\n execution: { kind: 'async', mutation: 'document' },\n capabilities: ['document:write', 'network:access'],\n input: v.strictObject({\n id: nodeIdInputSchema,\n image_data: v.optional(\n v.pipe(v.string(), v.description('Base64-encoded image bytes (PNG, JPEG, or WEBP)'))\n ),\n url: v.optional(\n v.pipe(\n v.string(),\n v.nonEmpty(),\n v.description('Image URL to fetch (http, https, or data), instead of image_data')\n )\n ),\n scale_mode: v.optional(\n v.pipe(\n v.picklist(['FILL', 'FIT', 'CROP', 'TILE', 'STRETCH']),\n v.description(\n 'Image scale mode. STRETCH stretches the whole image to the layer, ignoring its aspect ratio, as the Stretch mode of the image fill panel does.'\n )\n ),\n 'FILL'\n )\n }),\n execute: async (figma, { id, image_data, url, scale_mode }) => {\n if (!figma.getNodeById(id)) return { error: `Node \"${id}\" not found` }\n if ((image_data === undefined) === (url === undefined)) {\n return { error: 'Provide either image_data or url' }\n }\n let imageHash: string\n if (url !== undefined) {\n try {\n imageHash = (await figma.createImageAsync(url)).hash\n } catch (error) {\n return toolFailure(error)\n }\n } else {\n if (!image_data || !isValid(image_data)) return { error: 'image_data is not valid Base64' }\n imageHash = storeImage(figma.graph, toUint8Array(image_data))\n }\n // The fetch may outlast the node: another edit can remove it meanwhile.\n const node = figma.getNodeById(id)\n if (!node) return { error: `Node \"${id}\" not found` }\n node.fills = [\n scale_mode === 'STRETCH'\n ? { type: 'IMAGE', imageHash, scaleMode: 'CROP', imageTransform: STRETCH_IMAGE_TRANSFORM }\n : { type: 'IMAGE', imageHash, scaleMode: scale_mode }\n ]\n return { id, imageHash, scaleMode: scale_mode }\n }\n})\n"],"mappings":";;;;;;;;;;AAmBA,MAAM,0BAAgF,CACpF;CAAC;CAAG;CAAG;AAAC,GACR;CAAC;CAAG;CAAG;AAAC,CACV;AAEA,MAAa,UAAU,WAAW;CAChC,MAAM;CAEN,aACE;CACF,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAa;CAClD,OAAO,EAAE,aAAa;EACpB,IAAI;EACJ,OAAO,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,yCAAyC,CAAC;EAClF,WAAW,EAAE,SACX,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,iDAAiD,CAAC,CACrF;EACA,UAAU,EAAE,SACV,EAAE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CACF,CAAC;CACD,SAAS,OAAO,OAAO,EAAE,IAAI,YAAY,KAAK,iBAAiB;EAC7D,IAAI,CAAC,MAAM,YAAY,EAAE,GAAG,OAAO,EAAE,OAAO,SAAS,GAAG,aAAa;EACrE,IAAK,eAAe,KAAA,OAAgB,QAAQ,KAAA,IAC1C,OAAO,EAAE,OAAO,mCAAmC;EAErD,IAAI;EACJ,IAAI,QAAQ,KAAA,GACV,IAAI;GACF,aAAa,MAAM,MAAM,iBAAiB,GAAG,EAAA,CAAG;EAClD,SAAS,OAAO;GACd,OAAO,YAAY,KAAK;EAC1B;OACK;GACL,IAAI,CAAC,cAAc,CAAC,QAAQ,UAAU,GAAG,OAAO,EAAE,OAAO,iCAAiC;GAC1F,YAAY,WAAW,MAAM,OAAO,aAAa,UAAU,CAAC;EAC9D;EAEA,MAAM,OAAO,MAAM,YAAY,EAAE;EACjC,IAAI,CAAC,MAAM,OAAO,EAAE,OAAO,SAAS,GAAG,aAAa;EACpD,KAAK,QAAQ,CACX,eAAe,YACX;GAAE,MAAM;GAAS;GAAW,WAAW;GAAQ,gBAAgB;EAAwB,IACvF;GAAE,MAAM;GAAS;GAAW,WAAW;EAAW,CACxD;EACA,OAAO;GAAE;GAAI;GAAW,WAAW;EAAW;CAChD;AACF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"text.d.ts","names":[],"sources":["../../../src/tools/modify/text.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"text.d.ts","names":[],"sources":["../../../src/tools/modify/text.ts"],"mappings":";;;;;iBAqEgB,UAAU,OAAO,UAAU,aAAa;cAK3C,SAAA;cAoEA,SAAA;cA0FA,cAAA;cAoDA,eAAA;cAqBA,mBAAA"}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { collectNodeFontFaces } from "../../text/requirements/collect.js";
|
|
2
2
|
import { normalizeLinkURL } from "../../text/hyperlink.js";
|
|
3
|
-
import { defineTool, nodeIdInputSchema, nodeNotFound, toolFailure, toolNumber } from "../schema.js";
|
|
3
|
+
import { defineTool, nodeIdInputSchema, nodeNotFound, parseOptionalToolColor, toolFailure, toolNumber } from "../schema.js";
|
|
4
4
|
import { PairdrawAPI } from "../../pairdraw-api/index.js";
|
|
5
|
-
import { parseColor } from "@pairdraw/scene-graph/color";
|
|
6
5
|
import * as v from "valibot";
|
|
7
6
|
//#region src/tools/modify/text.ts
|
|
8
7
|
/**
|
|
@@ -67,7 +66,7 @@ const setText = defineTool({
|
|
|
67
66
|
}
|
|
68
67
|
});
|
|
69
68
|
/** Variable font axes a font tool can set, as Figma's `variationSettings`. */
|
|
70
|
-
const variationsInputSchema = v.optional(v.pipe(v.
|
|
69
|
+
const variationsInputSchema = v.optional(v.pipe(v.objectWithRest({}, v.number()), v.description("Variable font axis values by OpenType tag (e.g. {\"wght\": 550, \"wdth\": 75}); axes left out keep the style's values. Without a style, the nearest named style is picked.")));
|
|
71
70
|
/**
|
|
72
71
|
* The font a font tool gives text: what it names, the rest from `current`. Axes without a style
|
|
73
72
|
* leave the style out, for the nearest named style to be picked.
|
|
@@ -122,6 +121,8 @@ const setFont = defineTool({
|
|
|
122
121
|
execute: (figma, args) => {
|
|
123
122
|
const node = figma.getNodeById(args.id);
|
|
124
123
|
if (!node) return nodeNotFound(args.id);
|
|
124
|
+
const badTag = badVariationTag(args.variations);
|
|
125
|
+
if (badTag) return badTag;
|
|
125
126
|
const font = requestedFont(node, args);
|
|
126
127
|
try {
|
|
127
128
|
if (font && "whole" in font) node.fontName = font.whole;
|
|
@@ -142,6 +143,23 @@ function rangeFont(node, args) {
|
|
|
142
143
|
const current = args.start < node.characters.length ? node.getRangeFontName(args.start, args.start + 1) : node.fontName;
|
|
143
144
|
return fontNameInput(args, typeof current === "symbol" ? null : current);
|
|
144
145
|
}
|
|
146
|
+
/** Why a variation setting cannot apply: an axis tag is not four letters. */
|
|
147
|
+
function badVariationTag(variations) {
|
|
148
|
+
const tag = Object.keys(variations ?? {}).find((key) => key.length !== 4);
|
|
149
|
+
return tag === void 0 ? null : { error: `"${tag}" is not a four-letter OpenType axis tag` };
|
|
150
|
+
}
|
|
151
|
+
/** What a range edit sets, or why it cannot run: nothing named, a bad colour, or a bad link. */
|
|
152
|
+
function rangeEdit(args) {
|
|
153
|
+
if (!args.family && !args.size && !args.style && !args.variations && !args.color && args.hyperlink === void 0) return { error: "set_font_range needs at least one of family, size, style, variations, color, or hyperlink" };
|
|
154
|
+
const hyperlink = requestedHyperlink(args.hyperlink);
|
|
155
|
+
if (hyperlink && "error" in hyperlink) return hyperlink;
|
|
156
|
+
const color = parseOptionalToolColor(args.color);
|
|
157
|
+
if ("error" in color) return color;
|
|
158
|
+
return {
|
|
159
|
+
hyperlink: hyperlink ?? null,
|
|
160
|
+
color: color.color
|
|
161
|
+
};
|
|
162
|
+
}
|
|
145
163
|
const setFontRange = defineTool({
|
|
146
164
|
name: "set_font_range",
|
|
147
165
|
description: "Set font properties, color, or a link for a text range.",
|
|
@@ -171,15 +189,17 @@ const setFontRange = defineTool({
|
|
|
171
189
|
const node = figma.getNodeById(args.id);
|
|
172
190
|
if (!node) return nodeNotFound(args.id);
|
|
173
191
|
const { start, end } = args;
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
192
|
+
const badTag = badVariationTag(args.variations);
|
|
193
|
+
if (badTag) return badTag;
|
|
194
|
+
const edit = rangeEdit(args);
|
|
195
|
+
if ("error" in edit) return edit;
|
|
196
|
+
const { hyperlink, color } = edit;
|
|
177
197
|
try {
|
|
178
198
|
if (args.size) node.setRangeFontSize(start, end, args.size);
|
|
179
199
|
if (args.family || args.style || args.variations) node.setRangeFontName(start, end, rangeFont(node, args));
|
|
180
|
-
if (
|
|
200
|
+
if (color) node.setRangeFills(start, end, [{
|
|
181
201
|
type: "SOLID",
|
|
182
|
-
color
|
|
202
|
+
color
|
|
183
203
|
}]);
|
|
184
204
|
if (hyperlink) node.setRangeHyperlink(start, end, hyperlink.link);
|
|
185
205
|
} catch (error) {
|