@pairdraw/core 0.17.0 → 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/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/design-jsx/renderer.d.ts.map +1 -1
- package/dist/editor/bridges/undo.d.ts +1 -1
- package/dist/editor/create.d.ts +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/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 +3 -1
- 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/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 +2 -2
- 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 +16 -4
- 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/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/figma-api/index.ts +90 -9
- package/src/figma-api/serialization.ts +14 -0
- 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 +3 -1
- 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/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 +21 -4
- 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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/canvas/text/paragraph/index.ts"],"sourcesContent":["import type {\n CanvasKit,\n FontStyle,\n Paint,\n Paragraph,\n ParagraphBuilder,\n TextFontFeatures,\n TextFontVariations,\n TextHeightBehavior\n} from 'canvaskit-wasm'\n\nimport type { SceneNode } from '@pairdraw/scene-graph'\nimport { resolveRGBAForPreview } from '@pairdraw/scene-graph/color'\nimport { faceStyleKey, type NamedFace } from '@pairdraw/scene-graph/font-style'\nimport { rangeFontStyle } from '@pairdraw/scene-graph/shared-styles'\nimport { lineHeightPixels, textLengthPixels } from '@pairdraw/scene-graph/text'\nimport { resolveNodeTextDirection } from '@pairdraw/scene-graph/text/direction'\n\nimport {\n drawnFontVariations,\n loadedFace,\n resolveParagraphFontFamilies\n} from '#core/canvas/text/font-families'\nimport { laidOutText } from '#core/canvas/text/keycap'\nimport {\n pushParagraphStyle,\n type ParagraphPaintStyle,\n type ParagraphBuildOptions\n} from '#core/canvas/text/paint'\nimport type { TextRenderer } from '#core/canvas/text/renderer'\nimport { DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from '#core/constants'\nimport { shownTextSlice } from '#core/text/case'\nimport { ELLIPSIS } from '#core/text/ellipsis'\nimport { fontManager } from '#core/text/font/manager'\n\nimport type { ParagraphNode } from './inputs'\n\nexport function resolveParagraphLayoutWidth(node: ParagraphNode, maxWidth?: number): number {\n if (maxWidth !== undefined) return maxWidth\n if (node.textAutoResize === 'WIDTH_AND_HEIGHT') return 1e6\n return node.width || 1e6\n}\n\nexport function buildTruncateOpts(node: ParagraphNode): { maxLines?: number; ellipsis?: string } {\n if (node.textTruncation !== 'ENDING') return {}\n\n const opts: { maxLines?: number; ellipsis: string } = { ellipsis: ELLIPSIS }\n if (node.maxLines != null && node.maxLines > 0) {\n opts.maxLines = node.maxLines\n }\n return opts\n}\n\nfunction getParagraphTextAlign(\n ck: CanvasKit,\n node: Pick<SceneNode, 'textAlignHorizontal' | 'textDirection' | 'text'>\n) {\n const direction = resolveNodeTextDirection(node)\n switch (node.textAlignHorizontal) {\n case 'CENTER':\n return ck.TextAlign.Center\n case 'RIGHT':\n return direction === 'RTL' ? ck.TextAlign.Left : ck.TextAlign.Right\n case 'JUSTIFIED':\n return ck.TextAlign.Justify\n default:\n return direction === 'RTL' ? ck.TextAlign.Right : ck.TextAlign.Left\n }\n}\n\n/** Explicit axes win over the named-instance axes of a variable face (`implicit`). */\nexport function textFontVariations(\n variations: SceneNode['fontVariations'] | undefined,\n implicit: SceneNode['fontVariations'] | null = null\n): TextFontVariations[] | undefined {\n const explicitAxes = new Set(variations?.map((variation) => variation.axis))\n const merged = [\n ...(implicit ?? []).filter((variation) => !explicitAxes.has(variation.axis)),\n ...(variations ?? [])\n ]\n if (merged.length === 0) return undefined\n return merged.map((variation) => ({ axis: variation.axis, value: variation.value }))\n}\n\nexport function textFontFeatures(\n features: SceneNode['fontFeatures'] | undefined\n): TextFontFeatures[] | undefined {\n if (!features || features.length === 0) return undefined\n return features.map((feature) => ({\n name: feature.tag.toLowerCase(),\n value: feature.enabled ? 1 : 0\n }))\n}\n\nexport function textHeightBehaviorValue<T>(\n ck: { TextHeightBehavior: { DisableAll: T } },\n leadingTrim: SceneNode['leadingTrim']\n): T | undefined {\n return leadingTrim === 'CAP_HEIGHT' ? ck.TextHeightBehavior.DisableAll : undefined\n}\n\n/** Which edges of the text a paragraph is: leading trim only trims the text's own edges. */\nexport interface ParagraphEdges {\n first: boolean\n last: boolean\n}\n\nfunction blockHeightBehavior(\n ck: CanvasKit,\n leadingTrim: SceneNode['leadingTrim'],\n edges: ParagraphEdges | undefined\n): TextHeightBehavior | undefined {\n if (!edges) return textHeightBehaviorValue(ck, leadingTrim)\n const { first, last } = edges\n if (leadingTrim !== 'CAP_HEIGHT') return undefined\n if (first && last) return ck.TextHeightBehavior.DisableAll\n if (first) return ck.TextHeightBehavior.DisableFirstAscent\n if (last) return ck.TextHeightBehavior.DisableLastDescent\n return ck.TextHeightBehavior.All\n}\n\n/**\n * The style a paragraph asks CanvasKit for: the face of the family that is loaded. Asked for a\n * face it lacks, CanvasKit slants and emboldens another, which neither Figma, a browser, nor a\n * native text stack draws the same, so a missing face is drawn as the face that exists and\n * reported missing, as Figma does. A family with no face loaded asks for the style as given.\n */\nfunction drawnFontStyle(\n ck: CanvasKit,\n family: string,\n weight: number,\n italic: boolean,\n style: string\n): FontStyle {\n const face = loadedFace(family, weight, italic, style) ?? { weight, italic }\n return {\n weight: { value: face.weight },\n slant: face.italic ? ck.FontSlant.Italic : ck.FontSlant.Upright\n }\n}\n\n/** The colour a style run's text is drawn in: its first visible solid fill, or `baseColor`. */\nexport function styleRunColor(\n ck: CanvasKit,\n style: SceneNode['styleRuns'][number]['style'],\n baseColor: Float32Array\n): Float32Array {\n const visibleFill = style.fills?.find((fill) => fill.visible && fill.type === 'SOLID')\n if (!visibleFill) return baseColor\n const color = resolveRGBAForPreview(visibleFill.color).color\n return ck.Color4f(color.r, color.g, color.b, color.a * visibleFill.opacity)\n}\n\nfunction styleRunLanguage(\n style: SceneNode['styleRuns'][number]['style'],\n node: Pick<ParagraphNode, 'textLanguage'>\n): string | undefined {\n return (style.textLanguage !== undefined ? style.textLanguage : node.textLanguage) ?? undefined\n}\n\nfunction pushStyleRun(\n r: TextRenderer,\n builder: ParagraphBuilder,\n node: ParagraphNode,\n run: SceneNode['styleRuns'][number],\n baseColor: Float32Array,\n baseFontSize: number,\n fontFamilies: (primary: string, face: NamedFace) => string[],\n halfLeading: boolean,\n paintStyle?: ParagraphPaintStyle\n): void {\n const ck = r.ck\n const style = run.style\n const runFontSize = style.fontSize ?? baseFontSize\n // A percent follows the run's own font size, as in Figma.\n const runLineHeight = lineHeightPixels(\n style.lineHeight !== undefined ? style.lineHeight : node.lineHeight,\n runFontSize\n )\n const runFamily = style.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY)\n const runWeight = style.fontWeight ?? node.fontWeight\n const runItalic = style.italic ?? node.italic\n const runFace = {\n fontWeight: runWeight,\n italic: runItalic,\n fontStyle: rangeFontStyle(node, style)\n }\n const runKey = faceStyleKey(runFace)\n\n const textStyle = new ck.TextStyle({\n color: styleRunColor(ck, style, baseColor),\n fontFamilies: fontFamilies(runFamily, runFace),\n fontSize: runFontSize,\n locale: styleRunLanguage(style, node),\n fontStyle: drawnFontStyle(ck, runFamily, runWeight, runItalic, runKey),\n fontVariations: textFontVariations(\n drawnFontVariations({\n family: runFamily,\n weight: runWeight,\n italic: runItalic,\n style: runKey,\n fontSize: runFontSize,\n variations: style.fontVariations ?? node.fontVariations,\n opticalSizeFromFontSize: style.opticalSizeFromFontSize ?? node.opticalSizeFromFontSize\n })\n ),\n fontFeatures: textFontFeatures(style.fontFeatures ?? node.fontFeatures),\n letterSpacing: textLengthPixels(style.letterSpacing ?? node.letterSpacing, runFontSize),\n heightMultiplier: runLineHeight ? runLineHeight / runFontSize : undefined,\n halfLeading\n })\n pushParagraphStyle(builder, textStyle, paintStyle)\n}\n\n/** `text[start, end)` in the case each of its characters has. */\nfunction addParagraphText(\n builder: ParagraphBuilder,\n node: ParagraphNode,\n start: number,\n end: number\n): void {\n builder.addText(laidOutText(shownTextSlice(node, start, end)))\n}\n\nfunction addStyledRuns(\n r: TextRenderer,\n builder: ParagraphBuilder,\n node: ParagraphNode,\n baseColor: Float32Array,\n baseFontSize: number,\n fontFamilies: (primary: string, face: NamedFace) => string[],\n halfLeading: boolean,\n paintStyle?: ParagraphPaintStyle\n): void {\n const text = node.text\n let pos = 0\n\n for (const run of node.styleRuns) {\n if (pos < run.start) addParagraphText(builder, node, pos, run.start)\n pushStyleRun(\n r,\n builder,\n node,\n run,\n baseColor,\n baseFontSize,\n fontFamilies,\n halfLeading,\n paintStyle\n )\n addParagraphText(builder, node, run.start, run.start + run.length)\n builder.pop()\n pos = run.start + run.length\n }\n\n if (pos < text.length) addParagraphText(builder, node, pos, text.length)\n}\n\n/** What a paragraph that is one block of a longer text needs beyond its node's own style. */\nexport interface ParagraphBlockOptions {\n /** Room before the first line, as a plain paragraph's first-line indent. */\n firstLineIndent?: number\n /** Truncation for this block in place of the node's. */\n truncation?: { maxLines?: number; ellipsis?: string }\n edges?: ParagraphEdges\n}\n\n/** Room before a paragraph's first line, as an empty placeholder on its baseline. */\nfunction addFirstLineIndent(ck: CanvasKit, builder: ParagraphBuilder, width: number): void {\n builder.addPlaceholder(width, 0, ck.PlaceholderAlignment.Baseline, ck.TextBaseline.Alphabetic, 0)\n}\n\n/**\n * A native paragraph for `node`'s text in its style runs, not yet laid out. A first-line\n * indent is a placeholder before the text, which takes the first character index.\n */\nexport function buildSkParagraph(\n r: TextRenderer,\n node: ParagraphNode,\n color?: Float32Array,\n { halfLeading = false, foregroundPaint }: ParagraphBuildOptions = {},\n block: ParagraphBlockOptions = {}\n): Paragraph {\n const ck = r.ck\n const baseColor = color ?? ck.BLACK\n const baseFontSize = node.fontSize || DEFAULT_FONT_SIZE\n const baseLineHeight = lineHeightPixels(node.lineHeight, baseFontSize)\n const cjkFallbacks = fontManager.getCJKFallbackFamilies()\n const arabicFallbacks = fontManager.getArabicFallbackFamilies()\n const textDirection = resolveNodeTextDirection(node)\n\n const truncateOpts = block.truncation ?? buildTruncateOpts(node)\n\n const fontFamilies = (primary: string, face: NamedFace) =>\n resolveParagraphFontFamilies(\n primary,\n { weight: face.fontWeight, italic: face.italic, style: faceStyleKey(face) },\n arabicFallbacks,\n cjkFallbacks\n )\n const nodeKey = faceStyleKey(node)\n\n const baseTextStyle = {\n color: baseColor,\n fontFamilies: fontFamilies(node.fontFamily || DEFAULT_FONT_FAMILY, node),\n fontSize: baseFontSize,\n locale: node.textLanguage ?? undefined,\n fontStyle: drawnFontStyle(\n ck,\n node.fontFamily || DEFAULT_FONT_FAMILY,\n node.fontWeight,\n node.italic,\n nodeKey\n ),\n fontVariations: textFontVariations(\n drawnFontVariations({\n family: node.fontFamily || DEFAULT_FONT_FAMILY,\n weight: node.fontWeight,\n italic: node.italic,\n style: nodeKey,\n fontSize: baseFontSize,\n variations: node.fontVariations,\n opticalSizeFromFontSize: node.opticalSizeFromFontSize\n })\n ),\n fontFeatures: textFontFeatures(node.fontFeatures),\n letterSpacing: textLengthPixels(node.letterSpacing, baseFontSize),\n heightMultiplier: baseLineHeight ? baseLineHeight / baseFontSize : undefined,\n halfLeading\n }\n const paraStyle = new ck.ParagraphStyle({\n textAlign: getParagraphTextAlign(ck, node),\n textDirection: textDirection === 'RTL' ? ck.TextDirection.RTL : ck.TextDirection.LTR,\n textHeightBehavior: blockHeightBehavior(ck, node.leadingTrim, block.edges),\n ...truncateOpts,\n textStyle: baseTextStyle\n })\n\n if (!r.fontProvider) throw new Error('Font provider not initialized')\n const builder = ck.ParagraphBuilder.MakeFromFontProvider(paraStyle, r.fontProvider)\n\n let background: Paint | undefined\n try {\n let paintStyle: ParagraphPaintStyle | undefined\n if (foregroundPaint) {\n background = new ck.Paint()\n background.setColor(ck.TRANSPARENT)\n paintStyle = { foreground: foregroundPaint, background }\n builder.pushPaintStyle(new ck.TextStyle(baseTextStyle), foregroundPaint, background)\n }\n if (block.firstLineIndent) addFirstLineIndent(ck, builder, block.firstLineIndent)\n if (node.styleRuns.length === 0) {\n addParagraphText(builder, node, 0, node.text.length)\n } else {\n addStyledRuns(\n r,\n builder,\n node,\n baseColor,\n baseFontSize,\n fontFamilies,\n halfLeading,\n paintStyle\n )\n }\n\n return builder.build()\n } finally {\n builder.delete()\n background?.delete()\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAqCA,SAAgB,4BAA4B,MAAqB,UAA2B;CAC1F,IAAI,aAAa,KAAA,GAAW,OAAO;CACnC,IAAI,KAAK,mBAAmB,oBAAoB,OAAO;CACvD,OAAO,KAAK,SAAS;AACvB;AAEA,SAAgB,kBAAkB,MAA+D;CAC/F,IAAI,KAAK,mBAAmB,UAAU,OA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IAAI,CAAC,EAAE,cAAc,MAAM,IAAI,MAAM,+BAA+B;CACpE,MAAM,UAAU,GAAG,iBAAiB,qBAAqB,WAAW,EAAE,YAAY;CAElF,IAAI;CACJ,IAAI;EACF,IAAI;EACJ,IAAI,iBAAiB;GACnB,aAAa,IAAI,GAAG,MAAM;GAC1B,WAAW,SAAS,GAAG,WAAW;GAClC,aAAa;IAAE,YAAY;IAAiB;GAAW;GACvD,QAAQ,eAAe,IAAI,GAAG,UAAU,aAAa,GAAG,iBAAiB,UAAU;EACrF;EACA,IAAI,MAAM,iBAAiB,mBAAmB,IAAI,SAAS,MAAM,eAAe;EAChF,IAAI,KAAK,UAAU,WAAW,GAC5B,iBAAiB,SAAS,MAAM,GAAG,KAAK,KAAK,MAAM;OAEnD,cACE,GACA,SACA,MACA,WACA,cACA,cACA,aACA,UACF;EAGF,OAAO,QAAQ,MAAM;CACvB,UAAU;EACR,QAAQ,OAAO;EACf,YAAY,OAAO;CACrB;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/canvas/text/paragraph/index.ts"],"sourcesContent":["import type {\n CanvasKit,\n FontStyle,\n Paint,\n Paragraph,\n ParagraphBuilder,\n TextFontFeatures,\n TextFontVariations,\n TextHeightBehavior\n} from 'canvaskit-wasm'\n\nimport type { SceneNode } from '@pairdraw/scene-graph'\nimport { resolveRGBAForPreview } from '@pairdraw/scene-graph/color'\nimport { faceStyleKey, type NamedFace } from '@pairdraw/scene-graph/font-style'\nimport { rangeFontStyle } from '@pairdraw/scene-graph/shared-styles'\nimport { lineHeightPixels, textLengthPixels } from '@pairdraw/scene-graph/text'\nimport { resolveNodeTextDirection } from '@pairdraw/scene-graph/text/direction'\n\nimport {\n drawnFontVariations,\n loadedFace,\n resolveParagraphFontFamilies\n} from '#core/canvas/text/font-families'\nimport { laidOutText } from '#core/canvas/text/keycap'\nimport {\n pushParagraphStyle,\n type ParagraphPaintStyle,\n type ParagraphBuildOptions\n} from '#core/canvas/text/paint'\nimport type { TextRenderer } from '#core/canvas/text/renderer'\nimport { DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE } from '#core/constants'\nimport { shownTextSlice } from '#core/text/case'\nimport { ELLIPSIS } from '#core/text/ellipsis'\nimport { fontManager } from '#core/text/font/manager'\n\nimport type { ParagraphNode } from './inputs'\n\nexport function resolveParagraphLayoutWidth(node: ParagraphNode, maxWidth?: number): number {\n if (maxWidth !== undefined) return maxWidth\n if (node.textAutoResize === 'WIDTH_AND_HEIGHT') return 1e6\n return node.width || 1e6\n}\n\nexport function buildTruncateOpts(node: ParagraphNode): { maxLines?: number; ellipsis?: string } {\n if (node.textTruncation !== 'ENDING') return {}\n\n const opts: { maxLines?: number; ellipsis: string } = { ellipsis: ELLIPSIS }\n if (node.maxLines != null && node.maxLines > 0) {\n opts.maxLines = node.maxLines\n }\n return opts\n}\n\nfunction getParagraphTextAlign(\n ck: CanvasKit,\n node: Pick<SceneNode, 'textAlignHorizontal' | 'textDirection' | 'text'>\n) {\n const direction = resolveNodeTextDirection(node)\n switch (node.textAlignHorizontal) {\n case 'CENTER':\n return ck.TextAlign.Center\n case 'RIGHT':\n return direction === 'RTL' ? ck.TextAlign.Left : ck.TextAlign.Right\n case 'JUSTIFIED':\n return ck.TextAlign.Justify\n default:\n return direction === 'RTL' ? ck.TextAlign.Right : ck.TextAlign.Left\n }\n}\n\n/** Explicit axes win over the named-instance axes of a variable face (`implicit`). */\nexport function textFontVariations(\n variations: SceneNode['fontVariations'] | undefined,\n implicit: SceneNode['fontVariations'] | null = null\n): TextFontVariations[] | undefined {\n const explicitAxes = new Set(variations?.map((variation) => variation.axis))\n const merged = [\n ...(implicit ?? []).filter((variation) => !explicitAxes.has(variation.axis)),\n ...(variations ?? [])\n ]\n if (merged.length === 0) return undefined\n return merged.map((variation) => ({ axis: variation.axis, value: variation.value }))\n}\n\nexport function textFontFeatures(\n features: SceneNode['fontFeatures'] | undefined\n): TextFontFeatures[] | undefined {\n if (!features || features.length === 0) return undefined\n return features.map((feature) => ({\n name: feature.tag.toLowerCase(),\n value: feature.enabled ? 1 : 0\n }))\n}\n\nexport function textHeightBehaviorValue<T>(\n ck: { TextHeightBehavior: { DisableAll: T } },\n leadingTrim: SceneNode['leadingTrim']\n): T | undefined {\n return leadingTrim === 'CAP_HEIGHT' ? ck.TextHeightBehavior.DisableAll : undefined\n}\n\n/** Which edges of the text a paragraph is: leading trim only trims the text's own edges. */\nexport interface ParagraphEdges {\n first: boolean\n last: boolean\n}\n\nfunction blockHeightBehavior(\n ck: CanvasKit,\n leadingTrim: SceneNode['leadingTrim'],\n edges: ParagraphEdges | undefined\n): TextHeightBehavior | undefined {\n if (!edges) return textHeightBehaviorValue(ck, leadingTrim)\n const { first, last } = edges\n if (leadingTrim !== 'CAP_HEIGHT') return undefined\n if (first && last) return ck.TextHeightBehavior.DisableAll\n if (first) return ck.TextHeightBehavior.DisableFirstAscent\n if (last) return ck.TextHeightBehavior.DisableLastDescent\n return ck.TextHeightBehavior.All\n}\n\n/**\n * The style a paragraph asks CanvasKit for: the face of the family that is loaded. Asked for a\n * face it lacks, CanvasKit slants and emboldens another, which neither Figma, a browser, nor a\n * native text stack draws the same, so a missing face is drawn as the face that exists and\n * reported missing, as Figma does. A family with no face loaded asks for the style as given.\n */\nfunction drawnFontStyle(\n ck: CanvasKit,\n family: string,\n weight: number,\n italic: boolean,\n style: string\n): FontStyle {\n const face = loadedFace(family, weight, italic, style) ?? { weight, italic }\n return {\n weight: { value: face.weight },\n slant: face.italic ? ck.FontSlant.Italic : ck.FontSlant.Upright\n }\n}\n\n/** The colour a style run's text is drawn in: its first visible solid fill, or `baseColor`. */\nexport function styleRunColor(\n ck: CanvasKit,\n style: SceneNode['styleRuns'][number]['style'],\n baseColor: Float32Array\n): Float32Array {\n const visibleFill = style.fills?.find((fill) => fill.visible && fill.type === 'SOLID')\n if (!visibleFill) return baseColor\n const color = resolveRGBAForPreview(visibleFill.color).color\n return ck.Color4f(color.r, color.g, color.b, color.a * visibleFill.opacity)\n}\n\nfunction styleRunLanguage(\n style: SceneNode['styleRuns'][number]['style'],\n node: Pick<ParagraphNode, 'textLanguage'>\n): string | undefined {\n return (style.textLanguage !== undefined ? style.textLanguage : node.textLanguage) ?? undefined\n}\n\nfunction pushStyleRun(\n r: TextRenderer,\n builder: ParagraphBuilder,\n node: ParagraphNode,\n run: SceneNode['styleRuns'][number],\n baseColor: Float32Array,\n baseFontSize: number,\n fontFamilies: (primary: string, face: NamedFace) => string[],\n halfLeading: boolean,\n paintStyle?: ParagraphPaintStyle\n): void {\n const ck = r.ck\n const style = run.style\n const runFontSize = style.fontSize ?? baseFontSize\n // A percent follows the run's own font size, as in Figma.\n const runLineHeight = lineHeightPixels(\n style.lineHeight !== undefined ? style.lineHeight : node.lineHeight,\n runFontSize\n )\n const runFamily = style.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY)\n const runWeight = style.fontWeight ?? node.fontWeight\n const runItalic = style.italic ?? node.italic\n const runFace = {\n fontWeight: runWeight,\n italic: runItalic,\n fontStyle: rangeFontStyle(node, style)\n }\n const runKey = faceStyleKey(runFace)\n\n const textStyle = new ck.TextStyle({\n color: styleRunColor(ck, style, baseColor),\n fontFamilies: fontFamilies(runFamily, runFace),\n fontSize: runFontSize,\n locale: styleRunLanguage(style, node),\n fontStyle: drawnFontStyle(ck, runFamily, runWeight, runItalic, runKey),\n fontVariations: textFontVariations(\n drawnFontVariations({\n family: runFamily,\n weight: runWeight,\n italic: runItalic,\n style: runKey,\n fontSize: runFontSize,\n variations: style.fontVariations ?? node.fontVariations,\n opticalSizeFromFontSize: style.opticalSizeFromFontSize ?? node.opticalSizeFromFontSize\n })\n ),\n fontFeatures: textFontFeatures(style.fontFeatures ?? node.fontFeatures),\n letterSpacing: textLengthPixels(style.letterSpacing ?? node.letterSpacing, runFontSize),\n heightMultiplier: runLineHeight ? runLineHeight / runFontSize : undefined,\n halfLeading\n })\n pushParagraphStyle(builder, textStyle, paintStyle)\n}\n\n/** `text[start, end)` in the case each of its characters has. */\nfunction addParagraphText(\n builder: ParagraphBuilder,\n node: ParagraphNode,\n start: number,\n end: number\n): void {\n builder.addText(laidOutText(shownTextSlice(node, start, end)))\n}\n\nfunction addStyledRuns(\n r: TextRenderer,\n builder: ParagraphBuilder,\n node: ParagraphNode,\n baseColor: Float32Array,\n baseFontSize: number,\n fontFamilies: (primary: string, face: NamedFace) => string[],\n halfLeading: boolean,\n paintStyle?: ParagraphPaintStyle\n): void {\n const text = node.text\n let pos = 0\n\n for (const run of node.styleRuns) {\n if (pos < run.start) addParagraphText(builder, node, pos, run.start)\n pushStyleRun(\n r,\n builder,\n node,\n run,\n baseColor,\n baseFontSize,\n fontFamilies,\n halfLeading,\n paintStyle\n )\n addParagraphText(builder, node, run.start, run.start + run.length)\n builder.pop()\n pos = run.start + run.length\n }\n\n if (pos < text.length) addParagraphText(builder, node, pos, text.length)\n}\n\n/** What a paragraph that is one block of a longer text needs beyond its node's own style. */\nexport interface ParagraphBlockOptions {\n /** Room before the first line, as a plain paragraph's first-line indent. */\n firstLineIndent?: number\n /** Truncation for this block in place of the node's. */\n truncation?: { maxLines?: number; ellipsis?: string }\n edges?: ParagraphEdges\n}\n\n/** Room before a paragraph's first line, as an empty placeholder on its baseline. */\nfunction addFirstLineIndent(ck: CanvasKit, builder: ParagraphBuilder, width: number): void {\n builder.addPlaceholder(width, 0, ck.PlaceholderAlignment.Baseline, ck.TextBaseline.Alphabetic, 0)\n}\n\n/**\n * A native paragraph for `node`'s text in its style runs, not yet laid out. A first-line\n * indent is a placeholder before the text, which takes the first character index.\n */\nexport function buildSkParagraph(\n r: TextRenderer,\n node: ParagraphNode,\n color?: Float32Array,\n { halfLeading = false, foregroundPaint }: ParagraphBuildOptions = {},\n block: ParagraphBlockOptions = {}\n): Paragraph {\n const ck = r.ck\n const baseColor = color ?? ck.BLACK\n const baseFontSize = node.fontSize || DEFAULT_FONT_SIZE\n const baseLineHeight = lineHeightPixels(node.lineHeight, baseFontSize)\n const cjkFallbacks = fontManager.getCJKFallbackFamilies()\n const letterFallbacks = fontManager.getLetterFallbackFamilies()\n const textDirection = resolveNodeTextDirection(node)\n\n const truncateOpts = block.truncation ?? buildTruncateOpts(node)\n\n const fontFamilies = (primary: string, face: NamedFace) =>\n resolveParagraphFontFamilies(\n primary,\n { weight: face.fontWeight, italic: face.italic, style: faceStyleKey(face) },\n letterFallbacks,\n cjkFallbacks\n )\n const nodeKey = faceStyleKey(node)\n\n const baseTextStyle = {\n color: baseColor,\n fontFamilies: fontFamilies(node.fontFamily || DEFAULT_FONT_FAMILY, node),\n fontSize: baseFontSize,\n locale: node.textLanguage ?? undefined,\n fontStyle: drawnFontStyle(\n ck,\n node.fontFamily || DEFAULT_FONT_FAMILY,\n node.fontWeight,\n node.italic,\n nodeKey\n ),\n fontVariations: textFontVariations(\n drawnFontVariations({\n family: node.fontFamily || DEFAULT_FONT_FAMILY,\n weight: node.fontWeight,\n italic: node.italic,\n style: nodeKey,\n fontSize: baseFontSize,\n variations: node.fontVariations,\n opticalSizeFromFontSize: node.opticalSizeFromFontSize\n })\n ),\n fontFeatures: textFontFeatures(node.fontFeatures),\n letterSpacing: textLengthPixels(node.letterSpacing, baseFontSize),\n heightMultiplier: baseLineHeight ? baseLineHeight / baseFontSize : undefined,\n halfLeading\n }\n const paraStyle = new ck.ParagraphStyle({\n textAlign: getParagraphTextAlign(ck, node),\n textDirection: textDirection === 'RTL' ? ck.TextDirection.RTL : ck.TextDirection.LTR,\n textHeightBehavior: blockHeightBehavior(ck, node.leadingTrim, block.edges),\n ...truncateOpts,\n textStyle: baseTextStyle\n })\n\n if (!r.fontProvider) throw new Error('Font provider not initialized')\n const builder = ck.ParagraphBuilder.MakeFromFontProvider(paraStyle, r.fontProvider)\n\n let background: Paint | undefined\n try {\n let paintStyle: ParagraphPaintStyle | undefined\n if (foregroundPaint) {\n background = new ck.Paint()\n background.setColor(ck.TRANSPARENT)\n paintStyle = { foreground: foregroundPaint, background }\n builder.pushPaintStyle(new ck.TextStyle(baseTextStyle), foregroundPaint, background)\n }\n if (block.firstLineIndent) addFirstLineIndent(ck, builder, block.firstLineIndent)\n if (node.styleRuns.length === 0) {\n addParagraphText(builder, node, 0, node.text.length)\n } else {\n addStyledRuns(\n r,\n builder,\n node,\n baseColor,\n baseFontSize,\n fontFamilies,\n halfLeading,\n paintStyle\n )\n }\n\n return builder.build()\n } finally {\n builder.delete()\n background?.delete()\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAqCA,SAAgB,4BAA4B,MAAqB,UAA2B;CAC1F,IAAI,aAAa,KAAA,GAAW,OAAO;CACnC,IAAI,KAAK,mBAAmB,oBAAoB,OAAO;CACvD,OAAO,KAAK,SAAS;AACvB;AAEA,SAAgB,kBAAkB,MAA+D;CAC/F,IAAI,KAAK,mBAAmB,UAAU,OAAO,CAAC;CAE9C,MAAM,OAAgD,EAAE,UAAA,IAAmB;CAC3E,IAAI,KAAK,YAAY,QAAQ,KAAK,WAAW,GAC3C,KAAK,WAAW,KAAK;CAEvB,OAAO;AACT;AAEA,SAAS,sBACP,IACA,MACA;CACA,MAAM,YAAY,yBAAyB,IAAI;CAC/C,QAAQ,KAAK,qBAAb;EACE,KAAK,UACH,OAAO,GAAG,UAAU;EACtB,KAAK,SACH,OAAO,cAAc,QAAQ,GAAG,UAAU,OAAO,GAAG,UAAU;EAChE,KAAK,aACH,OAAO,GAAG,UAAU;EACtB,SACE,OAAO,cAAc,QAAQ,GAAG,UAAU,QAAQ,GAAG,UAAU;CACnE;AACF;;AAGA,SAAgB,mBACd,YACA,WAA+C,MACb;CAClC,MAAM,eAAe,IAAI,IAAI,YAAY,KAAK,cAAc,UAAU,IAAI,CAAC;CAC3E,MAAM,SAAS,CACb,IAAI,YAAY,CAAC,EAAA,CAAG,QAAQ,cAAc,CAAC,aAAa,IAAI,UAAU,IAAI,CAAC,GAC3E,GAAI,cAAc,CAAC,CACrB;CACA,IAAI,OAAO,WAAW,GAAG,OAAO,KAAA;CAChC,OAAO,O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ACF;EACA,gBAAgB,mBACd,oBAAoB;GAClB,QAAQ,KAAK,cAAA;GACb,QAAQ,KAAK;GACb,QAAQ,KAAK;GACb,OAAO;GACP,UAAU;GACV,YAAY,KAAK;GACjB,yBAAyB,KAAK;EAChC,CAAC,CACH;EACA,cAAc,iBAAiB,KAAK,YAAY;EAChD,eAAe,iBAAiB,KAAK,eAAe,YAAY;EAChE,kBAAkB,iBAAiB,iBAAiB,eAAe,KAAA;EACnE;CACF;CACA,MAAM,YAAY,IAAI,GAAG,eAAe;EACtC,WAAW,sBAAsB,IAAI,IAAI;EACzC,eAAe,kBAAkB,QAAQ,GAAG,cAAc,MAAM,GAAG,cAAc;EACjF,oBAAoB,oBAAoB,IAAI,KAAK,aAAa,MAAM,KAAK;EACzE,GAAG;EACH,WAAW;CACb,CAAC;CAED,IAAI,CAAC,EAAE,cAAc,MAAM,IAAI,MAAM,+BAA+B;CACpE,MAAM,UAAU,GAAG,iBAAiB,qBAAqB,WAAW,EAAE,YAAY;CAElF,IAAI;CACJ,IAAI;EACF,IAAI;EACJ,IAAI,iBAAiB;GACnB,aAAa,IAAI,GAAG,MAAM;GAC1B,WAAW,SAAS,GAAG,WAAW;GAClC,aAAa;IAAE,YAAY;IAAiB;GAAW;GACvD,QAAQ,eAAe,IAAI,GAAG,UAAU,aAAa,GAAG,iBAAiB,UAAU;EACrF;EACA,IAAI,MAAM,iBAAiB,mBAAmB,IAAI,SAAS,MAAM,eAAe;EAChF,IAAI,KAAK,UAAU,WAAW,GAC5B,iBAAiB,SAAS,MAAM,GAAG,KAAK,KAAK,MAAM;OAEnD,cACE,GACA,SACA,MACA,WACA,cACA,cACA,aACA,UACF;EAGF,OAAO,QAAQ,MAAM;CACvB,UAAU;EACR,QAAQ,OAAO;EACf,YAAY,OAAO;CACrB;AACF"}
|
|
@@ -78,10 +78,10 @@ function featuresOf(node, run) {
|
|
|
78
78
|
}
|
|
79
79
|
/**
|
|
80
80
|
* The style a family of the paragraph is drawn in: the face its own family draws the asked style
|
|
81
|
-
* in, and Regular for the
|
|
81
|
+
* in, and Regular for the script fallbacks, as the paragraph asks CanvasKit for them.
|
|
82
82
|
*/
|
|
83
83
|
function sourceStyle(family, font) {
|
|
84
|
-
if (family !== font.family && (fontManager.
|
|
84
|
+
if (family !== font.family && (fontManager.getLetterFallbackFamilies().includes(family) || fontManager.getCJKFallbackFamilies().includes(family))) return fontManager.isStyleLoaded(family, "Regular") ? "Regular" : null;
|
|
85
85
|
return loadedStyle(family, font.drawn.weight, font.drawn.italic, font.drawn.style);
|
|
86
86
|
}
|
|
87
87
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"placed.js","names":[],"sources":["../../../src/canvas/text/placed.ts"],"sourcesContent":["import type { Paragraph } from 'canvaskit-wasm'\nimport { uniq } from 'es-toolkit/array'\nimport { isEqual } from 'es-toolkit/predicate'\n\nimport type { SceneNode } from '@pairdraw/scene-graph'\nimport { textLengthPixels } from '@pairdraw/scene-graph/text'\nimport { resolveNodeTextDirection } from '@pairdraw/scene-graph/text/direction'\n\nimport {\n drawnFontVariations,\n loadedFace,\n paragraphSourceFamilies\n} from '#core/canvas/text/font-families'\nimport { laidOutText } from '#core/canvas/text/keycap'\nimport type { TextLayout, TextLayoutMarker } from '#core/canvas/text/layout'\nimport { utf16IndicesByUtf8 } from '#core/canvas/text/utf8'\nimport { DEFAULT_FONT_FAMILY } from '#core/constants'\nimport { shownCharacters } from '#core/text/case'\nimport { ELLIPSIS } from '#core/text/ellipsis'\nimport {\n glyphOutlineSourceSync,\n shardCovers,\n shardOutlineSources,\n type GlyphOutlineSource,\n type RunShaping,\n type ShapedGlyph\n} from '#core/text/font/glyphs'\nimport type { ShapingFeature } from '#core/text/font/harfbuzz'\nimport { fontManager } from '#core/text/font/manager'\nimport { textFontFace } from '#core/text/requirements/collect'\n\ntype GlyphRun = ReturnType<Paragraph['getShapedLines']>[number]['runs'][number]\n\n/** A glyph of laid-out text where the renderer draws it, with the font its outline comes from. */\nexport interface LaidOutGlyph {\n /** The glyph ID the shaper chose. */\n id: number\n x: number\n /** The baseline of its line. */\n y: number\n fontSize: number\n /** The character it draws, left out for a list marker. */\n firstCharacter?: number\n advance: number\n /** Where its line starts. */\n lineLeft: number\n /** The font that drew it, or `null` when the shaper may have used another. */\n source: GlyphOutlineSource | null\n}\n\n/** The loaded face of a family the paragraph draws a face in, as its key. */\nfunction loadedStyle(\n family: string,\n weight: number,\n italic: boolean,\n style: string\n): string | null {\n return loadedFace(family, weight, italic, style)?.style ?? null\n}\n\n/**\n * The font a character asks for: its family, weight, and slant, and the variable axes it sets;\n * and the face the paragraph asks every family for, the one its own family has loaded, as\n * `drawnFontStyle` asks CanvasKit.\n */\nfunction fontAt(node: SceneNode, index: number) {\n const run = styleRunAt(node, index)\n const family = run?.style.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY)\n const weight = run?.style.fontWeight ?? node.fontWeight\n const italic = run?.style.italic ?? node.italic\n const style = textFontFace(node, run?.style).style\n const variations = drawnFontVariations({\n family,\n weight,\n italic,\n style,\n fontSize: run?.style.fontSize ?? node.fontSize,\n variations: run?.style.fontVariations ?? node.fontVariations,\n opticalSizeFromFontSize: run?.style.opticalSizeFromFontSize ?? node.opticalSizeFromFontSize\n })\n const drawn = loadedFace(family, weight, italic, style) ?? { weight, italic, style }\n return { family, weight, italic, style, variations, drawn }\n}\n\ntype StyleRun = SceneNode['styleRuns'][number]\n\nfunction styleRunAt(node: SceneNode, index: number): StyleRun | undefined {\n return node.styleRuns.find((item) => index >= item.start && index < item.start + item.length)\n}\n\n/**\n * The style run of each code unit of the shown text from `start` to `end`, scanning the node's\n * style runs only where one ends.\n */\nfunction styleRunsOver(\n node: SceneNode,\n start: number,\n end: number,\n sourceAt: (index: number) => number\n): Array<StyleRun | undefined> {\n const runs: Array<StyleRun | undefined> = []\n let current: StyleRun | undefined\n for (let index = start; index < end; index++) {\n const source = sourceAt(index)\n if (!current || source < current.start || source >= current.start + current.length)\n current = styleRunAt(node, source)\n runs.push(current)\n }\n return runs\n}\n\n/** The letter spacing a style run sets after each of its characters, in pixels. */\nfunction letterSpacingOf(node: SceneNode, run: StyleRun | undefined): number {\n return textLengthPixels(\n run?.style.letterSpacing ?? node.letterSpacing,\n run?.style.fontSize ?? node.fontSize\n )\n}\n\n/** The features a style run shapes its characters with, as CanvasKit is given them. */\nfunction featuresOf(node: SceneNode, run: StyleRun | undefined): ShapingFeature[] {\n return (run?.style.fontFeatures ?? node.fontFeatures).map((feature) => ({\n tag: feature.tag.toLowerCase(),\n value: feature.enabled ? 1 : 0\n }))\n}\n\n/**\n * The style a family of the paragraph is drawn in: the face its own family draws the asked style\n * in, and Regular for the Arabic and CJK fallbacks, as the paragraph asks CanvasKit for them.\n */\nfunction sourceStyle(family: string, font: ReturnType<typeof fontAt>): string | null {\n const scriptFallback =\n family !== font.family &&\n (fontManager.getArabicFallbackFamilies().includes(family) ||\n fontManager.getCJKFallbackFamilies().includes(family))\n if (scriptFallback) return fontManager.isStyleLoaded(family, 'Regular') ? 'Regular' : null\n return loadedStyle(family, font.drawn.weight, font.drawn.italic, font.drawn.style)\n}\n\n/**\n * The outline source of each file the paragraph may have drawn a character in, in its order:\n * each family's own file, then its shards.\n */\nfunction* candidateSources(font: ReturnType<typeof fontAt>) {\n for (const family of paragraphSourceFamilies(font.family)) {\n const style = sourceStyle(family, font)\n if (!style) continue\n const source = glyphOutlineSourceSync(family, style, font.variations)\n if (source) yield source\n yield* shardOutlineSources(family, style, font.variations)\n }\n}\n\n/** The face and file the paragraph draws a character in. */\nexport interface CharacterFace {\n family: string\n style: string\n /** Which of the style's files: 0 for its own, then its shards, as `FontManager.shardData` lists them. */\n file: number\n /** Whether it is not the character's own family. */\n fallback: boolean\n}\n\n/**\n * The loaded face the paragraph draws the character at `index` of `text` in, as it falls back:\n * of the fonts it lists, the style's own then its fallbacks, each file then its shards, the first\n * that maps the character.\n */\nexport function characterFace(node: SceneNode, text: string, index: number): CharacterFace | null {\n const codePoint = text.codePointAt(index)\n if (codePoint === undefined) return null\n const character = String.fromCodePoint(codePoint)\n const font = fontAt(node, index)\n for (const family of paragraphSourceFamilies(font.family)) {\n const style = sourceStyle(family, font)\n if (!style) continue\n const fallback = family !== font.family\n if (glyphOutlineSourceSync(family, style, font.variations)?.covers(character))\n return { family, style, file: 0, fallback }\n const shard = fontManager\n .shardData(family, style)\n .findIndex((data) => shardCovers(data, character))\n if (shard !== -1) return { family, style, file: shard + 1, fallback }\n }\n return null\n}\n\n/** The family the paragraph draws the character at `index` of `text` in; see {@link characterFace}. */\nexport function characterFamily(node: SceneNode, text: string, index: number): string | null {\n return characterFace(node, text, index)?.family ?? null\n}\n\n/** The characters of a run as the paragraph laid them out, and the features it shaped them with. */\ninterface RunShape {\n text: string\n runText: string\n /** The character each glyph starts at. */\n offsets: number[]\n /** Where the characters a glyph starts at end. */\n nextBoundary: Map<number, number>\n start: number\n end: number\n /** How the paragraph shaped the run, worked out when HarfBuzz shapes it. */\n shaping: () => RunShaping\n}\n\n/**\n * Whether the font drew the run. Every glyph of one character being the one the font maps it to\n * says so. A run whose features or ligatures changed glyphs (\"12:30\", \"->\", Arabic forms) is the\n * font's when HarfBuzz shapes its characters to the same glyphs in it, as CanvasKit, which\n * shapes with HarfBuzz, shaped them. One matching glyph says nothing: two files of a family, such\n * as a static instance and the variable font, number most glyphs alike.\n */\nfunction drewRun(source: GlyphOutlineSource, run: GlyphRun, shape: RunShape): boolean {\n const mapped = Array.from(run.glyphs).every((glyph, index) => {\n const from = shape.offsets[index]\n const character = shape.text.slice(from, shape.nextBoundary.get(from))\n // A glyph for a ligature or a cluster does not map from one character.\n const codePoint = character.codePointAt(0)\n if (codePoint === undefined || String.fromCodePoint(codePoint) !== character) return false\n // The missing glyph, like whitespace, says nothing about which font drew it.\n return glyph === 0 || /\\s/.test(character) || source.glyphOf(character) === glyph\n })\n if (mapped) return true\n const glyphs = source.shape(shape.runText, shape.shaping())\n return (\n glyphs.length === run.glyphs.length && glyphs.every(({ id }, index) => id === run.glyphs[index])\n )\n}\n\n/** Characters a shaper draws as nothing, such as variation selectors and joiners, whatever the font. */\nconst DRAWN_AS_NOTHING = /[\\s\\p{Default_Ignorable_Code_Point}]/u\n\n/**\n * The characters a run draws with glyphs of its font, leaving out whitespace and characters the\n * shaper draws as nothing. A character no font has is shaped as the run font's missing glyph\n * (ID 0), which says nothing about which font that is, so it does not count against the font\n * the run's other characters confirm.\n */\nfunction drawnCharacters(run: GlyphRun, shape: RunShape): string {\n const { text, offsets, nextBoundary, start, end } = shape\n const missing = new Set<number>()\n for (const [index, glyph] of run.glyphs.entries()) {\n if (glyph !== 0) continue\n const from = offsets[index]\n const to = nextBoundary.get(from) ?? end\n for (let character = from; character < to; character++) missing.add(character)\n }\n let characters = ''\n for (let index = start; index < end;) {\n const codePoint = text.codePointAt(index) ?? 0\n const character = String.fromCodePoint(codePoint)\n if (!missing.has(index) && !DRAWN_AS_NOTHING.test(character)) characters += character\n index += character.length\n }\n return characters\n}\n\n/**\n * The font a run's outlines come from, and the glyphs to save when it shaped them itself:\n * HarfBuzz's, from the run's first character, with the letter spacing of each code unit's style.\n */\ntype RunOutline =\n | { source: GlyphOutlineSource; glyphs?: undefined }\n | { source: GlyphOutlineSource; glyphs: ShapedGlyph[]; start: number; letterSpacing: number[] }\n\n/**\n * The font a run was shaped with. CanvasKit leaves `GlyphRun.typeface` null, so the run's font\n * is found as the paragraph falls back: the first of the fonts it lists, the style's own then\n * its fallbacks, that has every character of the run, confirmed by the glyphs it chose. When no\n * font confirms them their IDs name no outline, so the text keeps its characters in the first\n * font that has them all, shaped by HarfBuzz as the paragraph would shape them in it.\n * The paragraph asks each family for a face it has loaded, so CanvasKit never fakes one.\n */\nfunction runOutline(\n node: SceneNode,\n shaped: string,\n run: GlyphRun,\n characterAt: (offset: number) => number,\n sourceAt: (index: number) => number\n): RunOutline | null {\n if (run.glyphs.length === 0) return null\n const offsets = Array.from(run.offsets, characterAt)\n const start = Math.min(...offsets)\n const end = Math.max(...offsets)\n // A glyph covers the characters up to the next greater offset in the run, whatever its\n // direction; the sorted offsets give that once for every glyph.\n const boundaries = uniq([...offsets, end]).sort((a, b) => a - b)\n const nextBoundary = new Map(\n boundaries.map((offset, index) => [offset, boundaries[index + 1] ?? end])\n )\n const font = fontAt(node, sourceAt(start))\n let styles: Array<StyleRun | undefined> | undefined\n const stylesOver = () => (styles ??= styleRunsOver(node, start, end, sourceAt))\n let shaping: RunShaping | undefined\n const shape: RunShape = {\n text: shaped,\n runText: shaped.slice(start, end),\n offsets,\n nextBoundary,\n start,\n end,\n shaping: () => (shaping ??= runShaping(node, run, offsets, stylesOver()))\n }\n const characters = drawnCharacters(run, shape)\n let primary: GlyphOutlineSource | null = null\n for (const source of candidateSources(font)) {\n if (!source.covers(characters)) continue\n if (characters === '' || drewRun(source, run, shape)) return { source }\n primary ??= source\n }\n if (!primary) return null\n return {\n source: primary,\n glyphs: primary.shape(shape.runText, shape.shaping()),\n start,\n letterSpacing: stylesOver().map((style) => letterSpacingOf(node, style))\n }\n}\n\n/**\n * How the paragraph shaped a run: with the features of each style run in it, as CanvasKit gives\n * them for blocks it shapes as one run; in the direction its glyphs, in visual order, show by\n * their characters, the paragraph's for one glyph; and in its style's language.\n */\nfunction runShaping(\n node: SceneNode,\n run: GlyphRun,\n offsets: readonly number[],\n styles: ReadonlyArray<StyleRun | undefined>\n): RunShaping {\n const glyphCount = run.glyphs.length\n const ranges: Array<{ start: number; features: ShapingFeature[] }> = []\n for (const [index, style] of styles.entries()) {\n if (index > 0 && style === styles[index - 1]) continue\n const features = featuresOf(node, style)\n if (!isEqual(ranges.at(-1)?.features, features)) ranges.push({ start: index, features })\n }\n const features =\n ranges.length === 1\n ? ranges[0].features\n : ranges.flatMap((range, index) =>\n range.features.map((feature) => ({\n ...feature,\n start: range.start,\n end: ranges.at(index + 1)?.start ?? styles.length\n }))\n )\n const rtl =\n glyphCount > 1 && offsets[0] !== offsets[glyphCount - 1]\n ? offsets[0] > offsets[glyphCount - 1]\n : resolveNodeTextDirection(node) === 'RTL'\n const style = styles.at(0)?.style\n const language =\n (style?.textLanguage !== undefined ? style.textLanguage : node.textLanguage) ?? undefined\n return { features, rtl, language }\n}\n\n/**\n * The font of the ellipsis that ends truncated text, when the run is that ellipsis: the\n * paragraph adds it after the last characters shown, from the first font that maps it.\n */\nfunction ellipsisSource(\n node: SceneNode,\n run: GlyphRun,\n characterAt: (offset: number) => number,\n sourceAt: (index: number) => number\n): GlyphOutlineSource | null {\n if (run.glyphs.length !== 1) return null\n for (const source of candidateSources(fontAt(node, sourceAt(characterAt(run.offsets[0]))))) {\n if (source.glyphOf(ELLIPSIS) === run.glyphs[0]) return source\n }\n return null\n}\n\n/**\n * The outline of a run of a line, and whether the run is the ellipsis that ends truncated text.\n * The last run of truncated text that no font confirms may be an ellipsis, which keeps its glyph\n * unoutlined: shaping it again would save the characters its offsets point at instead.\n */\nfunction lineRunOutline(\n node: SceneNode,\n shaped: string,\n run: GlyphRun,\n endsTruncated: boolean,\n indices: { characterAt: (offset: number) => number; sourceAt: (index: number) => number }\n): { outline: RunOutline | null; ellipsis: boolean } {\n const { characterAt, sourceAt } = indices\n const ellipsis = endsTruncated ? ellipsisSource(node, run, characterAt, sourceAt) : null\n if (ellipsis) return { outline: { source: ellipsis }, ellipsis: true }\n const outline = runOutline(node, shaped, run, characterAt, sourceAt)\n return { outline: endsTruncated && outline?.glyphs ? null : outline, ellipsis: false }\n}\n\n/**\n * The character of the node's own text each character of the shown `text` comes from, which\n * its style run is found by: a case can show one character as several, as `ß` upper-cases to\n * `SS`.\n */\nfunction sourceIndices(node: SceneNode, text: string): (index: number) => number {\n if (text === node.text) return (index) => index\n const indices: number[] = []\n for (const { character, sourceIndex } of shownCharacters(node)) {\n indices.push(...Array.from({ length: character.length }, () => sourceIndex))\n }\n return (index) => indices.at(index) ?? index\n}\n\n/** Whether HarfBuzz shaped the run to glyphs of the same characters as CanvasKit's. */\nfunction sameClusters(\n run: GlyphRun,\n outline: Extract<RunOutline, { glyphs: ShapedGlyph[] }>,\n characterAt: (offset: number) => number\n): boolean {\n return (\n outline.glyphs.length === run.glyphs.length &&\n outline.glyphs.every(\n (glyph, index) => outline.start + glyph.cluster === characterAt(run.offsets[index])\n )\n )\n}\n\n/**\n * The glyphs HarfBuzz shaped for a run, when they are not as many as CanvasKit's or stand for\n * other characters: placed one after another from where the run starts.\n */\nfunction reshapedGlyphs(\n run: GlyphRun,\n outline: Extract<RunOutline, { glyphs: ShapedGlyph[] }>,\n lineLeft: number,\n y: number\n): LaidOutGlyph[] {\n let x = run.positions[0]\n return outline.glyphs.map((glyph, index) => {\n // Spacing follows a character once, after its last glyph, so marks stay on their base.\n const endsCharacter = outline.glyphs.at(index + 1)?.cluster !== glyph.cluster\n const spacing = endsCharacter ? (outline.letterSpacing.at(glyph.cluster) ?? 0) : 0\n const advance = glyph.advance * run.size + spacing\n const placed: LaidOutGlyph = {\n id: glyph.id,\n x: x + glyph.xOffset * run.size,\n y: y - glyph.yOffset * run.size,\n fontSize: run.size,\n firstCharacter: outline.start + glyph.cluster,\n advance,\n lineLeft,\n source: outline.source\n }\n x += advance\n return placed\n })\n}\n\n/**\n * A list marker's glyphs as Figma saves them: placed beside their item and drawing no\n * character of the text.\n */\nfunction markerGlyphs(marker: TextLayoutMarker, offsetY: number): LaidOutGlyph[] {\n const source = glyphOutlineSourceSync(marker.face.family, marker.face.style)\n const baseline = marker.paragraph.getLineMetrics().at(0)?.baseline ?? 0\n const glyphs: LaidOutGlyph[] = []\n for (const line of marker.paragraph.getShapedLines()) {\n for (const run of line.runs) {\n for (let index = 0; index < run.glyphs.length; index++) {\n const x = run.positions[index * 2]\n glyphs.push({\n id: run.glyphs[index],\n x: marker.x + x,\n y: marker.y + baseline + offsetY,\n fontSize: run.size,\n advance: run.positions[(index + 1) * 2] - x,\n lineLeft: marker.x,\n source\n })\n }\n }\n }\n return glyphs\n}\n\n/**\n * Every glyph of laid-out `text`, `offsetY` below the layout's top, in drawing order: an item's\n * marker before the glyphs of its first line, as Figma saves them. Returns `null` when the\n * layout's lines do not match its shaped lines.\n */\nexport function laidOutGlyphs(\n node: SceneNode,\n layout: TextLayout,\n text: string,\n offsetY: number\n): LaidOutGlyph[] | null {\n const lines = layout.getShapedLines()\n const metrics = layout.getLineMetrics()\n if (lines.length === 0 || lines.length !== metrics.length) return null\n const characterAt = utf16IndicesByUtf8(text)\n // The runs drew the text as laid out, a keycap mark as a zero-width space.\n const shaped = laidOutText(text)\n const sourceAt = sourceIndices(node, text)\n const markers = new Map(layout.getMarkers().map((marker) => [marker.lineNumber, marker]))\n const glyphs: LaidOutGlyph[] = []\n for (const [lineIndex, line] of lines.entries()) {\n const marker = markers.get(lineIndex)\n if (marker) glyphs.push(...markerGlyphs(marker, offsetY))\n const { left, baseline } = metrics[lineIndex]\n const lastLine = lineIndex === lines.length - 1\n for (const [runIndex, run] of line.runs.entries()) {\n const endsTruncated =\n lastLine && runIndex === line.runs.length - 1 && layout.didExceedMaxLines()\n const { outline, ellipsis } = lineRunOutline(node, shaped, run, endsTruncated, {\n characterAt,\n sourceAt\n })\n // Run positions round the baseline to whole pixels; line metrics keep it exact.\n const y = baseline + offsetY\n if (outline?.glyphs && !sameClusters(run, outline, characterAt)) {\n glyphs.push(...reshapedGlyphs(run, outline, left, y))\n continue\n }\n for (let index = 0; index < run.glyphs.length; index++) {\n const x = run.positions[index * 2]\n glyphs.push({\n id: outline?.glyphs?.[index].id ?? run.glyphs[index],\n x,\n y,\n fontSize: run.size,\n // The ellipsis truncation adds draws no character, as Figma saves it.\n firstCharacter: ellipsis ? undefined : characterAt(run.offsets[index]),\n advance: run.positions[(index + 1) * 2] - x,\n lineLeft: left,\n source: outline?.source ?? null\n })\n }\n }\n }\n return glyphs\n}\n"],"mappings":";;;;;;;;;;;;;;;AAmDA,SAAS,YACP,QACA,QACA,QACA,OACe;CACf,OAAO,WAAW,QAAQ,QAAQ,QAAQ,KAAK,CAAC,EAAE,SAAS;AAC7D;;;;;;AAOA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C,MAAM,WAAW,cAAc,MAAM,SAAS;EAC9C,KAAK,MAAM,CAAC,UAAU,QAAQ,KAAK,KAAK,QAAQ,GAAG;GAGjD,MAAM,EAAE,SAAS,aAAa,eAAe,MAAM,QAAQ,KADzD,YAAY,aAAa,KAAK,KAAK,SAAS,KAAK,OAAO,kBAAkB,GACG;IAC7E;IACA;GACF,CAAC;GAED,MAAM,IAAI,WAAW;GACrB,IAAI,SAAS,UAAU,CAAC,aAAa,KAAK,SAAS,WAAW,GAAG;IAC/D,OAAO,KAAK,GAAG,eAAe,KAAK,SAAS,MAAM,CAAC,CAAC;IACpD;GACF;GACA,KAAK,IAAI,QAAQ,GAAG,QAAQ,IAAI,OAAO,QAAQ,SAAS;IACtD,MAAM,IAAI,IAAI,UAAU,QAAQ;IAChC,OAAO,KAAK;KACV,IAAI,SAAS,SAAS,MAAM,CAAC,MAAM,IAAI,OAAO;KAC9C;KACA;KACA,UAAU,IAAI;KAEd,gBAAgB,WAAW,KAAA,IAAY,YAAY,IAAI,QAAQ,MAAM;KACrE,SAAS,IAAI,WAAW,QAAQ,KAAK,KAAK;KAC1C,UAAU;KACV,QAAQ,SAAS,UAAU;IAC7B,CAAC;GACH;EACF;CACF;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"placed.js","names":[],"sources":["../../../src/canvas/text/placed.ts"],"sourcesContent":["import type { Paragraph } from 'canvaskit-wasm'\nimport { uniq } from 'es-toolkit/array'\nimport { isEqual } from 'es-toolkit/predicate'\n\nimport type { SceneNode } from '@pairdraw/scene-graph'\nimport { textLengthPixels } from '@pairdraw/scene-graph/text'\nimport { resolveNodeTextDirection } from '@pairdraw/scene-graph/text/direction'\n\nimport {\n drawnFontVariations,\n loadedFace,\n paragraphSourceFamilies\n} from '#core/canvas/text/font-families'\nimport { laidOutText } from '#core/canvas/text/keycap'\nimport type { TextLayout, TextLayoutMarker } from '#core/canvas/text/layout'\nimport { utf16IndicesByUtf8 } from '#core/canvas/text/utf8'\nimport { DEFAULT_FONT_FAMILY } from '#core/constants'\nimport { shownCharacters } from '#core/text/case'\nimport { ELLIPSIS } from '#core/text/ellipsis'\nimport {\n glyphOutlineSourceSync,\n shardCovers,\n shardOutlineSources,\n type GlyphOutlineSource,\n type RunShaping,\n type ShapedGlyph\n} from '#core/text/font/glyphs'\nimport type { ShapingFeature } from '#core/text/font/harfbuzz'\nimport { fontManager } from '#core/text/font/manager'\nimport { textFontFace } from '#core/text/requirements/collect'\n\ntype GlyphRun = ReturnType<Paragraph['getShapedLines']>[number]['runs'][number]\n\n/** A glyph of laid-out text where the renderer draws it, with the font its outline comes from. */\nexport interface LaidOutGlyph {\n /** The glyph ID the shaper chose. */\n id: number\n x: number\n /** The baseline of its line. */\n y: number\n fontSize: number\n /** The character it draws, left out for a list marker. */\n firstCharacter?: number\n advance: number\n /** Where its line starts. */\n lineLeft: number\n /** The font that drew it, or `null` when the shaper may have used another. */\n source: GlyphOutlineSource | null\n}\n\n/** The loaded face of a family the paragraph draws a face in, as its key. */\nfunction loadedStyle(\n family: string,\n weight: number,\n italic: boolean,\n style: string\n): string | null {\n return loadedFace(family, weight, italic, style)?.style ?? null\n}\n\n/**\n * The font a character asks for: its family, weight, and slant, and the variable axes it sets;\n * and the face the paragraph asks every family for, the one its own family has loaded, as\n * `drawnFontStyle` asks CanvasKit.\n */\nfunction fontAt(node: SceneNode, index: number) {\n const run = styleRunAt(node, index)\n const family = run?.style.fontFamily ?? (node.fontFamily || DEFAULT_FONT_FAMILY)\n const weight = run?.style.fontWeight ?? node.fontWeight\n const italic = run?.style.italic ?? node.italic\n const style = textFontFace(node, run?.style).style\n const variations = drawnFontVariations({\n family,\n weight,\n italic,\n style,\n fontSize: run?.style.fontSize ?? node.fontSize,\n variations: run?.style.fontVariations ?? node.fontVariations,\n opticalSizeFromFontSize: run?.style.opticalSizeFromFontSize ?? node.opticalSizeFromFontSize\n })\n const drawn = loadedFace(family, weight, italic, style) ?? { weight, italic, style }\n return { family, weight, italic, style, variations, drawn }\n}\n\ntype StyleRun = SceneNode['styleRuns'][number]\n\nfunction styleRunAt(node: SceneNode, index: number): StyleRun | undefined {\n return node.styleRuns.find((item) => index >= item.start && index < item.start + item.length)\n}\n\n/**\n * The style run of each code unit of the shown text from `start` to `end`, scanning the node's\n * style runs only where one ends.\n */\nfunction styleRunsOver(\n node: SceneNode,\n start: number,\n end: number,\n sourceAt: (index: number) => number\n): Array<StyleRun | undefined> {\n const runs: Array<StyleRun | undefined> = []\n let current: StyleRun | undefined\n for (let index = start; index < end; index++) {\n const source = sourceAt(index)\n if (!current || source < current.start || source >= current.start + current.length)\n current = styleRunAt(node, source)\n runs.push(current)\n }\n return runs\n}\n\n/** The letter spacing a style run sets after each of its characters, in pixels. */\nfunction letterSpacingOf(node: SceneNode, run: StyleRun | undefined): number {\n return textLengthPixels(\n run?.style.letterSpacing ?? node.letterSpacing,\n run?.style.fontSize ?? node.fontSize\n )\n}\n\n/** The features a style run shapes its characters with, as CanvasKit is given them. */\nfunction featuresOf(node: SceneNode, run: StyleRun | undefined): ShapingFeature[] {\n return (run?.style.fontFeatures ?? node.fontFeatures).map((feature) => ({\n tag: feature.tag.toLowerCase(),\n value: feature.enabled ? 1 : 0\n }))\n}\n\n/**\n * The style a family of the paragraph is drawn in: the face its own family draws the asked style\n * in, and Regular for the script fallbacks, as the paragraph asks CanvasKit for them.\n */\nfunction sourceStyle(family: string, font: ReturnType<typeof fontAt>): string | null {\n const scriptFallback =\n family !== font.family &&\n (fontManager.getLetterFallbackFamilies().includes(family) ||\n fontManager.getCJKFallbackFamilies().includes(family))\n if (scriptFallback) return fontManager.isStyleLoaded(family, 'Regular') ? 'Regular' : null\n return loadedStyle(family, font.drawn.weight, font.drawn.italic, font.drawn.style)\n}\n\n/**\n * The outline source of each file the paragraph may have drawn a character in, in its order:\n * each family's own file, then its shards.\n */\nfunction* candidateSources(font: ReturnType<typeof fontAt>) {\n for (const family of paragraphSourceFamilies(font.family)) {\n const style = sourceStyle(family, font)\n if (!style) continue\n const source = glyphOutlineSourceSync(family, style, font.variations)\n if (source) yield source\n yield* shardOutlineSources(family, style, font.variations)\n }\n}\n\n/** The face and file the paragraph draws a character in. */\nexport interface CharacterFace {\n family: string\n style: string\n /** Which of the style's files: 0 for its own, then its shards, as `FontManager.shardData` lists them. */\n file: number\n /** Whether it is not the character's own family. */\n fallback: boolean\n}\n\n/**\n * The loaded face the paragraph draws the character at `index` of `text` in, as it falls back:\n * of the fonts it lists, the style's own then its fallbacks, each file then its shards, the first\n * that maps the character.\n */\nexport function characterFace(node: SceneNode, text: string, index: number): CharacterFace | null {\n const codePoint = text.codePointAt(index)\n if (codePoint === undefined) return null\n const character = String.fromCodePoint(codePoint)\n const font = fontAt(node, index)\n for (const family of paragraphSourceFamilies(font.family)) {\n const style = sourceStyle(family, font)\n if (!style) continue\n const fallback = family !== font.family\n if (glyphOutlineSourceSync(family, style, font.variations)?.covers(character))\n return { family, style, file: 0, fallback }\n const shard = fontManager\n .shardData(family, style)\n .findIndex((data) => shardCovers(data, character))\n if (shard !== -1) return { family, style, file: shard + 1, fallback }\n }\n return null\n}\n\n/** The family the paragraph draws the character at `index` of `text` in; see {@link characterFace}. */\nexport function characterFamily(node: SceneNode, text: string, index: number): string | null {\n return characterFace(node, text, index)?.family ?? null\n}\n\n/** The characters of a run as the paragraph laid them out, and the features it shaped them with. */\ninterface RunShape {\n text: string\n runText: string\n /** The character each glyph starts at. */\n offsets: number[]\n /** Where the characters a glyph starts at end. */\n nextBoundary: Map<number, number>\n start: number\n end: number\n /** How the paragraph shaped the run, worked out when HarfBuzz shapes it. */\n shaping: () => RunShaping\n}\n\n/**\n * Whether the font drew the run. Every glyph of one character being the one the font maps it to\n * says so. A run whose features or ligatures changed glyphs (\"12:30\", \"->\", Arabic forms) is the\n * font's when HarfBuzz shapes its characters to the same glyphs in it, as CanvasKit, which\n * shapes with HarfBuzz, shaped them. One matching glyph says nothing: two files of a family, such\n * as a static instance and the variable font, number most glyphs alike.\n */\nfunction drewRun(source: GlyphOutlineSource, run: GlyphRun, shape: RunShape): boolean {\n const mapped = Array.from(run.glyphs).every((glyph, index) => {\n const from = shape.offsets[index]\n const character = shape.text.slice(from, shape.nextBoundary.get(from))\n // A glyph for a ligature or a cluster does not map from one character.\n const codePoint = character.codePointAt(0)\n if (codePoint === undefined || String.fromCodePoint(codePoint) !== character) return false\n // The missing glyph, like whitespace, says nothing about which font drew it.\n return glyph === 0 || /\\s/.test(character) || source.glyphOf(character) === glyph\n })\n if (mapped) return true\n const glyphs = source.shape(shape.runText, shape.shaping())\n return (\n glyphs.length === run.glyphs.length && glyphs.every(({ id }, index) => id === run.glyphs[index])\n )\n}\n\n/** Characters a shaper draws as nothing, such as variation selectors and joiners, whatever the font. */\nconst DRAWN_AS_NOTHING = /[\\s\\p{Default_Ignorable_Code_Point}]/u\n\n/**\n * The characters a run draws with glyphs of its font, leaving out whitespace and characters the\n * shaper draws as nothing. A character no font has is shaped as the run font's missing glyph\n * (ID 0), which says nothing about which font that is, so it does not count against the font\n * the run's other characters confirm.\n */\nfunction drawnCharacters(run: GlyphRun, shape: RunShape): string {\n const { text, offsets, nextBoundary, start, end } = shape\n const missing = new Set<number>()\n for (const [index, glyph] of run.glyphs.entries()) {\n if (glyph !== 0) continue\n const from = offsets[index]\n const to = nextBoundary.get(from) ?? end\n for (let character = from; character < to; character++) missing.add(character)\n }\n let characters = ''\n for (let index = start; index < end;) {\n const codePoint = text.codePointAt(index) ?? 0\n const character = String.fromCodePoint(codePoint)\n if (!missing.has(index) && !DRAWN_AS_NOTHING.test(character)) characters += character\n index += character.length\n }\n return characters\n}\n\n/**\n * The font a run's outlines come from, and the glyphs to save when it shaped them itself:\n * HarfBuzz's, from the run's first character, with the letter spacing of each code unit's style.\n */\ntype RunOutline =\n | { source: GlyphOutlineSource; glyphs?: undefined }\n | { source: GlyphOutlineSource; glyphs: ShapedGlyph[]; start: number; letterSpacing: number[] }\n\n/**\n * The font a run was shaped with. CanvasKit leaves `GlyphRun.typeface` null, so the run's font\n * is found as the paragraph falls back: the first of the fonts it lists, the style's own then\n * its fallbacks, that has every character of the run, confirmed by the glyphs it chose. When no\n * font confirms them their IDs name no outline, so the text keeps its characters in the first\n * font that has them all, shaped by HarfBuzz as the paragraph would shape them in it.\n * The paragraph asks each family for a face it has loaded, so CanvasKit never fakes one.\n */\nfunction runOutline(\n node: SceneNode,\n shaped: string,\n run: GlyphRun,\n characterAt: (offset: number) => number,\n sourceAt: (index: number) => number\n): RunOutline | null {\n if (run.glyphs.length === 0) return null\n const offsets = Array.from(run.offsets, characterAt)\n const start = Math.min(...offsets)\n const end = Math.max(...offsets)\n // A glyph covers the characters up to the next greater offset in the run, whatever its\n // direction; the sorted offsets give that once for every glyph.\n const boundaries = uniq([...offsets, end]).sort((a, b) => a - b)\n const nextBoundary = new Map(\n boundaries.map((offset, index) => [offset, boundaries[index + 1] ?? end])\n )\n const font = fontAt(node, sourceAt(start))\n let styles: Array<StyleRun | undefined> | undefined\n const stylesOver = () => (styles ??= styleRunsOver(node, start, end, sourceAt))\n let shaping: RunShaping | undefined\n const shape: RunShape = {\n text: shaped,\n runText: shaped.slice(start, end),\n offsets,\n nextBoundary,\n start,\n end,\n shaping: () => (shaping ??= runShaping(node, run, offsets, stylesOver()))\n }\n const characters = drawnCharacters(run, shape)\n let primary: GlyphOutlineSource | null = null\n for (const source of candidateSources(font)) {\n if (!source.covers(characters)) continue\n if (characters === '' || drewRun(source, run, shape)) return { source }\n primary ??= source\n }\n if (!primary) return null\n return {\n source: primary,\n glyphs: primary.shape(shape.runText, shape.shaping()),\n start,\n letterSpacing: stylesOver().map((style) => letterSpacingOf(node, style))\n }\n}\n\n/**\n * How the paragraph shaped a run: with the features of each style run in it, as CanvasKit gives\n * them for blocks it shapes as one run; in the direction its glyphs, in visual order, show by\n * their characters, the paragraph's for one glyph; and in its style's language.\n */\nfunction runShaping(\n node: SceneNode,\n run: GlyphRun,\n offsets: readonly number[],\n styles: ReadonlyArray<StyleRun | undefined>\n): RunShaping {\n const glyphCount = run.glyphs.length\n const ranges: Array<{ start: number; features: ShapingFeature[] }> = []\n for (const [index, style] of styles.entries()) {\n if (index > 0 && style === styles[index - 1]) continue\n const features = featuresOf(node, style)\n if (!isEqual(ranges.at(-1)?.features, features)) ranges.push({ start: index, features })\n }\n const features =\n ranges.length === 1\n ? ranges[0].features\n : ranges.flatMap((range, index) =>\n range.features.map((feature) => ({\n ...feature,\n start: range.start,\n end: ranges.at(index + 1)?.start ?? styles.length\n }))\n )\n const rtl =\n glyphCount > 1 && offsets[0] !== offsets[glyphCount - 1]\n ? offsets[0] > offsets[glyphCount - 1]\n : resolveNodeTextDirection(node) === 'RTL'\n const style = styles.at(0)?.style\n const language =\n (style?.textLanguage !== undefined ? style.textLanguage : node.textLanguage) ?? undefined\n return { features, rtl, language }\n}\n\n/**\n * The font of the ellipsis that ends truncated text, when the run is that ellipsis: the\n * paragraph adds it after the last characters shown, from the first font that maps it.\n */\nfunction ellipsisSource(\n node: SceneNode,\n run: GlyphRun,\n characterAt: (offset: number) => number,\n sourceAt: (index: number) => number\n): GlyphOutlineSource | null {\n if (run.glyphs.length !== 1) return null\n for (const source of candidateSources(fontAt(node, sourceAt(characterAt(run.offsets[0]))))) {\n if (source.glyphOf(ELLIPSIS) === run.glyphs[0]) return source\n }\n return null\n}\n\n/**\n * The outline of a run of a line, and whether the run is the ellipsis that ends truncated text.\n * The last run of truncated text that no font confirms may be an ellipsis, which keeps its glyph\n * unoutlined: shaping it again would save the characters its offsets point at instead.\n */\nfunction lineRunOutline(\n node: SceneNode,\n shaped: string,\n run: GlyphRun,\n endsTruncated: boolean,\n indices: { characterAt: (offset: number) => number; sourceAt: (index: number) => number }\n): { outline: RunOutline | null; ellipsis: boolean } {\n const { characterAt, sourceAt } = indices\n const ellipsis = endsTruncated ? ellipsisSource(node, run, characterAt, sourceAt) : null\n if (ellipsis) return { outline: { source: ellipsis }, ellipsis: true }\n const outline = runOutline(node, shaped, run, characterAt, sourceAt)\n return { outline: endsTruncated && outline?.glyphs ? null : outline, ellipsis: false }\n}\n\n/**\n * The character of the node's own text each character of the shown `text` comes from, which\n * its style run is found by: a case can show one character as several, as `ß` upper-cases to\n * `SS`.\n */\nfunction sourceIndices(node: SceneNode, text: string): (index: number) => number {\n if (text === node.text) return (index) => index\n const indices: number[] = []\n for (const { character, sourceIndex } of shownCharacters(node)) {\n indices.push(...Array.from({ length: character.length }, () => sourceIndex))\n }\n return (index) => indices.at(index) ?? index\n}\n\n/** Whether HarfBuzz shaped the run to glyphs of the same characters as CanvasKit's. */\nfunction sameClusters(\n run: GlyphRun,\n outline: Extract<RunOutline, { glyphs: ShapedGlyph[] }>,\n characterAt: (offset: number) => number\n): boolean {\n return (\n outline.glyphs.length === run.glyphs.length &&\n outline.glyphs.every(\n (glyph, index) => outline.start + glyph.cluster === characterAt(run.offsets[index])\n )\n )\n}\n\n/**\n * The glyphs HarfBuzz shaped for a run, when they are not as many as CanvasKit's or stand for\n * other characters: placed one after another from where the run starts.\n */\nfunction reshapedGlyphs(\n run: GlyphRun,\n outline: Extract<RunOutline, { glyphs: ShapedGlyph[] }>,\n lineLeft: number,\n y: number\n): LaidOutGlyph[] {\n let x = run.positions[0]\n return outline.glyphs.map((glyph, index) => {\n // Spacing follows a character once, after its last glyph, so marks stay on their base.\n const endsCharacter = outline.glyphs.at(index + 1)?.cluster !== glyph.cluster\n const spacing = endsCharacter ? (outline.letterSpacing.at(glyph.cluster) ?? 0) : 0\n const advance = glyph.advance * run.size + spacing\n const placed: LaidOutGlyph = {\n id: glyph.id,\n x: x + glyph.xOffset * run.size,\n y: y - glyph.yOffset * run.size,\n fontSize: run.size,\n firstCharacter: outline.start + glyph.cluster,\n advance,\n lineLeft,\n source: outline.source\n }\n x += advance\n return placed\n })\n}\n\n/**\n * A list marker's glyphs as Figma saves them: placed beside their item and drawing no\n * character of the text.\n */\nfunction markerGlyphs(marker: TextLayoutMarker, offsetY: number): LaidOutGlyph[] {\n const source = glyphOutlineSourceSync(marker.face.family, marker.face.style)\n const baseline = marker.paragraph.getLineMetrics().at(0)?.baseline ?? 0\n const glyphs: LaidOutGlyph[] = []\n for (const line of marker.paragraph.getShapedLines()) {\n for (const run of line.runs) {\n for (let index = 0; index < run.glyphs.length; index++) {\n const x = run.positions[index * 2]\n glyphs.push({\n id: run.glyphs[index],\n x: marker.x + x,\n y: marker.y + baseline + offsetY,\n fontSize: run.size,\n advance: run.positions[(index + 1) * 2] - x,\n lineLeft: marker.x,\n source\n })\n }\n }\n }\n return glyphs\n}\n\n/**\n * Every glyph of laid-out `text`, `offsetY` below the layout's top, in drawing order: an item's\n * marker before the glyphs of its first line, as Figma saves them. Returns `null` when the\n * layout's lines do not match its shaped lines.\n */\nexport function laidOutGlyphs(\n node: SceneNode,\n layout: TextLayout,\n text: string,\n offsetY: number\n): LaidOutGlyph[] | null {\n const lines = layout.getShapedLines()\n const metrics = layout.getLineMetrics()\n if (lines.length === 0 || lines.length !== metrics.length) return null\n const characterAt = utf16IndicesByUtf8(text)\n // The runs drew the text as laid out, a keycap mark as a zero-width space.\n const shaped = laidOutText(text)\n const sourceAt = sourceIndices(node, text)\n const markers = new Map(layout.getMarkers().map((marker) => [marker.lineNumber, marker]))\n const glyphs: LaidOutGlyph[] = []\n for (const [lineIndex, line] of lines.entries()) {\n const marker = markers.get(lineIndex)\n if (marker) glyphs.push(...markerGlyphs(marker, offsetY))\n const { left, baseline } = metrics[lineIndex]\n const lastLine = lineIndex === lines.length - 1\n for (const [runIndex, run] of line.runs.entries()) {\n const endsTruncated =\n lastLine && runIndex === line.runs.length - 1 && layout.didExceedMaxLines()\n const { outline, ellipsis } = lineRunOutline(node, shaped, run, endsTruncated, {\n characterAt,\n sourceAt\n })\n // Run positions round the baseline to whole pixels; line metrics keep it exact.\n const y = baseline + offsetY\n if (outline?.glyphs && !sameClusters(run, outline, characterAt)) {\n glyphs.push(...reshapedGlyphs(run, outline, left, y))\n continue\n }\n for (let index = 0; index < run.glyphs.length; index++) {\n const x = run.positions[index * 2]\n glyphs.push({\n id: outline?.glyphs?.[index].id ?? run.glyphs[index],\n x,\n y,\n fontSize: run.size,\n // The ellipsis truncation adds draws no character, as Figma saves it.\n firstCharacter: ellipsis ? undefined : characterAt(run.offsets[index]),\n advance: run.positions[(index + 1) * 2] - x,\n lineLeft: left,\n source: outline?.source ?? null\n })\n }\n }\n }\n return glyphs\n}\n"],"mappings":";;;;;;;;;;;;;;;AAmDA,SAAS,YACP,QACA,QACA,QACA,OACe;CACf,OAAO,WAAW,QAAQ,QAAQ,QAAQ,KAAK,CAAC,EAAE,SAAS;AAC7D;;;;;;AAOA,SAAS,OAAO,MAAiB,OAAe;CAC9C,MAAM,MAAM,WAAW,MAAM,KAAK;CAClC,MAAM,SAAS,KAAK,MAAM,eAAe,KAAK,cAAA;CAC9C,MAAM,SAAS,KAAK,MAAM,cAAc,KAAK;CAC7C,MAAM,SAAS,KAAK,MAAM,UAAU,KAAK;CACzC,MAAM,QAAQ,aAAa,MAAM,KAAK,KAAK,CAAC,CAAC;CAW7C,OAAO;EAAE;EAAQ;EAAQ;EAAQ;EAAO,YAVrB,oBAAoB;GACrC;GACA;GACA;GACA;GACA,UAAU,KAAK,MAAM,YAAY,KAAK;GACtC,YAAY,KAAK,MAAM,kBAAkB,KAAK;GAC9C,yBAAyB,KAAK,MAAM,2BAA2B,KAAK;EACtE,CAEiD;EAAG,OADtC,WAAW,QAAQ,QAAQ,QAAQ,KAAK,KAAK;GAAE;GAAQ;GAAQ;EAAM;CACzB;AAC5D;AAIA,SAAS,WAAW,MAAiB,OAAqC;CACxE,OAAO,KAAK,UAAU,MAAM,SAAS,SAAS,KAAK,SAAS,QAAQ,KAAK,QAAQ,KAAK,MAAM;AAC9F;;;;;AAMA,SAAS,cACP,MACA,OACA,KACA,UAC6B;CAC7B,MAAM,OAAoC,CAAC;CAC3C,IAAI;CACJ,KAAK,IAAI,QAAQ,OAAO,QAAQ,KAAK,SAAS;EAC5C,MAAM,SAAS,SAAS,KAAK;EAC7B,IA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?: TypefaceFontProvider | null;
|
|
10
10
|
fontsLoaded?: boolean;
|
|
11
|
+
/** The renderer has finished preparing its fonts, so a face still pending will not arrive. */
|
|
12
|
+
exportFontsSettled?: boolean;
|
|
11
13
|
onFontResolutionSettled?: FontResolutionSettled;
|
|
12
14
|
trackFontDemand?: (node: SceneNode, key: string) => void;
|
|
13
15
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"renderer.d.ts","names":[],"sources":["../../../src/canvas/text/renderer.ts"],"mappings":";;;;;UAQiB;EACf,uBAAuB;EACvB,KAAK;EACL,eAAe;EACf;EACA,0BAA0B;EAC1B,mBAAmB,MAAM,WAAW;;UAGrB,qBAAqB;EACpC,IAAI;EACJ,cAAc;EACd"}
|
|
1
|
+
{"version":3,"file":"renderer.d.ts","names":[],"sources":["../../../src/canvas/text/renderer.ts"],"mappings":";;;;;UAQiB;EACf,uBAAuB;EACvB,KAAK;EACL,eAAe;EACf;;EAEA;EACA,0BAA0B;EAC1B,mBAAmB,MAAM,WAAW;;UAGrB,qBAAqB;EACpC,IAAI;EACJ,cAAc;EACd"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"renderer.d.ts","names":[],"sources":["../../src/design-jsx/renderer.ts"],"mappings":";;;;;;;iBAkEgB,kBAAkB,QAAO;
|
|
1
|
+
{"version":3,"file":"renderer.d.ts","names":[],"sources":["../../src/design-jsx/renderer.ts"],"mappings":";;;;;;;iBAkEgB,kBAAkB,QAAO;EAW2mR,YAAA,uCAAA,YAAA,mBAAA,yCAAC,kBAAA,uCAAA;EAA8K,aAAA,uCAAA,YAAA,qCAAA,UAAA,yCAAC,kBAAA,uCAAA;;;cADrzR,YAAS,uCAAA,YAAA,mBAAA,yCAAA,kBAAA,uCAAA,iBAAE,aAAU,uCAAA,YAAA,qCAAA,UAAA,yCAAA,kBAAA,uCAAA"}
|
|
@@ -15,7 +15,7 @@ declare function createUndoBridge(undoActions: UndoActions, selection: Selection
|
|
|
15
15
|
commitMove: (originals: Map<string, import("@pairdraw/scene-graph/primitives").Vector>) => void;
|
|
16
16
|
commitMoveWithReparent: (originals: Map<string, MovePlace>) => void;
|
|
17
17
|
commitDuplicateMove: (rootIds: string[], previousSelection: Set<string>) => void;
|
|
18
|
-
commitResize: (nodeId: string, original: import("@pairdraw/scene-graph/primitives").Rect & Partial<Pick<import("@pairdraw/scene-graph").SceneNode, "
|
|
18
|
+
commitResize: (nodeId: string, original: import("@pairdraw/scene-graph/primitives").Rect & Partial<Pick<import("@pairdraw/scene-graph").SceneNode, "vectorNetwork" | "fillGeometry" | "strokeGeometry" | "derivedTextGlyphs" | "strokes" | "textPathData" | "textPathBox">>) => void;
|
|
19
19
|
commitGroupResize: (nodeId: string, origRect: import("@pairdraw/scene-graph/primitives").Rect, origChildren: Map<string, import("@pairdraw/scene-graph/resize").ResizeSnapshot>) => void;
|
|
20
20
|
commitRotation: (nodeId: string, origRotation: number) => void;
|
|
21
21
|
commitNodeUpdate: (nodeId: string, previous: Partial<import("@pairdraw/scene-graph").SceneNode>, label?: string) => void;
|
package/dist/editor/create.d.ts
CHANGED
|
@@ -183,7 +183,7 @@ declare function createEditor(options?: EditorOptions): {
|
|
|
183
183
|
commitMove: (originals: Map<string, import("@pairdraw/scene-graph/primitives").Vector>) => void;
|
|
184
184
|
commitMoveWithReparent: (originals: Map<string, MovePlace>) => void;
|
|
185
185
|
commitDuplicateMove: (rootIds: string[], previousSelection: Set<string>) => void;
|
|
186
|
-
commitResize: (nodeId: string, original: import("@pairdraw/scene-graph/primitives").Rect & Partial<Pick<SceneNode, "
|
|
186
|
+
commitResize: (nodeId: string, original: import("@pairdraw/scene-graph/primitives").Rect & Partial<Pick<SceneNode, "vectorNetwork" | "fillGeometry" | "strokeGeometry" | "derivedTextGlyphs" | "strokes" | "textPathData" | "textPathBox">>) => void;
|
|
187
187
|
commitGroupResize: (nodeId: string, origRect: import("@pairdraw/scene-graph/primitives").Rect, origChildren: Map<string, import("@pairdraw/scene-graph/resize").ResizeSnapshot>) => void;
|
|
188
188
|
commitRotation: (nodeId: string, origRotation: number) => void;
|
|
189
189
|
snapshotPage: (pageId?: string) => PageSnapshot;
|
|
@@ -21,10 +21,45 @@ import { SceneGraph } from "@pairdraw/scene-graph";
|
|
|
21
21
|
import { GroupFitOptions } from "@pairdraw/scene-graph/group-bounds";
|
|
22
22
|
import { Rect, Vector } from "@pairdraw/scene-graph/primitives";
|
|
23
23
|
//#region src/figma-api/index.d.ts
|
|
24
|
+
/** A view of the document: its centre point and its zoom. */
|
|
25
|
+
interface FigmaViewport {
|
|
26
|
+
center: Vector;
|
|
27
|
+
zoom: number;
|
|
28
|
+
}
|
|
24
29
|
/** What a host passes to `FigmaAPI` beyond the document. */
|
|
25
30
|
interface FigmaAPIOptions {
|
|
26
31
|
/** Fetches the HTTP(S) URLs `figma.createImageAsync` loads; the global `fetch` by default. */
|
|
27
32
|
fetch?: ImageFetch;
|
|
33
|
+
/**
|
|
34
|
+
* Runs when a script puts the API on another page, so a host can show that page too. The host
|
|
35
|
+
* owns which page is on screen, and a plugin that switches page expects to see it switched.
|
|
36
|
+
*/
|
|
37
|
+
onPageChange?: (pageId: string) => void | Promise<void>;
|
|
38
|
+
/**
|
|
39
|
+
* Runs when a script moves the viewport, so a host can show the same view. A host owns the
|
|
40
|
+
* viewport on screen, and a plugin that pans or zooms expects to see the result.
|
|
41
|
+
*/
|
|
42
|
+
onViewportChange?: (viewport: FigmaViewport) => void;
|
|
43
|
+
/**
|
|
44
|
+
* The page the host already shows. Seeded here rather than assigned after construction, so a
|
|
45
|
+
* plain tool call does not ask the host to switch to the page it is already on.
|
|
46
|
+
*/
|
|
47
|
+
pageId?: string;
|
|
48
|
+
/**
|
|
49
|
+
* The view the host already shows, seeded for the same reason: a tool that only reads or draws
|
|
50
|
+
* must not move the viewport of whoever is looking at the document.
|
|
51
|
+
*/
|
|
52
|
+
viewport?: FigmaViewport;
|
|
53
|
+
/**
|
|
54
|
+
* Runs when a script sets the page selection, so a host can select those layers too. The host
|
|
55
|
+
* owns which layers are selected on screen, and a plugin that selects expects to see them selected.
|
|
56
|
+
*/
|
|
57
|
+
onSelectionChange?: (ids: readonly string[], pageId: string) => void;
|
|
58
|
+
/**
|
|
59
|
+
* The selection the host already shows, seeded for the same reason as the page and the viewport:
|
|
60
|
+
* a tool that only reads must not reselect what is already selected.
|
|
61
|
+
*/
|
|
62
|
+
selection?: readonly string[];
|
|
28
63
|
}
|
|
29
64
|
declare class FigmaAPI implements NodeProxyHost {
|
|
30
65
|
#private;
|
|
@@ -103,17 +138,17 @@ declare class FigmaAPI implements NodeProxyHost {
|
|
|
103
138
|
flatten(nodes: ReadonlyArray<FigmaNodeProxy>, parent?: FigmaNodeProxy, index?: number): FigmaVectorNode;
|
|
104
139
|
flatten(nodes: ReadonlyArray<BaseNode>, parent?: BaseNode & ChildrenMixin, index?: number): VectorNode;
|
|
105
140
|
private _viewport;
|
|
106
|
-
get viewport(): {
|
|
107
|
-
center: Vector;
|
|
108
|
-
zoom: number;
|
|
141
|
+
get viewport(): FigmaViewport & {
|
|
109
142
|
scrollAndZoomIntoView: (nodes: readonly {
|
|
110
143
|
absoluteBoundingBox: Rect;
|
|
111
144
|
}[]) => void;
|
|
112
145
|
};
|
|
113
|
-
set viewport(v:
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
146
|
+
set viewport(v: FigmaViewport);
|
|
147
|
+
/**
|
|
148
|
+
* Moves the viewport and puts the host on the same view. A tool that scrolls nodes into view
|
|
149
|
+
* does not call this: only a viewport a writer asks for moves the view of whoever is looking.
|
|
150
|
+
*/
|
|
151
|
+
private _showViewport;
|
|
117
152
|
createImage(data: Uint8Array): Image;
|
|
118
153
|
getImageByHash(hash: string): Image | null;
|
|
119
154
|
/** Fetches the image at `src` through the host's `fetch` and stores it as `createImage` does. */
|
|
@@ -149,5 +184,5 @@ declare class FigmaAPI implements NodeProxyHost {
|
|
|
149
184
|
changeBaseline?: (pageId: string) => SceneGraph | null;
|
|
150
185
|
}
|
|
151
186
|
//#endregion
|
|
152
|
-
export { type ExportImageOptions, FigmaAPI, FigmaAPIOptions, type FigmaBooleanOperationNode, type FigmaComponentNode, type FigmaComponentSetNode, type FigmaComposedColor, type FigmaConnectorNode, type FigmaEffect, type FigmaEllipseNode, type FigmaFont, type FigmaFontName, type FigmaFontNameInput, type FigmaFrameNode, type FigmaGroupNode, type FigmaInstanceNode, type FigmaLineNode, FigmaNodeProxy, type FigmaPolygonNode, type FigmaRectangleNode, type FigmaSectionNode, type FigmaShapeWithTextNode, type FigmaSlotNode, type FigmaStarNode, type FigmaTextNode, FigmaVariable, type FigmaVariableAlias, FigmaVariableCollection, type FigmaVariableValue, FigmaVariablesAPI, type FigmaVariationSettings, type FigmaVectorNode, type ImageFetch, ImageTooLargeError, MAX_IMAGE_FETCH_BYTES, flushPendingLayout, getPageBackgrounds, readBoundedImage, setPageBackgrounds };
|
|
187
|
+
export { type ExportImageOptions, FigmaAPI, FigmaAPIOptions, type FigmaBooleanOperationNode, type FigmaComponentNode, type FigmaComponentSetNode, type FigmaComposedColor, type FigmaConnectorNode, type FigmaEffect, type FigmaEllipseNode, type FigmaFont, type FigmaFontName, type FigmaFontNameInput, type FigmaFrameNode, type FigmaGroupNode, type FigmaInstanceNode, type FigmaLineNode, FigmaNodeProxy, type FigmaPolygonNode, type FigmaRectangleNode, type FigmaSectionNode, type FigmaShapeWithTextNode, type FigmaSlotNode, type FigmaStarNode, type FigmaTextNode, FigmaVariable, type FigmaVariableAlias, FigmaVariableCollection, type FigmaVariableValue, FigmaVariablesAPI, type FigmaVariationSettings, type FigmaVectorNode, FigmaViewport, type ImageFetch, ImageTooLargeError, MAX_IMAGE_FETCH_BYTES, flushPendingLayout, getPageBackgrounds, readBoundedImage, setPageBackgrounds };
|
|
153
188
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/figma-api/index.ts"],"mappings":";;;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UAiBK;EAqBR,MACE,OAAO,cAAc,iBACrB,QAAQ,gBACR,iBACC;EACH,MACE,OAAO,cAAc,WACrB,QAAQ,WAAW,eACnB,iBACC;EASH,SACE,OAAO,cAAc,iBACrB,QAAQ,gBACR,iBACC;EACH,SACE,OAAO,cAAc,WACrB,QAAQ,WAAW,eACnB,iBACC;EASH,UACE,OAAO,cAAc,iBACrB,QAAQ,gBACR,iBACC;EACH,UACE,OAAO,cAAc,WACrB,QAAQ,WAAW,eACnB,iBACC;EASH,QACE,OAAO,cAAc,iBACrB,QAAQ,gBACR,iBACC;EACH,QACE,OAAO,cAAc,WACrB,QAAQ,WAAW,eACnB,iBACC;EAWH,QACE,OAAO,cAAc,iBACrB,SAAS,gBACT,iBACC;EACH,QACE,OAAO,cAAc,WACrB,SAAS,WAAW,eACpB,iBACC;UAwBK;MAEJ,YAAY;IACd,wBAAwB;MAAkB,qBAAqB;;;MAsB7D,SAAS,GAAG;;;;;UAQR;EAOR,YAAY,MAAM,aAAa;EAI/B,eAAe,eAAe;;EAK9B,iBAAiB,cAAc,QAAQ;;EAOjC,cAAc,UAAU,qBAAqB;;;;;;EASnD,2BAA2B;EAUrB,2BAA2B,QAAQ;EAMzC,aAAa,MAAM;EAInB,aAAa,eAAe;EAK5B,OAAO;IAAoB;;;;;;EAS3B,YAAY;;EAKN,qBAAqB;EAI3B;EAIA;EAIA,eAAe,mBAAmB,SAAS,uBAAuB,QAAQ;;EAE1E,OAAO;EACP,cAAc;;EAEd,kBAAkB,mBAAmB"}
|
package/dist/figma-api/index.js
CHANGED
|
@@ -42,13 +42,26 @@ var FigmaAPI = class {
|
|
|
42
42
|
variables;
|
|
43
43
|
/** How `createImageAsync` fetches HTTP(S) URLs; a host passes one that gets past CORS. */
|
|
44
44
|
#fetch;
|
|
45
|
+
#onPageChange;
|
|
46
|
+
#onViewportChange;
|
|
47
|
+
#onSelectionChange;
|
|
48
|
+
/** The last host page switch, so `setCurrentPageAsync` can wait for it. */
|
|
49
|
+
#pageChange = Promise.resolve();
|
|
45
50
|
constructor(graph, options = {}) {
|
|
46
51
|
this.graph = graph;
|
|
47
52
|
this.#fetch = options.fetch ?? ((input, init) => fetch(input, init));
|
|
53
|
+
this.#onPageChange = options.onPageChange;
|
|
54
|
+
this.#onViewportChange = options.onViewportChange;
|
|
55
|
+
this.#onSelectionChange = options.onSelectionChange;
|
|
48
56
|
this.variables = new FigmaVariablesAPI(graph);
|
|
49
57
|
startPendingLayout(graph);
|
|
50
|
-
|
|
51
|
-
this.
|
|
58
|
+
this._currentPageId = pageIdToStart(graph, options.pageId);
|
|
59
|
+
if (options.viewport) this._viewport = {
|
|
60
|
+
x: options.viewport.center.x,
|
|
61
|
+
y: options.viewport.center.y,
|
|
62
|
+
zoom: options.viewport.zoom
|
|
63
|
+
};
|
|
64
|
+
this._selection = (options.selection ?? []).flatMap((id) => this.graph.getNode(id) ? [this.wrapNode(id)] : []);
|
|
52
65
|
}
|
|
53
66
|
setRenderer(renderer) {
|
|
54
67
|
this._renderer = renderer;
|
|
@@ -72,7 +85,11 @@ var FigmaAPI = class {
|
|
|
72
85
|
Object.defineProperty(proxy, "selection", {
|
|
73
86
|
get: () => this._selection,
|
|
74
87
|
set: (nodes) => {
|
|
88
|
+
const next = nodes.map((node) => node[INTERNAL_ID]);
|
|
89
|
+
const current = this._selection.map((node) => node[INTERNAL_ID]);
|
|
75
90
|
this._selection = nodes;
|
|
91
|
+
if (next.length === current.length && next.every((id, index) => id === current[index])) return;
|
|
92
|
+
this.#onSelectionChange?.(next, this._currentPageId);
|
|
76
93
|
},
|
|
77
94
|
enumerable: true,
|
|
78
95
|
configurable: true
|
|
@@ -88,7 +105,10 @@ var FigmaAPI = class {
|
|
|
88
105
|
return this._ensurePageProxy(this.wrapNode(this._currentPageId));
|
|
89
106
|
}
|
|
90
107
|
set currentPage(page) {
|
|
91
|
-
|
|
108
|
+
const pageId = page[INTERNAL_ID];
|
|
109
|
+
if (pageId === this._currentPageId) return;
|
|
110
|
+
this._currentPageId = pageId;
|
|
111
|
+
this.#pageChange = Promise.resolve(this.#onPageChange?.(pageId));
|
|
92
112
|
}
|
|
93
113
|
getNodeById(id) {
|
|
94
114
|
return this.graph.getNode(id) ? this.wrapNode(id) : null;
|
|
@@ -101,7 +121,8 @@ var FigmaAPI = class {
|
|
|
101
121
|
if (page == null) throw new Error(`in setCurrentPageAsync: Expected node, got ${String(page)}`);
|
|
102
122
|
if (this._rawNode(page).type !== "CANVAS") return Promise.reject(/* @__PURE__ */ new Error("figma.setCurrentPageAsync expects a PageNode"));
|
|
103
123
|
this._currentPageId = this._nodeId(page);
|
|
104
|
-
|
|
124
|
+
this.#pageChange = Promise.resolve(this.#onPageChange?.(this._currentPageId));
|
|
125
|
+
return this.#pageChange;
|
|
105
126
|
}
|
|
106
127
|
/** New layers start as the editor's tools make them, which is how Figma's plugin API makes them. */
|
|
107
128
|
_createNode(type) {
|
|
@@ -272,11 +293,27 @@ var FigmaAPI = class {
|
|
|
272
293
|
};
|
|
273
294
|
}
|
|
274
295
|
set viewport(v) {
|
|
275
|
-
this.
|
|
296
|
+
this._showViewport({
|
|
276
297
|
x: v.center.x,
|
|
277
298
|
y: v.center.y,
|
|
278
299
|
zoom: v.zoom
|
|
279
|
-
};
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Moves the viewport and puts the host on the same view. A tool that scrolls nodes into view
|
|
304
|
+
* does not call this: only a viewport a writer asks for moves the view of whoever is looking.
|
|
305
|
+
*/
|
|
306
|
+
_showViewport(next) {
|
|
307
|
+
const current = this._viewport;
|
|
308
|
+
this._viewport = next;
|
|
309
|
+
if (current.x === next.x && current.y === next.y && current.zoom === next.zoom) return;
|
|
310
|
+
this.#onViewportChange?.({
|
|
311
|
+
center: {
|
|
312
|
+
x: next.x,
|
|
313
|
+
y: next.y
|
|
314
|
+
},
|
|
315
|
+
zoom: next.zoom
|
|
316
|
+
});
|
|
280
317
|
}
|
|
281
318
|
createImage(data) {
|
|
282
319
|
return createImage(this.graph, data);
|
|
@@ -334,6 +371,11 @@ var FigmaAPI = class {
|
|
|
334
371
|
/** The document as it was before the current AI run first edited `pageId`, or null if unedited. */
|
|
335
372
|
changeBaseline;
|
|
336
373
|
};
|
|
374
|
+
/** The page an API starts on: the one the host shows, else the document's first page. */
|
|
375
|
+
function pageIdToStart(graph, pageId) {
|
|
376
|
+
const pages = graph.getPages();
|
|
377
|
+
return pageId ?? (pages.length > 0 ? pages[0].id : graph.rootId);
|
|
378
|
+
}
|
|
337
379
|
//#endregion
|
|
338
380
|
export { FigmaAPI, FigmaNodeProxy, FigmaVariable, FigmaVariableCollection, FigmaVariablesAPI, ImageTooLargeError, MAX_IMAGE_FETCH_BYTES, flushPendingLayout, getPageBackgrounds, readBoundedImage, setPageBackgrounds };
|
|
339
381
|
|