@pairdraw/core 0.21.0 → 0.21.1

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.
Files changed (42) hide show
  1. package/dist/canvas/shaders/compile.d.ts +3 -1
  2. package/dist/canvas/shaders/compile.d.ts.map +1 -1
  3. package/dist/canvas/shaders/compile.js +12 -3
  4. package/dist/canvas/shaders/compile.js.map +1 -1
  5. package/dist/canvas/shaders/draw.d.ts.map +1 -1
  6. package/dist/canvas/shaders/draw.js +10 -3
  7. package/dist/canvas/shaders/draw.js.map +1 -1
  8. package/dist/canvas/shaders/effect.d.ts.map +1 -1
  9. package/dist/canvas/shaders/effect.js +6 -16
  10. package/dist/canvas/shaders/effect.js.map +1 -1
  11. package/dist/editor/bridges/undo.d.ts +1 -1
  12. package/dist/editor/clipboard/export.js +2 -2
  13. package/dist/editor/clipboard/export.js.map +1 -1
  14. package/dist/editor/create.d.ts +1 -1
  15. package/dist/io/formats/drawio/warnings.d.ts +17 -2
  16. package/dist/io/formats/drawio/warnings.d.ts.map +1 -1
  17. package/dist/io/formats/drawio/warnings.js +14 -7
  18. package/dist/io/formats/drawio/warnings.js.map +1 -1
  19. package/dist/io/formats/html/index.d.ts +1 -0
  20. package/dist/io/formats/html/index.d.ts.map +1 -1
  21. package/dist/io/formats/html/index.js +5 -3
  22. package/dist/io/formats/html/index.js.map +1 -1
  23. package/dist/io/formats/pen/index.d.ts.map +1 -1
  24. package/dist/io/formats/pen/index.js +13 -4
  25. package/dist/io/formats/pen/index.js.map +1 -1
  26. package/dist/io/formats.d.ts.map +1 -1
  27. package/dist/io/formats.js +10 -4
  28. package/dist/io/formats.js.map +1 -1
  29. package/dist/io/index.d.ts +2 -2
  30. package/dist/io/types.d.ts +11 -2
  31. package/dist/io/types.d.ts.map +1 -1
  32. package/package.json +9 -9
  33. package/src/canvas/shaders/compile.ts +14 -3
  34. package/src/canvas/shaders/draw.ts +11 -4
  35. package/src/canvas/shaders/effect.ts +6 -18
  36. package/src/editor/clipboard/export.ts +2 -2
  37. package/src/io/formats/drawio/warnings.ts +27 -8
  38. package/src/io/formats/html/index.ts +9 -3
  39. package/src/io/formats/pen/index.ts +14 -6
  40. package/src/io/formats.ts +10 -4
  41. package/src/io/index.ts +1 -0
  42. package/src/io/types.ts +10 -0
@@ -9,6 +9,8 @@ interface CompiledShader {
9
9
  effect: RuntimeEffect | null;
10
10
  error: string | null;
11
11
  }
12
+ /** Sources compiled per CanvasKit instance; the shader library and edits share this budget. */
13
+ declare const SHADER_CACHE_ENTRIES = 64;
12
14
  /** The frame values the renderer supplies instead of the document. */
