@pairdraw/core 0.16.2 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/canvas/outline-stroke.d.ts.map +1 -1
- package/dist/canvas/outline-stroke.js.map +1 -1
- package/dist/canvas/overlays/prototype.d.ts +2 -5
- package/dist/canvas/overlays/prototype.d.ts.map +1 -1
- package/dist/canvas/overlays/prototype.js +3 -19
- package/dist/canvas/overlays/prototype.js.map +1 -1
- package/dist/canvas/renderer/fonts.js +2 -1
- package/dist/canvas/renderer/fonts.js.map +1 -1
- package/dist/canvas/renderer.d.ts +4 -0
- package/dist/canvas/renderer.d.ts.map +1 -1
- package/dist/canvas/renderer.js +4 -0
- package/dist/canvas/renderer.js.map +1 -1
- package/dist/canvas/rulers.js +1 -1
- package/dist/canvas/rulers.js.map +1 -1
- package/dist/canvas/scene.d.ts.map +1 -1
- package/dist/canvas/scene.js +61 -37
- package/dist/canvas/scene.js.map +1 -1
- package/dist/canvas/text/font-families.d.ts +4 -3
- package/dist/canvas/text/font-families.d.ts.map +1 -1
- package/dist/canvas/text/font-families.js +8 -7
- package/dist/canvas/text/font-families.js.map +1 -1
- package/dist/canvas/text/index.d.ts.map +1 -1
- package/dist/canvas/text/index.js +1 -1
- package/dist/canvas/text/index.js.map +1 -1
- package/dist/canvas/text/paragraph/index.js +2 -2
- package/dist/canvas/text/paragraph/index.js.map +1 -1
- package/dist/canvas/text/placed.js +2 -2
- package/dist/canvas/text/placed.js.map +1 -1
- package/dist/canvas/text/renderer.d.ts +2 -0
- package/dist/canvas/text/renderer.d.ts.map +1 -1
- package/dist/clipboard/pairdraw.d.ts.map +1 -1
- package/dist/clipboard/pairdraw.js +53 -7
- package/dist/clipboard/pairdraw.js.map +1 -1
- package/dist/design-jsx/preview/picture.js +6 -1
- package/dist/design-jsx/preview/picture.js.map +1 -1
- package/dist/design-jsx/renderer.d.ts.map +1 -1
- package/dist/editor/alignment.d.ts.map +1 -1
- package/dist/editor/alignment.js +35 -27
- package/dist/editor/alignment.js.map +1 -1
- package/dist/editor/bridges/undo.d.ts +1 -1
- package/dist/editor/clipboard/detach.d.ts.map +1 -1
- package/dist/editor/clipboard/detach.js +3 -3
- package/dist/editor/clipboard/detach.js.map +1 -1
- package/dist/editor/clipboard/paste/properties.d.ts.map +1 -1
- package/dist/editor/clipboard/paste/properties.js +3 -1
- package/dist/editor/clipboard/paste/properties.js.map +1 -1
- package/dist/editor/create.d.ts +1 -1
- package/dist/editor/structure.d.ts.map +1 -1
- package/dist/editor/structure.js +3 -1
- package/dist/editor/structure.js.map +1 -1
- package/dist/editor/viewport.js +2 -2
- package/dist/editor/viewport.js.map +1 -1
- package/dist/figma-api/index.d.ts +43 -8
- package/dist/figma-api/index.d.ts.map +1 -1
- package/dist/figma-api/index.js +48 -6
- package/dist/figma-api/index.js.map +1 -1
- package/dist/figma-api/serialization.js +10 -0
- package/dist/figma-api/serialization.js.map +1 -1
- package/dist/figma-api/text/bindings.d.ts.map +1 -1
- package/dist/figma-api/text/bindings.js +20 -8
- package/dist/figma-api/text/bindings.js.map +1 -1
- package/dist/figma-api/text/index.js +1 -1
- package/dist/geometry/connectors.js +2 -14
- package/dist/geometry/connectors.js.map +1 -1
- package/dist/geometry/index.d.ts +2 -2
- package/dist/geometry/scene.d.ts +3 -1
- package/dist/geometry/scene.d.ts.map +1 -1
- package/dist/geometry/scene.js +16 -1
- package/dist/geometry/scene.js.map +1 -1
- package/dist/geometry/types.d.ts +7 -1
- package/dist/geometry/types.d.ts.map +1 -1
- package/dist/io/formats/drawio/export.d.ts.map +1 -1
- package/dist/io/formats/drawio/export.js +10 -0
- package/dist/io/formats/drawio/export.js.map +1 -1
- package/dist/io/formats/drawio/index.d.ts.map +1 -1
- package/dist/io/formats/drawio/index.js +32 -1
- package/dist/io/formats/drawio/index.js.map +1 -1
- package/dist/io/formats/drawio/shapes.d.ts +10 -5
- package/dist/io/formats/drawio/shapes.d.ts.map +1 -1
- package/dist/io/formats/drawio/shapes.js +10 -6
- package/dist/io/formats/drawio/shapes.js.map +1 -1
- package/dist/io/formats/drawio/warnings.d.ts +11 -0
- package/dist/io/formats/drawio/warnings.d.ts.map +1 -0
- package/dist/io/formats/drawio/warnings.js +23 -0
- package/dist/io/formats/drawio/warnings.js.map +1 -0
- package/dist/io/formats/pdf/dom.d.ts +10 -1
- package/dist/io/formats/pdf/dom.d.ts.map +1 -1
- package/dist/io/formats/pdf/dom.js +31 -1
- package/dist/io/formats/pdf/dom.js.map +1 -1
- package/dist/io/formats/pdf/export.js +3 -2
- package/dist/io/formats/pdf/export.js.map +1 -1
- package/dist/io/formats/raster/headless.d.ts +2 -2
- package/dist/io/formats/raster/headless.d.ts.map +1 -1
- package/dist/io/formats/raster/headless.js +2 -2
- package/dist/io/formats/raster/headless.js.map +1 -1
- package/dist/io/formats/raster/render.d.ts +1 -1
- package/dist/io/formats/raster/render.d.ts.map +1 -1
- package/dist/io/formats/raster/render.js +2 -2
- package/dist/io/formats/raster/render.js.map +1 -1
- package/dist/io/formats.d.ts.map +1 -1
- package/dist/io/formats.js +6 -6
- package/dist/io/formats.js.map +1 -1
- package/dist/io/registry.d.ts +2 -0
- package/dist/io/registry.d.ts.map +1 -1
- package/dist/io/registry.js +5 -0
- package/dist/io/registry.js.map +1 -1
- package/dist/io/types.d.ts +2 -0
- package/dist/io/types.d.ts.map +1 -1
- package/dist/library/snapshot.d.ts.map +1 -1
- package/dist/library/snapshot.js +1 -0
- package/dist/library/snapshot.js.map +1 -1
- package/dist/lint/linter.d.ts.map +1 -1
- package/dist/lint/linter.js +11 -2
- package/dist/lint/linter.js.map +1 -1
- package/dist/rpc/variables-command.d.ts.map +1 -1
- package/dist/rpc/variables-command.js +4 -2
- package/dist/rpc/variables-command.js.map +1 -1
- package/dist/text/character-style.d.ts.map +1 -1
- package/dist/text/character-style.js +2 -1
- package/dist/text/character-style.js.map +1 -1
- package/dist/text/coverage.d.ts.map +1 -1
- package/dist/text/coverage.js +6 -3
- package/dist/text/coverage.js.map +1 -1
- package/dist/text/fallbacks.d.ts +8 -2
- package/dist/text/fallbacks.d.ts.map +1 -1
- package/dist/text/fallbacks.js +73 -7
- package/dist/text/fallbacks.js.map +1 -1
- package/dist/text/font/manager.d.ts +14 -6
- package/dist/text/font/manager.d.ts.map +1 -1
- package/dist/text/font/manager.js +40 -14
- package/dist/text/font/manager.js.map +1 -1
- package/dist/text/index.d.ts +2 -2
- package/dist/text/index.js +3 -3
- package/dist/text/outlines.js +1 -1
- package/dist/text/outlines.js.map +1 -1
- package/dist/text/path/caret.d.ts +2 -4
- package/dist/text/path/caret.d.ts.map +1 -1
- package/dist/text/path/caret.js.map +1 -1
- package/dist/text/prepare.d.ts +5 -1
- package/dist/text/prepare.d.ts.map +1 -1
- package/dist/text/prepare.js +19 -2
- package/dist/text/prepare.js.map +1 -1
- package/dist/text/web-font/assets.d.ts.map +1 -1
- package/dist/text/web-font/assets.js +13 -21
- package/dist/text/web-font/assets.js.map +1 -1
- package/dist/text/web-font/resolver.d.ts.map +1 -1
- package/dist/text/web-font/resolver.js +4 -1
- package/dist/text/web-font/resolver.js.map +1 -1
- package/dist/tools/create/components.d.ts +2 -1
- package/dist/tools/create/components.d.ts.map +1 -1
- package/dist/tools/create/components.js +27 -1
- package/dist/tools/create/components.js.map +1 -1
- package/dist/tools/create/icons.d.ts.map +1 -1
- package/dist/tools/create/icons.js +11 -5
- package/dist/tools/create/icons.js.map +1 -1
- package/dist/tools/create/vector.d.ts.map +1 -1
- package/dist/tools/create/vector.js +9 -6
- package/dist/tools/create/vector.js.map +1 -1
- package/dist/tools/create.d.ts +2 -2
- package/dist/tools/create.js +2 -2
- package/dist/tools/modify/effects.d.ts.map +1 -1
- package/dist/tools/modify/effects.js +5 -3
- package/dist/tools/modify/effects.js.map +1 -1
- package/dist/tools/modify/matching.d.ts.map +1 -1
- package/dist/tools/modify/matching.js +9 -6
- package/dist/tools/modify/matching.js.map +1 -1
- package/dist/tools/modify/paint.d.ts.map +1 -1
- package/dist/tools/modify/paint.js +7 -5
- package/dist/tools/modify/paint.js.map +1 -1
- package/dist/tools/modify/text.d.ts.map +1 -1
- package/dist/tools/modify/text.js +28 -8
- package/dist/tools/modify/text.js.map +1 -1
- package/dist/tools/read/libraries.d.ts.map +1 -1
- package/dist/tools/read/libraries.js +20 -8
- package/dist/tools/read/libraries.js.map +1 -1
- package/dist/tools/read/pages.d.ts.map +1 -1
- package/dist/tools/read/pages.js.map +1 -1
- package/dist/tools/registry/extended.d.ts.map +1 -1
- package/dist/tools/registry/extended.js +2 -1
- package/dist/tools/registry/extended.js.map +1 -1
- package/dist/tools/schema.d.ts +24 -5
- package/dist/tools/schema.d.ts.map +1 -1
- package/dist/tools/schema.js +80 -6
- package/dist/tools/schema.js.map +1 -1
- package/dist/tools/structure/batch.d.ts.map +1 -1
- package/dist/tools/structure/batch.js +4 -3
- package/dist/tools/structure/batch.js.map +1 -1
- package/dist/tools/variables/values.d.ts.map +1 -1
- package/dist/tools/variables/values.js +4 -2
- package/dist/tools/variables/values.js.map +1 -1
- package/dist/tools/vector/export.d.ts.map +1 -1
- package/dist/tools/vector/export.js +5 -2
- package/dist/tools/vector/export.js.map +1 -1
- package/package.json +9 -9
- package/src/canvas/outline-stroke.ts +2 -6
- package/src/canvas/overlays/prototype.ts +5 -27
- package/src/canvas/renderer/fonts.ts +2 -1
- package/src/canvas/renderer.ts +4 -0
- package/src/canvas/rulers.ts +1 -1
- package/src/canvas/scene.ts +92 -63
- package/src/canvas/text/font-families.ts +8 -7
- package/src/canvas/text/index.ts +3 -1
- package/src/canvas/text/paragraph/index.ts +2 -2
- package/src/canvas/text/placed.ts +2 -2
- package/src/canvas/text/renderer.ts +2 -0
- package/src/clipboard/pairdraw.ts +51 -7
- package/src/design-jsx/preview/picture.ts +8 -2
- package/src/editor/alignment.ts +33 -29
- package/src/editor/clipboard/detach.ts +9 -3
- package/src/editor/clipboard/paste/properties.ts +3 -1
- package/src/editor/structure.ts +3 -1
- package/src/editor/viewport.ts +2 -2
- package/src/figma-api/index.ts +90 -9
- package/src/figma-api/serialization.ts +14 -0
- package/src/figma-api/text/bindings.ts +26 -8
- package/src/geometry/connectors.ts +2 -12
- package/src/geometry/index.ts +1 -1
- package/src/geometry/scene.ts +19 -0
- package/src/geometry/types.ts +8 -0
- package/src/io/formats/drawio/export.ts +11 -0
- package/src/io/formats/drawio/index.ts +36 -1
- package/src/io/formats/drawio/shapes.ts +13 -9
- package/src/io/formats/drawio/warnings.ts +27 -0
- package/src/io/formats/pdf/dom.ts +29 -0
- package/src/io/formats/pdf/export.ts +3 -2
- package/src/io/formats/raster/headless.ts +10 -3
- package/src/io/formats/raster/render.ts +4 -2
- package/src/io/formats.ts +8 -10
- package/src/io/registry.ts +12 -0
- package/src/io/types.ts +2 -0
- package/src/library/snapshot.ts +1 -0
- package/src/lint/linter.ts +12 -2
- package/src/rpc/variables-command.ts +6 -5
- package/src/text/character-style.ts +8 -4
- package/src/text/coverage.ts +17 -2
- package/src/text/fallbacks.ts +81 -7
- package/src/text/font/manager.ts +50 -17
- package/src/text/outlines.ts +1 -1
- package/src/text/path/caret.ts +3 -4
- package/src/text/prepare.ts +34 -2
- package/src/text/web-font/assets.ts +11 -15
- package/src/text/web-font/resolver.ts +7 -1
- package/src/tools/create/components.ts +33 -0
- package/src/tools/create/icons.ts +13 -5
- package/src/tools/create/vector.ts +16 -6
- package/src/tools/create.ts +1 -0
- package/src/tools/modify/effects.ts +11 -4
- package/src/tools/modify/matching.ts +10 -6
- package/src/tools/modify/paint.ts +13 -5
- package/src/tools/modify/text.ts +53 -20
- package/src/tools/read/libraries.ts +35 -11
- package/src/tools/read/pages.ts +1 -0
- package/src/tools/registry/extended.ts +2 -0
- package/src/tools/schema.ts +109 -5
- package/src/tools/structure/batch.ts +10 -5
- package/src/tools/variables/values.ts +6 -3
- package/src/tools/vector/export.ts +5 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/canvas/text/index.ts"],"sourcesContent":["import type { SceneNode } from '@pairdraw/scene-graph'\n\nimport { DEFAULT_FONT_FAMILY } from '#core/constants'\nimport { shownCharacters, shownText } from '#core/text/case'\nimport { fontManager } from '#core/text/font/manager'\nimport { textFontFace } from '#core/text/requirements/collect'\nimport {\n fontCoverageDemand,\n fontFaceDemand,\n fontRemoteCoverageDemand,\n fontResolver,\n missingGlyphOccurrences,\n missingGlyphsByScript\n} from '#core/text/resolver'\n\nimport { drawTextLayout } from './decorations'\nimport { buildParagraph } from './layout/build'\nimport { resolveParagraphLayoutWidth } from './paragraph'\nimport { withPreparedText } from './preparation'\nimport type { FontReadinessRenderer, TextRenderer } from './renderer'\n\nexport { buildParagraph } from './layout/build'\nexport type { TextLayout } from './layout'\nexport type { ParagraphBuildOptions } from './paint'\nexport { textFontFeatures, textFontVariations, textHeightBehaviorValue } from './paragraph'\nexport { withTextParagraph } from './preparation'\n\nfunction demandFace(\n r: FontReadinessRenderer,\n node: SceneNode,\n family: string,\n style: string\n): boolean {\n if (fontManager.isStyleLoaded(family, style)) return true\n const demand = fontFaceDemand(family, style, node.text)\n r.trackFontDemand?.(node, demand.key)\n void fontResolver.demandForNode(demand, node.id, r.onFontResolutionSettled)\n return false\n}\n\nfunction requiredNodeFaces(node: SceneNode): Array<{ family: string; style: string }> {\n const baseFamily = node.fontFamily || DEFAULT_FONT_FAMILY\n const faces = new Map<string, { family: string; style: string }>()\n const add = (family: string, style: string) => faces.set(`${family}\\0${style}`, { family, style })\n add(baseFamily, textFontFace(node).style)\n for (const run of node.styleRuns) {\n add(run.style.fontFamily ?? baseFamily, textFontFace(node, run.style).style)\n }\n return Array.from(faces.values())\n}\n\nfunction languageForCharacter(node: SceneNode, sourceIndex: number): string | null {\n const run = node.styleRuns.find(\n (item) => sourceIndex >= item.start && sourceIndex < item.start + item.length\n )\n return run?.style.textLanguage !== undefined ? run.style.textLanguage : node.textLanguage\n}\n\nfunction transformedSourceOffsets(node: SceneNode): number[] {\n return shownCharacters(node).map((shown) => shown.sourceIndex)\n}\n\nexport type NodeFontReadiness = 'ready' | 'substituted' | 'pending' | 'exhausted'\n\nfunction requiredFacesReadiness(r: FontReadinessRenderer, node: SceneNode): NodeFontReadiness {\n let pending = false\n let exhausted = false\n for (const { family, style } of requiredNodeFaces(node)) {\n if (fontManager.isStyleLoaded(family, style)) continue\n const demand = fontFaceDemand(family, style, node.text)\n const state = fontResolver.state(demand).state\n demandFace(r, node, family, style)\n if (state === 'failed' || state === 'exhausted') {\n // A missing face is drawn in another loaded face of the family, as Figma draws it, and\n // reported missing; the text stays visible when an exact face (Italic) is unavailable.\n if (fontManager.isLoaded(family)) continue\n exhausted = true\n } else {\n pending = true\n }\n }\n if (pending) return 'pending'\n if (exhausted && fontManager.isStyleLoaded(DEFAULT_FONT_FAMILY, 'Regular')) return 'substituted'\n return exhausted ? 'exhausted' : 'ready'\n}\n\nfunction demandRemoteCoverage(r: TextRenderer, node: SceneNode, characters: string[]): boolean {\n for (const { family, style } of requiredNodeFaces(node)) {\n if (!fontManager.remoteStyleNeedsCoverage(family, style, characters)) continue\n const demand = fontRemoteCoverageDemand(family, style, characters)\n const state = fontResolver.state(demand).state\n if (state === 'idle') {\n r.trackFontDemand?.(node, demand.key)\n void fontResolver.demandForNode(demand, node.id, r.onFontResolutionSettled)\n return true\n }\n if (state === 'loading') return true\n if (state === 'loaded') fontResolver.exhaust(demand)\n }\n return false\n}\n\nfunction observedGlyphReadiness(r: TextRenderer, node: SceneNode): NodeFontReadiness {\n if (\n r.fontProvider &&\n r.textPreparationCache?.hasGlyphCoverage(node, fontManager.generation(), r.fontProvider)\n )\n return 'ready'\n\n const missingOccurrences = withPreparedText(\n r,\n node,\n 'coverage',\n () => buildParagraph(r, node),\n (prepared) => {\n if (!prepared.missingGlyphs) {\n prepared.paragraph.layout(resolveParagraphLayoutWidth(node))\n prepared.missingGlyphs = missingGlyphOccurrences(\n shownText(node),\n prepared.paragraph.getShapedLines(),\n transformedSourceOffsets(node)\n )\n }\n return prepared.missingGlyphs\n }\n )\n if (missingOccurrences.length === 0) {\n r.textPreparationCache?.recordGlyphCoverage(node)\n return 'ready'\n }\n\n const charactersByScript = missingGlyphsByScript(missingOccurrences, (offset) =>\n languageForCharacter(node, offset)\n )\n\n let pending = false\n let exhausted = charactersByScript.size === 0\n for (const [script, characters] of charactersByScript) {\n if (demandRemoteCoverage(r, node, characters)) {\n pending = true\n continue\n }\n\n const demand = fontCoverageDemand(script, characters)\n const state = fontResolver.state(demand).state\n if (state === 'loaded') {\n fontResolver.exhaust(demand)\n exhausted = true\n continue\n }\n if (state === 'exhausted' || state === 'failed') {\n exhausted = true\n continue\n }\n pending = true\n if (state === 'idle') {\n r.trackFontDemand?.(node, demand.key)\n void fontResolver.demandForNode(demand, node.id, r.onFontResolutionSettled)\n }\n }\n if (pending) return 'pending'\n // Once no fallback is left for a character, the text draws with the fonts it has, the font's\n // missing-glyph box standing in for that character, rather than not at all.\n return exhausted ? 'substituted' : 'ready'\n}\n\nfunction canObserveGlyphCoverage(r: FontReadinessRenderer): r is TextRenderer {\n return r.ck !== undefined && r.fontProvider != null && r.fontsLoaded !== undefined\n}\n\nexport function nodeFontReadiness(r: FontReadinessRenderer, node: SceneNode): NodeFontReadiness {\n if (node.type !== 'TEXT') return 'ready'\n const faces = requiredFacesReadiness(r, node)\n if (faces === 'pending' || faces === 'exhausted') return faces\n if (!node.text || !canObserveGlyphCoverage(r)) return faces\n const glyphs = observedGlyphReadiness(r, node)\n // Substituted text still needs script fallbacks (for example CJK) for glyphs the substitute\n // lacks, but stays visible when none can be found.\n if (faces === 'substituted') return glyphs === 'pending' ? 'pending' : 'substituted'\n return glyphs\n}\n\nexport function isNodeFontLoaded(r: FontReadinessRenderer, node: SceneNode): boolean {\n const readiness = nodeFontReadiness(r, node)\n return readiness === 'ready' || readiness === 'substituted'\n}\n\nexport function measureTextNode(\n r: TextRenderer,\n node: SceneNode,\n maxWidth?: number\n): { width: number; height: number } | null {\n if (!r.fontsLoaded || !r.fontProvider || !isNodeFontLoaded(r, node)) return null\n if (node.type !== 'TEXT' || !node.text) return null\n\n const layoutWidth = resolveParagraphLayoutWidth(node, maxWidth)\n const measure = () => {\n const paragraph = buildParagraph(r, node)\n paragraph.layout(layoutWidth)\n const width = paragraph.getLongestLine()\n const height = paragraph.getHeight()\n paragraph.delete()\n return { width: Math.ceil(width), height: Math.ceil(height) }\n }\n // Layout asks for the same text at the same width many times per pass.\n return r.textPreparationCache\n ? r.textPreparationCache.measure(\n node,\n layoutWidth,\n fontManager.generation(),\n r.fontProvider,\n measure\n )\n : measure()\n}\n\nexport function buildTextPicture(r: TextRenderer, node: SceneNode): Uint8Array | null {\n if (!r.fontsLoaded || !r.fontProvider || !isNodeFontLoaded(r, node)) return null\n if (node.type !== 'TEXT' || !node.text) return null\n\n const ck = r.ck\n const recorder = new ck.PictureRecorder()\n const bounds = ck.LTRBRect(0, 0, node.width || 1e6, node.height || 1e6)\n const recCanvas = recorder.beginRecording(bounds)\n\n const layout = buildParagraph(r, node)\n const paint = new ck.Paint()\n try {\n drawTextLayout(ck, recCanvas, node, { paragraph: layout }, 0, paint)\n } finally {\n paint.delete()\n layout.delete()\n }\n\n const picture = recorder.finishRecordingAsPicture()\n recorder.delete()\n\n const bytes = picture.serialize()\n picture.delete()\n return bytes ?? null\n}\n\n/** Offset that places laid-out text of `contentHeight` in the node box by vertical alignment. */\nexport function textVerticalOffset(node: SceneNode, contentHeight: number): number {\n const available = Math.max(0, node.height - contentHeight)\n if (node.textAlignVertical === 'CENTER') return available / 2\n if (node.textAlignVertical === 'BOTTOM') return available\n return 0\n}\n"],"mappings":";;;;;;;;;;;AA2BA,SAAS,WACP,GACA,MACA,QACA,OACS;CACT,IAAI,YAAY,cAAc,QAAQ,KAAK,GAAG,OAAO;CACrD,MAAM,SAAS,eAAe,QAAQ,OAAO,KAAK,IAAI;CACtD,EAAE,kBAAkB,MAAM,OAAO,GAAG;CACpC,aAAkB,cAAc,QAAQ,KAAK,IAAI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/text/index.ts"],"sourcesContent":["import type { SceneNode } from '@pairdraw/scene-graph'\n\nimport { DEFAULT_FONT_FAMILY } from '#core/constants'\nimport { shownCharacters, shownText } from '#core/text/case'\nimport { fontManager } from '#core/text/font/manager'\nimport { textFontFace } from '#core/text/requirements/collect'\nimport {\n fontCoverageDemand,\n fontFaceDemand,\n fontRemoteCoverageDemand,\n fontResolver,\n missingGlyphOccurrences,\n missingGlyphsByScript\n} from '#core/text/resolver'\n\nimport { drawTextLayout } from './decorations'\nimport { buildParagraph } from './layout/build'\nimport { resolveParagraphLayoutWidth } from './paragraph'\nimport { withPreparedText } from './preparation'\nimport type { FontReadinessRenderer, TextRenderer } from './renderer'\n\nexport { buildParagraph } from './layout/build'\nexport type { TextLayout } from './layout'\nexport type { ParagraphBuildOptions } from './paint'\nexport { textFontFeatures, textFontVariations, textHeightBehaviorValue } from './paragraph'\nexport { withTextParagraph } from './preparation'\n\nfunction demandFace(\n r: FontReadinessRenderer,\n node: SceneNode,\n family: string,\n style: string\n): boolean {\n if (fontManager.isStyleLoaded(family, style)) return true\n const demand = fontFaceDemand(family, style, node.text)\n r.trackFontDemand?.(node, demand.key)\n void fontResolver.demandForNode(demand, node.id, r.onFontResolutionSettled)\n return false\n}\n\nfunction requiredNodeFaces(node: SceneNode): Array<{ family: string; style: string }> {\n const baseFamily = node.fontFamily || DEFAULT_FONT_FAMILY\n const faces = new Map<string, { family: string; style: string }>()\n const add = (family: string, style: string) => faces.set(`${family}\\0${style}`, { family, style })\n add(baseFamily, textFontFace(node).style)\n for (const run of node.styleRuns) {\n add(run.style.fontFamily ?? baseFamily, textFontFace(node, run.style).style)\n }\n return Array.from(faces.values())\n}\n\nfunction languageForCharacter(node: SceneNode, sourceIndex: number): string | null {\n const run = node.styleRuns.find(\n (item) => sourceIndex >= item.start && sourceIndex < item.start + item.length\n )\n return run?.style.textLanguage !== undefined ? run.style.textLanguage : node.textLanguage\n}\n\nfunction transformedSourceOffsets(node: SceneNode): number[] {\n return shownCharacters(node).map((shown) => shown.sourceIndex)\n}\n\nexport type NodeFontReadiness = 'ready' | 'substituted' | 'pending' | 'exhausted'\n\nfunction requiredFacesReadiness(r: FontReadinessRenderer, node: SceneNode): NodeFontReadiness {\n let pending = false\n let exhausted = false\n for (const { family, style } of requiredNodeFaces(node)) {\n if (fontManager.isStyleLoaded(family, style)) continue\n const demand = fontFaceDemand(family, style, node.text)\n const state = fontResolver.state(demand).state\n demandFace(r, node, family, style)\n if (state === 'failed' || state === 'exhausted') {\n // A missing face is drawn in another loaded face of the family, as Figma draws it, and\n // reported missing; the text stays visible when an exact face (Italic) is unavailable.\n if (fontManager.isLoaded(family)) continue\n exhausted = true\n } else {\n pending = true\n }\n }\n if (pending) return 'pending'\n if (exhausted && fontManager.isStyleLoaded(DEFAULT_FONT_FAMILY, 'Regular')) return 'substituted'\n return exhausted ? 'exhausted' : 'ready'\n}\n\nfunction demandRemoteCoverage(r: TextRenderer, node: SceneNode, characters: string[]): boolean {\n for (const { family, style } of requiredNodeFaces(node)) {\n if (!fontManager.remoteStyleNeedsCoverage(family, style, characters)) continue\n const demand = fontRemoteCoverageDemand(family, style, characters)\n const state = fontResolver.state(demand).state\n if (state === 'idle') {\n r.trackFontDemand?.(node, demand.key)\n void fontResolver.demandForNode(demand, node.id, r.onFontResolutionSettled)\n return true\n }\n if (state === 'loading') return true\n if (state === 'loaded') fontResolver.exhaust(demand)\n }\n return false\n}\n\nfunction observedGlyphReadiness(r: TextRenderer, node: SceneNode): NodeFontReadiness {\n if (\n r.fontProvider &&\n r.textPreparationCache?.hasGlyphCoverage(node, fontManager.generation(), r.fontProvider)\n )\n return 'ready'\n\n const missingOccurrences = withPreparedText(\n r,\n node,\n 'coverage',\n () => buildParagraph(r, node),\n (prepared) => {\n if (!prepared.missingGlyphs) {\n prepared.paragraph.layout(resolveParagraphLayoutWidth(node))\n prepared.missingGlyphs = missingGlyphOccurrences(\n shownText(node),\n prepared.paragraph.getShapedLines(),\n transformedSourceOffsets(node)\n )\n }\n return prepared.missingGlyphs\n }\n )\n if (missingOccurrences.length === 0) {\n r.textPreparationCache?.recordGlyphCoverage(node)\n return 'ready'\n }\n\n const charactersByScript = missingGlyphsByScript(missingOccurrences, (offset) =>\n languageForCharacter(node, offset)\n )\n\n let pending = false\n let exhausted = charactersByScript.size === 0\n for (const [script, characters] of charactersByScript) {\n if (demandRemoteCoverage(r, node, characters)) {\n pending = true\n continue\n }\n\n const demand = fontCoverageDemand(script, characters)\n const state = fontResolver.state(demand).state\n if (state === 'loaded') {\n fontResolver.exhaust(demand)\n exhausted = true\n continue\n }\n if (state === 'exhausted' || state === 'failed') {\n exhausted = true\n continue\n }\n pending = true\n if (state === 'idle') {\n r.trackFontDemand?.(node, demand.key)\n void fontResolver.demandForNode(demand, node.id, r.onFontResolutionSettled)\n }\n }\n // An export draws once: a face that has not arrived by then is not coming, and the characters\n // it would have covered keep the text's own fonts rather than leaving the layer blank.\n if (pending) return r.exportFontsSettled ? 'substituted' : 'pending'\n // Once no fallback is left for a character, the text draws with the fonts it has, the font's\n // missing-glyph box standing in for that character, rather than not at all.\n return exhausted ? 'substituted' : 'ready'\n}\n\nfunction canObserveGlyphCoverage(r: FontReadinessRenderer): r is TextRenderer {\n return r.ck !== undefined && r.fontProvider != null && r.fontsLoaded !== undefined\n}\n\nexport function nodeFontReadiness(r: FontReadinessRenderer, node: SceneNode): NodeFontReadiness {\n if (node.type !== 'TEXT') return 'ready'\n const faces = requiredFacesReadiness(r, node)\n if (faces === 'pending' || faces === 'exhausted') return faces\n if (!node.text || !canObserveGlyphCoverage(r)) return faces\n const glyphs = observedGlyphReadiness(r, node)\n // Substituted text still needs script fallbacks (for example CJK) for glyphs the substitute\n // lacks, but stays visible when none can be found.\n if (faces === 'substituted') return glyphs === 'pending' ? 'pending' : 'substituted'\n return glyphs\n}\n\nexport function isNodeFontLoaded(r: FontReadinessRenderer, node: SceneNode): boolean {\n const readiness = nodeFontReadiness(r, node)\n return readiness === 'ready' || readiness === 'substituted'\n}\n\nexport function measureTextNode(\n r: TextRenderer,\n node: SceneNode,\n maxWidth?: number\n): { width: number; height: number } | null {\n if (!r.fontsLoaded || !r.fontProvider || !isNodeFontLoaded(r, node)) return null\n if (node.type !== 'TEXT' || !node.text) return null\n\n const layoutWidth = resolveParagraphLayoutWidth(node, maxWidth)\n const measure = () => {\n const paragraph = buildParagraph(r, node)\n paragraph.layout(layoutWidth)\n const width = paragraph.getLongestLine()\n const height = paragraph.getHeight()\n paragraph.delete()\n return { width: Math.ceil(width), height: Math.ceil(height) }\n }\n // Layout asks for the same text at the same width many times per pass.\n return r.textPreparationCache\n ? r.textPreparationCache.measure(\n node,\n layoutWidth,\n fontManager.generation(),\n r.fontProvider,\n measure\n )\n : measure()\n}\n\nexport function buildTextPicture(r: TextRenderer, node: SceneNode): Uint8Array | null {\n if (!r.fontsLoaded || !r.fontProvider || !isNodeFontLoaded(r, node)) return null\n if (node.type !== 'TEXT' || !node.text) return null\n\n const ck = r.ck\n const recorder = new ck.PictureRecorder()\n const bounds = ck.LTRBRect(0, 0, node.width || 1e6, node.height || 1e6)\n const recCanvas = recorder.beginRecording(bounds)\n\n const layout = buildParagraph(r, node)\n const paint = new ck.Paint()\n try {\n drawTextLayout(ck, recCanvas, node, { paragraph: layout }, 0, paint)\n } finally {\n paint.delete()\n layout.delete()\n }\n\n const picture = recorder.finishRecordingAsPicture()\n recorder.delete()\n\n const bytes = picture.serialize()\n picture.delete()\n return bytes ?? null\n}\n\n/** Offset that places laid-out text of `contentHeight` in the node box by vertical alignment. */\nexport function textVerticalOffset(node: SceneNode, contentHeight: number): number {\n const available = Math.max(0, node.height - contentHeight)\n if (node.textAlignVertical === 'CENTER') return available / 2\n if (node.textAlignVertical === 'BOTTOM') return available\n return 0\n}\n"],"mappings":";;;;;;;;;;;AA2BA,SAAS,WACP,GACA,MACA,QACA,OACS;CACT,IAAI,YAAY,cAAc,QAAQ,KAAK,GAAG,OAAO;CACrD,MAAM,SAAS,eAAe,QAAQ,OAA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YAAY;CAC5D,IAAI,KAAK,sBAAsB,UAAU,OAAO;CAChD,OAAO;AACT"}
|
|
@@ -152,14 +152,14 @@ function buildSkParagraph(r, node, color, { halfLeading = false, foregroundPaint
|
|
|
152
152
|
const baseFontSize = node.fontSize || 14;
|
|
153
153
|
const baseLineHeight = lineHeightPixels(node.lineHeight, baseFontSize);
|
|
154
154
|
const cjkFallbacks = fontManager.getCJKFallbackFamilies();
|
|
155
|
-
const
|
|
155
|
+
const letterFallbacks = fontManager.getLetterFallbackFamilies();
|
|
156
156
|
const textDirection = resolveNodeTextDirection(node);
|
|
157
157
|
const truncateOpts = block.truncation ?? buildTruncateOpts(node);
|
|
158
158
|
const fontFamilies = (primary, face) => resolveParagraphFontFamilies(primary, {
|
|
159
159
|
weight: face.fontWeight,
|
|
160
160
|
italic: face.italic,
|
|
161
161
|
style: faceStyleKey(face)
|
|
162
|
-
},
|
|
162
|
+
}, letterFallbacks, cjkFallbacks);
|
|
163
163
|
const nodeKey = faceStyleKey(node);
|
|
164
164
|
const baseTextStyle = {
|
|
165
165
|
color: baseColor,
|
|
@@ -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,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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","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,O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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,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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,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,O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AI,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"}
|
|
@@ -8,6 +8,8 @@ interface FontReadinessRenderer {
|
|
|
8
8
|
ck?: CanvasKit;
|
|
9
9
|
fontProvider?: 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":"pairdraw.d.ts","names":[],"sources":["../../src/clipboard/pairdraw.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"pairdraw.d.ts","names":[],"sources":["../../src/clipboard/pairdraw.ts"],"mappings":";;;;KAkJY,wBAAwB,KAAK;iBAEzB,uBAAuB,eAAe;KAiF1C,sBAAsB,MAAM,cAAc;iBAgBtC,2BACd,OAAO,aACP,OAAO,YACP,qBAAqB"}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { deflateSync, inflateSync } from "fflate";
|
|
2
2
|
import { fromUint8Array, isValid, toUint8Array } from "js-base64";
|
|
3
|
+
import { isPlainObject, omit } from "es-toolkit";
|
|
3
4
|
import * as v from "valibot";
|
|
4
5
|
import { createInstanceOverrideState, deserializeInstanceOverrideState, serializeInstanceOverrideState, setInstanceOverride } from "@pairdraw/scene-graph/instances/overrides";
|
|
6
|
+
import { fillSchema } from "@pairdraw/scene-graph/paints";
|
|
5
7
|
//#region src/clipboard/pairdraw.ts
|
|
6
8
|
const NODE_TYPES = {
|
|
7
9
|
CANVAS: true,
|
|
@@ -43,6 +45,40 @@ const serializedClipboardNodeSchema = v.looseObject({
|
|
|
43
45
|
strokeGeometry: serializedGeometrySchema,
|
|
44
46
|
children: v.optional(v.array(v.lazy(() => serializedClipboardNodeSchema)))
|
|
45
47
|
});
|
|
48
|
+
const paintsSchema = v.array(fillSchema);
|
|
49
|
+
const effectsSchema = v.array(v.unknown());
|
|
50
|
+
const sourceMetadataSchema = v.looseObject({
|
|
51
|
+
format: v.nullable(v.literal("fig")),
|
|
52
|
+
id: v.nullable(v.string()),
|
|
53
|
+
orderKey: v.nullable(v.string()),
|
|
54
|
+
editedFields: v.array(v.string()),
|
|
55
|
+
fig: v.looseObject({})
|
|
56
|
+
});
|
|
57
|
+
/**
|
|
58
|
+
* Fields the graph reads without checking. `v.is` checks them without parsing, which would reorder
|
|
59
|
+
* paint keys; a malformed field is dropped and the rest of the layer kept.
|
|
60
|
+
*/
|
|
61
|
+
const CHECKED_FIELDS = [
|
|
62
|
+
["fills", paintsSchema],
|
|
63
|
+
["strokes", paintsSchema],
|
|
64
|
+
["effects", effectsSchema],
|
|
65
|
+
["source", sourceMetadataSchema]
|
|
66
|
+
];
|
|
67
|
+
function malformedFields(fields, checked = CHECKED_FIELDS) {
|
|
68
|
+
return checked.filter(([key, schema]) => key in fields && !v.is(schema, fields[key])).map(([key]) => key);
|
|
69
|
+
}
|
|
70
|
+
/** Payloads from v0.15.1 and earlier wrote strokes without a paint type; they are solid. */
|
|
71
|
+
function withStrokeTypes(fields) {
|
|
72
|
+
if (!Array.isArray(fields.strokes)) return fields;
|
|
73
|
+
const strokes = fields.strokes.map((stroke) => isPlainObject(stroke) && !Object.hasOwn(stroke, "type") ? {
|
|
74
|
+
...stroke,
|
|
75
|
+
type: "SOLID"
|
|
76
|
+
} : stroke);
|
|
77
|
+
return {
|
|
78
|
+
...fields,
|
|
79
|
+
strokes
|
|
80
|
+
};
|
|
81
|
+
}
|
|
46
82
|
/** Clipboard HTML is writable by any application, so the payload is validated before paste. */
|
|
47
83
|
const pairdrawClipboardSchema = v.pipe(v.string(), v.parseJson(), v.object({
|
|
48
84
|
format: v.literal("pairdraw/v1"),
|
|
@@ -87,10 +123,14 @@ function legacyInstanceOverrides(nodeId, overrides) {
|
|
|
87
123
|
return state;
|
|
88
124
|
}
|
|
89
125
|
function restoreGeometry(paths) {
|
|
90
|
-
return (paths ?? []).map((path) =>
|
|
91
|
-
...path
|
|
92
|
-
|
|
93
|
-
|
|
126
|
+
return (paths ?? []).map((path) => {
|
|
127
|
+
const { fills, ...rest } = path;
|
|
128
|
+
return {
|
|
129
|
+
...rest,
|
|
130
|
+
...v.is(paintsSchema, fills) ? { fills } : {},
|
|
131
|
+
commandsBlob: Uint8Array.from(Object.values(path.commandsBlob))
|
|
132
|
+
};
|
|
133
|
+
});
|
|
94
134
|
}
|
|
95
135
|
/** Clipboard HTML comes from other applications, so its Base64 is checked before decoding. */
|
|
96
136
|
function clipboardBytes(value) {
|
|
@@ -99,12 +139,18 @@ function clipboardBytes(value) {
|
|
|
99
139
|
}
|
|
100
140
|
function restoreNodeData(nodes) {
|
|
101
141
|
return nodes.map((node) => {
|
|
102
|
-
const { children, instanceOverrides, overrides, textPicture, ...
|
|
142
|
+
const { children, instanceOverrides, overrides, textPicture, ...fields } = node;
|
|
143
|
+
const typed = withStrokeTypes(fields);
|
|
144
|
+
const rest = {
|
|
145
|
+
...omit(typed, malformedFields(typed)),
|
|
146
|
+
id: node.id,
|
|
147
|
+
type: node.type
|
|
148
|
+
};
|
|
103
149
|
const overrideState = instanceOverrides ? deserializeInstanceOverrideState(instanceOverrides) : legacyInstanceOverrides(rest.id, overrides);
|
|
104
150
|
return {
|
|
105
151
|
...rest,
|
|
106
|
-
fillGeometry: restoreGeometry(
|
|
107
|
-
strokeGeometry: restoreGeometry(
|
|
152
|
+
fillGeometry: restoreGeometry(node.fillGeometry),
|
|
153
|
+
strokeGeometry: restoreGeometry(node.strokeGeometry),
|
|
108
154
|
instanceOverrides: overrideState,
|
|
109
155
|
textPicture: typeof textPicture === "string" ? clipboardBytes(textPicture) : textPicture,
|
|
110
156
|
...children ? { children: restoreNodeData(children) } : {}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pairdraw.js","names":[],"sources":["../../src/clipboard/pairdraw.ts"],"sourcesContent":["import { deflateSync, inflateSync } from 'fflate'\nimport { fromUint8Array, isValid, toUint8Array } from 'js-base64'\nimport * as v from 'valibot'\n\nimport type {\n GeometryPath,\n NodeType,\n SceneGraph,\n SceneNode,\n WindingRule\n} from '@pairdraw/scene-graph'\nimport {\n createInstanceOverrideState,\n deserializeInstanceOverrideState,\n serializeInstanceOverrideState,\n setInstanceOverride,\n type InstanceOverrideState\n} from '@pairdraw/scene-graph/instances/overrides'\nimport type { JSONObject } from '@pairdraw/scene-graph/primitives'\n\nimport type { ClipboardSnapshot } from '#core/editor/clipboard/copy'\n\nconst NODE_TYPES: Record<NodeType, true> = {\n CANVAS: true,\n FRAME: true,\n RECTANGLE: true,\n ROUNDED_RECTANGLE: true,\n ELLIPSE: true,\n TEXT: true,\n LINE: true,\n STAR: true,\n POLYGON: true,\n VECTOR: true,\n BOOLEAN_OPERATION: true,\n GROUP: true,\n SECTION: true,\n COMPONENT: true,\n COMPONENT_SET: true,\n INSTANCE: true,\n CONNECTOR: true,\n SHAPE_WITH_TEXT: true,\n STICKY: true,\n SCRIPT: true\n}\n\ninterface SerializedGeometryPath {\n windingRule: WindingRule\n commandsBlob: Record<string, number>\n [key: string]: unknown\n}\n\n/** The node fields paste dereferences; the remaining SceneNode fields pass through. */\ninterface SerializedClipboardNode {\n id: string\n type: NodeType\n x: number\n y: number\n overrides?: Record<string, unknown>\n instanceOverrides?: unknown\n textPicture?: string | null\n fillGeometry?: SerializedGeometryPath[]\n strokeGeometry?: SerializedGeometryPath[]\n children?: SerializedClipboardNode[]\n [key: string]: unknown\n}\n\nconst finiteNumberSchema = v.pipe(v.number(), v.finite())\nconst byteSchema = v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(255))\n\nconst serializedGeometrySchema = v.optional(\n v.array(\n v.looseObject({\n windingRule: v.picklist(['NONZERO', 'EVENODD']),\n commandsBlob: v.record(v.string(), byteSchema)\n })\n )\n)\n\nconst serializedClipboardNodeSchema: v.GenericSchema<unknown, SerializedClipboardNode> =\n v.looseObject({\n id: v.string(),\n type: v.custom<NodeType>(\n (value) => typeof value === 'string' && Object.hasOwn(NODE_TYPES, value)\n ),\n // Older clipboard payloads may omit a position; paste offsets from the origin then.\n x: v.optional(finiteNumberSchema, 0),\n y: v.optional(finiteNumberSchema, 0),\n overrides: v.optional(v.record(v.string(), v.unknown())),\n instanceOverrides: v.optional(v.unknown()),\n textPicture: v.optional(v.nullable(v.string())),\n fillGeometry: serializedGeometrySchema,\n strokeGeometry: serializedGeometrySchema,\n children: v.optional(v.array(v.lazy(() => serializedClipboardNodeSchema)))\n })\n\n/** Clipboard HTML is writable by any application, so the payload is validated before paste. */\nconst pairdrawClipboardSchema = v.pipe(\n v.string(),\n v.parseJson(),\n v.object({\n format: v.literal('pairdraw/v1'),\n nodes: v.array(serializedClipboardNodeSchema),\n images: v.optional(v.record(v.string(), v.unknown()))\n })\n)\n\ntype ClipboardNode = SceneNode & { children?: ClipboardNode[] }\n\nexport type PairdrawClipboardData = Pick<ClipboardSnapshot, 'nodes' | 'images'>\n\nexport function parsePairdrawClipboard(html: string): PairdrawClipboardData | null {\n const match = html.match(/<!--\\(pairdraw\\)(.*?)\\(\\/pairdraw\\)-->/s)\n if (!match) return null\n\n try {\n const raw = clipboardBytes(match[1])\n let bytes: Uint8Array\n try {\n bytes = inflateSync(raw)\n } catch {\n bytes = raw\n }\n const decoded = v.safeParse(pairdrawClipboardSchema, new TextDecoder().decode(bytes))\n if (!decoded.success) {\n console.warn('Ignoring malformed Pairdraw clipboard data:', v.summarize(decoded.issues))\n return null\n }\n const nodes = restoreNodeData(decoded.output.nodes)\n const images = new Map<string, Uint8Array>()\n for (const [hash, b64] of Object.entries(decoded.output.images ?? {})) {\n if (typeof b64 === 'string') images.set(hash, clipboardBytes(b64))\n }\n return { nodes, images }\n } catch (e) {\n console.warn('Failed to parse Pairdraw clipboard data:', e)\n }\n return null\n}\n\nfunction legacyInstanceOverrides(\n nodeId: string,\n overrides: Record<string, unknown> | undefined\n): InstanceOverrideState {\n const state = createInstanceOverrideState()\n for (const [key, value] of Object.entries(overrides ?? {})) {\n const separator = key.lastIndexOf(':')\n if (separator === -1) {\n setInstanceOverride(state, nodeId, nodeId, key, value)\n } else {\n setInstanceOverride(state, nodeId, key.slice(0, separator), key.slice(separator + 1), value)\n }\n }\n return state\n}\n\nfunction restoreGeometry(paths: SerializedGeometryPath[] | undefined): GeometryPath[] {\n return (paths ?? []).map((path) => ({\n ...path,\n commandsBlob: Uint8Array.from(Object.values(path.commandsBlob))\n }))\n}\n\n/** Clipboard HTML comes from other applications, so its Base64 is checked before decoding. */\nfunction clipboardBytes(value: string): Uint8Array {\n if (!isValid(value)) throw new TypeError('Invalid Base64 string')\n return toUint8Array(value)\n}\n\nfunction restoreNodeData(nodes: SerializedClipboardNode[]): ClipboardNode[] {\n return nodes.map((node) => {\n const { children, instanceOverrides, overrides, textPicture, ...rest } = node\n const overrideState = instanceOverrides\n ? deserializeInstanceOverrideState(instanceOverrides)\n : legacyInstanceOverrides(rest.id, overrides)\n return {\n ...rest,\n fillGeometry: restoreGeometry(rest.fillGeometry),\n strokeGeometry: restoreGeometry(rest.strokeGeometry),\n instanceOverrides: overrideState,\n textPicture: typeof textPicture === 'string' ? clipboardBytes(textPicture) : textPicture,\n ...(children ? { children: restoreNodeData(children) } : {})\n } as ClipboardNode\n })\n}\n\nexport type TextPictureBuilder = (node: SceneNode) => Uint8Array | null\n\nfunction collectImageHashes(nodes: SceneNode[], graph: SceneGraph): Set<string> {\n const hashes = new Set<string>()\n function walk(nodeList: SceneNode[]) {\n for (const node of nodeList) {\n for (const fill of node.fills) {\n if (fill.imageHash) hashes.add(fill.imageHash)\n }\n walk(graph.getChildren(node.id))\n }\n }\n walk(nodes)\n return hashes\n}\n\nexport function buildPairdrawClipboardHTML(\n nodes: SceneNode[],\n graph: SceneGraph,\n textPictureBuilder?: TextPictureBuilder\n): string {\n const nodeTree = collectNodeTree(nodes, graph, textPictureBuilder)\n const hashes = collectImageHashes(nodes, graph)\n const images: Record<string, string> = {}\n for (const hash of hashes) {\n const bytes = graph.images.get(hash)\n if (bytes) images[hash] = fromUint8Array(bytes)\n }\n const data = {\n format: 'pairdraw/v1',\n nodes: nodeTree,\n images\n }\n const compressed = deflateSync(new TextEncoder().encode(JSON.stringify(data)))\n return `<!--(pairdraw)${fromUint8Array(compressed)}(/pairdraw)-->`\n}\n\nfunction collectNodeTree(\n nodes: SceneNode[],\n graph: SceneGraph,\n textPictureBuilder?: TextPictureBuilder\n): JSONObject[] {\n return nodes.map((node) => {\n const children = graph.getChildren(node.id)\n const serialized: Record<string, unknown> = {\n ...node,\n instanceOverrides: serializeInstanceOverrideState(node.instanceOverrides)\n }\n\n if (node.type === 'TEXT' && node.text && textPictureBuilder) {\n const pic = node.textPicture ?? textPictureBuilder(node)\n if (pic) serialized.textPicture = fromUint8Array(pic)\n } else {\n delete serialized.textPicture\n }\n\n if (children.length > 0) {\n serialized.children = collectNodeTree(children, graph, textPictureBuilder)\n }\n return serialized\n })\n}\n"],"mappings":";;;;;AAsBA,MAAM,aAAqC;CACzC,QAAQ;CACR,OAAO;CACP,WAAW;CACX,mBAAmB;CACnB,SAAS;CACT,MAAM;CACN,MAAM;CACN,MAAM;CACN,SAAS;CACT,QAAQ;CACR,mBAAmB;CACnB,OAAO;CACP,SAAS;CACT,WAAW;CACX,eAAe;CACf,UAAU;CACV,WAAW;CACX,iBAAiB;CACjB,QAAQ;CACR,QAAQ;AACV;AAuBA,MAAM,qBAAqB,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC;AACxD,MAAM,aAAa,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,QAAQ,GAAG,EAAE,SAAS,CAAC,GAAG,EAAE,SAAS,GAAG,CAAC;AAEjF,MAAM,2BAA2B,EAAE,SACjC,EAAE,MACA,EAAE,YAAY;CACZ,aAAa,EAAE,SAAS,CAAC,WAAW,SAAS,CAAC;CAC9C,cAAc,EAAE,OAAO,EAAE,OAAO,GAAG,UAAU;AAC/C,CAAC,CACH,CACF;AAEA,MAAM,gCACJ,EAAE,YAAY;CACZ,IAAI,EAAE,OAAO;CACb,MAAM,EAAE,QACL,UAAU,OAAO,UAAU,YAAY,OAAO,OAAO,YAAY,KAAK,CACzE;CAEA,GAAG,EAAE,SAAS,oBAAoB,CAAC;CACnC,GAAG,EAAE,SAAS,oBAAoB,CAAC;CACnC,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,GA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IAAI,KAAK,WAAW,OAAO,IAAI,KAAK,SAAS;GAE/C,KAAK,MAAM,YAAY,KAAK,EAAE,CAAC;EACjC;CACF;CACA,KAAK,KAAK;CACV,OAAO;AACT;AAEA,SAAgB,2BACd,OACA,OACA,oBACQ;CACR,MAAM,WAAW,gBAAgB,OAAO,OAAO,kBAAkB;CACjE,MAAM,SAAS,mBAAmB,OAAO,KAAK;CAC9C,MAAM,SAAiC,CAAC;CACxC,KAAK,MAAM,QAAQ,QAAQ;EACzB,MAAM,QAAQ,MAAM,OAAO,IAAI,IAAI;EACnC,IAAI,OAAO,OAAO,QAAQ,eAAe,KAAK;CAChD;CACA,MAAM,OAAO;EACX,QAAQ;EACR,OAAO;EACP;CACF;CACA,MAAM,aAAa,YAAY,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,UAAU,IAAI,CAAC,CAAC;CAC7E,OAAO,iBAAiB,eAAe,UAAU,EAAE;AACrD;AAEA,SAAS,gBACP,OACA,OACA,oBACc;CACd,OAAO,MAAM,KAAK,SAAS;EACzB,MAAM,WAAW,MAAM,YAAY,KAAK,EAAE;EAC1C,MAAM,aAAsC;GAC1C,GAAG;GACH,mBAAmB,+BAA+B,KAAK,iBAAiB;EAC1E;EAEA,IAAI,KAAK,SAAS,UAAU,KAAK,QAAQ,oBAAoB;GAC3D,MAAM,MAAM,KAAK,eAAe,mBAAmB,IAAI;GACvD,IAAI,KAAK,WAAW,cAAc,eAAe,GAAG;EACtD,OACE,OAAO,WAAW;EAGpB,IAAI,SAAS,SAAS,GACpB,WAAW,WAAW,gBAAgB,UAAU,OAAO,kBAAkB;EAE3E,OAAO;CACT,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"pairdraw.js","names":[],"sources":["../../src/clipboard/pairdraw.ts"],"sourcesContent":["import { isPlainObject, omit } from 'es-toolkit'\nimport { deflateSync, inflateSync } from 'fflate'\nimport { fromUint8Array, isValid, toUint8Array } from 'js-base64'\nimport * as v from 'valibot'\n\nimport type {\n GeometryPath,\n NodeType,\n SceneGraph,\n SceneNode,\n WindingRule\n} from '@pairdraw/scene-graph'\nimport {\n createInstanceOverrideState,\n deserializeInstanceOverrideState,\n serializeInstanceOverrideState,\n setInstanceOverride,\n type InstanceOverrideState\n} from '@pairdraw/scene-graph/instances/overrides'\nimport { fillSchema } from '@pairdraw/scene-graph/paints'\nimport type { JSONObject } from '@pairdraw/scene-graph/primitives'\n\nimport type { ClipboardSnapshot } from '#core/editor/clipboard/copy'\n\nconst NODE_TYPES: Record<NodeType, true> = {\n CANVAS: true,\n FRAME: true,\n RECTANGLE: true,\n ROUNDED_RECTANGLE: true,\n ELLIPSE: true,\n TEXT: true,\n LINE: true,\n STAR: true,\n POLYGON: true,\n VECTOR: true,\n BOOLEAN_OPERATION: true,\n GROUP: true,\n SECTION: true,\n COMPONENT: true,\n COMPONENT_SET: true,\n INSTANCE: true,\n CONNECTOR: true,\n SHAPE_WITH_TEXT: true,\n STICKY: true,\n SCRIPT: true\n}\n\ninterface SerializedGeometryPath {\n windingRule: WindingRule\n commandsBlob: Record<string, number>\n [key: string]: unknown\n}\n\n/** The node fields paste dereferences; the remaining SceneNode fields pass through. */\ninterface SerializedClipboardNode {\n id: string\n type: NodeType\n x: number\n y: number\n overrides?: Record<string, unknown>\n instanceOverrides?: unknown\n textPicture?: string | null\n fillGeometry?: SerializedGeometryPath[]\n strokeGeometry?: SerializedGeometryPath[]\n children?: SerializedClipboardNode[]\n [key: string]: unknown\n}\n\nconst finiteNumberSchema = v.pipe(v.number(), v.finite())\nconst byteSchema = v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(255))\n\nconst serializedGeometrySchema = v.optional(\n v.array(\n v.looseObject({\n windingRule: v.picklist(['NONZERO', 'EVENODD']),\n commandsBlob: v.record(v.string(), byteSchema)\n })\n )\n)\n\nconst serializedClipboardNodeSchema: v.GenericSchema<unknown, SerializedClipboardNode> =\n v.looseObject({\n id: v.string(),\n type: v.custom<NodeType>(\n (value) => typeof value === 'string' && Object.hasOwn(NODE_TYPES, value)\n ),\n // Older clipboard payloads may omit a position; paste offsets from the origin then.\n x: v.optional(finiteNumberSchema, 0),\n y: v.optional(finiteNumberSchema, 0),\n overrides: v.optional(v.record(v.string(), v.unknown())),\n instanceOverrides: v.optional(v.unknown()),\n textPicture: v.optional(v.nullable(v.string())),\n fillGeometry: serializedGeometrySchema,\n strokeGeometry: serializedGeometrySchema,\n children: v.optional(v.array(v.lazy(() => serializedClipboardNodeSchema)))\n })\n\nconst paintsSchema = v.array(fillSchema)\nconst effectsSchema = v.array(v.unknown())\nconst sourceMetadataSchema = v.looseObject({\n format: v.nullable(v.literal('fig')),\n id: v.nullable(v.string()),\n orderKey: v.nullable(v.string()),\n editedFields: v.array(v.string()),\n fig: v.looseObject({})\n})\n\n/**\n * Fields the graph reads without checking. `v.is` checks them without parsing, which would reorder\n * paint keys; a malformed field is dropped and the rest of the layer kept.\n */\nconst CHECKED_FIELDS: [string, v.GenericSchema][] = [\n ['fills', paintsSchema],\n ['strokes', paintsSchema],\n ['effects', effectsSchema],\n ['source', sourceMetadataSchema]\n]\n\nfunction malformedFields(fields: Record<string, unknown>, checked = CHECKED_FIELDS): string[] {\n return checked\n .filter(([key, schema]) => key in fields && !v.is(schema, fields[key]))\n .map(([key]) => key)\n}\n\n/** Payloads from v0.15.1 and earlier wrote strokes without a paint type; they are solid. */\nfunction withStrokeTypes(fields: Record<string, unknown>): Record<string, unknown> {\n if (!Array.isArray(fields.strokes)) return fields\n const strokes = fields.strokes.map((stroke: unknown) =>\n isPlainObject(stroke) && !Object.hasOwn(stroke, 'type') ? { ...stroke, type: 'SOLID' } : stroke\n )\n return { ...fields, strokes }\n}\n\n/** Clipboard HTML is writable by any application, so the payload is validated before paste. */\nconst pairdrawClipboardSchema = v.pipe(\n v.string(),\n v.parseJson(),\n v.object({\n format: v.literal('pairdraw/v1'),\n nodes: v.array(serializedClipboardNodeSchema),\n images: v.optional(v.record(v.string(), v.unknown()))\n })\n)\n\ntype ClipboardNode = SceneNode & { children?: ClipboardNode[] }\n\nexport type PairdrawClipboardData = Pick<ClipboardSnapshot, 'nodes' | 'images'>\n\nexport function parsePairdrawClipboard(html: string): PairdrawClipboardData | null {\n const match = html.match(/<!--\\(pairdraw\\)(.*?)\\(\\/pairdraw\\)-->/s)\n if (!match) return null\n\n try {\n const raw = clipboardBytes(match[1])\n let bytes: Uint8Array\n try {\n bytes = inflateSync(raw)\n } catch {\n bytes = raw\n }\n const decoded = v.safeParse(pairdrawClipboardSchema, new TextDecoder().decode(bytes))\n if (!decoded.success) {\n console.warn('Ignoring malformed Pairdraw clipboard data:', v.summarize(decoded.issues))\n return null\n }\n const nodes = restoreNodeData(decoded.output.nodes)\n const images = new Map<string, Uint8Array>()\n for (const [hash, b64] of Object.entries(decoded.output.images ?? {})) {\n if (typeof b64 === 'string') images.set(hash, clipboardBytes(b64))\n }\n return { nodes, images }\n } catch (e) {\n console.warn('Failed to parse Pairdraw clipboard data:', e)\n }\n return null\n}\n\nfunction legacyInstanceOverrides(\n nodeId: string,\n overrides: Record<string, unknown> | undefined\n): InstanceOverrideState {\n const state = createInstanceOverrideState()\n for (const [key, value] of Object.entries(overrides ?? {})) {\n const separator = key.lastIndexOf(':')\n if (separator === -1) {\n setInstanceOverride(state, nodeId, nodeId, key, value)\n } else {\n setInstanceOverride(state, nodeId, key.slice(0, separator), key.slice(separator + 1), value)\n }\n }\n return state\n}\n\nfunction restoreGeometry(paths: SerializedGeometryPath[] | undefined): GeometryPath[] {\n return (paths ?? []).map((path) => {\n const { fills, ...rest } = path\n return {\n ...rest,\n ...(v.is(paintsSchema, fills) ? { fills } : {}),\n commandsBlob: Uint8Array.from(Object.values(path.commandsBlob))\n }\n })\n}\n\n/** Clipboard HTML comes from other applications, so its Base64 is checked before decoding. */\nfunction clipboardBytes(value: string): Uint8Array {\n if (!isValid(value)) throw new TypeError('Invalid Base64 string')\n return toUint8Array(value)\n}\n\nfunction restoreNodeData(nodes: SerializedClipboardNode[]): ClipboardNode[] {\n return nodes.map((node) => {\n const { children, instanceOverrides, overrides, textPicture, ...fields } = node\n const typed = withStrokeTypes(fields)\n const rest = { ...omit(typed, malformedFields(typed)), id: node.id, type: node.type }\n const overrideState = instanceOverrides\n ? deserializeInstanceOverrideState(instanceOverrides)\n : legacyInstanceOverrides(rest.id, overrides)\n return {\n ...rest,\n fillGeometry: restoreGeometry(node.fillGeometry),\n strokeGeometry: restoreGeometry(node.strokeGeometry),\n instanceOverrides: overrideState,\n textPicture: typeof textPicture === 'string' ? clipboardBytes(textPicture) : textPicture,\n ...(children ? { children: restoreNodeData(children) } : {})\n } as ClipboardNode\n })\n}\n\nexport type TextPictureBuilder = (node: SceneNode) => Uint8Array | null\n\nfunction collectImageHashes(nodes: SceneNode[], graph: SceneGraph): Set<string> {\n const hashes = new Set<string>()\n function walk(nodeList: SceneNode[]) {\n for (const node of nodeList) {\n for (const fill of node.fills) {\n if (fill.imageHash) hashes.add(fill.imageHash)\n }\n walk(graph.getChildren(node.id))\n }\n }\n walk(nodes)\n return hashes\n}\n\nexport function buildPairdrawClipboardHTML(\n nodes: SceneNode[],\n graph: SceneGraph,\n textPictureBuilder?: TextPictureBuilder\n): string {\n const nodeTree = collectNodeTree(nodes, graph, textPictureBuilder)\n const hashes = collectImageHashes(nodes, graph)\n const images: Record<string, string> = {}\n for (const hash of hashes) {\n const bytes = graph.images.get(hash)\n if (bytes) images[hash] = fromUint8Array(bytes)\n }\n const data = {\n format: 'pairdraw/v1',\n nodes: nodeTree,\n images\n }\n const compressed = deflateSync(new TextEncoder().encode(JSON.stringify(data)))\n return `<!--(pairdraw)${fromUint8Array(compressed)}(/pairdraw)-->`\n}\n\nfunction collectNodeTree(\n nodes: SceneNode[],\n graph: SceneGraph,\n textPictureBuilder?: TextPictureBuilder\n): JSONObject[] {\n return nodes.map((node) => {\n const children = graph.getChildren(node.id)\n const serialized: Record<string, unknown> = {\n ...node,\n instanceOverrides: serializeInstanceOverrideState(node.instanceOverrides)\n }\n\n if (node.type === 'TEXT' && node.text && textPictureBuilder) {\n const pic = node.textPicture ?? textPictureBuilder(node)\n if (pic) serialized.textPicture = fromUint8Array(pic)\n } else {\n delete serialized.textPicture\n }\n\n if (children.length > 0) {\n serialized.children = collectNodeTree(children, graph, textPictureBuilder)\n }\n return serialized\n })\n}\n"],"mappings":";;;;;;;AAwBA,MAAM,aAAqC;CACzC,QAAQ;CACR,OAAO;CACP,WAAW;CACX,mBAAmB;CACnB,SAAS;CACT,MAAM;CACN,MAAM;CACN,MAAM;CACN,SAAS;CACT,QAAQ;CACR,mBAAmB;CACnB,OAAO;CACP,SAAS;CACT,WAAW;CACX,eAAe;CACf,UAAU;CACV,WAAW;CACX,iBAAiB;CACjB,QAAQ;CACR,QAAQ;AACV;AAuBA,MAAM,qBAAqB,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC;AACxD,MAAM,aAAa,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,QAAQ,GAAG,EAAE,SAAS,CAAC,GAAG,EAAE,SAAS,GAAG,CAAC;AAEjF,MAAM,2BAA2B,EAAE,SACjC,EAAE,MACA,EAAE,YAAY;CACZ,aAAa,EAAE,SAAS,CAAC,WAAW,SAAS,CAAC;CAC9C,cAAc,EAAE,OAAO,EAAE,OAAO,GAAG,UAAU;AAC/C,CAAC,CACH,CACF;AAEA,MAAM,gCACJ,EAAE,YAAY;CACZ,IAAI,EAAE,OAAO;CACb,MAAM,EAAE,QACL,UAAU,OAAO,UAAU,YAAY,OAAO,OAAO,YAAY,KAAK,CACzE;CAEA,GAAG,EAAE,SAAS,oBAAoB,CAAC;CACnC,GAAG,EAAE,SAAS,oBAAoB,CAAC;CACnC,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC;CACvD,mBAAmB,EAAE,SAAS,EAAE,QAAQ,CAAC;CACzC,aAAa,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;CAC9C,cAAc;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gB,OAAO,OAAO,kBAAkB;CACjE,MAAM,SAAS,mBAAmB,OAAO,KAAK;CAC9C,MAAM,SAAiC,CAAC;CACxC,KAAK,MAAM,QAAQ,QAAQ;EACzB,MAAM,QAAQ,MAAM,OAAO,IAAI,IAAI;EACnC,IAAI,OAAO,OAAO,QAAQ,eAAe,KAAK;CAChD;CACA,MAAM,OAAO;EACX,QAAQ;EACR,OAAO;EACP;CACF;CACA,MAAM,aAAa,YAAY,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,UAAU,IAAI,CAAC,CAAC;CAC7E,OAAO,iBAAiB,eAAe,UAAU,EAAE;AACrD;AAEA,SAAS,gBACP,OACA,OACA,oBACc;CACd,OAAO,MAAM,KAAK,SAAS;EACzB,MAAM,WAAW,MAAM,YAAY,KAAK,EAAE;EAC1C,MAAM,aAAsC;GAC1C,GAAG;GACH,mBAAmB,+BAA+B,KAAK,iBAAiB;EAC1E;EAEA,IAAI,KAAK,SAAS,UAAU,KAAK,QAAQ,oBAAoB;GAC3D,MAAM,MAAM,KAAK,eAAe,mBAAmB,IAAI;GACvD,IAAI,KAAK,WAAW,cAAc,eAAe,GAAG;EACtD,OACE,OAAO,WAAW;EAGpB,IAAI,SAAS,SAAS,GACpB,WAAW,WAAW,gBAAgB,UAAU,OAAO,kBAAkB;EAE3E,OAAO;CACT,CAAC;AACH"}
|
|
@@ -33,8 +33,13 @@ function createJSXPreviewRecorder(ck) {
|
|
|
33
33
|
const surface = ck.MakeSurface(1, 1);
|
|
34
34
|
if (!surface) return null;
|
|
35
35
|
const created = new SkiaRenderer(ck, surface);
|
|
36
|
+
try {
|
|
37
|
+
await created.loadFonts();
|
|
38
|
+
} catch (error) {
|
|
39
|
+
created.destroy();
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
36
42
|
renderer = created;
|
|
37
|
-
await created.loadFonts();
|
|
38
43
|
return created;
|
|
39
44
|
}
|
|
40
45
|
async function recordNext(staged, signal) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"picture.js","names":[],"sources":["../../../src/design-jsx/preview/picture.ts"],"sourcesContent":["import type { CanvasKit, SkPicture } from 'canvaskit-wasm'\n\nimport { computeDescendantVisualBounds, type VisualBounds } from '@pairdraw/scene-graph/geometry'\n\nimport { SkiaRenderer } from '#core/canvas/renderer'\nimport { recordWorldPicture } from '#core/canvas/renderer/picture'\n\nimport type { StagedJSXPreview } from './stage'\n\nconst MAX_PREVIEW_DIMENSION = 8192\n\nfunction fitsPreview({ minX, minY, maxX, maxY }: VisualBounds): boolean {\n const width = maxX - minX\n const height = maxY - minY\n return (\n Number.isFinite(width + height) &&\n width > 0 &&\n height > 0 &&\n width <= MAX_PREVIEW_DIMENSION &&\n height <= MAX_PREVIEW_DIMENSION\n )\n}\n\nasync function recordStaged(\n renderer: SkiaRenderer,\n { graph, pageId, nodeIds }: StagedJSXPreview,\n signal: AbortSignal\n): Promise<SkPicture | null> {\n renderer.pageId = pageId\n await renderer.prepareForExport(graph, pageId, nodeIds)\n signal.throwIfAborted()\n const bounds = computeDescendantVisualBounds(\n nodeIds,\n (id) => graph.getNode(id),\n (id) => graph.getAbsolutePosition(id)\n )\n if (!bounds || !fitsPreview(bounds)) return null\n return recordWorldPicture(renderer, bounds, (canvas) => {\n for (const id of nodeIds) renderer.renderNode(canvas, graph, id, {})\n })\n}\n\nexport interface JSXPreviewRecorder {\n /** Record `staged` as a picture the caller owns, even when its request becomes stale. */\n record(staged: StagedJSXPreview, signal: AbortSignal): Promise<SkPicture | null>\n /** Free the private renderer once the records already asked for finish. */\n destroy(): void\n}\n\n/**\n * A private renderer that records preview pictures one at a time, for previews of JSX that is\n * still streaming. Each record draws a new graph, so only what identical text shaped to carries\n * over: a preview that grows measures just its new text instead of all of it again. Neither\n * speculative nodes nor renderer caches enter the live document.\n */\nexport function createJSXPreviewRecorder(ck: CanvasKit): JSXPreviewRecorder {\n let renderer: SkiaRenderer | null = null\n let destroyed = false\n // Records share one renderer, whose caches and page one record at a time may use.\n let queue: Promise<unknown> = Promise.resolve()\n\n async function rendererFor(): Promise<SkiaRenderer | null> {\n if (renderer) return renderer\n const surface = ck.MakeSurface(1, 1)\n if (!surface) return null\n const created = new SkiaRenderer(ck, surface)\n
|
|
1
|
+
{"version":3,"file":"picture.js","names":[],"sources":["../../../src/design-jsx/preview/picture.ts"],"sourcesContent":["import type { CanvasKit, SkPicture } from 'canvaskit-wasm'\n\nimport { computeDescendantVisualBounds, type VisualBounds } from '@pairdraw/scene-graph/geometry'\n\nimport { SkiaRenderer } from '#core/canvas/renderer'\nimport { recordWorldPicture } from '#core/canvas/renderer/picture'\n\nimport type { StagedJSXPreview } from './stage'\n\nconst MAX_PREVIEW_DIMENSION = 8192\n\nfunction fitsPreview({ minX, minY, maxX, maxY }: VisualBounds): boolean {\n const width = maxX - minX\n const height = maxY - minY\n return (\n Number.isFinite(width + height) &&\n width > 0 &&\n height > 0 &&\n width <= MAX_PREVIEW_DIMENSION &&\n height <= MAX_PREVIEW_DIMENSION\n )\n}\n\nasync function recordStaged(\n renderer: SkiaRenderer,\n { graph, pageId, nodeIds }: StagedJSXPreview,\n signal: AbortSignal\n): Promise<SkPicture | null> {\n renderer.pageId = pageId\n await renderer.prepareForExport(graph, pageId, nodeIds)\n signal.throwIfAborted()\n const bounds = computeDescendantVisualBounds(\n nodeIds,\n (id) => graph.getNode(id),\n (id) => graph.getAbsolutePosition(id)\n )\n if (!bounds || !fitsPreview(bounds)) return null\n return recordWorldPicture(renderer, bounds, (canvas) => {\n for (const id of nodeIds) renderer.renderNode(canvas, graph, id, {})\n })\n}\n\nexport interface JSXPreviewRecorder {\n /** Record `staged` as a picture the caller owns, even when its request becomes stale. */\n record(staged: StagedJSXPreview, signal: AbortSignal): Promise<SkPicture | null>\n /** Free the private renderer once the records already asked for finish. */\n destroy(): void\n}\n\n/**\n * A private renderer that records preview pictures one at a time, for previews of JSX that is\n * still streaming. Each record draws a new graph, so only what identical text shaped to carries\n * over: a preview that grows measures just its new text instead of all of it again. Neither\n * speculative nodes nor renderer caches enter the live document.\n */\nexport function createJSXPreviewRecorder(ck: CanvasKit): JSXPreviewRecorder {\n let renderer: SkiaRenderer | null = null\n let destroyed = false\n // Records share one renderer, whose caches and page one record at a time may use.\n let queue: Promise<unknown> = Promise.resolve()\n\n async function rendererFor(): Promise<SkiaRenderer | null> {\n if (renderer) return renderer\n const surface = ck.MakeSurface(1, 1)\n if (!surface) return null\n const created = new SkiaRenderer(ck, surface)\n // Loading fonts drops every cache, so it happens once rather than before each record; a\n // renderer whose fonts failed to load is not kept, so the next record tries again.\n try {\n await created.loadFonts()\n } catch (error) {\n created.destroy()\n throw error\n }\n renderer = created\n return created\n }\n\n async function recordNext(\n staged: StagedJSXPreview,\n signal: AbortSignal\n ): Promise<SkPicture | null> {\n signal.throwIfAborted()\n const current = destroyed ? null : await rendererFor()\n if (!current) return null\n signal.throwIfAborted()\n // Layer IDs repeat between staged graphs with different content, so nothing keyed by them stays.\n current.invalidateAllPictures({ keepShapedText: true })\n return recordStaged(current, staged, signal)\n }\n\n return {\n record(staged, signal) {\n const result = queue.then(() => recordNext(staged, signal))\n queue = result.catch(() => undefined)\n return result\n },\n destroy() {\n destroyed = true\n const release = () => {\n renderer?.destroy()\n renderer = null\n }\n queue = queue.then(release)\n }\n }\n}\n"],"mappings":";;;;AASA,MAAM,wBAAwB;AAE9B,SAAS,YAAY,EAAE,MAAM,MAAM,MAAM,QAA+B;CACtE,MAAM,QAAQ,OAAO;CACrB,MAAM,SAAS,OAAO;CACtB,OACE,OAAO,SAAS,QAAQ,MAAM,KAC9B,QAAQ,KACR,SAAS,KACT,SAAS,yBACT,UAAU;AAEd;AAEA,eAAe,aACb,UACA,EAAE,OAAO,QAAQ,WACjB,QAC2B;CAC3B,SAAS,SAAS;CAClB,MAAM,SAAS,iBAAiB,OAAO,QAAQ,OAAO;CACtD,OAAO,eAAe;CACtB,MAAM,SAAS,8BACb,UACC,OAAO,MAAM,QAAQ,EAAE,IACvB,OAAO,MAAM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
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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"alignment.d.ts","names":[],"sources":["../../src/editor/alignment.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"alignment.d.ts","names":[],"sources":["../../src/editor/alignment.ts"],"mappings":";;;KAkIK;;UAGY;EACf,MAAM;;EAEN;;iBAqCc,uBAAuB,KAAK;EAyD/B,aAAA,mBAAQ,iCACc;6CA1DS;EAmGR,kBAAA;EA0DI,sBAAA;EA5GD,qBAAA;EAkCH,kBAAA,mBAAQ;EA3EP,mBAAA,+BAAoB;EAYjB,sBAAA,4BAAiB;;EAiI3B,YAAA,mBAAQ,MAAQ;;EALhB,YAAA"}
|