13
15
  interface ShaderFrame {
14
16
  width: number;
@@ -30,5 +32,5 @@ declare function shaderSamplers(compiled: CompiledShader): string[];
30
32
  */
31
33
  declare function compileShader(ck: CanvasKit, source: string): CompiledShader;
32
34
  //#endregion
33
- export { CompiledShader, ShaderFrame, compileShader, packShaderUniforms, shaderSamplers };
35
+ export { CompiledShader, SHADER_CACHE_ENTRIES, ShaderFrame, compileShader, packShaderUniforms, shaderSamplers };
34
36
  //# sourceMappingURL=compile.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"compile.d.ts","names":[],"sources":["../../../src/canvas/shaders/compile.ts"],"mappings":";;;;;UAmBiB;EACf;EACA,UAAU;EACV,QAAQ;EACR;;;UAOe;EACf;EACA;EACA;EACA,OAAO;;;;;;;iBA6BO,mBACd,UAAU,gBACV,QAAQ,SAAS,eAAe,sBAChC,OAAO,cACN;;iBAiCa,eAAe,UAAU;;;;;iBAQzB,cAAc,IAAI,WAAW,iBAAiB"}
1
+ {"version":3,"file":"compile.d.ts","names":[],"sources":["../../../src/canvas/shaders/compile.ts"],"mappings":";;;;;UAqBiB;EACf;EACA,UAAU;EACV,QAAQ;EACR;;;cAIW;;UASI;EACf;EACA;EACA;EACA,OAAO;;;;;;;iBA6BO,mBACd,UAAU,gBACV,QAAQ,SAAS,eAAe,sBAChC,OAAO,cACN;;iBAiCa,eAAe,UAAU;;;;;iBAQzB,cAAc,IAAI,WAAW,iBAAiB"}
@@ -1,7 +1,13 @@
1
+ import { ResourceCache } from "../../cache/resource.js";
1
2
  import { translateShader } from "./translate.js";
2
3
  import { parseShaderUniforms } from "@pairdraw/scene-graph/shaders";
3
4
  //#region src/canvas/shaders/compile.ts
4
- /** One cache per CanvasKit instance, so a reload gets fresh effects. */
5
+ /** Sources compiled per CanvasKit instance; the shader library and edits share this budget. */
6
+ const SHADER_CACHE_ENTRIES = 64;
7
+ /**
8
+ * One owning cache per CanvasKit instance, so a reload gets fresh effects. Effects are native
9
+ * handles: the cache is their only owner, and disposing a slot is what frees one.
10
+ */
5
11
  const caches = /* @__PURE__ */ new WeakMap();
6
12
  /** The floats of one uniform value, in its declared component count. */
7
13
  function uniformFloats(uniform, value) {
@@ -69,7 +75,10 @@ function shaderSamplers(compiled) {
69
75
  function compileShader(ck, source) {
70
76
  let cache = caches.get(ck);
71
77
  if (!cache) {
72
- cache = /* @__PURE__ */ new Map();
78
+ cache = new ResourceCache({
79
+ maxEntries: 64,
80
+ dispose: (compiled) => compiled.effect?.delete()
81
+ });
73
82
  caches.set(ck, cache);
74
83
  }
75
84
  const cached = cache.get(source);
@@ -112,6 +121,6 @@ function compileShader(ck, source) {
112
121
  return compiled;
113
122
  }
114
123
  //#endregion
115
- export { compileShader, packShaderUniforms, shaderSamplers };
124
+ export { SHADER_CACHE_ENTRIES, compileShader, packShaderUniforms, shaderSamplers };
116
125
 
117
126
  //# sourceMappingURL=compile.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"compile.js","names":[],"sources":["../../../src/canvas/shaders/compile.ts"],"sourcesContent":["/**\n * Compiles a user shader once per source and packs its uniforms for drawing. The declared\n * uniforms order the panel's controls; the compiled effect orders the uniform array, so packing\n * follows the effect's own slot table and the two cannot drift.\n */\n\nimport type { CanvasKit, RuntimeEffect } from 'canvaskit-wasm'\n\nimport type { Vector } from '@pairdraw/scene-graph/primitives'\nimport {\n parseShaderUniforms,\n type ShaderAutomaticInput,\n type ShaderUniform,\n type ShaderUniformValue\n} from '@pairdraw/scene-graph/shaders'\n\nimport { FRAME_HEIGHT_UNIFORM, OBJECT_SIZE_UNIFORM, translateShader } from './translate'\n\n/** A shader source with its compiled effect, or why it could not compile. */\nexport interface CompiledShader {\n source: string\n uniforms: ShaderUniform[]\n effect: RuntimeEffect | null\n error: string | null\n}\n\n/** One cache per CanvasKit instance, so a reload gets fresh effects. */\nconst caches = new WeakMap<CanvasKit, Map<string, CompiledShader>>()\n\n/** The frame values the renderer supplies instead of the document. */\nexport interface ShaderFrame {\n width: number\n height: number\n time: number\n mouse: Vector\n}\n\n/** The floats of one uniform value, in its declared component count. */\nfunction uniformFloats(uniform: ShaderUniform, value: ShaderUniformValue | undefined): number[] {\n const fallback = uniform.default ?? (uniform.kind === 'color' ? '#000000' : 0)\n const read = value ?? fallback\n if (uniform.kind === 'color') {\n const text = typeof read === 'string' ? read : '#000000'\n const hex = text.replace('#', '')\n const digits = hex.length === 3 ? hex.replace(/./g, (c) => c + c) : hex\n const channel = (at: number) => (Number.parseInt(digits.slice(at, at + 2), 16) || 0) / 255\n const alpha = digits.length >= 8 ? channel(6) : 1\n return [channel(0), channel(2), channel(4), alpha]\n }\n if (uniform.kind === 'boolean') return [typeof read === 'boolean' && read ? 1 : 0]\n if (Array.isArray(read)) {\n return Array.from({ length: uniform.components }, (_, at) => Number(read[at] ?? 0))\n }\n if (typeof read === 'number') return [read]\n if (typeof read === 'boolean') return [read ? 1 : 0]\n return [0]\n}\n\n/**\n * The uniform array for `compiled`, with the frame's own values for `@time`, `@resolution`, and\n * `@mouse`. A uniform the effect does not declare is skipped, and a declared one with no value\n * takes the document's default.\n */\nexport function packShaderUniforms(\n compiled: CompiledShader,\n values: Readonly<Record<string, ShaderUniformValue>>,\n frame: ShaderFrame\n): Float32Array {\n const effect = compiled.effect\n if (!effect) return new Float32Array(0)\n const packed = new Float32Array(effect.getUniformFloatCount())\n const declared = new Map(compiled.uniforms.map((uniform) => [uniform.name, uniform]))\n for (let index = 0; index < effect.getUniformCount(); index++) {\n const name = effect.getUniformName(index)\n const slot = effect.getUniform(index).slot\n // The translator's own uniforms, which the user never declares.\n if (name === FRAME_HEIGHT_UNIFORM) {\n packed[slot] = frame.height\n continue\n }\n if (name === OBJECT_SIZE_UNIFORM) {\n packed[slot] = frame.width\n packed[slot + 1] = frame.height\n continue\n }\n const uniform = declared.get(name)\n if (!uniform) continue\n let floats: number[]\n if (uniform.automatic === 'resolution') floats = [frame.width, frame.height]\n else if (uniform.automatic === 'time') floats = [frame.time]\n else if (uniform.automatic === 'mouse') floats = [frame.mouse.x, frame.mouse.y]\n else floats = uniformFloats(uniform, values[name])\n for (let at = 0; at < floats.length && slot + at < packed.length; at++) {\n packed[slot + at] = floats[at] ?? 0\n }\n }\n return packed\n}\n\n/** The sampler uniforms in child order, which is the order the source declares them. */\nexport function shaderSamplers(compiled: CompiledShader): string[] {\n return compiled.uniforms.filter((uniform) => uniform.kind === 'sampler').map((u) => u.name)\n}\n\n/**\n * `source` compiled to a runtime effect, cached. A translation or SkSL error returns `effect:\n * null` with its message; the uniforms parsed before the error stay, so the panel can show them.\n */\nexport function compileShader(ck: CanvasKit, source: string): CompiledShader {\n let cache = caches.get(ck)\n if (!cache) {\n cache = new Map()\n caches.set(ck, cache)\n }\n const cached = cache.get(source)\n if (cached) return cached\n\n const parsed = parseShaderUniforms(source)\n if (parsed.error) {\n const failed: CompiledShader = {\n source,\n uniforms: parsed.uniforms,\n effect: null,\n error: parsed.error\n }\n cache.set(source, failed)\n return failed\n }\n const samplerKinds: Record<string, ShaderAutomaticInput | undefined> = {}\n for (const uniform of parsed.uniforms) {\n if (uniform.kind === 'sampler') samplerKinds[uniform.name] = uniform.automatic\n }\n const translation = translateShader(source, samplerKinds)\n if (translation.error) {\n const failed: CompiledShader = {\n source,\n uniforms: parsed.uniforms,\n effect: null,\n error: translation.error\n }\n cache.set(source, failed)\n return failed\n }\n\n const failure: { message: string | null } = { message: null }\n const effect = ck.RuntimeEffect.Make(translation.sksl, (error: string) => {\n failure.message = error\n })\n const compiled: CompiledShader = {\n source,\n uniforms: parsed.uniforms,\n effect: effect ?? null,\n error: effect ? null : (failure.message ?? 'The shader could not compile')\n }\n cache.set(source, compiled)\n return compiled\n}\n"],"mappings":";;;;AA2BA,MAAM,yBAAS,IAAI,QAAgD;;AAWnE,SAAS,cAAc,SAAwB,OAAiD;CAC9F,MAAM,WAAW,QAAQ,YAAY,QAAQ,SAAS,UAAU,YAAY;CAC5E,MAAM,OAAO,SAAS;CACtB,IAAI,QAAQ,SAAS,SAAS;EAE5B,MAAM,OADO,OAAO,SAAS,WAAW,OAAO,UAAA,CAC9B,QAAQ,KAAK,EAAE;EAChC,MAAM,SAAS,IAAI,WAAW,IAAI,IAAI,QAAQ,OAAO,MAAM,IAAI,CAAC,IAAI;EACpE,MAAM,WAAW,QAAgB,OAAO,SAAS,OAAO,MAAM,IAAI,KAAK,CAAC,GAAG,EAAE,KAAK,KAAK;EACvF,MAAM,QAAQ,OAAO,UAAU,IAAI,QAAQ,CAAC,IAAI;EAChD,OAAO;GAAC,QAAQ,CAAC;GAAG,QAAQ,CAAC;GAAG,QAAQ,CAAC;GAAG;EAAK;CACnD;CACA,IAAI,QAAQ,SAAS,WAAW,OAAO,CAAC,OAAO,SAAS,aAAa,OAAO,IAAI,CAAC;CACjF,IAAI,MAAM,QAAQ,IAAI,GACpB,OAAO,MAAM,KAAK,EAAE,QAAQ,QAAQ,WAAW,IAAI,GAAG,OAAO,OAAO,KAAK,OAAO,CAAC,CAAC;CAEpF,IAAI,OAAO,SAAS,UAAU,OAAO,CAAC,IAAI;CAC1C,IAAI,OAAO,SAAS,WAAW,OAAO,CAAC,OAAO,IAAI,CAAC;CACnD,OAAO,CAAC,CAAC;AACX;;;;;;AAOA,SAAgB,mBACd,UACA,QACA,OACc;CACd,MAAM,SAAS,SAAS;CACxB,IAAI,CAAC,QAAQ,uBAAO,IAAI,aAAa,CAAC;CACtC,MAAM,SA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,MAAM,SAAS,oBAAoB,MAAM;CACzC,IAAI,OAAO,OAAO;EAChB,MAAM,SAAyB;GAC7B;GACA,UAAU,OAAO;GACjB,QAAQ;GACR,OAAO,OAAO;EAChB;EACA,MAAM,IAAI,QAAQ,MAAM;EACxB,OAAO;CACT;CACA,MAAM,eAAiE,CAAC;CACxE,KAAK,MAAM,WAAW,OAAO,UAC3B,IAAI,QAAQ,SAAS,WAAW,aAAa,QAAQ,QAAQ,QAAQ;CAEvE,MAAM,cAAc,gBAAgB,QAAQ,YAAY;CACxD,IAAI,YAAY,OAAO;EACrB,MAAM,SAAyB;GAC7B;GACA,UAAU,OAAO;GACjB,QAAQ;GACR,OAAO,YAAY;EACrB;EACA,MAAM,IAAI,QAAQ,MAAM;EACxB,OAAO;CACT;CAEA,MAAM,UAAsC,EAAE,SAAS,KAAK;CAC5D,MAAM,SAAS,GAAG,cAAc,KAAK,YAAY,OAAO,UAAkB;EACxE,QAAQ,UAAU;CACpB,CAAC;CACD,MAAM,WAA2B;EAC/B;EACA,UAAU,OAAO;EACjB,QAAQ,UAAU;EAClB,OAAO,SAAS,OAAQ,QAAQ,WAAW;CAC7C;CACA,MAAM,IAAI,QAAQ,QAAQ;CAC1B,OAAO;AACT"}
1
+ {"version":3,"file":"compile.js","names":[],"sources":["../../../src/canvas/shaders/compile.ts"],"sourcesContent":["/**\n * Compiles a user shader once per source and packs its uniforms for drawing. The declared\n * uniforms order the panel's controls; the compiled effect orders the uniform array, so packing\n * follows the effect's own slot table and the two cannot drift.\n */\n\nimport type { CanvasKit, RuntimeEffect } from 'canvaskit-wasm'\n\nimport type { Vector } from '@pairdraw/scene-graph/primitives'\nimport {\n parseShaderUniforms,\n type ShaderAutomaticInput,\n type ShaderUniform,\n type ShaderUniformValue\n} from '@pairdraw/scene-graph/shaders'\n\nimport { ResourceCache } from '#core/cache/resource'\n\nimport { FRAME_HEIGHT_UNIFORM, OBJECT_SIZE_UNIFORM, translateShader } from './translate'\n\n/** A shader source with its compiled effect, or why it could not compile. */\nexport interface CompiledShader {\n source: string\n uniforms: ShaderUniform[]\n effect: RuntimeEffect | null\n error: string | null\n}\n\n/** Sources compiled per CanvasKit instance; the shader library and edits share this budget. */\nexport const SHADER_CACHE_ENTRIES = 64\n\n/**\n * One owning cache per CanvasKit instance, so a reload gets fresh effects. Effects are native\n * handles: the cache is their only owner, and disposing a slot is what frees one.\n */\nconst caches = new WeakMap<CanvasKit, ResourceCache<string, CompiledShader>>()\n\n/** The frame values the renderer supplies instead of the document. */\nexport interface ShaderFrame {\n width: number\n height: number\n time: number\n mouse: Vector\n}\n\n/** The floats of one uniform value, in its declared component count. */\nfunction uniformFloats(uniform: ShaderUniform, value: ShaderUniformValue | undefined): number[] {\n const fallback = uniform.default ?? (uniform.kind === 'color' ? '#000000' : 0)\n const read = value ?? fallback\n if (uniform.kind === 'color') {\n const text = typeof read === 'string' ? read : '#000000'\n const hex = text.replace('#', '')\n const digits = hex.length === 3 ? hex.replace(/./g, (c) => c + c) : hex\n const channel = (at: number) => (Number.parseInt(digits.slice(at, at + 2), 16) || 0) / 255\n const alpha = digits.length >= 8 ? channel(6) : 1\n return [channel(0), channel(2), channel(4), alpha]\n }\n if (uniform.kind === 'boolean') return [typeof read === 'boolean' && read ? 1 : 0]\n if (Array.isArray(read)) {\n return Array.from({ length: uniform.components }, (_, at) => Number(read[at] ?? 0))\n }\n if (typeof read === 'number') return [read]\n if (typeof read === 'boolean') return [read ? 1 : 0]\n return [0]\n}\n\n/**\n * The uniform array for `compiled`, with the frame's own values for `@time`, `@resolution`, and\n * `@mouse`. A uniform the effect does not declare is skipped, and a declared one with no value\n * takes the document's default.\n */\nexport function packShaderUniforms(\n compiled: CompiledShader,\n values: Readonly<Record<string, ShaderUniformValue>>,\n frame: ShaderFrame\n): Float32Array {\n const effect = compiled.effect\n if (!effect) return new Float32Array(0)\n const packed = new Float32Array(effect.getUniformFloatCount())\n const declared = new Map(compiled.uniforms.map((uniform) => [uniform.name, uniform]))\n for (let index = 0; index < effect.getUniformCount(); index++) {\n const name = effect.getUniformName(index)\n const slot = effect.getUniform(index).slot\n // The translator's own uniforms, which the user never declares.\n if (name === FRAME_HEIGHT_UNIFORM) {\n packed[slot] = frame.height\n continue\n }\n if (name === OBJECT_SIZE_UNIFORM) {\n packed[slot] = frame.width\n packed[slot + 1] = frame.height\n continue\n }\n const uniform = declared.get(name)\n if (!uniform) continue\n let floats: number[]\n if (uniform.automatic === 'resolution') floats = [frame.width, frame.height]\n else if (uniform.automatic === 'time') floats = [frame.time]\n else if (uniform.automatic === 'mouse') floats = [frame.mouse.x, frame.mouse.y]\n else floats = uniformFloats(uniform, values[name])\n for (let at = 0; at < floats.length && slot + at < packed.length; at++) {\n packed[slot + at] = floats[at] ?? 0\n }\n }\n return packed\n}\n\n/** The sampler uniforms in child order, which is the order the source declares them. */\nexport function shaderSamplers(compiled: CompiledShader): string[] {\n return compiled.uniforms.filter((uniform) => uniform.kind === 'sampler').map((u) => u.name)\n}\n\n/**\n * `source` compiled to a runtime effect, cached. A translation or SkSL error returns `effect:\n * null` with its message; the uniforms parsed before the error stay, so the panel can show them.\n */\nexport function compileShader(ck: CanvasKit, source: string): CompiledShader {\n let cache = caches.get(ck)\n if (!cache) {\n cache = new ResourceCache<string, CompiledShader>({\n maxEntries: SHADER_CACHE_ENTRIES,\n dispose: (compiled) => compiled.effect?.delete()\n })\n caches.set(ck, cache)\n }\n const cached = cache.get(source)\n if (cached) return cached\n\n const parsed = parseShaderUniforms(source)\n if (parsed.error) {\n const failed: CompiledShader = {\n source,\n uniforms: parsed.uniforms,\n effect: null,\n error: parsed.error\n }\n cache.set(source, failed)\n return failed\n }\n const samplerKinds: Record<string, ShaderAutomaticInput | undefined> = {}\n for (const uniform of parsed.uniforms) {\n if (uniform.kind === 'sampler') samplerKinds[uniform.name] = uniform.automatic\n }\n const translation = translateShader(source, samplerKinds)\n if (translation.error) {\n const failed: CompiledShader = {\n source,\n uniforms: parsed.uniforms,\n effect: null,\n error: translation.error\n }\n cache.set(source, failed)\n return failed\n }\n\n const failure: { message: string | null } = { message: null }\n const effect = ck.RuntimeEffect.Make(translation.sksl, (error: string) => {\n failure.message = error\n })\n const compiled: CompiledShader = {\n source,\n uniforms: parsed.uniforms,\n effect: effect ?? null,\n error: effect ? null : (failure.message ?? 'The shader could not compile')\n }\n cache.set(source, compiled)\n return compiled\n}\n"],"mappings":";;;;;AA6BA,MAAa,uBAAuB;;;;;AAMpC,MAAM,yBAAS,IAAI,QAA0D;;AAW7E,SAAS,cAAc,SAAwB,OAAiD;CAC9F,MAAM,WAAW,QAAQ,YAAY,QAAQ,SAAS,UAAU,YAAY;CAC5E,MAAM,OAAO,SAAS;CACtB,IAAI,QAAQ,SAAS,SAAS;EAE5B,MAAM,OADO,OAAO,SAAS,WAAW,OAAO,UAAA,CAC9B,QAAQ,KAAK,EAAE;EAChC,MAAM,SAAS,IAAI,WAAW,IAAI,IAAI,QAAQ,OAAO,MAAM,IAAI,CAAC,IAAI;EACpE,MAAM,WAAW,QAAgB,OAAO,SAAS,OAAO,MAAM,IAAI,KAAK,CAAC,GAAG,EAAE,KAAK,KAAK;EACvF,MAAM,QAAQ,OAAO,UAAU,IAAI,QAAQ,CAAC,IAAI;EAChD,OAAO;GAAC,QAAQ,CAAC;GAAG,QAAQ,CAAC;GAAG,QAAQ,CAAC;GAAG;EAAK;CACnD;CACA,IAAI,QAAQ,SAAS,WAAW,OAAO,CAAC,OAAO,SAAS,aAAa,OAAO,IAAI,CAAC;CACjF,IAAI,MAAM,QAAQ,IAAI,GACpB,OAAO,MAAM,KAAK,EAAE,QAAQ,QAAQ,WAAW,IAAI,GAAG,OAAO,OAAO,KAAK,OAAO,CAAC,CAAC;CAEpF,IAAI,OAAO,SAAS,UAAU,OAAO,CAAC,IAAI;CAC1C,IAAI,OAAO,SAAS,WAAW,OAAO,CAAC,OAAO,IAAI,CAAC;CACnD,OAAO,CAAC,CAAC;AACX;;;;;;AAOA,SAAgB,mBACd,UACA,QACA,OACc;CAC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AAU,aAAa,SAAS,QAAQ,OAAO;EACjD,CAAC;EACD,OAAO,IAAI,IAAI,KAAK;CACtB;CACA,MAAM,SAAS,MAAM,IAAI,MAAM;CAC/B,IAAI,QAAQ,OAAO;CAEnB,MAAM,SAAS,oBAAoB,MAAM;CACzC,IAAI,OAAO,OAAO;EAChB,MAAM,SAAyB;GAC7B;GACA,UAAU,OAAO;GACjB,QAAQ;GACR,OAAO,OAAO;EAChB;EACA,MAAM,IAAI,QAAQ,MAAM;EACxB,OAAO;CACT;CACA,MAAM,eAAiE,CAAC;CACxE,KAAK,MAAM,WAAW,OAAO,UAC3B,IAAI,QAAQ,SAAS,WAAW,aAAa,QAAQ,QAAQ,QAAQ;CAEvE,MAAM,cAAc,gBAAgB,QAAQ,YAAY;CACxD,IAAI,YAAY,OAAO;EACrB,MAAM,SAAyB;GAC7B;GACA,UAAU,OAAO;GACjB,QAAQ;GACR,OAAO,YAAY;EACrB;EACA,MAAM,IAAI,QAAQ,MAAM;EACxB,OAAO;CACT;CAEA,MAAM,UAAsC,EAAE,SAAS,KAAK;CAC5D,MAAM,SAAS,GAAG,cAAc,KAAK,YAAY,OAAO,UAAkB;EACxE,QAAQ,UAAU;CACpB,CAAC;CACD,MAAM,WAA2B;EAC/B;EACA,UAAU,OAAO;EACjB,QAAQ,UAAU;EAClB,OAAO,SAAS,OAAQ,QAAQ,WAAW;CAC7C;CACA,MAAM,IAAI,QAAQ,QAAQ;CAC1B,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"draw.d.ts","names":[],"sources":["../../../src/canvas/shaders/draw.ts"],"mappings":";;;;;;;iBA2DgB,mBACd,GAAG,cACH,MAAM,MACN,MAAM,WACN,OAAO"}
1
+ {"version":3,"file":"draw.d.ts","names":[],"sources":["../../../src/canvas/shaders/draw.ts"],"mappings":";;;;;;;iBAkEgB,mBACd,GAAG,cACH,MAAM,MACN,MAAM,WACN,OAAO"}
@@ -5,7 +5,11 @@ import { isShaderSourcePaint, shaderOfPaint } from "@pairdraw/scene-graph/shader
5
5
  //#region src/canvas/shaders/draw.ts
6
6
  /** When the page started drawing shaders, which is what `@time` counts from. */
7
7
  const startedAt = Date.now();
8
- /** The effect each paint last compiled with, by frame image, so a broken edit keeps drawing. */
8
+ /**
9
+ * The source each paint last compiled from, by frame image, so a broken edit keeps drawing. A source
10
+ * is stored rather than the compiled object: the compile cache owns the handle, and a remembered
11
+ * object could be disposed by an eviction between the edit and the draw.
12
+ */
9
13
  const lastGood = /* @__PURE__ */ new Map();
10
14
  /** How many paints keep a last good effect, so a long session does not hold every one forever. */
11
15
  const KEEP_LAST_GOOD = 32;
@@ -21,7 +25,7 @@ function effectFor(r, shader) {
21
25
  const compiled = compileShader(r.ck, shader.source);
22
26
  if (compiled.effect) {
23
27
  lastGood.delete(shader.image);
24
- lastGood.set(shader.image, compiled);
28
+ lastGood.set(shader.image, shader.source);
25
29
  while (lastGood.size > KEEP_LAST_GOOD) {
26
30
  const oldest = lastGood.keys().next().value;
27
31
  if (oldest === void 0) break;
@@ -29,7 +33,10 @@ function effectFor(r, shader) {
29
33
  }
30
34
  return compiled;
31
35
  }
32
- return lastGood.get(shader.image) ?? null;
36
+ const goodSource = lastGood.get(shader.image);
37
+ if (goodSource === void 0) return null;
38
+ const good = compileShader(r.ck, goodSource);
39
+ return good.effect ? good : null;
33
40
  }
34
41
  /**
35
42
  * Draws `fill` as the shader it names, when that shader is user code. Returns false when the fill
@@ -1 +1 @@
1
- {"version":3,"file":"draw.js","names":[],"sources":["../../../src/canvas/shaders/draw.ts"],"sourcesContent":["/**\n * Draws a fill whose paint is shader code the user wrote. The code compiles to a CanvasKit runtime\n * effect, the SDF uniforms become child shaders, and the result replaces the fill's image shader.\n * A source that stops compiling keeps the effect it had while it did, so an edit in the panel\n * never blanks the layer mid-typing.\n */\n\nimport type { Shader } from 'canvaskit-wasm'\n\nimport type { Fill, SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport {\n isShaderSourcePaint,\n shaderOfPaint,\n type ShaderSourcePaint\n} from '@pairdraw/scene-graph/shaders'\n\nimport type { SkiaRenderer } from '#core/canvas/renderer'\n\nimport { boundUniformValues } from './bindings'\nimport { compileShader, packShaderUniforms, shaderSamplers, type CompiledShader } from './compile'\nimport { sdfShader } from './sdf'\n\n/** When the page started drawing shaders, which is what `@time` counts from. */\nconst startedAt = Date.now()\n\n/** The effect each paint last compiled with, by frame image, so a broken edit keeps drawing. */\nconst lastGood = new Map<string, CompiledShader>()\n\n/** How many paints keep a last good effect, so a long session does not hold every one forever. */\nconst KEEP_LAST_GOOD = 32\n\n/** The seconds since the page started, which `@time` reports. */\nfunction shaderSeconds(): number {\n return (Date.now() - startedAt) / 1000\n}\n\n/**\n * The effect to draw `shader` with: its own compile, or the one it last compiled with. Null when\n * it has never compiled, which leaves the fill drawing its still frame.\n */\nfunction effectFor(r: SkiaRenderer, shader: ShaderSourcePaint): CompiledShader | null {\n const compiled = compileShader(r.ck, shader.source)\n if (compiled.effect) {\n lastGood.delete(shader.image)\n lastGood.set(shader.image, compiled)\n while (lastGood.size > KEEP_LAST_GOOD) {\n const oldest = lastGood.keys().next().value\n if (oldest === undefined) break\n lastGood.delete(oldest)\n }\n return compiled\n }\n return lastGood.get(shader.image) ?? null\n}\n\n/**\n * Draws `fill` as the shader it names, when that shader is user code. Returns false when the fill\n * is not a source shader or nothing compiled yet, so the caller draws the image it holds.\n */\nexport function drawUserShaderFill(\n r: SkiaRenderer,\n fill: Fill,\n node: SceneNode,\n graph: SceneGraph\n): boolean {\n const shader = shaderOfPaint(node, fill)\n if (!shader || !isShaderSourcePaint(shader)) return false\n const compiled = effectFor(r, shader)\n if (!compiled?.effect) return false\n\n const uniforms = packShaderUniforms(\n compiled,\n boundUniformValues(shader.uniforms, shader.uniformBindings, graph, node.id),\n {\n width: node.width,\n height: node.height,\n time: shaderSeconds(),\n mouse: { x: 0, y: 0 }\n }\n )\n\n const children: Shader[] = []\n try {\n for (let at = 0; at < shaderSamplers(compiled).length; at++) {\n const child = sdfShader(r.ck, r, node)\n if (!child) return false\n children.push(child)\n }\n const drawn = compiled.effect.makeShaderWithChildren(uniforms, children)\n r.fillPaint.setShader(drawn)\n drawn.delete()\n return true\n } finally {\n for (const child of children) child.delete()\n }\n}\n"],"mappings":";;;;;;AAuBA,MAAM,YAAY,KAAK,IAAI;;AAG3B,MAAM,2BAAW,IAAI,IAA4B;;AAGjD,MAAM,iBAAiB;;AAGvB,SAAS,gBAAwB;CAC/B,QAAQ,KAAK,IAAI,IAAI,aAAa;AACpC;;;;;AAMA,SAAS,UAAU,GAAiB,QAAkD;CACpF,MAAM,WAAW,cAAc,EAAE,IAAI,OAAO,MAAM;CAClD,IAAI,SAAS,QAAQ;EACnB,SAAS,OAAO,OAAO,KAAK;EAC5B,SAAS,IAAI,OAAO,OAAO,QAAQ;EACnC,OAAO,SAAS,OAAO,gBAAgB;GACrC,MAAM,SAAS,SAAS,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;GACtC,IAAI,WAAW,KAAA,GAAW;GAC1B,SAAS,OAAO,MAAM;EACxB;EACA,OAAO;CACT;CACA,OAAO,SAAS,IAAI,OAAO,KAAK,KAAK;AACvC;;;;;AAMA,SAAgB,mBACd,GACA,MACA,MACA,OACS;CACT,MAAM,SAAS,cAAc,MAAM,IAAI;CACvC,IAAI,CAAC,UAAU,CAAC,oBAAoB,MAAM,GAAG,OAAO;CACpD,MAAM,WAAW,UAAU,GAAG,MAAM;CACpC,IAAI,CAAC,UAAU,QAAQ,OAAO;CAE9B,MAAM,WAAW,mBACf,UACA,mBAAmB,OAAO,UAAU,OAAO,iBAAiB,OAAO,KAAK,EAAE,GAC1E;EACE,OAAO,KAAK;EACZ,QAAQ,KAAK;EACb,MAAM,cAAc;EACpB,OAAO;GAAE,GAAG;GAAG,GAAG;EAAE;CACtB,CACF;CAEA,MAAM,WAAqB,CAAC;CAC5B,IAAI;EACF,KAAK,IAAI,KAAK,GAAG,KAAK,eAAe,QAAQ,CAAC,CAAC,QAAQ,MAAM;GAC3D,MAAM,QAAQ,UAAU,EAAE,IAAI,GAAG,IAAI;GACrC,IAAI,CAAC,OAAO,OAAO;GACnB,SAAS,KAAK,KAAK;EACrB;EACA,MAAM,QAAQ,SAAS,OAAO,uBAAuB,UAAU,QAAQ;EACvE,EAAE,UAAU,UAAU,KAAK;EAC3B,MAAM,OAAO;EACb,OAAO;CACT,UAAU;EACR,KAAK,MAAM,SAAS,UAAU,MAAM,OAAO;CAC7C;AACF"}
1
+ {"version":3,"file":"draw.js","names":[],"sources":["../../../src/canvas/shaders/draw.ts"],"sourcesContent":["/**\n * Draws a fill whose paint is shader code the user wrote. The code compiles to a CanvasKit runtime\n * effect, the SDF uniforms become child shaders, and the result replaces the fill's image shader.\n * A source that stops compiling keeps the effect it had while it did, so an edit in the panel\n * never blanks the layer mid-typing.\n */\n\nimport type { Shader } from 'canvaskit-wasm'\n\nimport type { Fill, SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport {\n isShaderSourcePaint,\n shaderOfPaint,\n type ShaderSourcePaint\n} from '@pairdraw/scene-graph/shaders'\n\nimport type { SkiaRenderer } from '#core/canvas/renderer'\n\nimport { boundUniformValues } from './bindings'\nimport { compileShader, packShaderUniforms, shaderSamplers, type CompiledShader } from './compile'\nimport { sdfShader } from './sdf'\n\n/** When the page started drawing shaders, which is what `@time` counts from. */\nconst startedAt = Date.now()\n\n/**\n * The source each paint last compiled from, by frame image, so a broken edit keeps drawing. A source\n * is stored rather than the compiled object: the compile cache owns the handle, and a remembered\n * object could be disposed by an eviction between the edit and the draw.\n */\nconst lastGood = new Map<string, string>()\n\n/** How many paints keep a last good effect, so a long session does not hold every one forever. */\nconst KEEP_LAST_GOOD = 32\n\n/** The seconds since the page started, which `@time` reports. */\nfunction shaderSeconds(): number {\n return (Date.now() - startedAt) / 1000\n}\n\n/**\n * The effect to draw `shader` with: its own compile, or the one it last compiled with. Null when\n * it has never compiled, which leaves the fill drawing its still frame.\n */\nfunction effectFor(r: SkiaRenderer, shader: ShaderSourcePaint): CompiledShader | null {\n const compiled = compileShader(r.ck, shader.source)\n if (compiled.effect) {\n lastGood.delete(shader.image)\n lastGood.set(shader.image, shader.source)\n while (lastGood.size > KEEP_LAST_GOOD) {\n const oldest = lastGood.keys().next().value\n if (oldest === undefined) break\n lastGood.delete(oldest)\n }\n return compiled\n }\n const goodSource = lastGood.get(shader.image)\n if (goodSource === undefined) return null\n const good = compileShader(r.ck, goodSource)\n return good.effect ? good : null\n}\n\n/**\n * Draws `fill` as the shader it names, when that shader is user code. Returns false when the fill\n * is not a source shader or nothing compiled yet, so the caller draws the image it holds.\n */\nexport function drawUserShaderFill(\n r: SkiaRenderer,\n fill: Fill,\n node: SceneNode,\n graph: SceneGraph\n): boolean {\n const shader = shaderOfPaint(node, fill)\n if (!shader || !isShaderSourcePaint(shader)) return false\n const compiled = effectFor(r, shader)\n if (!compiled?.effect) return false\n\n const uniforms = packShaderUniforms(\n compiled,\n boundUniformValues(shader.uniforms, shader.uniformBindings, graph, node.id),\n {\n width: node.width,\n height: node.height,\n time: shaderSeconds(),\n mouse: { x: 0, y: 0 }\n }\n )\n\n const children: Shader[] = []\n try {\n for (let at = 0; at < shaderSamplers(compiled).length; at++) {\n const child = sdfShader(r.ck, r, node)\n if (!child) return false\n children.push(child)\n }\n const drawn = compiled.effect.makeShaderWithChildren(uniforms, children)\n r.fillPaint.setShader(drawn)\n drawn.delete()\n return true\n } finally {\n for (const child of children) child.delete()\n }\n}\n"],"mappings":";;;;;;AAuBA,MAAM,YAAY,KAAK,IAAI;;;;;;AAO3B,MAAM,2BAAW,IAAI,IAAoB;;AAGzC,MAAM,iBAAiB;;AAGvB,SAAS,gBAAwB;CAC/B,QAAQ,KAAK,IAAI,IAAI,aAAa;AACpC;;;;;AAMA,SAAS,UAAU,GAAiB,QAAkD;CACpF,MAAM,WAAW,cAAc,EAAE,IAAI,OAAO,MAAM;CAClD,IAAI,SAAS,QAAQ;EACnB,SAAS,OAAO,OAAO,KAAK;EAC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as/shaders/effect.ts"],"mappings":";;;;;;;;;iBAsEgB,sBACd,GAAG,cACH,QAAQ,QACR,OAAO,YACP,MAAM,WACN,kBAAkB,gBAClB,gBAAgB,QAAQ;;;;;;iBAmBV,sBACd,GAAG,cACH,QAAQ,QACR,OAAO,YACP,MAAM,WACN,QAAQ,cACR,gBAAgB,QAAQ"}
1
+ {"version":3,"file":"effect.d.ts","names":[],"sources":["../../../src/canvas/shaders/effect.ts"],"mappings":";;;;;;;;;iBA0DgB,sBACd,GAAG,cACH,QAAQ,QACR,OAAO,YACP,MAAM,WACN,kBAAkB,gBAClB,gBAAgB,QAAQ;;;;;;iBAmBV,sBACd,GAAG,cACH,QAAQ,QACR,OAAO,YACP,MAAM,WACN,QAAQ,cACR,gBAAgB,QAAQ"}
@@ -8,24 +8,14 @@ import { sdfShader } from "./sdf.js";
8
8
  const MAX_SIDE = 4096;
9
9
  /** When the page started drawing shaders, which is what `@time` counts from. */
10
10
  const startedAt = Date.now();
11
- /** The effect each layer last compiled with, so a broken edit keeps drawing instead of blanking. */
12
- const lastGood = /* @__PURE__ */ new Map();
13
- /** How many layers keep a last good effect, so a long session does not hold every one forever. */
14
- const KEEP_LAST_GOOD = 32;
15
- /** The effect to draw `effect` with: its own compile, or the one it last compiled with. */
11
+ /**
12
+ * The effect to draw `effect` with. A failed compile has nothing to fall back to here: the last
13
+ * good compile of a source is that same source's entry, which `compileShader` memoizes, so its
14
+ * effect is already returned by a successful compile. The compile cache owns the handle.
15
+ */
16
16
  function effectFor(r, effect) {
17
17
  const compiled = compileShader(r.ck, effect.source);
18
- if (compiled.effect) {
19
- lastGood.delete(effect.source);
20
- lastGood.set(effect.source, compiled);
21
- while (lastGood.size > KEEP_LAST_GOOD) {
22
- const oldest = lastGood.keys().next().value;
23
- if (oldest === void 0) break;
24
- lastGood.delete(oldest);
25
- }
26
- return compiled;
27
- }
28
- return lastGood.get(effect.source) ?? null;
18
+ return compiled.effect ? compiled : null;
29
19
  }
30
20
  /** The device pixels one layer coordinate spans, so the snapshot draws at the canvas's own rate. */
31
21
  function deviceScale(canvas) {
@@ -1 +1 @@
1
- {"version":3,"file":"effect.js","names":[],"sources":["../../../src/canvas/shaders/effect.ts"],"sourcesContent":["/**\n * Draws a layer shader effect: the layer renders itself into an offscreen surface, that surface\n * becomes the `@object` texture, and the effect's shader draws over the layer's bounds. Snapshot\n * and redraw costs one surface per effected layer per frame, which is the ceiling this trades for\n * an object texture and effect children the runtime effect can sample.\n */\n\nimport type { Canvas, Image, Shader, Surface } from 'canvaskit-wasm'\n\nimport type { SceneGraph, SceneNode, ShaderEffect } from '@pairdraw/scene-graph'\n\nimport { setPaintBlendMode } from '#core/canvas/blend'\nimport type { SkiaRenderer } from '#core/canvas/renderer'\nimport { skColorSpace } from '#core/canvas/renderer/colors'\n\nimport { boundUniformValues } from './bindings'\nimport { compileShader, packShaderUniforms, type CompiledShader, type ShaderFrame } from './compile'\nimport { sdfShader } from './sdf'\n\n/** The largest snapshot a layer shader may make, per side, so a huge layer cannot exhaust memory. */\nconst MAX_SIDE = 4096\n\n/** When the page started drawing shaders, which is what `@time` counts from. */\nconst startedAt = Date.now()\n\n/** The effect each layer last compiled with, so a broken edit keeps drawing instead of blanking. */\nconst lastGood = new Map<string, CompiledShader>()\n\n/** How many layers keep a last good effect, so a long session does not hold every one forever. */\nconst KEEP_LAST_GOOD = 32\n\n/** The effect to draw `effect` with: its own compile, or the one it last compiled with. */\nfunction effectFor(r: SkiaRenderer, effect: ShaderEffect): CompiledShader | null {\n const compiled = compileShader(r.ck, effect.source)\n if (compiled.effect) {\n lastGood.delete(effect.source)\n lastGood.set(effect.source, compiled)\n while (lastGood.size > KEEP_LAST_GOOD) {\n const oldest = lastGood.keys().next().value\n if (oldest === undefined) break\n lastGood.delete(oldest)\n }\n return compiled\n }\n return lastGood.get(effect.source) ?? null\n}\n\n/** The device pixels one layer coordinate spans, so the snapshot draws at the canvas's own rate. */\nfunction deviceScale(canvas: Canvas): number {\n const matrix = canvas.getTotalMatrix()\n return Math.hypot(matrix[0] ?? 1, matrix[1] ?? 0) || 1\n}\n\n/** The `@object` shader for `image`, sampling it in the layer's own pixels. */\nfunction objectShader(r: SkiaRenderer, image: Image, scale: number): Shader {\n const toImage = [scale, 0, 0, 0, scale, 0, 0, 0, 1]\n return image.makeShaderOptions(\n r.ck.TileMode.Clamp,\n r.ck.TileMode.Clamp,\n r.ck.FilterMode.Linear,\n r.ck.MipmapMode.None,\n toImage\n )\n}\n\n/**\n * Draws `node`'s content into `canvas` with `effects` applied in document order, each sampling what\n * the one before it drew. The content is drawn exactly once: an effect that cannot compile or is too\n * large to snapshot is skipped, and the rest of the chain still draws.\n */\nexport function drawShaderEffectChain(\n r: SkiaRenderer,\n canvas: Canvas,\n graph: SceneGraph,\n node: SceneNode,\n effects: readonly ShaderEffect[],\n renderContent: (canvas: Canvas) => void\n): void {\n const effect = effects.at(-1)\n const below = effects.slice(0, -1)\n if (!effect) {\n renderContent(canvas)\n return\n }\n const drawn = drawShaderEffectLayer(r, canvas, graph, node, effect, (offscreen) =>\n drawShaderEffectChain(r, offscreen, graph, node, below, renderContent)\n )\n if (!drawn) drawShaderEffectChain(r, canvas, graph, node, below, renderContent)\n}\n\n/**\n * Draws `effect` over `node`'s bounds, calling `renderContent` with an offscreen canvas to paint\n * the layer into. Returns false when nothing compiled or the layer is too large to snapshot, so\n * the caller draws the layer as it would without the effect.\n */\nexport function drawShaderEffectLayer(\n r: SkiaRenderer,\n canvas: Canvas,\n graph: SceneGraph,\n node: SceneNode,\n effect: ShaderEffect,\n renderContent: (canvas: Canvas) => void\n): boolean {\n if (!(node.width > 0) || !(node.height > 0)) return false\n const compiled = effectFor(r, effect)\n if (!compiled?.effect) return false\n\n const scale = deviceScale(canvas)\n const width = Math.ceil(node.width * scale)\n const height = Math.ceil(node.height * scale)\n if (width > MAX_SIDE || height > MAX_SIDE) return false\n\n let surface: Surface | null = null\n let image: Image | null = null\n const children: Shader[] = []\n let drawn: Shader | null = null\n try {\n surface = r.surface.makeSurface({\n width,\n height,\n colorType: r.ck.ColorType.RGBA_8888,\n alphaType: r.ck.AlphaType.Premul,\n colorSpace: skColorSpace(r.ck, r.documentColorSpace)\n })\n const offscreen = surface.getCanvas()\n offscreen.clear(r.ck.TRANSPARENT)\n offscreen.scale(scale, scale)\n renderContent(offscreen)\n surface.flush()\n\n image = surface.makeImageSnapshot()\n const samplers = compiled.uniforms.filter((uniform) => uniform.kind === 'sampler')\n for (const sampler of samplers) {\n if (sampler.automatic === 'object') {\n children.push(objectShader(r, image, scale))\n continue\n }\n const child = sdfShader(r.ck, r, node)\n if (!child) return false\n children.push(child)\n }\n\n const frame: ShaderFrame = {\n width: node.width,\n height: node.height,\n time: (Date.now() - startedAt) / 1000,\n mouse: { x: 0, y: 0 }\n }\n const uniforms = packShaderUniforms(\n compiled,\n boundUniformValues(effect.uniforms, effect.uniformBindings, graph, node.id),\n frame\n )\n drawn = compiled.effect.makeShaderWithChildren(uniforms, children)\n r.auxFill.setShader(drawn)\n r.auxFill.setAlphaf(1)\n setPaintBlendMode(r, r.auxFill, effect.blendMode)\n canvas.drawRect(r.ck.LTRBRect(0, 0, node.width, node.height), r.auxFill)\n r.auxFill.setShader(null)\n return true\n } catch {\n return false\n } finally {\n drawn?.delete()\n for (const child of children) child.delete()\n image?.delete()\n surface?.delete()\n }\n}\n"],"mappings":";;;;;;;AAoBA,MAAM,WAAW;;AAGjB,MAAM,YAAY,KAAK,IAAI;;AAG3B,MAAM,2BAAW,IAAI,IAA4B;;AAGjD,MAAM,iBAAiB;;AAGvB,SAAS,UAAU,GAAiB,QAA6C;CAC/E,MAAM,WAAW,cAAc,EAAE,IAAI,OAAO,MAAM;CAClD,IAAI,SAAS,QAAQ;EACnB,SAAS,OAAO,OAAO,MAAM;EAC7B,SAAS,IAAI,OAAO,QAAQ,QAAQ;EACpC,OAAO,SAAS,OAAO,gBAAgB;GACrC,MAAM,SAAS,SAAS,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;GAC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O;CACT,QAAQ;EACN,OAAO;CACT,UAAU;EACR,OAAO,OAAO;EACd,KAAK,MAAM,SAAS,UAAU,MAAM,OAAO;EAC3C,OAAO,OAAO;EACd,SAAS,OAAO;CAClB;AACF"}
1
+ {"version":3,"file":"effect.js","names":[],"sources":["../../../src/canvas/shaders/effect.ts"],"sourcesContent":["/**\n * Draws a layer shader effect: the layer renders itself into an offscreen surface, that surface\n * becomes the `@object` texture, and the effect's shader draws over the layer's bounds. Snapshot\n * and redraw costs one surface per effected layer per frame, which is the ceiling this trades for\n * an object texture and effect children the runtime effect can sample.\n */\n\nimport type { Canvas, Image, Shader, Surface } from 'canvaskit-wasm'\n\nimport type { SceneGraph, SceneNode, ShaderEffect } from '@pairdraw/scene-graph'\n\nimport { setPaintBlendMode } from '#core/canvas/blend'\nimport type { SkiaRenderer } from '#core/canvas/renderer'\nimport { skColorSpace } from '#core/canvas/renderer/colors'\n\nimport { boundUniformValues } from './bindings'\nimport { compileShader, packShaderUniforms, type CompiledShader, type ShaderFrame } from './compile'\nimport { sdfShader } from './sdf'\n\n/** The largest snapshot a layer shader may make, per side, so a huge layer cannot exhaust memory. */\nconst MAX_SIDE = 4096\n\n/** When the page started drawing shaders, which is what `@time` counts from. */\nconst startedAt = Date.now()\n\n/**\n * The effect to draw `effect` with. A failed compile has nothing to fall back to here: the last\n * good compile of a source is that same source's entry, which `compileShader` memoizes, so its\n * effect is already returned by a successful compile. The compile cache owns the handle.\n */\nfunction effectFor(r: SkiaRenderer, effect: ShaderEffect): CompiledShader | null {\n const compiled = compileShader(r.ck, effect.source)\n return compiled.effect ? compiled : null\n}\n\n/** The device pixels one layer coordinate spans, so the snapshot draws at the canvas's own rate. */\nfunction deviceScale(canvas: Canvas): number {\n const matrix = canvas.getTotalMatrix()\n return Math.hypot(matrix[0] ?? 1, matrix[1] ?? 0) || 1\n}\n\n/** The `@object` shader for `image`, sampling it in the layer's own pixels. */\nfunction objectShader(r: SkiaRenderer, image: Image, scale: number): Shader {\n const toImage = [scale, 0, 0, 0, scale, 0, 0, 0, 1]\n return image.makeShaderOptions(\n r.ck.TileMode.Clamp,\n r.ck.TileMode.Clamp,\n r.ck.FilterMode.Linear,\n r.ck.MipmapMode.None,\n toImage\n )\n}\n\n/**\n * Draws `node`'s content into `canvas` with `effects` applied in document order, each sampling what\n * the one before it drew. The content is drawn exactly once: an effect that cannot compile or is too\n * large to snapshot is skipped, and the rest of the chain still draws.\n */\nexport function drawShaderEffectChain(\n r: SkiaRenderer,\n canvas: Canvas,\n graph: SceneGraph,\n node: SceneNode,\n effects: readonly ShaderEffect[],\n renderContent: (canvas: Canvas) => void\n): void {\n const effect = effects.at(-1)\n const below = effects.slice(0, -1)\n if (!effect) {\n renderContent(canvas)\n return\n }\n const drawn = drawShaderEffectLayer(r, canvas, graph, node, effect, (offscreen) =>\n drawShaderEffectChain(r, offscreen, graph, node, below, renderContent)\n )\n if (!drawn) drawShaderEffectChain(r, canvas, graph, node, below, renderContent)\n}\n\n/**\n * Draws `effect` over `node`'s bounds, calling `renderContent` with an offscreen canvas to paint\n * the layer into. Returns false when nothing compiled or the layer is too large to snapshot, so\n * the caller draws the layer as it would without the effect.\n */\nexport function drawShaderEffectLayer(\n r: SkiaRenderer,\n canvas: Canvas,\n graph: SceneGraph,\n node: SceneNode,\n effect: ShaderEffect,\n renderContent: (canvas: Canvas) => void\n): boolean {\n if (!(node.width > 0) || !(node.height > 0)) return false\n const compiled = effectFor(r, effect)\n if (!compiled?.effect) return false\n\n const scale = deviceScale(canvas)\n const width = Math.ceil(node.width * scale)\n const height = Math.ceil(node.height * scale)\n if (width > MAX_SIDE || height > MAX_SIDE) return false\n\n let surface: Surface | null = null\n let image: Image | null = null\n const children: Shader[] = []\n let drawn: Shader | null = null\n try {\n surface = r.surface.makeSurface({\n width,\n height,\n colorType: r.ck.ColorType.RGBA_8888,\n alphaType: r.ck.AlphaType.Premul,\n colorSpace: skColorSpace(r.ck, r.documentColorSpace)\n })\n const offscreen = surface.getCanvas()\n offscreen.clear(r.ck.TRANSPARENT)\n offscreen.scale(scale, scale)\n renderContent(offscreen)\n surface.flush()\n\n image = surface.makeImageSnapshot()\n const samplers = compiled.uniforms.filter((uniform) => uniform.kind === 'sampler')\n for (const sampler of samplers) {\n if (sampler.automatic === 'object') {\n children.push(objectShader(r, image, scale))\n continue\n }\n const child = sdfShader(r.ck, r, node)\n if (!child) return false\n children.push(child)\n }\n\n const frame: ShaderFrame = {\n width: node.width,\n height: node.height,\n time: (Date.now() - startedAt) / 1000,\n mouse: { x: 0, y: 0 }\n }\n const uniforms = packShaderUniforms(\n compiled,\n boundUniformValues(effect.uniforms, effect.uniformBindings, graph, node.id),\n frame\n )\n drawn = compiled.effect.makeShaderWithChildren(uniforms, children)\n r.auxFill.setShader(drawn)\n r.auxFill.setAlphaf(1)\n setPaintBlendMode(r, r.auxFill, effect.blendMode)\n canvas.drawRect(r.ck.LTRBRect(0, 0, node.width, node.height), r.auxFill)\n r.auxFill.setShader(null)\n return true\n } catch {\n return false\n } finally {\n drawn?.delete()\n for (const child of children) child.delete()\n image?.delete()\n surface?.delete()\n }\n}\n"],"mappings":";;;;;;;AAoBA,MAAM,WAAW;;AAGjB,MAAM,YAAY,KAAK,IAAI;;;;;;AAO3B,SAAS,UAAU,GAAiB,QAA6C;CAC/E,MAAM,WAAW,cAAc,EAAE,IAAI,OAAO,MAAM;CAClD,OAAO,SAAS,SAAS,WAAW;AACtC;;AAGA,SAAS,YAAY,QAAwB;CAC3C,MAAM,SAAS,OAAO,eAAe;CACrC,OAAO,KAAK,MAAM,OAAO,MAAM,GAAG,OAAO,MAAM,CAAC,KAAK;AACvD;;AAGA,SAAS,aAAa,GAAiB,OAAc,OAAuB;CAC1E,MAAM,UAAU;EAAC;EAAO;EAAG;EAAG;EAAG;EAAO;EAAG;EAAG;EAAG;CAAC;CAClD,OAAO,MAAM,kBACX,EAAE,GAAG,SAAS,OACd,EAAE,GAAG,SAAS,OACd,EAAE,GAAG,WAAW,QAChB,EAAE,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,SAAS,SAAS;EACjF,KAAK,MAAM,WAAW,UAAU;GAC9B,IAAI,QAAQ,cAAc,UAAU;IAClC,SAAS,KAAK,aAAa,GAAG,OAAO,KAAK,CAAC;IAC3C;GACF;GACA,MAAM,QAAQ,UAAU,EAAE,IAAI,GAAG,IAAI;GACrC,IAAI,CAAC,OAAO,OAAO;GACnB,SAAS,KAAK,KAAK;EACrB;EAEA,MAAM,QAAqB;GACzB,OAAO,KAAK;GACZ,QAAQ,KAAK;GACb,OAAO,KAAK,IAAI,IAAI,aAAa;GACjC,OAAO;IAAE,GAAG;IAAG,GAAG;GAAE;EACtB;EACA,MAAM,WAAW,mBACf,UACA,mBAAmB,OAAO,UAAU,OAAO,iBAAiB,OAAO,KAAK,EAAE,GAC1E,KACF;EACA,QAAQ,SAAS,OAAO,uBAAuB,UAAU,QAAQ;EACjE,EAAE,QAAQ,UAAU,KAAK;EACzB,EAAE,QAAQ,UAAU,CAAC;EACrB,kBAAkB,GAAG,EAAE,SAAS,OAAO,SAAS;EAChD,OAAO,SAAS,EAAE,GAAG,SAAS,GAAG,GAAG,KAAK,OAAO,KAAK,MAAM,GAAG,EAAE,OAAO;EACvE,EAAE,QAAQ,UAAU,IAAI;EACxB,OAAO;CACT,QAAQ;EACN,OAAO;CACT,UAAU;EACR,OAAO,OAAO;EACd,KAAK,MAAM,SAAS,UAAU,MAAM,OAAO;EAC3C,OAAO,OAAO;EACd,SAAS,OAAO;CAClB;AACF"}
@@ -15,7 +15,7 @@ declare function createUndoBridge(undoActions: UndoActions, selection: Selection
15
15
  commitMove: (originals: Map<string, import("@pairdraw/scene-graph/primitives").Vector>) => void;
16
16
  commitMoveWithReparent: (originals: Map<string, MovePlace>) => void;
17
17
  commitDuplicateMove: (rootIds: string[], previousSelection: Set<string>) => void;
18
- commitResize: (nodeId: string, original: import("@pairdraw/scene-graph/primitives").Rect & Partial<Pick<import("@pairdraw/scene-graph").SceneNode, "vectorNetwork" | "fillGeometry" | "strokeGeometry" | "derivedTextGlyphs" | "strokes" | "textPathData" | "textPathBox">>) => void;
18
+ commitResize: (nodeId: string, original: import("@pairdraw/scene-graph/primitives").Rect & Partial<Pick<import("@pairdraw/scene-graph").SceneNode, "strokes" | "vectorNetwork" | "fillGeometry" | "strokeGeometry" | "derivedTextGlyphs" | "textPathData" | "textPathBox">>) => void;
19
19
  commitGroupResize: (nodeId: string, origRect: import("@pairdraw/scene-graph/primitives").Rect, origChildren: Map<string, import("@pairdraw/scene-graph/resize").ResizeSnapshot>) => void;
20
20
  commitRotation: (nodeId: string, origRotation: number) => void;
21
21
  commitNodeUpdate: (nodeId: string, previous: Partial<import("@pairdraw/scene-graph").SceneNode>, label?: string) => void;
@@ -31,7 +31,7 @@ function createClipboardExportActions(ctx) {
31
31
  async function copySelectionAsHTML(ids) {
32
32
  if (ids.length === 0) return null;
33
33
  const { renderNodesToHTML } = await import("../../io/formats/html/index.js");
34
- const { html } = await renderNodesToHTML(ctx.graph, ids, {
34
+ const { html, draws } = await renderNodesToHTML(ctx.graph, ids, {
35
35
  html: "fragment",
36
36
  style: "inline",
37
37
  assets: "inline"
@@ -39,7 +39,7 @@ function createClipboardExportActions(ctx) {
39
39
  canvasKit: ctx.getCk() ?? void 0,
40
40
  renderer: ctx.getRenderer() ?? void 0
41
41
  });
42
- return html || null;
42
+ return draws ? html || null : null;
43
43
  }
44
44
  return {
45
45
  copySelectionAsText,
@@ -1 +1 @@
1
- {"version":3,"file":"export.js","names":[],"sources":["../../../src/editor/clipboard/export.ts"],"sourcesContent":["import { selectionToJSX } from '@pairdraw/design-jsx'\n\nimport type { EditorContext } from '#core/editor/types'\nimport type { BooleanPathResolver } from '#core/io/formats/boolean-path'\nimport { renderNodesToLaidOutSVG } from '#core/io/formats/svg/text/layout'\n\nexport function createClipboardExportActions(ctx: EditorContext) {\n /**\n * The copies compute an authored boolean's result with the app's own renderer, as an export\n * does, so copying never loads a second CanvasKit; a headless editor falls back to one. The\n * module is imported on copy rather than statically because it carries the raster renderer,\n * which the editor would otherwise load for a feature most copies never use.\n */\n async function booleanPath(): Promise<BooleanPathResolver | undefined> {\n const { booleanPathResolver, needsBooleanPaths } = await import('#core/io/formats/boolean-path')\n if (!needsBooleanPaths(ctx.graph)) return undefined\n return booleanPathResolver(ctx.getCk() ?? undefined, ctx.getRenderer() ?? undefined)\n }\n\n function copySelectionAsText(ids: string[]): string {\n return ids.map((id) => ctx.graph.getNode(id)?.name ?? id).join('\\n')\n }\n\n async function copySelectionAsSVG(ids: string[]): Promise<string | null> {\n const nodeIds =\n ids.length > 0 ? ids : ctx.graph.getChildren(ctx.state.currentPageId).map((n) => n.id)\n return renderNodesToLaidOutSVG(ctx.graph, ctx.state.currentPageId, nodeIds, {\n booleanPath: await booleanPath()\n })\n }\n\n function copySelectionAsJSX(ids: string[]): string | null {\n return ids.length > 0 ? selectionToJSX(ids, ctx.graph) : null\n }\n\n /**\n * The layers as one self-contained HTML fragment, as the HTML export writes them: inline\n * styles, and images inlined as data URLs so the markup works wherever it is pasted. Null for\n * no layers or none that draw.\n */\n async function copySelectionAsHTML(ids: string[]): Promise<string | null> {\n if (ids.length === 0) return null\n const { renderNodesToHTML } = await import('#core/io/formats/html')\n const { html } = await renderNodesToHTML(\n ctx.graph,\n ids,\n { html: 'fragment', style: 'inline', assets: 'inline' },\n undefined,\n { canvasKit: ctx.getCk() ?? undefined, renderer: ctx.getRenderer() ?? undefined }\n )\n return html || null\n }\n\n return { copySelectionAsText, copySelectionAsSVG, copySelectionAsJSX, copySelectionAsHTML }\n}\n"],"mappings":";;;AAMA,SAAgB,6BAA6B,KAAoB;;;;;;;CAO/D,eAAe,cAAwD;EACrE,MAAM,EAAE,qBAAqB,sBAAsB,MAAM,OAAO;EAChE,IAAI,CAAC,kBAAkB,IAAI,KAAK,GAAG,OAAO,KAAA;EAC1C,OAAO,oBAAoB,IAAI,MAAM,KAAK,KAAA,GAAW,IAAI,YAAY,KAAK,KAAA,CAAS;CACrF;CAEA,SAAS,oBAAoB,KAAuB;EAClD,OAAO,IAAI,KAAK,OAAO,IAAI,MAAM,QAAQ,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,KAAK,IAAI;CACrE;CAEA,eAAe,mBAAmB,KAAuC;EACvE,MAAM,UACJ,IAAI,SAAS,IAAI,MAAM,IAAI,MAAM,YAAY,IAAI,MAAM,aAAa,CAAC,CAAC,KAAK,MAAM,EAAE,EAAE;EACvF,OAAO,wBAAwB,IAAI,OAAO,IAAI,MAAM,eAAe,SAAS,EAC1E,aAAa,MAAM,YAAY,EACjC,CAAC;CACH;CAEA,SAAS,mBAAmB,KAA8B;EACxD,OAAO,IAAI,SAAS,IAAI,eAAe,KAAK,IAAI,KAAK,IAAI;CAC3D;;;;;;CAOA,eAAe,oBAAoB,KAAuC;EACxE,IAAI,IAAI,WAAW,GAAG,OAAO;EAC7B,MAAM,EAAE,sBAAsB,MAAM,OAAO;EAC3C,MAAM,EAAE,SAAS,MAAM,kBACrB,IAAI,OACJ,KACA;GAAE,MAAM;GAAY,OAAO;GAAU,QAAQ;EAAS,GACtD,KAAA,GACA;GAAE,WAAW,IAAI,MAAM,KAAK,KAAA;GAAW,UAAU,IAAI,YAAY,KAAK,KAAA;EAAU,CAClF;EACA,OAAO,QAAQ;CACjB;CAEA,OAAO;EAAE;EAAqB;EAAoB;EAAoB;CAAoB;AAC5F"}
1
+ {"version":3,"file":"export.js","names":[],"sources":["../../../src/editor/clipboard/export.ts"],"sourcesContent":["import { selectionToJSX } from '@pairdraw/design-jsx'\n\nimport type { EditorContext } from '#core/editor/types'\nimport type { BooleanPathResolver } from '#core/io/formats/boolean-path'\nimport { renderNodesToLaidOutSVG } from '#core/io/formats/svg/text/layout'\n\nexport function createClipboardExportActions(ctx: EditorContext) {\n /**\n * The copies compute an authored boolean's result with the app's own renderer, as an export\n * does, so copying never loads a second CanvasKit; a headless editor falls back to one. The\n * module is imported on copy rather than statically because it carries the raster renderer,\n * which the editor would otherwise load for a feature most copies never use.\n */\n async function booleanPath(): Promise<BooleanPathResolver | undefined> {\n const { booleanPathResolver, needsBooleanPaths } = await import('#core/io/formats/boolean-path')\n if (!needsBooleanPaths(ctx.graph)) return undefined\n return booleanPathResolver(ctx.getCk() ?? undefined, ctx.getRenderer() ?? undefined)\n }\n\n function copySelectionAsText(ids: string[]): string {\n return ids.map((id) => ctx.graph.getNode(id)?.name ?? id).join('\\n')\n }\n\n async function copySelectionAsSVG(ids: string[]): Promise<string | null> {\n const nodeIds =\n ids.length > 0 ? ids : ctx.graph.getChildren(ctx.state.currentPageId).map((n) => n.id)\n return renderNodesToLaidOutSVG(ctx.graph, ctx.state.currentPageId, nodeIds, {\n booleanPath: await booleanPath()\n })\n }\n\n function copySelectionAsJSX(ids: string[]): string | null {\n return ids.length > 0 ? selectionToJSX(ids, ctx.graph) : null\n }\n\n /**\n * The layers as one self-contained HTML fragment, as the HTML export writes them: inline\n * styles, and images inlined as data URLs so the markup works wherever it is pasted. Null for\n * no layers or none that draw.\n */\n async function copySelectionAsHTML(ids: string[]): Promise<string | null> {\n if (ids.length === 0) return null\n const { renderNodesToHTML } = await import('#core/io/formats/html')\n const { html, draws } = await renderNodesToHTML(\n ctx.graph,\n ids,\n { html: 'fragment', style: 'inline', assets: 'inline' },\n undefined,\n { canvasKit: ctx.getCk() ?? undefined, renderer: ctx.getRenderer() ?? undefined }\n )\n return draws ? html || null : null\n }\n\n return { copySelectionAsText, copySelectionAsSVG, copySelectionAsJSX, copySelectionAsHTML }\n}\n"],"mappings":";;;AAMA,SAAgB,6BAA6B,KAAoB;;;;;;;CAO/D,eAAe,cAAwD;EACrE,MAAM,EAAE,qBAAqB,sBAAsB,MAAM,OAAO;EAChE,IAAI,CAAC,kBAAkB,IAAI,KAAK,GAAG,OAAO,KAAA;EAC1C,OAAO,oBAAoB,IAAI,MAAM,KAAK,KAAA,GAAW,IAAI,YAAY,KAAK,KAAA,CAAS;CACrF;CAEA,SAAS,oBAAoB,KAAuB;EAClD,OAAO,IAAI,KAAK,OAAO,IAAI,MAAM,QAAQ,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,KAAK,IAAI;CACrE;CAEA,eAAe,mBAAmB,KAAuC;EACvE,MAAM,UACJ,IAAI,SAAS,IAAI,MAAM,IAAI,MAAM,YAAY,IAAI,MAAM,aAAa,CAAC,CAAC,KAAK,MAAM,EAAE,EAAE;EACvF,OAAO,wBAAwB,IAAI,OAAO,IAAI,MAAM,eAAe,SAAS,EAC1E,aAAa,MAAM,YAAY,EACjC,CAAC;CACH;CAEA,SAAS,mBAAmB,KAA8B;EACxD,OAAO,IAAI,SAAS,IAAI,eAAe,KAAK,IAAI,KAAK,IAAI;CAC3D;;;;;;CAOA,eAAe,oBAAoB,KAAuC;EACxE,IAAI,IAAI,WAAW,GAAG,OAAO;EAC7B,MAAM,EAAE,sBAAsB,MAAM,OAAO;EAC3C,MAAM,EAAE,MAAM,UAAU,MAAM,kBAC5B,IAAI,OACJ,KACA;GAAE,MAAM;GAAY,OAAO;GAAU,QAAQ;EAAS,GACtD,KAAA,GACA;GAAE,WAAW,IAAI,MAAM,KAAK,KAAA;GAAW,UAAU,IAAI,YAAY,KAAK,KAAA;EAAU,CAClF;EACA,OAAO,QAAQ,QAAQ,OAAO;CAChC;CAEA,OAAO;EAAE;EAAqB;EAAoB;EAAoB;CAAoB;AAC5F"}
@@ -193,7 +193,7 @@ declare function createEditor(options?: EditorOptions): {
193
193
  commitMove: (originals: Map<string, import("@pairdraw/scene-graph/primitives").Vector>) => void;
194
194
  commitMoveWithReparent: (originals: Map<string, MovePlace>) => void;
195
195
  commitDuplicateMove: (rootIds: string[], previousSelection: Set<string>) => void;
196
- commitResize: (nodeId: string, original: import("@pairdraw/scene-graph/primitives").Rect & Partial<Pick<SceneNode, "vectorNetwork" | "fillGeometry" | "strokeGeometry" | "derivedTextGlyphs" | "strokes" | "textPathData" | "textPathBox">>) => void;
196
+ commitResize: (nodeId: string, original: import("@pairdraw/scene-graph/primitives").Rect & Partial<Pick<SceneNode, "strokes" | "vectorNetwork" | "fillGeometry" | "strokeGeometry" | "derivedTextGlyphs" | "textPathData" | "textPathBox">>) => void;
197
197
  commitGroupResize: (nodeId: string, origRect: import("@pairdraw/scene-graph/primitives").Rect, origChildren: Map<string, import("@pairdraw/scene-graph/resize").ResizeSnapshot>) => void;
198
198
  commitRotation: (nodeId: string, origRotation: number) => void;
199
199
  snapshotPage: (pageId?: string) => PageSnapshot;
@@ -1,11 +1,26 @@
1
1
  import { SceneGraph } from "@pairdraw/scene-graph";
2
2
  //#region src/io/formats/drawio/warnings.d.ts
3
+ /**
4
+ * What a draw.io file could not hold, as facts rather than a sentence: the app shows these in the
5
+ * reader's language, while the CLI and MCP print `drawioWriteWarningText` of each.
6
+ */
7
+ interface DrawioWriteWarning {
8
+ kind: 'unbound-variables';
9
+ /** Variables the graph holds, none of which draw.io can carry. */
10
+ variables: number;
11
+ /** The collections those variables belong to, by name. */
12
+ collections: string[];
13
+ /** Layers painted through a binding, which open without it. */
14
+ layers: number;
15
+ }
3
16
  /**
4
17
  * What a draw.io file cannot hold. draw.io has no variable model and no style that reads one, so
5
18
  * a document that paints with variables arrives in draw.io as plain colours and comes back
6
19
  * unbound. The writer names that loss instead of writing a file that looks complete.
7
20
  */
8
- declare function drawioDroppedWarnings(graph: SceneGraph): string[];
21
+ declare function drawioWriteWarnings(graph: SceneGraph): DrawioWriteWarning[];
22
+ /** The English sentence a write warning has always been reported as. */
23
+ declare function drawioWriteWarningText(warning: DrawioWriteWarning): string;
9
24
  //#endregion
10
- export { drawioDroppedWarnings };
25
+ export { DrawioWriteWarning, drawioWriteWarningText, drawioWriteWarnings };
11
26
  //# sourceMappingURL=warnings.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"warnings.d.ts","names":[],"sources":["../../../../src/io/formats/drawio/warnings.ts"],"mappings":";;;;;;;iBAYgB,sBAAsB,OAAO"}
1
+ {"version":3,"file":"warnings.d.ts","names":[],"sources":["../../../../src/io/formats/drawio/warnings.ts"],"mappings":";;;;;;UAWiB;EACf;;EAEA;;EAEA;;EAEA;;;;;;;iBAQc,oBAAoB,OAAO,aAAa;;iBAWxC,uBAAuB,SAAS"}
@@ -8,16 +8,23 @@ function counted(count, one, many) {
8
8
  * a document that paints with variables arrives in draw.io as plain colours and comes back
9
9
  * unbound. The writer names that loss instead of writing a file that looks complete.
10
10
  */
11
- function drawioDroppedWarnings(graph) {
11
+ function drawioWriteWarnings(graph) {
12
12
  const variables = graph.getLiveVariables().length;
13
13
  if (variables === 0) return [];
14
- const names = graph.getLiveCollections().map((collection) => collection.name);
15
- const dropped = `draw.io has no variables: ${counted(variables, "variable", "variables")} in ${counted(names.length, "collection", "collections")} (${names.join(", ")}) not written`;
16
- const bound = [...graph.nodes.values()].filter((node) => Object.keys(node.boundVariables).length > 0).length;
17
- if (bound === 0) return [dropped];
18
- return [`${dropped}, and ${bound === 1 ? "1 layer that uses one lost the binding" : `${counted(bound, "layer", "layers")} that use them lost the binding`}`];
14
+ return [{
15
+ kind: "unbound-variables",
16
+ variables,
17
+ collections: graph.getLiveCollections().map((collection) => collection.name),
18
+ layers: [...graph.nodes.values()].filter((node) => Object.keys(node.boundVariables).length > 0).length
19
+ }];
20
+ }
21
+ /** The English sentence a write warning has always been reported as. */
22
+ function drawioWriteWarningText(warning) {
23
+ const dropped = `draw.io has no variables: ${counted(warning.variables, "variable", "variables")} in ${counted(warning.collections.length, "collection", "collections")} (${warning.collections.join(", ")}) not written`;
24
+ if (warning.layers === 0) return dropped;
25
+ return `${dropped}, and ${warning.layers === 1 ? "1 layer that uses one lost the binding" : `${counted(warning.layers, "layer", "layers")} that use them lost the binding`}`;
19
26
  }
20
27
  //#endregion
21
- export { drawioDroppedWarnings };
28
+ export { drawioWriteWarningText, drawioWriteWarnings };
22
29
 
23
30
  //# sourceMappingURL=warnings.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"warnings.js","names":[],"sources":["../../../../src/io/formats/drawio/warnings.ts"],"sourcesContent":["import type { SceneGraph } from '@pairdraw/scene-graph'\n\n/** `3 variables`, with the noun matching the count. */\nfunction counted(count: number, one: string, many: string): string {\n return `${count} ${count === 1 ? one : many}`\n}\n\n/**\n * What a draw.io file cannot hold. draw.io has no variable model and no style that reads one, so\n * a document that paints with variables arrives in draw.io as plain colours and comes back\n * unbound. The writer names that loss instead of writing a file that looks complete.\n */\nexport function drawioDroppedWarnings(graph: SceneGraph): string[] {\n const variables = graph.getLiveVariables().length\n if (variables === 0) return []\n const names = graph.getLiveCollections().map((collection) => collection.name)\n const dropped = `draw.io has no variables: ${counted(variables, 'variable', 'variables')} in ${counted(names.length, 'collection', 'collections')} (${names.join(', ')}) not written`\n const bound = [...graph.nodes.values()].filter(\n (node) => Object.keys(node.boundVariables).length > 0\n ).length\n if (bound === 0) return [dropped]\n const users =\n bound === 1\n ? '1 layer that uses one lost the binding'\n : `${counted(bound, 'layer', 'layers')} that use them lost the binding`\n return [`${dropped}, and ${users}`]\n}\n"],"mappings":";;AAGA,SAAS,QAAQ,OAAe,KAAa,MAAsB;CACjE,OAAO,GAAG,MAAM,GAAG,UAAU,IAAI,MAAM;AACzC;;;;;;AAOA,SAAgB,sBAAsB,OAA6B;CACjE,MAAM,YAAY,MAAM,iBAAiB,CAAC,CAAC;CAC3C,IAAI,cAAc,GAAG,OAAO,CAAC;CAC7B,MAAM,QAAQ,MAAM,mBAAmB,CAAC,CAAC,KAAK,eAAe,WAAW,IAAI;CAC5E,MAAM,UAAU,6BAA6B,QAAQ,WAAW,YAAY,WAAW,EAAE,MAAM,QAAQ,MAAM,QAAQ,cAAc,aAAa,EAAE,IAAI,MAAM,KAAK,IAAI,EAAE;CACvK,MAAM,QAAQ,CAAC,GAAG,MAAM,MAAM,OAAO,CAAC,CAAC,CAAC,QACrC,SAAS,OAAO,KAAK,KAAK,cAAc,CAAC,CAAC,SAAS,CACtD,CAAC,CAAC;CACF,IAAI,UAAU,GAAG,OAAO,CAAC,OAAO;CAKhC,OAAO,CAAC,GAAG,QAAQ,QAHjB,UAAU,IACN,2CACA,GAAG,QAAQ,OAAO,SAAS,QAAQ,EAAE,kCACT;AACpC"}
1
+ {"version":3,"file":"warnings.js","names":[],"sources":["../../../../src/io/formats/drawio/warnings.ts"],"sourcesContent":["import type { SceneGraph } from '@pairdraw/scene-graph'\n\n/** `3 variables`, with the noun matching the count. */\nfunction counted(count: number, one: string, many: string): string {\n return `${count} ${count === 1 ? one : many}`\n}\n\n/**\n * What a draw.io file could not hold, as facts rather than a sentence: the app shows these in the\n * reader's language, while the CLI and MCP print `drawioWriteWarningText` of each.\n */\nexport interface DrawioWriteWarning {\n kind: 'unbound-variables'\n /** Variables the graph holds, none of which draw.io can carry. */\n variables: number\n /** The collections those variables belong to, by name. */\n collections: string[]\n /** Layers painted through a binding, which open without it. */\n layers: number\n}\n\n/**\n * What a draw.io file cannot hold. draw.io has no variable model and no style that reads one, so\n * a document that paints with variables arrives in draw.io as plain colours and comes back\n * unbound. The writer names that loss instead of writing a file that looks complete.\n */\nexport function drawioWriteWarnings(graph: SceneGraph): DrawioWriteWarning[] {\n const variables = graph.getLiveVariables().length\n if (variables === 0) return []\n const collections = graph.getLiveCollections().map((collection) => collection.name)\n const layers = [...graph.nodes.values()].filter(\n (node) => Object.keys(node.boundVariables).length > 0\n ).length\n return [{ kind: 'unbound-variables', variables, collections, layers }]\n}\n\n/** The English sentence a write warning has always been reported as. */\nexport function drawioWriteWarningText(warning: DrawioWriteWarning): string {\n const dropped = `draw.io has no variables: ${counted(warning.variables, 'variable', 'variables')} in ${counted(warning.collections.length, 'collection', 'collections')} (${warning.collections.join(', ')}) not written`\n if (warning.layers === 0) return dropped\n const users =\n warning.layers === 1\n ? '1 layer that uses one lost the binding'\n : `${counted(warning.layers, 'layer', 'layers')} that use them lost the binding`\n return `${dropped}, and ${users}`\n}\n"],"mappings":";;AAGA,SAAS,QAAQ,OAAe,KAAa,MAAsB;CACjE,OAAO,GAAG,MAAM,GAAG,UAAU,IAAI,MAAM;AACzC;;;;;;AAqBA,SAAgB,oBAAoB,OAAyC;CAC3E,MAAM,YAAY,MAAM,iBAAiB,CAAC,CAAC;CAC3C,IAAI,cAAc,GAAG,OAAO,CAAC;CAK7B,OAAO,CAAC;EAAE,MAAM;EAAqB;EAAW,aAJ5B,MAAM,mBAAmB,CAAC,CAAC,KAAK,eAAe,WAAW,IAIpB;EAAG,QAH9C,CAAC,GAAG,MAAM,MAAM,OAAO,CAAC,CAAC,CAAC,QACtC,SAAS,OAAO,KAAK,KAAK,cAAc,CAAC,CAAC,SAAS,CACtD,CAAC,CAAC;CACkE,CAAC;AACvE;;AAGA,SAAgB,uBAAuB,SAAqC;CAC1E,MAAM,UAAU,6BAA6B,QAAQ,QAAQ,WAAW,YAAY,WAAW,EAAE,MAAM,QAAQ,QAAQ,YAAY,QAAQ,cAAc,aAAa,EAAE,IAAI,QAAQ,YAAY,KAAK,IAAI,EAAE;CAC3M,IAAI,QAAQ,WAAW,GAAG,OAAO;CAKjC,OAAO,GAAG,QAAQ,QAHhB,QAAQ,WAAW,IACf,2CACA,GAAG,QAAQ,QAAQ,QAAQ,SAAS,QAAQ,EAAE;AAEtD"}
@@ -4,6 +4,7 @@ import { SceneGraph } from "@pairdraw/scene-graph";
4
4
  declare function renderNodesToHTML(graph: SceneGraph, nodeIds: string[], options?: HTMLExportOptions, fileName?: string, context?: IOContext): Promise<{
5
5
  html: string;
6
6
  assets: ExportAsset[];
7
+ draws: boolean;
7
8
  }>;
8
9
  //#endregion
9
10
  export { renderNodesToHTML };
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/io/formats/html/index.ts"],"mappings":";;;iBAwCsB,kBACpB,OAAO,YACP,mBACA,UAAS,mBACT,mBACA,UAAU,YACT;EAAU;EAAc,QAAQ"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/io/formats/html/index.ts"],"mappings":";;;iBAyCsB,kBACpB,OAAO,YACP,mBACA,UAAS,mBACT,mBACA,UAAU,YACT;EAAU;EAAc,QAAQ;EAAe"}
@@ -1,7 +1,7 @@
1
1
  import { vectorElement } from "./vectors.js";
2
2
  import { exportWebFontFaceAssets } from "../../../text/web-font/assets.js";
3
3
  import { filename } from "pathe/utils";
4
- import { exportHTMLBundle, sceneNodesToDesignDocument } from "@pairdraw/dom-css/export";
4
+ import { designNodeDraws, exportHTMLBundle, sceneNodesToDesignDocument } from "@pairdraw/dom-css/export";
5
5
  //#region src/io/formats/html/index.ts
6
6
  async function designDocument(graph, nodeIds, options, context) {
7
7
  const { booleanPathResolver, needsBooleanPaths } = await import("../boolean-path.js");
@@ -18,7 +18,8 @@ function assetBasePath(fileName) {
18
18
  return `${fileName && filename(fileName) || "export"}.assets`;
19
19
  }
20
20
  async function renderNodesToHTML(graph, nodeIds, options = {}, fileName, context) {
21
- const bundle = await exportHTMLBundle(await designDocument(graph, nodeIds, options, context), {
21
+ const projected = await designDocument(graph, nodeIds, options, context);
22
+ const bundle = await exportHTMLBundle(projected, {
22
23
  html: options.html,
23
24
  style: options.style,
24
25
  assets: options.assets,
@@ -33,7 +34,8 @@ async function renderNodesToHTML(graph, nodeIds, options = {}, fileName, context
33
34
  if (typeof page?.content !== "string") throw new Error("HTML export produced no page");
34
35
  return {
35
36
  html: page.content,
36
- assets: bundle.files.filter((file) => file !== page)
37
+ assets: bundle.files.filter((file) => file !== page),
38
+ draws: projected.children.some(designNodeDraws)
37
39
  };
38
40
  }
39
41
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../src/io/formats/html/index.ts"],"sourcesContent":["import { filename } from 'pathe/utils'\n\nimport {\n exportHTMLBundle,\n sceneNodesToDesignDocument,\n type DesignDocument\n} from '@pairdraw/dom-css/export'\nimport type { SceneGraph } from '@pairdraw/scene-graph'\n\nimport type { ExportAsset, HTMLExportOptions, IOContext } from '#core/io/types'\nimport { exportWebFontFaceAssets } from '#core/text/web-font/assets'\n\nimport { vectorElement } from './vectors'\n\nasync function designDocument(\n graph: SceneGraph,\n nodeIds: string[],\n options: HTMLExportOptions,\n context?: IOContext\n): Promise<DesignDocument> {\n const { booleanPathResolver, needsBooleanPaths } = await import('#core/io/formats/boolean-path')\n const booleanPath = needsBooleanPaths(graph)\n ? await booleanPathResolver(context?.canvasKit, context?.renderer)\n : undefined\n // Layer names help find a layer in the markup; IDs only matter to tools that link back.\n const projection = {\n vectorElement: (vectorGraph: SceneGraph, node: Parameters<typeof vectorElement>[1]) =>\n vectorElement(vectorGraph, node, booleanPath),\n includeLayerNames: options.layerNames ?? true,\n includeSourceIds: options.layerIds ?? false\n }\n return sceneNodesToDesignDocument(graph, nodeIds, projection)\n}\n\n/** `card.html` keeps its external files in `card.assets/` next to it, whatever the path style. */\nfunction assetBasePath(fileName: string | undefined): string {\n const name = fileName && filename(fileName)\n return `${name || 'export'}.assets`\n}\n\nexport async function renderNodesToHTML(\n graph: SceneGraph,\n nodeIds: string[],\n options: HTMLExportOptions = {},\n fileName?: string,\n context?: IOContext\n): Promise<{ html: string; assets: ExportAsset[] }> {\n const bundle = await exportHTMLBundle(await designDocument(graph, nodeIds, options, context), {\n html: options.html,\n style: options.style,\n assets: options.assets,\n fonts:\n options.fonts === 'assets'\n ? async (fonts, basePath) =>\n (await exportWebFontFaceAssets({ fonts, assetBasePath: basePath })).assets\n : 'none',\n assetBasePath: assetBasePath(fileName),\n loadTailwindStylesheet: options.loadTailwindStylesheet\n })\n const page = bundle.files.find((file) => file.path === bundle.entrypoint)\n if (typeof page?.content !== 'string') throw new Error('HTML export produced no page')\n return { html: page.content, assets: bundle.files.filter((file) => file !== page) }\n}\n"],"mappings":";;;;;AAcA,eAAe,eACb,OACA,SACA,SACA,SACyB;CACzB,MAAM,EAAE,qBAAqB,sBAAsB,MAAM,OAAO;CAChE,MAAM,cAAc,kBAAkB,KAAK,IACvC,MAAM,oBAAoB,SAAS,WAAW,SAAS,QAAQ,IAC/D,KAAA;CAEJ,MAAM,aAAa;EACjB,gBAAgB,aAAyB,SACvC,cAAc,aAAa,MAAM,WAAW;EAC9C,mBAAmB,QAAQ,cAAc;EACzC,kBAAkB,QAAQ,YAAY;CACxC;CACA,OAAO,2BAA2B,OAAO,SAAS,UAAU;AAC9D;;AAGA,SAAS,cAAc,UAAsC;CAE3D,OAAO,GADM,YAAY,SAAS,QAAQ,KACxB,SAAS;AAC7B;AAEA,eAAsB,kBACpB,OACA,SACA,UAA6B,CAAC,GAC9B,UACA,SACkD;CAClD,MAAM,SAAS,MAAM,iBAAiB,MAAM,eAAe,OAAO,SAAS,SAAS,OAAO,GAAG;EAC5F,MAAM,QAAQ;EACd,OAAO,QAAQ;EACf,QAAQ,QAAQ;EAChB,OACE,QAAQ,UAAU,WACd,OAAO,OAAO,cACX,MAAM,wBAAwB;GAAE;GAAO,eAAe;EAAS,CAAC,EAAA,CAAG,SACtE;EACN,eAAe,cAAc,QAAQ;EACrC,wBAAwB,QAAQ;CAClC,CAAC;CACD,MAAM,OAAO,OAAO,MAAM,MAAM,SAAS,KAAK,SAAS,OAAO,UAAU;CACxE,IAAI,OAAO,MAAM,YAAY,UAAU,MAAM,IAAI,MAAM,8BAA8B;CACrF,OAAO;EAAE,MAAM,KAAK;EAAS,QAAQ,OAAO,MAAM,QAAQ,SAAS,SAAS,IAAI;CAAE;AACpF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../src/io/formats/html/index.ts"],"sourcesContent":["import { filename } from 'pathe/utils'\n\nimport {\n designNodeDraws,\n exportHTMLBundle,\n sceneNodesToDesignDocument,\n type DesignDocument\n} from '@pairdraw/dom-css/export'\nimport type { SceneGraph } from '@pairdraw/scene-graph'\n\nimport type { ExportAsset, HTMLExportOptions, IOContext } from '#core/io/types'\nimport { exportWebFontFaceAssets } from '#core/text/web-font/assets'\n\nimport { vectorElement } from './vectors'\n\nasync function designDocument(\n graph: SceneGraph,\n nodeIds: string[],\n options: HTMLExportOptions,\n context?: IOContext\n): Promise<DesignDocument> {\n const { booleanPathResolver, needsBooleanPaths } = await import('#core/io/formats/boolean-path')\n const booleanPath = needsBooleanPaths(graph)\n ? await booleanPathResolver(context?.canvasKit, context?.renderer)\n : undefined\n // Layer names help find a layer in the markup; IDs only matter to tools that link back.\n const projection = {\n vectorElement: (vectorGraph: SceneGraph, node: Parameters<typeof vectorElement>[1]) =>\n vectorElement(vectorGraph, node, booleanPath),\n includeLayerNames: options.layerNames ?? true,\n includeSourceIds: options.layerIds ?? false\n }\n return sceneNodesToDesignDocument(graph, nodeIds, projection)\n}\n\n/** `card.html` keeps its external files in `card.assets/` next to it, whatever the path style. */\nfunction assetBasePath(fileName: string | undefined): string {\n const name = fileName && filename(fileName)\n return `${name || 'export'}.assets`\n}\n\nexport async function renderNodesToHTML(\n graph: SceneGraph,\n nodeIds: string[],\n options: HTMLExportOptions = {},\n fileName?: string,\n context?: IOContext\n): Promise<{ html: string; assets: ExportAsset[]; draws: boolean }> {\n const projected = await designDocument(graph, nodeIds, options, context)\n const bundle = await exportHTMLBundle(projected, {\n html: options.html,\n style: options.style,\n assets: options.assets,\n fonts:\n options.fonts === 'assets'\n ? async (fonts, basePath) =>\n (await exportWebFontFaceAssets({ fonts, assetBasePath: basePath })).assets\n : 'none',\n assetBasePath: assetBasePath(fileName),\n loadTailwindStylesheet: options.loadTailwindStylesheet\n })\n const page = bundle.files.find((file) => file.path === bundle.entrypoint)\n if (typeof page?.content !== 'string') throw new Error('HTML export produced no page')\n return {\n html: page.content,\n assets: bundle.files.filter((file) => file !== page),\n draws: projected.children.some(designNodeDraws)\n }\n}\n"],"mappings":";;;;;AAeA,eAAe,eACb,OACA,SACA,SACA,SACyB;CACzB,MAAM,EAAE,qBAAqB,sBAAsB,MAAM,OAAO;CAChE,MAAM,cAAc,kBAAkB,KAAK,IACvC,MAAM,oBAAoB,SAAS,WAAW,SAAS,QAAQ,IAC/D,KAAA;CAEJ,MAAM,aAAa;EACjB,gBAAgB,aAAyB,SACvC,cAAc,aAAa,MAAM,WAAW;EAC9C,mBAAmB,QAAQ,cAAc;EACzC,kBAAkB,QAAQ,YAAY;CACxC;CACA,OAAO,2BAA2B,OAAO,SAAS,UAAU;AAC9D;;AAGA,SAAS,cAAc,UAAsC;CAE3D,OAAO,GADM,YAAY,SAAS,QAAQ,KACxB,SAAS;AAC7B;AAEA,eAAsB,kBACpB,OACA,SACA,UAA6B,CAAC,GAC9B,UACA,SACkE;CAClE,MAAM,YAAY,MAAM,eAAe,OAAO,SAAS,SAAS,OAAO;CACvE,MAAM,SAAS,MAAM,iBAAiB,WAAW;EAC/C,MAAM,QAAQ;EACd,OAAO,QAAQ;EACf,QAAQ,QAAQ;EAChB,OACE,QAAQ,UAAU,WACd,OAAO,OAAO,cACX,MAAM,wBAAwB;GAAE;GAAO,eAAe;EAAS,CAAC,EAAA,CAAG,SACtE;EACN,eAAe,cAAc,QAAQ;EACrC,wBAAwB,QAAQ;CAClC,CAAC;CACD,MAAM,OAAO,OAAO,MAAM,MAAM,SAAS,KAAK,SAAS,OAAO,UAAU;CACxE,IAAI,OAAO,MAAM,YAAY,UAAU,MAAM,IAAI,MAAM,8BAA8B;CACrF,OAAO;EACL,MAAM,KAAK;EACX,QAAQ,OAAO,MAAM,QAAQ,SAAS,SAAS,IAAI;EACnD,OAAO,UAAU,SAAS,KAAK,eAAe;CAChD;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/io/formats/pen/index.ts"],"mappings":";;cAoJa,WAAW"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../../src/io/formats/pen/index.ts"],"mappings":";;cA0Ja,WAAW"}
@@ -152,13 +152,22 @@ const penFormat = {
152
152
  },
153
153
  async writeDocument(graph) {
154
154
  const warnings = [];
155
- return {
155
+ const warningDetails = [];
156
+ const written = {
156
157
  format: "pen",
157
158
  mimeType: "application/json",
158
159
  extension: "pen",
159
- data: writePenDocument(graph, { warnings }),
160
- encoding: "utf8",
161
- ...warnings.length > 0 ? { warnings } : {}
160
+ data: writePenDocument(graph, {
161
+ warnings,
162
+ warningDetails
163
+ }),
164
+ encoding: "utf8"
165
+ };
166
+ if (warningDetails.length === 0) return written;
167
+ return {
168
+ ...written,
169
+ warnings,
170
+ warningDetails
162
171
  };
163
172
  }
164
173
  };
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../src/io/formats/pen/index.ts"],"sourcesContent":["import { groupBy } from 'es-toolkit'\n\nimport {\n buildPenGraph,\n isDataURL,\n parseImportedImageURL,\n parsePenDocument,\n penAssets,\n withUsedImports,\n writePenDocument,\n type PenIconRequest,\n type PenIconSource\n} from '@pairdraw/pen'\n\nimport { defaultIcons, drawIcon, type IconData, type IconProvider } from '#core/icons'\nimport type { IOFormatAdapter, ReadDocumentInput, ReadDocumentWarning } from '#core/io/types'\nimport { layoutAuthoredNodes } from '#core/layout'\n\nimport { loadPenFonts } from './fonts'\nimport { loadPenImports, readImportedImage, UnresolvedImports, type OpenedImport } from './imports'\n\n/** The size icons are fetched at; each is scaled to the box it is drawn in. */\nconst PEN_ICON_SIZE = 24\n\n/** How many names one warning lists, so a broken document cannot flood the host's notice. */\nconst WARNING_NAMES = 10\n\n/** One warning for the names found, capped, or none when nothing was found. */\nfunction warningList<K extends 'unknown-variable' | 'missing-image' | 'unknown-node'>(\n kind: K,\n field: K extends 'unknown-variable' ? 'names' : K extends 'missing-image' ? 'urls' : 'types',\n names: ReadonlySet<string>\n): ReadDocumentWarning[] {\n return names.size > 0\n ? [{ kind, [field]: [...names].slice(0, WARNING_NAMES) } as ReadDocumentWarning]\n : []\n}\n\n/**\n * The path a percent-encoded image URL names, decoded one step at a time: a step that would become\n * a separator or a parent keeps its escape, so a URL cannot name a file outside its folder.\n */\nfunction decodeAssetPath(url: string): string {\n return url\n .split('/')\n .map((segment) => {\n let decoded: string\n try {\n decoded = decodeURIComponent(segment)\n } catch {\n return segment\n }\n if (decoded === '.' || decoded === '..') return segment\n return decoded.replaceAll('/', '%2F').replaceAll('\\\\', '%5C')\n })\n .join('/')\n}\n\n/**\n * An image's bytes: a data URL decoded by the platform's own URL handling, an imported document's\n * file beside that document, and any other file through the host; null when that fails.\n */\nasync function loadPenFile(\n url: string,\n input: ReadDocumentInput,\n opened: ReadonlyMap<string, OpenedImport>\n): Promise<Uint8Array | null> {\n try {\n if (parseImportedImageURL(url)) return await readImportedImage(opened, url)\n // pen.dev writes the path percent-encoded, as `My%20Design-assets/…`.\n if (!isDataURL(url)) return (await input.readAsset?.(decodeAssetPath(url))) ?? null\n // Through `URL`, which lowercases the scheme for runtimes that only fetch `data:`.\n return new Uint8Array(await (await fetch(new URL(url))).arrayBuffer())\n } catch {\n return null\n }\n}\n\n/**\n * The shader files the document's paints and effects name, as their source text. One whose file the\n * host cannot read is left out, so its shader draws nothing rather than an empty frame.\n */\nasync function loadPenShaders(\n urls: readonly string[],\n input: ReadDocumentInput,\n opened: ReadonlyMap<string, OpenedImport>\n): Promise<Map<string, string>> {\n const shaders = new Map<string, string>()\n await Promise.all(\n urls.map(async (url) => {\n const bytes = await loadPenFile(url, input, opened)\n if (bytes) shaders.set(url, new TextDecoder().decode(bytes))\n })\n )\n return shaders\n}\n\n/** The images the host has, and the URLs it does not, whose paints are dropped. */\nasync function loadPenImages(\n urls: readonly string[],\n input: ReadDocumentInput,\n opened: ReadonlyMap<string, OpenedImport>\n): Promise<{ images: Map<string, Uint8Array>; missing: Set<string> }> {\n const images = new Map<string, Uint8Array>()\n const missing = new Set<string>()\n await Promise.all(\n urls.map(async (url) => {\n const bytes = await loadPenFile(url, input, opened)\n if (bytes) images.set(url, bytes)\n else missing.add(url)\n })\n )\n return { images, missing }\n}\n\n/** A request's options as a key, so requests drawn the same way share a fetch. */\nconst optionsKey = (options: Record<string, number> | undefined) => JSON.stringify(options ?? null)\n\n/**\n * Icons from `provider`, fetched once for each way they are drawn; a document whose icons cannot\n * be fetched opens with empty icons.\n */\nasync function loadPenIcons(\n requests: readonly PenIconRequest[],\n provider: IconProvider\n): Promise<PenIconSource> {\n const glyphs = new Map<string, IconData>()\n const byOptions = groupBy(requests, (request) => optionsKey(request.options))\n await Promise.all(\n Object.values(byOptions).map(async (group) => {\n const names = group.map((request) => request.name)\n const found = await provider\n .icons(names, PEN_ICON_SIZE, group[0]?.options)\n .catch(() => new Map<string, IconData>())\n for (const [name, icon] of found)\n glyphs.set(`${name}\\0${optionsKey(group[0]?.options)}`, icon)\n })\n )\n return {\n draw(graph, frameId, name, size, color, options) {\n const icon = glyphs.get(`${name}\\0${optionsKey(options)}`)\n if (!icon) return false\n drawIcon(graph, frameId, icon, size, color)\n return true\n }\n }\n}\n\nexport const penFormat: IOFormatAdapter<'pen'> = {\n id: 'pen',\n label: 'Pencil Document',\n role: 'interchange-document',\n category: 'document',\n extensions: ['pen'],\n mimeTypes: ['application/json', 'text/plain'],\n support: {\n readDocument: true,\n writeDocument: true\n },\n laysOutOnRead: true,\n matchesFile(fileName, mimeType) {\n return fileName.toLowerCase().endsWith('.pen') || mimeType === 'application/json'\n },\n async readDocument(input, context) {\n const doc = parsePenDocument(new TextDecoder().decode(input.data))\n // The libraries it imports, whose components it uses draw as library components; what the host\n // cannot read draws as placeholders the warnings tell the host about.\n const unresolved = new UnresolvedImports()\n const unknownVariables = new Set<string>()\n const unknownNodes = new Set<string>()\n const { imports, opened } = await loadPenImports(doc, input, unresolved)\n const importsIncomplete = unresolved.warnings().length > 0\n const assets = penAssets(withUsedImports(doc, imports))\n const [{ images, missing }, shaders, icons, fonts] = await Promise.all([\n loadPenImages(assets.images, input, opened),\n loadPenShaders(assets.shaders, input, opened),\n loadPenIcons(assets.icons, context?.icons ?? defaultIcons),\n loadPenFonts(doc.fonts ?? [], (url) => loadPenFile(url, input, opened))\n ])\n // A .pen file stores its layout intent, not the sizes and positions it implies; the hidden\n // library page's components are laid out too, as instances of them copy their layers.\n const graph = buildPenGraph(doc, {\n images,\n shaders,\n icons,\n fonts,\n imports,\n onUnknownVariable: (name) => {\n // A variable of a library that opened without its own imports is covered by that warning.\n if (name.includes(':') && importsIncomplete) return\n unknownVariables.add(name)\n },\n onUnknownNodeType: (type) => unknownNodes.add(type),\n layout: (target) =>\n layoutAuthoredNodes(\n target,\n target.getPages(true).map((page) => page.id)\n )\n })\n const warnings: ReadDocumentWarning[] = [\n ...unresolved.warnings(),\n ...warningList('unknown-variable', 'names', unknownVariables),\n ...warningList('missing-image', 'urls', missing),\n ...warningList('unknown-node', 'types', unknownNodes)\n ]\n return warnings.length > 0\n ? { graph, sourceFormat: 'pen', warnings }\n : { graph, sourceFormat: 'pen' }\n },\n async writeDocument(graph) {\n const warnings: string[] = []\n const data = writePenDocument(graph, { warnings })\n return {\n format: 'pen',\n mimeType: 'application/json',\n extension: 'pen',\n data,\n encoding: 'utf8',\n ...(warnings.length > 0 ? { warnings } : {})\n }\n }\n}\n"],"mappings":";;;;;;;;;AAsBA,MAAM,gBAAgB;;AAGtB,MAAM,gBAAgB;;AAGtB,SAAS,YACP,MACA,OACA,OACuB;CACvB,OAAO,MAAM,OAAO,IAChB,CAAC;EAAE;GAAO,QAAQ,CAAC,GAAG,KAAK,CAAC,CAAC,MAAM,GAAG,aAAa;CAAE,CAAwB,IAC7E,CAAC;AACP;;;;;AAMA,SAAS,gBAAgB,KAAqB;CAC5C,OAAO,IACJ,MAAM,GAAG,CAAC,CACV,KAAK,YAAY;EAChB,IAAI;EACJ,IAAI;GACF,UAAU,mBAAmB,OAAO;EACtC,QAAQ;GACN,OAAO;EACT;EACA,IAAI,YAAY,OAAO,YAAY,MAAM,OAAO;EAChD,OAAO,QAAQ,WAAW,KAAK,KAAK,CAAC,CAAC,WAAW,MAAM,KAAK;CAC9D,CAAC,CAAC,CACD,KAAK,GAAG;AACb;;;;;AAMA,eAAe,YACb,KACA,OACA,QAC4B;CAC5B,IAAI;EACF,IAAI,sBAAsB,GAAG,GAAG,OAAO,MAAM,kBAAkB,QAAQ,GAAG;EAE1E,IAAI,CAAC,UAAU,GAAG,GAAG,OAAQ,MAAM,MAAM,YAAY,gBAAgB,GAAG,CAAC,KAAM;EAE/E,OAAO,IAAI,W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AAS;IAE3B,IAAI,KAAK,SAAS,GAAG,KAAK,mBAAmB;IAC7C,iBAAiB,IAAI,IAAI;GAC3B;GACA,oBAAoB,SAAS,aAAa,IAAI,IAAI;GAClD,SAAS,WACP,oBACE,QACA,OAAO,SAAS,IAAI,CAAC,CAAC,KAAK,SAAS,KAAK,EAAE,CAC7C;EACJ,CAAC;EACD,MAAM,WAAkC;GACtC,GAAG,WAAW,SAAS;GACvB,GAAG,YAAY,oBAAoB,SAAS,gBAAgB;GAC5D,GAAG,YAAY,iBAAiB,QAAQ,OAAO;GAC/C,GAAG,YAAY,gBAAgB,SAAS,YAAY;EACtD;EACA,OAAO,SAAS,SAAS,IACrB;GAAE;GAAO,cAAc;GAAO;EAAS,IACvC;GAAE;GAAO,cAAc;EAAM;CACnC;CACA,MAAM,cAAc,OAAO;EACzB,MAAM,WAAqB,CAAC;EAE5B,OAAO;GACL,QAAQ;GACR,UAAU;GACV,WAAW;GACX,MALW,iBAAiB,OAAO,EAAE,SAAS,CAK3C;GACH,UAAU;GACV,GAAI,SAAS,SAAS,IAAI,EAAE,SAAS,IAAI,CAAC;EAC5C;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../../src/io/formats/pen/index.ts"],"sourcesContent":["import { groupBy } from 'es-toolkit'\n\nimport {\n buildPenGraph,\n isDataURL,\n parseImportedImageURL,\n parsePenDocument,\n penAssets,\n withUsedImports,\n writePenDocument,\n type PenIconRequest,\n type PenIconSource,\n type PenWriteWarning\n} from '@pairdraw/pen'\n\nimport { defaultIcons, drawIcon, type IconData, type IconProvider } from '#core/icons'\nimport type {\n ExportResult,\n IOFormatAdapter,\n ReadDocumentInput,\n ReadDocumentWarning\n} from '#core/io/types'\nimport { layoutAuthoredNodes } from '#core/layout'\n\nimport { loadPenFonts } from './fonts'\nimport { loadPenImports, readImportedImage, UnresolvedImports, type OpenedImport } from './imports'\n\n/** The size icons are fetched at; each is scaled to the box it is drawn in. */\nconst PEN_ICON_SIZE = 24\n\n/** How many names one warning lists, so a broken document cannot flood the host's notice. */\nconst WARNING_NAMES = 10\n\n/** One warning for the names found, capped, or none when nothing was found. */\nfunction warningList<K extends 'unknown-variable' | 'missing-image' | 'unknown-node'>(\n kind: K,\n field: K extends 'unknown-variable' ? 'names' : K extends 'missing-image' ? 'urls' : 'types',\n names: ReadonlySet<string>\n): ReadDocumentWarning[] {\n return names.size > 0\n ? [{ kind, [field]: [...names].slice(0, WARNING_NAMES) } as ReadDocumentWarning]\n : []\n}\n\n/**\n * The path a percent-encoded image URL names, decoded one step at a time: a step that would become\n * a separator or a parent keeps its escape, so a URL cannot name a file outside its folder.\n */\nfunction decodeAssetPath(url: string): string {\n return url\n .split('/')\n .map((segment) => {\n let decoded: string\n try {\n decoded = decodeURIComponent(segment)\n } catch {\n return segment\n }\n if (decoded === '.' || decoded === '..') return segment\n return decoded.replaceAll('/', '%2F').replaceAll('\\\\', '%5C')\n })\n .join('/')\n}\n\n/**\n * An image's bytes: a data URL decoded by the platform's own URL handling, an imported document's\n * file beside that document, and any other file through the host; null when that fails.\n */\nasync function loadPenFile(\n url: string,\n input: ReadDocumentInput,\n opened: ReadonlyMap<string, OpenedImport>\n): Promise<Uint8Array | null> {\n try {\n if (parseImportedImageURL(url)) return await readImportedImage(opened, url)\n // pen.dev writes the path percent-encoded, as `My%20Design-assets/…`.\n if (!isDataURL(url)) return (await input.readAsset?.(decodeAssetPath(url))) ?? null\n // Through `URL`, which lowercases the scheme for runtimes that only fetch `data:`.\n return new Uint8Array(await (await fetch(new URL(url))).arrayBuffer())\n } catch {\n return null\n }\n}\n\n/**\n * The shader files the document's paints and effects name, as their source text. One whose file the\n * host cannot read is left out, so its shader draws nothing rather than an empty frame.\n */\nasync function loadPenShaders(\n urls: readonly string[],\n input: ReadDocumentInput,\n opened: ReadonlyMap<string, OpenedImport>\n): Promise<Map<string, string>> {\n const shaders = new Map<string, string>()\n await Promise.all(\n urls.map(async (url) => {\n const bytes = await loadPenFile(url, input, opened)\n if (bytes) shaders.set(url, new TextDecoder().decode(bytes))\n })\n )\n return shaders\n}\n\n/** The images the host has, and the URLs it does not, whose paints are dropped. */\nasync function loadPenImages(\n urls: readonly string[],\n input: ReadDocumentInput,\n opened: ReadonlyMap<string, OpenedImport>\n): Promise<{ images: Map<string, Uint8Array>; missing: Set<string> }> {\n const images = new Map<string, Uint8Array>()\n const missing = new Set<string>()\n await Promise.all(\n urls.map(async (url) => {\n const bytes = await loadPenFile(url, input, opened)\n if (bytes) images.set(url, bytes)\n else missing.add(url)\n })\n )\n return { images, missing }\n}\n\n/** A request's options as a key, so requests drawn the same way share a fetch. */\nconst optionsKey = (options: Record<string, number> | undefined) => JSON.stringify(options ?? null)\n\n/**\n * Icons from `provider`, fetched once for each way they are drawn; a document whose icons cannot\n * be fetched opens with empty icons.\n */\nasync function loadPenIcons(\n requests: readonly PenIconRequest[],\n provider: IconProvider\n): Promise<PenIconSource> {\n const glyphs = new Map<string, IconData>()\n const byOptions = groupBy(requests, (request) => optionsKey(request.options))\n await Promise.all(\n Object.values(byOptions).map(async (group) => {\n const names = group.map((request) => request.name)\n const found = await provider\n .icons(names, PEN_ICON_SIZE, group[0]?.options)\n .catch(() => new Map<string, IconData>())\n for (const [name, icon] of found)\n glyphs.set(`${name}\\0${optionsKey(group[0]?.options)}`, icon)\n })\n )\n return {\n draw(graph, frameId, name, size, color, options) {\n const icon = glyphs.get(`${name}\\0${optionsKey(options)}`)\n if (!icon) return false\n drawIcon(graph, frameId, icon, size, color)\n return true\n }\n }\n}\n\nexport const penFormat: IOFormatAdapter<'pen'> = {\n id: 'pen',\n label: 'Pencil Document',\n role: 'interchange-document',\n category: 'document',\n extensions: ['pen'],\n mimeTypes: ['application/json', 'text/plain'],\n support: {\n readDocument: true,\n writeDocument: true\n },\n laysOutOnRead: true,\n matchesFile(fileName, mimeType) {\n return fileName.toLowerCase().endsWith('.pen') || mimeType === 'application/json'\n },\n async readDocument(input, context) {\n const doc = parsePenDocument(new TextDecoder().decode(input.data))\n // The libraries it imports, whose components it uses draw as library components; what the host\n // cannot read draws as placeholders the warnings tell the host about.\n const unresolved = new UnresolvedImports()\n const unknownVariables = new Set<string>()\n const unknownNodes = new Set<string>()\n const { imports, opened } = await loadPenImports(doc, input, unresolved)\n const importsIncomplete = unresolved.warnings().length > 0\n const assets = penAssets(withUsedImports(doc, imports))\n const [{ images, missing }, shaders, icons, fonts] = await Promise.all([\n loadPenImages(assets.images, input, opened),\n loadPenShaders(assets.shaders, input, opened),\n loadPenIcons(assets.icons, context?.icons ?? defaultIcons),\n loadPenFonts(doc.fonts ?? [], (url) => loadPenFile(url, input, opened))\n ])\n // A .pen file stores its layout intent, not the sizes and positions it implies; the hidden\n // library page's components are laid out too, as instances of them copy their layers.\n const graph = buildPenGraph(doc, {\n images,\n shaders,\n icons,\n fonts,\n imports,\n onUnknownVariable: (name) => {\n // A variable of a library that opened without its own imports is covered by that warning.\n if (name.includes(':') && importsIncomplete) return\n unknownVariables.add(name)\n },\n onUnknownNodeType: (type) => unknownNodes.add(type),\n layout: (target) =>\n layoutAuthoredNodes(\n target,\n target.getPages(true).map((page) => page.id)\n )\n })\n const warnings: ReadDocumentWarning[] = [\n ...unresolved.warnings(),\n ...warningList('unknown-variable', 'names', unknownVariables),\n ...warningList('missing-image', 'urls', missing),\n ...warningList('unknown-node', 'types', unknownNodes)\n ]\n return warnings.length > 0\n ? { graph, sourceFormat: 'pen', warnings }\n : { graph, sourceFormat: 'pen' }\n },\n async writeDocument(graph) {\n const warnings: string[] = []\n const warningDetails: PenWriteWarning[] = []\n const data = writePenDocument(graph, { warnings, warningDetails })\n const written: ExportResult = {\n format: 'pen',\n mimeType: 'application/json',\n extension: 'pen',\n data,\n encoding: 'utf8'\n }\n if (warningDetails.length === 0) return written\n return { ...written, warnings, warningDetails }\n }\n}\n"],"mappings":";;;;;;;;;AA4BA,MAAM,gBAAgB;;AAGtB,MAAM,gBAAgB;;AAGtB,SAAS,YACP,MACA,OACA,OACuB;CACvB,OAAO,MA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MAAM,UAAwB;GAC5B,QAAQ;GACR,UAAU;GACV,WAAW;GACX,MALW,iBAAiB,OAAO;IAAE;IAAU;GAAe,CAK3D;GACH,UAAU;EACZ;EACA,IAAI,eAAe,WAAW,GAAG,OAAO;EACxC,OAAO;GAAE,GAAG;GAAS;GAAU;EAAe;CAChD;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"formats.d.ts","names":[],"sources":["../../src/io/formats.ts"],"mappings":";;;;;cAiKa,qBAAqB,SAAS,OAAO;cAKrC,WAAW;cA8DX,cAAc;cA2Dd,eAAe;cAwCf,WAAS;cACT,WAAS;cACT,YAAU;cAEV,WAAW;cA0EX,WAAW;cA6CX,YAAY;cA2BZ,WAAW;cAqDX,YAAY;cA+BZ,mBAAmB;cAkCnB,8BAAkB,wBAAA,wBAAA,2BAAA,4BAAA,wBAAA,wBAAA,yBAAA,wBAAA,wBAAA,yBAAA,wBAAA,iCAAA;KAgBnB,4BAA4B"}
1
+ {"version":3,"file":"formats.d.ts","names":[],"sources":["../../src/io/formats.ts"],"mappings":";;;;;cAiKa,qBAAqB,SAAS,OAAO;cAKrC,WAAW;cA8DX,cAAc;cA2Dd,eAAe;cA8Cf,WAAS;cACT,WAAS;cACT,YAAU;cAEV,WAAW;cA0EX,WAAW;cA6CX,YAAY;cA2BZ,WAAW;cAqDX,YAAY;cA+BZ,mBAAmB;cAkCnB,8BAAkB,wBAAA,wBAAA,2BAAA,4BAAA,wBAAA,wBAAA,yBAAA,wBAAA,wBAAA,yBAAA,wBAAA,iCAAA;KAgBnB,4BAA4B"}
@@ -255,14 +255,20 @@ const mermaidFormat = {
255
255
  async function writeDrawIO(graph, target) {
256
256
  const { writeDrawIOFile } = await import("@pairdraw/drawio");
257
257
  const { sceneGraphToDrawIO } = await import("./formats/drawio/index.js");
258
- const { drawioDroppedWarnings } = await import("./formats/drawio/warnings.js");
259
- return {
258
+ const { drawioWriteWarnings, drawioWriteWarningText } = await import("./formats/drawio/warnings.js");
259
+ const warningDetails = drawioWriteWarnings(graph);
260
+ const written = {
260
261
  format: "drawio",
261
262
  mimeType: "application/vnd.jgraph.mxfile",
262
263
  extension: "drawio",
263
264
  data: writeDrawIOFile(sceneGraphToDrawIO(graph, target)),
264
- encoding: "utf8",
265
- warnings: drawioDroppedWarnings(graph)
265
+ encoding: "utf8"
266
+ };
267
+ if (warningDetails.length === 0) return written;
268
+ return {
269
+ ...written,
270
+ warnings: warningDetails.map(drawioWriteWarningText),
271
+ warningDetails
266
272
  };
267
273
  }
268
274
  const pngFormat = rasterFormat("PNG");