@pixerate/editor 0.37.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/editor/editor/packages/core/dist/vector/index.cjs","../../src/vector/types.ts","../../src/vector/corners.ts","../../src/vector/width.ts","../../src/vector/varstroke.ts","../../src/vector/stroke.ts","../../src/vector/geometry.ts","../../src/vector/svg.ts","../../src/vector/snap.ts","../../src/vector/pathEdit.ts","../../src/vector/pathCut.ts","../../src/vector/ink.ts","../../src/vector/controller.ts","../../src/vector/render.ts","../../src/vector/commands.ts"],"names":["t","v","p","sub","len","w","cross","dot","polygon","near","pt","s","dist","EPS","KAPPA","out","corners","width","node","lines","crossing","length","movesX","unit","onAnchor","at","along","from","to","line","last","editable","toScreen","flatten","ref","list"],"mappings":"AAAA;AACE;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACA;ACbO,IAAM,oBAAA,EAAmD,CAAC,OAAA,EAAS,UAAA,EAAY,SAAS,CAAA;AAkDxF,IAAM,kBAAA,EAAgD,CAAC,UAAA,EAAY,OAAA,EAAS,MAAA,EAAQ,QAAA,EAAU,QAAA,EAAU,KAAK,CAAA;AAsH7G,IAAM,aAAA,EAAsC,CAAC,QAAA,EAAU,QAAA,EAAU,KAAA,EAAO,QAAA,EAAU,MAAA,EAAQ,SAAA,EAAW,SAAA,EAAW,MAAA,EAAQ,MAAA,EAAQ,UAAA,EAAY,OAAA,EAAS,QAAA,EAAU,OAAO,CAAA;AAatK,IAAM,yBAAA,EAA6D,CAAC,IAAA,EAAM,GAAA,EAAK,IAAA,EAAM,GAAA,EAAK,IAAA,EAAM,GAAA,EAAK,IA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AAA;AACR;AAYM;AACC,EAAA;AACE,EAAA;AACR,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACa,EAAA;AACd;AAES;AACM,EAAA;AACF,EAAA;AACD,EAAA;AACA,IAAA;AACC,IAAA;AACC,IAAA;AACH,IAAA;AACV,EAAA;AACO,EAAA;AACR;AAES;AACE,EAAA;AAGF,IAAA;AACI,MAAA;AAIV,IAAA;AACY,IAAA;AACN,IAAA;AACA,IAAA;AACC,IAAA;AACE,MAAA;AACD,MAAA;AACH,MAAA;AACL,IAAA;AACA,EAAA;AACH;AAEkB;AACP,EAAA;AACA,EAAA;AACE,EAAA;AACE,EAAA;AACf;AAES;AACA,EAAA;AACG,EAAA;AACZ;AAES;AACG,EAAA;AACA,EAAA;AACA,EAAA;AACC,EAAA;AACC,EAAA;AACF,EAAA;AACA,EAAA;AACJ,EAAA;AACG,IAAA;AACV,EAAA;AACW,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AAEG,EAAA;AACL,EAAA;AACV;AAGgB;AACF,EAAA;AACF,EAAA;AACG,EAAA;AACR,EAAA;AACA,EAAA;AACQ,EAAA;AACF,IAAA;AACA,IAAA;AACF,MAAA;AACD,MAAA;AACR,IAAA;AACW,IAAA;AACJ,IAAA;AACK,IAAA;AACL,IAAA;AACR,EAAA;AAEM,EAAA;AACN,EAAA;AACc,EAAA;AACH,IAAA;AACE,IAAA;AACH,IAAA;AACC,IAAA;AACHd,IAAAA;AACR,EAAA;AAEM,EAAA;AACQ,EAAA;AACR,EAAA;AACA,EAAA;AAEO,EAAA;AAEP,EAAA;AACK,IAAA;AACC,IAAA;AACL,MAAA;AAEE,QAAA;AACC,UAAA;AACF,UAAA;AACL,QAAA;AACO,QAAA;AACR,MAAA;AACK,MAAA;AACE,QAAA;AACA,QAAA;AACF,QAAA;AACE,QAAA;AACE,QAAA;AACT,MAAA;AACK,MAAA;AACE,QAAA;AACF,QAAA;AACE,QAAA;AACA,QAAA;AACE,QAAA;AACT,MAAA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A;AACI,YAAA;AACJ,YAAA;AACC,cAAA;AACA,cAAA;AACD,YAAA;AACA,UAAA;AACF,QAAA;AACD,MAAA;AACU,MAAA;AACJ,MAAA;AACA,MAAA;AACC,QAAA;AACA,QAAA;AACA,QAAA;AACC,QAAA;AACR,MAAA;AACS,MAAA;AACFiB,QAAAA;AACAC,QAAAA;AACF,QAAA;AACC,QAAA;AACL,QAAA;AACD,MAAA;AACA,IAAA;AACU,IAAA;AACH,IAAA;AACF,IAAA;AAEAZ,IAAAA;AACG,IAAA;AACD,IAAA;AACF,IAAA;AACA,IAAA;AACK,IAAA;AACL,IAAA;AACG,IAAA;AACF,MAAA;AACA,MAAA;AACA,MAAA;AACG,QAAA;AACA,QAAA;AACT,MAAA;AACM,IAAA;AAEA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACE,QAAA;AACC,QAAA;AACR,MAAA;AACF,IAAA;AACY,IAAA;AACA,IAAA;AACZ,IAAA;AACD,EAAA;AACc,EAAA;AACf;AAOgB;AACH,EAAA;AACF,EAAA;AACD,EAAA;AACK,EAAA;AACF,EAAA;AACA,IAAA;AACD,IAAA;AACH,IAAA;AACE,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACT,IAAA;AACD,EAAA;AACyB,EAAA;AAClB,EAAA;AACR;AAMgB;AACT,EAAA;AACD,EAAA;AACQ,EAAA;AACN,EAAA;AACR;AAOgB;AACT,EAAA;AACD,EAAA;AACM,EAAA;AACG,EAAA;AACH,EAAA;AACL,EAAA;AAEmB,EAAA;AACL,EAAA;AACV,EAAA;AACG,EAAA;AACA,IAAA;AACD,IAAA;AACC,IAAA;AACH,IAAA;AACR,MAAA;AACO,QAAA;AACA,QAAA;AACN,QAAA;AACD,MAAA;AACD,IAAA;AACY,IAAA;AACH,IAAA;AACF,MAAA;AACA,MAAA;AACG,MAAA;AACL,MAAA;AACG,QAAA;AACE,QAAA;AACD,QAAA;AACD,MAAA;AACR,IAAA;AAC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ACb,EAAA;AACD;AAmBa;AACP;AAGU;AACD,EAAA;AACR,IAAA;AACG,MAAA;AACH,IAAA;AACG,MAAA;AACH,IAAA;AACG,MAAA;AACH,IAAA;AACG,MAAA;AACT,EAAA;AACD;AAEwB;AAEV;AACJ,EAAA;AACE,EAAA;AACA,EAAA;AACC,EAAA;AACD,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACX,EAAA;AACY,EAAA;AACb;AAES;AACM,EAAA;AACA,EAAA;AACD,EAAA;AACH,EAAA;AACG,EAAA;AACd;AAES;AACG,EAAA;AACE,EAAA;AACN,EAAA;AACR;AAGS;AACG,EAAA;AACA,EAAA;AACD,EAAA;AACC,EAAA;AACA,EAAA;AACD,EAAA;AACE,EAAA;AACA,EAAA;AACb;AAGS;AACK,EAAA;AACD,IAAA;AACH,IAAA;AACT,EAAA;AACc,EAAA;AACf;AAGS;AACM,EAAA;AACD,EAAA;AACF,EAAA;AACA,EAAA;AACD,EAAA;AACG,EAAA;AACd;AAGkC;AACrB,EAAA;AACD,EAAA;AACE,EAAA;AACH,EAAA;AACwB,EAAA;AACrB,EAAA;AACD,IAAA;AACD,IAAA;AACC,IAAA;AACF,IAAA;AACE,MAAA;AACF,MAAA;AACA,QAAA;AACD,QAAA;AACP,MAAA;AACD,IAAA;AACW,IAAA;AACF,MAAA;AACF,MAAA;AACP,IAAA;AACD,EAAA;AACS,EAAA;AACV;AAGS;AACI,EAAA;AACE,EAAA;AACJ,EAAA;AACC,EAAA;AACG,EAAA;AACHT,IAAAA;AACF,IAAA;AACA,MAAA;AACD,MAAA;AACP,IAAA;AACA,EAAA;AACW,EAAA;AACA,EAAA;AACC,EAAA;AACA,EAAA;AAEJ,EAAA;AACA,EAAA;AACI,EAAA;AACD,EAAA;AACD,IAAA;AACJ,IAAA;AACK,IAAA;AACC,IAAA;AACH,IAAA;AACE,MAAA;AACF,MAAA;AACC,QAAA;AACD,QAAA;AACR,MAAA;AACD,IAAA;AACY,IAAA;AACH,IAAA;A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A;AACD,MAAA;AACF,IAAA;AACD,EAAA;AACO,EAAA;AACR;AAGgB;AACF,EAAA;AACA,EAAA;AACd;AAGgB;AACL,EAAA;AACF,EAAA;AACE,EAAA;AACA,EAAA;AACI,EAAA;AACf;AAgBgB;AACD,EAAA;AACH,EAAA;AACL,EAAA;AACO,EAAA;AACC,EAAA;AACR,EAAA;AACI,EAAA;AACG,EAAA;AACd;AAEM;AAGU;AACD,EAAA;AACP,EAAA;AACI,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACX,EAAA;AACD;AAgBgB;AACL,EAAA;AACI,EAAA;AACF,EAAA;AACNO,EAAAA;AACA,EAAA;AACAhB,EAAAA;AACO,IAAA;AACH,IAAA;AACA,IAAA;AACG,IAAA;AACPgB,EAAAA;AACK,EAAA;AACG,EAAA;AACf;AAEM;AACA;AAGU;AACX,EAAA;AACS,EAAA;AACN,EAAA;AACR;AAGM;AACG,EAAA;AACA,EAAA;AACH,EAAA;AACG,EAAA;AACF,EAAA;AACG,EAAA;AACA,EAAA;AACH,EAAA;AACA,EAAA;AACI,EAAA;AACH,EAAA;AACC,EAAA;AACD,EAAA;AACR;AAE8C;AAE9B;AACR,EAAA;AACR;AAGa;AACJ,EAAA;AACA,EAAA;AACH,EAAA;AACG,EAAA;AACF,EAAA;AACG,EAAA;AACA,EAAA;AACH,EAAA;AACA,EAAA;AACI,EAAA;AACH,EAAA;AACC,EAAA;AACD,EAAA;AACR;AAGa;AACJ,EAAA;AACA,EAAA;AACH,EAAA;AACG,EAAA;AACF,EAAA;AACG,EAAA;AACA,EAAA;AACH,EAAA;AACA,EAAA;AACI,EAAA;AACH,EAAA;AACC,EAAA;AACD,EAAA;AACR;AAGM;AAEA;AACE,EAAA;AACG,EAAA;AACC,EAAA;AACF,EAAA;AACV;AAEM;AAGG;AACM,EAAA;AACa,EAAA;AAChB,EAAA;AACC,IAAA;AACC,IAAA;AAC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;AACM,IAAA;AACF,IAAA;AACChB,MAAAA;AACA,MAAA;AACA,MAAA;AACI,QAAA;AACF,QAAA;AACGA,QAAAA;AACT,MAAA;AACK,MAAA;AACA,MAAA;AACA,MAAA;AACCgB,MAAAA;AACD,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACL,MAAA;AACD,IAAA;AACW,IAAA;AACL,IAAA;AACM,IAAA;AACD,IAAA;AACN,IAAA;AACA,IAAA;AACO,IAAA;AACP,IAAA;AACO,IAAA;AACP,IAAA;AACO,IAAA;AACb,EAAA;AAE4B,EAAA;AACrB,IAAA;AACA,IAAA;AACI,MAAA;AACH,MAAA;AACA,MAAA;AACE,MAAA;AACR,MAAA;AACA,MAAA;AACU,MAAA;AACX,IAAA;AACY,IAAA;AACN,IAAA;AACK,IAAA;AACL,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACM,IAAA;AACP,IAAA;AACO,IAAA;AACb,EAAA;AAE2B,EAAA;AACpB,IAAA;AAEA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACM,IAAA;AACA,IAAA;AACP,IAAA;AACO,IAAA;AACb,EAAA;AAAA;AAGY,EAAA;AACD,IAAA;AACJ,IAAA;AACK,IAAA;AACJ,MAAA;AACA,MAAA;AACA,MAAA;AACD,MAAA;AACC,MAAA;AACG,MAAA;AACJ,MAAA;AACA,MAAA;AACL,MAAA;AACD,IAAA;AACK,IAAA;AACG,IAAA;AACF,MAAA;AACC,QAAA;AACA,QAAA;AACL,QAAA;AACI,MAAA;AACA,QAAA;AACA,QAAA;AACC,QAAA;AACA,QAAA;AACD,QAAA;AACA,QAAA;AACE,UAAA;AACC,UAAA;AACD,UAAA;AACA,UAAA;AAEA,UAAA;AACN,QAAA;AACO,QAAA;AACF,QAAA;AACA,QAAA;AACA,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AAEE,QAAA;AACA,QAAA;AACA,QAAA;AACF,QAAA;AACE,UAAA;AACC,UAAA;AACH,UAAA;AACE,UAAA;AACC,QAAA;AACD,QAAA;AACD,QAAA;AACA,QAAA;AACA,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACE,QAAA;AACA,QAAA;AACF,QAAA;AACA,QAAA;AACC,QAAA;AACA,QAAA;AACA,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACE,QAAA;AACD,QAAA;AACD,QAAA;AACG,UAAA;AACL,YAAA;AACA,YAAA;AACA,UAAA;AACI,UAAA;AACC,QAAA;AACA,UAAA;AAGJ,YAAA;AACA,YAAA;AAEA,UAAA;AACG,UAAA;AACN,QAAA;AACK,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACA,QAAA;AACA,QAAA;AACC,QAAA;AACA,QAAA;AACC,QAAA;AACF,QAAA;AAEG,UAAA;AACA,UAAA;AACD,UAAA;AACA,UAAA;AACN,QAAA;AACM,QAAA;AACA,QAAA;AAEF,QAAA;AACC,QAAA;AACA,QAAA;AACA,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACE,QAAA;AACA,QAAA;AACAxB,QAAAA;AACA,QAAA;AACD,QAAA;AACA,QAAA;AACA,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACC,QAAA;AACA,QAAA;AACC,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACD,QAAA;AACA,QAAA;AACA,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACC,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACE,QAAA;AACF,QAAA;AACC,QAAA;AACA,QAAA;AACA,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACE,QAAA;AACD,QAAA;AACD,QAAA;AACE,UAAA;AACA,UAAA;AACL,UAAA;AACD,QAAA;AACK,QAAA;AACDA,QAAAA;AACA,QAAA;AACE,QAAA;AAEA,QAAA;AACD,QAAA;AACA,UAAA;AACJ,UAAA;AACA,QAAA;AACI,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACE,QAAA;AACF,QAAA;AACE,QAAA;AACF,QAAA;AACC,QAAA;AACD,QAAA;AACA,QAAA;AACA,QAAA;AACC,UAAA;AACA,UAAA;AACJ,UAAA;AACM,QAAA;AACF,UAAA;AACA,UAAA;AACA,UAAA;AACH,YAAA;AACI,YAAA;AACA,YAAA;AACL,UAAA;AACI,UAAA;AACE,UAAA;AACA,UAAA;AACN,UAAA;AACD,QAAA;AACM,QAAA;AACD,QAAA;AACA,QAAA;AACA,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACC,QAAA;AACA,QAAA;AACC,QAAA;AACA,QAAA;AACF,QAAA;AACA,QAAA;AACG,UAAA;AACAD,UAAAA;AACDA,UAAAA;AACL,UAAA;AACM,QAAA;AACA,UAAA;AACA,UAAA;AAEN,UAAA;AACD,QAAA;AACK,QAAA;AACC,QAAA;AACD,QAAA;AACA,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACE,QAAA;AACF,QAAA;AACA,QAAA;AACJ,QAAA;AACK,UAAA;AACC,UAAA;AACA,0BAAA;AACL,UAAA;AACD,QAAA;AACM,QAAA;AACA,QAAA;AACF,QAAA;AACC,QAAA;AACA,UAAA;AACH,YAAA;AACA,YAAA;AACD,UAAA;AACA,UAAA;AACD,QAAA;AACK,QAAA;AACC,QAAA;AACA,QAAA;AACD,QAAA;AACE,UAAA;AACA,UAAA;AACN,UAAA;AACA,UAAA;AACI,UAAA;AACL,QAAA;AACK,QAAA;AACL,QAAA;AACD,MAAA;AACD,IAAA;AACD,EAAA;AAAA;AAGiB,EAAA;AACV,IAAA;AACI,IAAA;AACJ,MAAA;AACI,MAAA;AACV,IAAA;AAEM,IAAA;AACI,IAAA;AACD,IAAA;AACH,MAAA;AACC,MAAA;AACP,IAAA;AACK,IAAA;AACE,IAAA;AACG,MAAA;AACA,MAAA;AACV,IAAA;AACD,EAAA;AAAA;AAGmB,EAAA;AACN,IAAA;AACH,IAAA;AACE,MAAA;AACH,MAAA;AACR,IAAA;AACwB,IAAA;AACb,IAAA;AACA,MAAA;AACA,MAAA;AACX,IAAA;AACO,IAAA;AACR,EAAA;AAAA;AAGQ,EAAA;AAEG,IAAA;AACE,IAAA;AACA,IAAA;AACN,IAAA;AACK,IAAA;AACA,MAAA;AACJL,MAAAA;AACFA,MAAAA;AACI,MAAA;AACF,MAAA;AACC,MAAA;AACA,MAAA;AACR,IAAA;AACK,IAAA;AACE,IAAA;AACR,EAAA;AAAA;AAGU,EAAA;AAEL,IAAA;AACE,IAAA;AACM,IAAA;AACP,IAAA;AACA,IAAA;AACM,IAAA;AACH,IAAA;AACF,MAAA;AACA,MAAA;AACC,QAAA;AACL,QAAA;AACI,MAAA;AACC,QAAA;AACA,UAAA;AACC,UAAA;AACL,UAAA;AACD,QAAA;AACO,QAAA;AACH,MAAA;AACG,QAAA;AACH,MAAA;AACG,QAAA;AACH,MAAA;AACC,QAAA;AACA,UAAA;AACA,UAAA;AACC,UAAA;AACL,UAAA;AACD,QAAA;AACO,QAAA;AACH,MAAA;AACG,QAAA;AACH,MAAA;AACC,QAAA;AACC,UAAA;AACL,UAAA;AACD,QAAA;AACO,QAAA;AACH,MAAA;AACA,QAAA;AACA,QAAA;AACG,UAAA;AACD,UAAA;AACL,UAAA;AACD,QAAA;AAEM,QAAA;AACA,QAAA;AACD,QAAA;AACA,QAAA;AACA,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACA,QAAA;AAEA,QAAA;AACE,UAAA;AACA,UAAA;AACA,UAAA;AACC,QAAA;AACP,QAAA;AACD,MAAA;AACK,MAAA;AACC,QAAA;AACD,QAAA;AACC,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACA,QAAA;AACG,QAAA;AACH,MAAA;AACE,QAAA;AACA,QAAA;AACA,QAAA;AACD,QAAA;AACC,UAAA;AACA,UAAA;AACL,UAAA;AACD,QAAA;AACK,QAAA;AACA,QAAA;AACA,QAAA;AACE,QAA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AACE,EAAA;AACb;AAGgB;AACF,EAAA;AACA,EAAA;AACC,EAAA;AACA,EAAA;AACR,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACG,EAAA;AACA,EAAA;AACA,EAAA;AACH,IAAA;AACM,MAAA;AACA,MAAA;AACA,MAAA;AACA,IAAA;AACD,IAAA;AACX,EAAA;AACa,EAAA;AACd;AAGS;AACK,EAAA;AACT,EAAA;AACO,IAAA;AACJ,IAAA;AACM,IAAA;AACb,EAAA;AACO,EAAA;AACR;AAGS;AACI,EAAA;AACF,EAAA;AACI,EAAA;AACR,EAAA;AACK,EAAA;AACZ;AAGS;AACE,EAAA;AACC,EAAA;AACC,EAAA;AACC,EAAA;AACC,EAAA;AACA,EAAA;AACP,EAAA;AACR;AZo6FgB;AACA;Aax9MH;AACK;AAET;AACC,EAAA;AACA,EAAA;AACF,IAAA;AACG,IAAA;AACV,EAAA;AACa,EAAA;AACP,EAAA;AACG,EAAA;AACE,EAAA;AACL,EAAA;AACC,EAAA;AACA,IAAA;AACG,IAAA;AACA,IAAA;AACL,IAAA;AACD,IAAA;AACQ,IAAA;AACH,IAAA;AACR,IAAA;AACS,IAAA;AACA,IAAA;AACA,IAAA;AACC,IAAA;AACD,IAAA;AACV,EAAA;AACD;AAMgB;AACiB,EAAA;AAC1B,EAAA;AACQ,EAAA;AACJ,EAAA;AACH,EAAA;AACK,IAAA;AACJ,IAAA;AACC,IAAA;AACE,IAAA;AACV,IAAA;AACA,IAAA;AACD,EAAA;AACD;AAEkB;AAET;AACE,EAAA;AACkBH,EAAAA;AACtB,EAAA;AACC,EAAA;AAGR;AAGS;AACC,EAAA;AACC,EAAA;AACE,EAAA;AACb;AAES;AACC,EAAA;AACG,EAAA;AACb;AAGgB;AACH,EAAA;AACF,EAAA;AACJ,EAAA;AACO,EAAA;AACP,EAAA;AACI,IAAA;AACH,IAAA;AACD,IAAA;AACM,IAAA;AACF,IAAA;AACV,EAAA;AACW,EAAA;AACD,EAAA;AACA,EAAA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A;AACR,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACA,MAAA;AACV,MAAA;AACU,MAAA;AACA,MAAA;AACJ,MAAA;AACC,QAAA;AACC,QAAA;AACR,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACV,MAAA;AACU,MAAA;AACD,MAAA;AACC,MAAA;AACJ,MAAA;AACC,QAAA;AACC,QAAA;AACR,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACV,MAAA;AACU,MAAA;AACA,MAAA;AACJ,MAAA;AACC,QAAA;AACC,QAAA;AACR,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACV,MAAA;AACU,MAAA;AACA,MAAA;AACJ,MAAA;AACD,QAAA;AACE,UAAA;AACD,UAAA;AACE,UAAA;AACD,UAAA;AACL,UAAA;AACD,QAAA;AACM,QAAA;AACC,QAAA;AACR,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACV,MAAA;AACU,MAAA;AACA,MAAA;AACJ,MAAA;AACC,QAAA;AACD,QAAA;AACE,QAAA;AACR,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACV,MAAA;AAEU,MAAA;AACA,MAAA;AACJ,MAAA;AACC,QAAA;AACD,QAAA;AACE,QAAA;AACR,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACV,MAAA;AAEQ,MAAA;AACD,QAAA;AACN,QAAA;AACC,UAAA;AACA,UAAA;AACA,UAAA;AACA,UAAA;AACA,UAAA;AACA,UAAA;AACD,QAAA;AACD,MAAA;AACM,MAAA;AACC,QAAA;AACN,QAAA;AACA,QAAA;AACO,QAAA;AACR,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACV,MAAA;AACU,MAAA;AACJ,MAAA;AACL,QAAA;AACO,QAAA;AACR,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACA,MAAA;AACV,MAAA;AACU,MAAA;AACJ,MAAA;AACP,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACV,MAAA;AACU,MAAA;AACA,MAAA;AACJ,MAAA;AACC,QAAA;AACC,QAAA;AACR,MAAA;AACD,IAAA;AACD,EAAA;AACD;Ad26NgB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/editor/editor/packages/core/dist/vector/index.cjs","sourcesContent":[null,"import type { CanvasGradientDef } from '../canvas/gradient.js';\n\n/** An affine matrix `[a, b, c, d, e, f]`: `x' = a·x + c·y + e`, `y' = b·x + d·y + f` (SVG order). */\nexport type VectorMatrix = readonly [number, number, number, number, number, number];\n\n/** A point in document coordinates. */\nexport interface Vec2 {\n\tx: number;\n\ty: number;\n}\n\n/**\n * How an anchor's handles relate:\n * - `corner`: handles move independently (or are absent).\n * - `smooth`: handles stay on one line through the anchor, lengths independent.\n * - `symmetric`: handles stay on one line with equal lengths.\n */\nexport type VectorAnchorType = 'corner' | 'smooth' | 'symmetric';\n\n/**\n * Live corner shapes: `round` (an arc tangent to both sides), `inverted` (an arc centred on\n * the corner, cut into the shape) and `chamfer` (a straight bevel).\n */\nexport type VectorCornerKind = 'round' | 'inverted' | 'chamfer';\n\nexport const VECTOR_CORNER_KINDS: readonly VectorCornerKind[] = ['round', 'inverted', 'chamfer'];\n\n/**\n * A live corner: drawn rounded (or cut) at render, hit-test, bounds, boolean, outline and export\n * time while the stored anchor stays sharp. The radius shrinks to fit when the sides are short:\n * the cut reaches at most halfway along each side.\n */\nexport interface VectorCorner {\n\tradius: number;\n\t/** Default `round`. */\n\tkind?: VectorCornerKind;\n}\n\n/**\n * One anchor of a subpath. Handles are absolute document positions; a missing (or `null`)\n * handle sits on the anchor, so a segment with no handles at either end is a straight line.\n */\nexport interface VectorAnchor {\n\tx: number;\n\ty: number;\n\t/** Control point of the segment arriving at this anchor. */\n\tin?: Vec2 | null;\n\t/** Control point of the segment leaving this anchor. */\n\tout?: Vec2 | null;\n\t/** Default `corner`. */\n\ttype?: VectorAnchorType;\n\t/** Live corner radius. Ignored on smooth / symmetric anchors and the ends of open subpaths. */\n\tcorner?: VectorCorner | null;\n}\n\n/** A chain of anchors joined by line or cubic Bézier segments. */\nexport interface VectorSubpath {\n\tanchors: VectorAnchor[];\n\t/** Joins the last anchor back to the first. */\n\tclosed: boolean;\n}\n\n/** A fill or stroke: any CSS colour, a gradient, or `null` / `'none'` for no paint. */\nexport type VectorPaint = string | CanvasGradientDef | null;\n\nexport type VectorFillRule = 'nonzero' | 'evenodd';\nexport type VectorLineCap = 'butt' | 'round' | 'square';\nexport type VectorLineJoin = 'miter' | 'round' | 'bevel';\n/**\n * Where the stroke sits on the outline: centred on it, inside the shape or outside it. Only\n * shapes whose subpaths are all closed have an inside; open paths always stroke centred.\n */\nexport type VectorStrokeAlign = 'center' | 'inside' | 'outside';\n/** Arrowheads and end markers for the ends of open paths. */\nexport type VectorArrowhead = 'triangle' | 'arrow' | 'open' | 'circle' | 'square' | 'bar';\nexport const VECTOR_ARROWHEADS: readonly VectorArrowhead[] = ['triangle', 'arrow', 'open', 'circle', 'square', 'bar'];\n/**\n * `extend`: the head's tip sits past the end point and the path keeps its length; `tip`: the\n * tip sits on the end point and the stroke is shortened under the head.\n */\nexport type VectorArrowAlign = 'extend' | 'tip';\n\n/**\n * One point of a variable-width stroke profile. `t` is the position along the subpath by\n * length (0 at its start, 1 at its end); `left` and `right` are how far the stroke reaches on\n * each side, as multiples of half the stroke width (looking along the path on screen, y down).\n * A uniform stroke has 1 on both sides. Two points at the same `t` make a step.\n */\nexport interface VectorWidthPoint {\n\tt: number;\n\tleft: number;\n\tright: number;\n}\n\n/** Paint and stroke settings of a path. */\nexport interface VectorStyle {\n\tfill?: VectorPaint;\n\tstroke?: VectorPaint;\n\t/** Default 1. */\n\tstrokeWidth?: number;\n\tstrokeLinecap?: VectorLineCap;\n\tstrokeLinejoin?: VectorLineJoin;\n\tstrokeDasharray?: number[];\n\t/** Default `nonzero`. */\n\tfillRule?: VectorFillRule;\n\t/** Default `center`. */\n\tstrokeAlign?: VectorStrokeAlign;\n\t/** Head at the start of the first subpath when it is open, or none. */\n\tstartArrow?: VectorArrowhead | null;\n\t/** Head at the end of the last subpath when it is open, or none. */\n\tendArrow?: VectorArrowhead | null;\n\t/** Default `extend`. */\n\tarrowAlign?: VectorArrowAlign;\n\t/** Size of the start head as a multiple of the stroke width (default 1: a head 4 widths long). */\n\tstartArrowScale?: number;\n\t/** Size of the end head (default 1). */\n\tendArrowScale?: number;\n\t/**\n\t * Variable width: side scales along each subpath, interpolated with a monotone cubic (see\n\t * `widthProfileAt`). Absent, empty or `null` strokes at a uniform width. A profiled stroke is\n\t * drawn as its filled outline.\n\t */\n\tstrokeWidthProfile?: VectorWidthPoint[] | null;\n}\n\ninterface VectorNodeBase {\n\tid: string;\n\tname?: string;\n\t/** Default true. */\n\tvisible?: boolean;\n\t/** Locked nodes are drawn but cannot be picked or edited on the canvas. */\n\tlocked?: boolean;\n\t/** 0–1, default 1. */\n\topacity?: number;\n\t/**\n\t * Placement in the parent's space: a rigid matrix (rotation + translation). Anchors and\n\t * children are in the node's own space. Omitted for unrotated nodes, whose positions are\n\t * stored directly. Scale and skew are never stored here — `transformVectorNode` bakes\n\t * them into the geometry, so stroke widths and the rotated selection box stay exact.\n\t */\n\ttransform?: VectorMatrix;\n}\n\n/** A shape made of one or more subpaths (holes and compound shapes included). */\nexport interface VectorPathNode extends VectorNodeBase, VectorStyle {\n\ttype: 'path';\n\tsubpaths: VectorSubpath[];\n}\n\n/** A group of nodes that select and transform together. */\nexport interface VectorGroupNode extends VectorNodeBase {\n\ttype: 'group';\n\tchildren: VectorNode[];\n}\n\nexport type VectorNode = VectorPathNode | VectorGroupNode;\n\n/** A vector drawing: an artboard and its nodes, bottom to top. */\nexport interface VectorDocument {\n\twidth: number;\n\theight: number;\n\t/** Artboard colour (default: transparent). */\n\tbackground?: string;\n\tnodes: VectorNode[];\n}\n\n/** An axis-aligned rectangle. */\nexport interface VectorBounds {\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n}\n\n/** Identifies one anchor of a path node. */\nexport interface VectorAnchorRef {\n\tnodeId: string;\n\tsubpath: number;\n\tindex: number;\n}\n\n/** Identifies one handle of an anchor. */\nexport interface VectorHandleRef extends VectorAnchorRef {\n\thandle: 'in' | 'out';\n}\n\n/**\n * Canvas tools. `direct` edits anchors, handles and segments; the shape tools drag out a new\n * shape; `scissors` cuts a path at a point, `knife` cuts filled shapes along a freehand stroke,\n * `eraser` rubs out the area under one and `width` drags a stroke's width at a point.\n */\nexport type VectorTool = 'select' | 'direct' | 'pen' | 'pencil' | 'rect' | 'ellipse' | 'polygon' | 'star' | 'line' | 'scissors' | 'knife' | 'eraser' | 'width';\n\nexport const VECTOR_TOOLS: readonly VectorTool[] = ['select', 'direct', 'pen', 'pencil', 'rect', 'ellipse', 'polygon', 'star', 'line', 'scissors', 'knife', 'eraser', 'width'];\n\n/** Keyboard modifiers held during a pointer event. */\nexport interface VectorModifiers {\n\tshift?: boolean;\n\talt?: boolean;\n\t/** Cmd on macOS, Ctrl elsewhere. */\n\tmod?: boolean;\n}\n\n/** The eight resize handles of a selection box and the rotation handle. */\nexport type VectorTransformHandle = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'rotate';\n\nexport const VECTOR_TRANSFORM_HANDLES: readonly VectorTransformHandle[] = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'rotate'];\n\n/** Pan and zoom of the canvas: `screen = document × zoom + (x, y)`. */\nexport interface VectorViewport {\n\t/** Screen position of the document origin, in screen pixels. */\n\tx: number;\n\ty: number;\n\tzoom: number;\n}\n\n/** What the next shape and pen path are drawn with. */\nexport interface VectorDefaults extends VectorStyle {\n\t/** Sides of the polygon tool (default 6). */\n\tpolygonSides?: number;\n\t/** Points of the star tool (default 5). */\n\tstarPoints?: number;\n\t/** Inner radius of the star tool as a fraction of the outer one (default 0.5). */\n\tstarInnerRatio?: number;\n\t/** Live corner radius the rectangle, polygon and star tools give their corners (default 0). */\n\tcornerRadius?: number;\n\t/** Corner kind of those tools (default `round`). */\n\tcornerKind?: VectorCornerKind;\n}\n\nexport type VectorAlign = 'left' | 'center' | 'right' | 'top' | 'middle' | 'bottom';\nexport type VectorDistribute = 'horizontal' | 'vertical';\nexport type VectorBooleanOperation = 'union' | 'subtract' | 'intersect' | 'exclude';\nexport type VectorArrange = 'front' | 'forward' | 'backward' | 'back';\n/** Average: line anchors up on a horizontal line (same y), a vertical one (same x), or both. */\nexport type VectorAverageAxis = 'horizontal' | 'vertical' | 'both';\n\n/** Identifies one segment of a path node: from anchor `segment` to the next. */\nexport interface VectorSegmentRef {\n\tnodeId: string;\n\tsubpath: number;\n\tsegment: number;\n}\n","/**\n * Live corners: a radius stored on an anchor, drawn as a round, inverted or chamfered cut when\n * the path is turned into curves. The stored anchors never change; `expandVectorCorners` is the\n * one place the cut geometry is made, and `subpathsToBezier` calls it, so rendering,\n * hit-testing, bounds, booleans, stroke outlines and SVG export all see the same shape.\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, see THIRD_PARTY_NOTICES.md):\n * - figcraft `crates/doc/src/vector.rs` — `VectorNetwork::rounded` / `corner` and `trim`: each\n * side is trimmed by arc length (the radius clamped so a cut takes at most half of each\n * side) and the round cut is a cubic with handles `4/3 · tan(φ/4) · ρ` along the sides'\n * directions at the cut, φ the turn between them and ρ the radius of the circle through\n * both ends. That is exact at any angle and works where a curve meets a corner.\n * - vectorcraft `crates/geom/src/corners.rs` — `path_corners`, `Corner` (setback, max radius,\n * bisector and radius change for the drag widget) and `cut_corners` (inverted round and\n * chamfer kinds, trimming curved sides between cuts, a closed subpath whose first corner is\n * cut starting where that cut ends).\n */\nimport type { Point } from '../canvas/types.js';\nimport { segmentDerivative, segmentLength, segmentParamAtLength, segmentPoint, subSegment } from '../canvas/pathops/bezier.js';\nimport type { VectorAnchor, VectorCornerKind, VectorSubpath, Vec2 } from './types.js';\n\nconst EPS = 1e-9;\n/** Sides closer than this to straight on (or folded back), as the sine of their angle, make no corner. */\nconst MIN_SINE = 1e-6;\n\nconst sub = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x - b.x, y: a.y - b.y });\nconst add = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x + b.x, y: a.y + b.y });\nconst mul = (a: Vec2, k: number): Vec2 => ({ x: a.x * k, y: a.y * k });\nconst dot = (a: Vec2, b: Vec2) => a.x * b.x + a.y * b.y;\nconst cross = (a: Vec2, b: Vec2) => a.x * b.y - a.y * b.x;\nconst len = (a: Vec2) => Math.hypot(a.x, a.y);\nconst pt = (p: Vec2): Point => [p.x, p.y];\nconst vec = (p: Point): Vec2 => ({ x: p[0], y: p[1] });\nconst onAnchor = (a: VectorAnchor, h: Vec2 | null | undefined) => !h || (Math.abs(h.x - a.x) < EPS && Math.abs(h.y - a.y) < EPS);\n\n/** A side of a corner: the segment from the corner's anchor to a neighbour, as a cubic leaving the corner. */\nclass Side {\n\treadonly curve: Point[];\n\treadonly straight: boolean;\n\treadonly length: number;\n\tconstructor(a: VectorAnchor, h1: Vec2 | null | undefined, h2: Vec2 | null | undefined, b: VectorAnchor) {\n\t\tthis.straight = onAnchor(a, h1) && onAnchor(b, h2);\n\t\tthis.curve = this.straight ? [pt(a), pt(b)] : [pt(a), pt(h1 ?? a), pt(h2 ?? b), pt(b)];\n\t\tthis.length = this.straight ? Math.hypot(b.x - a.x, b.y - a.y) : segmentLength(this.curve);\n\t}\n\n\t/** Unit direction the side leaves the corner in (towards its first control point off the corner). */\n\tdirection(): Vec2 | null {\n\t\tconst p0 = vec(this.curve[0]);\n\t\tfor (const q of this.curve.slice(1)) {\n\t\t\tconst d = sub(vec(q), p0);\n\t\t\tconst l = len(d);\n\t\t\tif (l > EPS) return mul(d, 1 / l);\n\t\t}\n\t\treturn null;\n\t}\n\n\t/** The point `s` along the side from the corner: its parameter, position and the direction the side runs on in there. */\n\tat(s: number, u: Vec2): { t: number; p: Vec2; dir: Vec2 } {\n\t\tif (this.straight) {\n\t\t\tconst t = this.length > EPS ? Math.min(1, Math.max(0, s / this.length)) : 0;\n\t\t\treturn { t, p: add(vec(this.curve[0]), mul(u, s)), dir: u };\n\t\t}\n\t\tconst t = segmentParamAtLength(this.curve, s, this.length);\n\t\tconst d = vec(segmentDerivative(this.curve, t));\n\t\tconst l = len(d);\n\t\treturn { t, p: vec(segmentPoint(this.curve, t)), dir: l > EPS ? mul(d, 1 / l) : u };\n\t}\n}\n\n/**\n * A corner a live radius can cut: an anchor that is not smooth, where two sides (straight or\n * curved) meet at an angle. Positions are in the path node's own space.\n */\nexport interface VectorCornerInfo {\n\tsubpath: number;\n\tindex: number;\n\t/** Where the sides meet. */\n\tat: Vec2;\n\t/** Unit directions the sides leave the corner in: towards the previous anchor, then the next one. */\n\tu: Vec2;\n\tv: Vec2;\n\t/** The sides' lengths (along curves), in the same order. */\n\tlu: number;\n\tlv: number;\n\t/** Cosine and sine of the angle between the sides. */\n\tcos: number;\n\tsin: number;\n\t/** The angle between the sides in degrees (90 at a rectangle's corners). */\n\tangle: number;\n\t/** The largest radius that fits: its cut then reaches halfway along the shorter side. */\n\tmaxRadius: number;\n}\n\ninterface CornerData extends VectorCornerInfo {\n\tsideU: Side;\n\tsideV: Side;\n}\n\nfunction cornerOf(sp: VectorSubpath, s: number, i: number): CornerData | null {\n\tconst n = sp.anchors.length;\n\tif (n < 2 || (!sp.closed && (i === 0 || i === n - 1))) return null;\n\tif (n === 2 && sp.closed) return null;\n\tconst a = sp.anchors[i];\n\tif (a.type === 'smooth' || a.type === 'symmetric') return null;\n\tconst prev = sp.anchors[(i - 1 + n) % n];\n\tconst next = sp.anchors[(i + 1) % n];\n\tconst sideU = new Side(a, a.in, prev.out, prev);\n\tconst sideV = new Side(a, a.out, next.in, next);\n\tconst u = sideU.direction();\n\tconst v = sideV.direction();\n\tif (!u || !v) return null;\n\tconst lu = sideU.length;\n\tconst lv = sideV.length;\n\tif (!(lu > EPS && lv > EPS) || !Number.isFinite(lu) || !Number.isFinite(lv)) return null;\n\tconst cos = Math.max(-1, Math.min(1, dot(u, v)));\n\tconst sin = Math.abs(cross(u, v));\n\tif (sin <= MIN_SINE) return null;\n\treturn { subpath: s, index: i, at: { x: a.x, y: a.y }, u, v, lu, lv, cos, sin, angle: (Math.atan2(sin, cos) * 180) / Math.PI, maxRadius: ((Math.min(lu, lv) / 2) * sin) / (1 + cos), sideU, sideV };\n}\n\nconst strip = ({ sideU: _u, sideV: _v, ...info }: CornerData): VectorCornerInfo => info;\n\n/** The corner at anchor `index` of a subpath, or null when the anchor makes none (an open end, smooth, or straight on). */\nexport function vectorCornerAt(sp: VectorSubpath, index: number, subpath = 0): VectorCornerInfo | null {\n\tconst c = cornerOf(sp, subpath, index);\n\treturn c ? strip(c) : null;\n}\n\n/** Every corner of the subpaths that a live radius can cut, in anchor order. */\nexport function vectorCorners(subpaths: readonly VectorSubpath[]): VectorCornerInfo[] {\n\tconst out: VectorCornerInfo[] = [];\n\tsubpaths.forEach((sp, s) => {\n\t\tfor (let i = 0; i < sp.anchors.length; i++) {\n\t\t\tconst c = cornerOf(sp, s, i);\n\t\t\tif (c) out.push(strip(c));\n\t\t}\n\t});\n\treturn out;\n}\n\n/** How far from the corner a round cut of radius `r` meets each side: r / tan(angle / 2). */\nexport const cornerSetback = (c: Pick<VectorCornerInfo, 'cos' | 'sin'>, r: number) => (r * (1 + c.cos)) / c.sin;\n\n/** `radius` clamped to what the corner can draw (0 for negative or non-finite radii). */\nexport const fitCornerRadius = (c: Pick<VectorCornerInfo, 'maxRadius'>, radius: number) => (Number.isFinite(radius) ? Math.min(Math.max(0, radius), c.maxRadius) : 0);\n\n/** The point `k` along the corner's bisector, measured in (u + v): a round cut of radius r is centred at k = r / sin. */\nexport const cornerBisectorPoint = (c: VectorCornerInfo, k: number): Vec2 => add(c.at, mul(add(c.u, c.v), k));\n\n/** How much the radius grows when the round cut's centre moves by `d` (its part along the bisector, in radius units). */\nexport const cornerRadiusChange = (c: VectorCornerInfo, d: Vec2) => (dot(d, add(c.u, c.v)) * c.sin) / (2 + 2 * c.cos);\n\n/** Handle length per unit radius of a cubic arc spanning the angle whose cosine is `cos`: 4/3 · tan(angle / 4). */\nfunction arcHandle(cos: number): number {\n\tconst c = Math.max(-1, Math.min(1, cos));\n\tconst sinHalf = Math.sqrt(Math.max(0, (1 - c) / 2));\n\tconst cosHalf = Math.sqrt(Math.max(0, (1 + c) / 2));\n\treturn ((4 / 3) * sinHalf) / (1 + cosHalf);\n}\n\n/** The unit direction square to unit `a`, on `b`'s side. */\nfunction squareTo(a: Vec2, b: Vec2): Vec2 {\n\tconst w = sub(b, mul(a, dot(a, b)));\n\tconst l = len(w);\n\treturn l > EPS ? mul(w, 1 / l) : { x: 0, y: 0 };\n}\n\ninterface Cut {\n\t/** Parameters along each side (from the corner) where the cut meets it. */\n\ttu: number;\n\ttv: number;\n\tstart: Vec2;\n\t/** Handles of the cut's own segment (absent for a chamfer). */\n\tout: Vec2 | null;\n\tin: Vec2 | null;\n\tend: Vec2;\n}\n\nfunction cutCorner(c: CornerData, radius: number, kind: VectorCornerKind): Cut | null {\n\t// figcraft `corner`: trim each side by arc length, at most half of it.\n\tconst s = Math.min(cornerSetback(c, radius), Math.min(c.lu, c.lv) / 2);\n\tif (!(s > EPS)) return null;\n\tconst a = c.sideU.at(s, c.u);\n\tconst b = c.sideV.at(s, c.v);\n\tif (kind === 'chamfer') return { tu: a.t, tv: b.t, start: a.p, out: null, in: null, end: b.p };\n\tif (kind === 'inverted') {\n\t\t// vectorcraft `cut`: an arc centred on the corner through both ends, spanning the corner's angle.\n\t\tconst h = s * arcHandle(dot(a.dir, b.dir));\n\t\treturn { tu: a.t, tv: b.t, start: a.p, out: add(a.p, mul(squareTo(a.dir, b.dir), h)), in: add(b.p, mul(squareTo(b.dir, a.dir), h)), end: b.p };\n\t}\n\t// Round: d1, d2 point back towards the corner at the cut's ends; φ is the turn between them\n\t// and ρ the radius of the circle through both ends.\n\tconst d1 = mul(a.dir, -1);\n\tconst d2 = mul(b.dir, -1);\n\tconst turn = Math.acos(Math.max(-1, Math.min(1, -dot(d1, d2))));\n\tconst chord = len(sub(b.p, a.p));\n\tconst k = turn < 1e-9 ? chord / 3 : (((4 / 3) * Math.tan(turn / 4) * chord) / (2 * Math.sin(turn / 2)));\n\tif (!Number.isFinite(k)) return null;\n\treturn { tu: a.t, tv: b.t, start: a.p, out: add(a.p, mul(d1, k)), in: add(b.p, mul(d2, k)), end: b.p };\n}\n\nconst radiusOf = (a: VectorAnchor) => {\n\tconst r = a.corner?.radius;\n\treturn typeof r === 'number' && r > 0 && Number.isFinite(r) ? r : 0;\n};\n\n/** True when any anchor of the subpaths has a live corner radius. */\nexport function hasVectorCorners(subpaths: readonly VectorSubpath[]): boolean {\n\treturn subpaths.some((sp) => sp.anchors.some((a) => radiusOf(a) > 0));\n}\n\n/** One subpath with its corners cut; `sources[i]` is the stored anchor each output anchor comes from. */\nexport function expandVectorCornersOf(sp: VectorSubpath, subpath = 0): { subpath: VectorSubpath; sources: number[] } {\n\tconst n = sp.anchors.length;\n\tconst cuts: (Cut | null)[] = sp.anchors.map((a, i) => {\n\t\tconst r = radiusOf(a);\n\t\tif (!r) return null;\n\t\tconst c = cornerOf(sp, subpath, i);\n\t\tif (!c) return null;\n\t\tconst fitted = fitCornerRadius(c, r);\n\t\treturn fitted > EPS ? cutCorner(c, fitted, a.corner?.kind ?? 'round') : null;\n\t});\n\tif (!cuts.some(Boolean)) return { subpath: { closed: sp.closed, anchors: sp.anchors.map(plain) }, sources: sp.anchors.map((_, i) => i) };\n\t// Each segment from anchor j trimmed to what the cuts at its ends leave: its handles, or\n\t// undefined when it is untouched (null handles: a straight segment).\n\tconst trimmed: ({ out: Vec2 | null; in: Vec2 | null } | undefined)[] = sp.anchors.map((a, j) => {\n\t\tconst k = (j + 1) % n;\n\t\tif (k === 0 && !sp.closed) return undefined;\n\t\tconst b = sp.anchors[k];\n\t\tconst from = cuts[j];\n\t\tconst to = cuts[k];\n\t\tif (!from && !to) return undefined;\n\t\tif (onAnchor(a, a.out) && onAnchor(b, b.in)) return { out: null, in: null };\n\t\tconst s0 = from ? from.tv : 0;\n\t\tconst s1 = to ? 1 - to.tu : 1;\n\t\tconst seg: Point[] = [pt(a), pt(a.out ?? a), pt(b.in ?? b), pt(b)];\n\t\tconst part = subSegment(seg, s0, Math.max(s0, s1));\n\t\treturn { out: vec(part[1]), in: vec(part[2]) };\n\t});\n\tconst anchors: VectorAnchor[] = [];\n\tconst sources: number[] = [];\n\tlet closing: VectorAnchor | null = null;\n\tconst handleIn = (i: number, a: VectorAnchor) => {\n\t\tconst t = trimmed[(i - 1 + n) % n];\n\t\treturn t ? t.in : (a.in ?? null);\n\t};\n\tconst handleOut = (i: number, a: VectorAnchor) => {\n\t\tconst t = trimmed[i];\n\t\treturn t ? t.out : (a.out ?? null);\n\t};\n\tsp.anchors.forEach((a, i) => {\n\t\tconst c = cuts[i];\n\t\tif (!c) {\n\t\t\tanchors.push(withHandles({ x: a.x, y: a.y, ...(a.type ? { type: a.type } : {}) }, handleIn(i, a), handleOut(i, a)));\n\t\t\tsources.push(i);\n\t\t\treturn;\n\t\t}\n\t\tconst start = withHandles({ x: c.start.x, y: c.start.y }, handleIn(i, a), c.out);\n\t\tconst end = withHandles({ x: c.end.x, y: c.end.y }, c.in, handleOut(i, a));\n\t\tif (i === 0 && sp.closed) closing = start;\n\t\telse {\n\t\t\tanchors.push(start);\n\t\t\tsources.push(i);\n\t\t}\n\t\tanchors.push(end);\n\t\tsources.push(i);\n\t});\n\tif (closing) {\n\t\tanchors.push(closing);\n\t\tsources.push(0);\n\t}\n\treturn { subpath: { closed: sp.closed, anchors }, sources };\n}\n\nfunction withHandles(a: VectorAnchor, hin: Vec2 | null, hout: Vec2 | null): VectorAnchor {\n\tif (hin && !onAnchor(a, hin)) a.in = { x: hin.x, y: hin.y };\n\tif (hout && !onAnchor(a, hout)) a.out = { x: hout.x, y: hout.y };\n\treturn a;\n}\n\nfunction plain(a: VectorAnchor): VectorAnchor {\n\tif (!('corner' in a)) return a;\n\tconst { corner: _c, ...rest } = a;\n\treturn rest;\n}\n\n/**\n * The subpaths with every live corner cut (round, inverted or chamfer), each radius no larger\n * than fits. A cut corner becomes two anchors and curved sides are trimmed to what the cuts\n * leave of them. Subpaths without corners come back unchanged.\n */\nexport function expandVectorCorners(subpaths: readonly VectorSubpath[]): VectorSubpath[] {\n\tif (!hasVectorCorners(subpaths)) return subpaths as VectorSubpath[];\n\treturn subpaths.map((sp, s) => (sp.anchors.some((a) => radiusOf(a) > 0) ? expandVectorCornersOf(sp, s).subpath : sp));\n}\n\n/**\n * Sets (or clears, with radius 0) the live corner of anchors. `kind` keeps each anchor's own\n * kind when omitted. Anchors that make no corner keep the radius too, so it applies once they do.\n */\nexport function setAnchorCorner(a: VectorAnchor, radius: number, kind?: VectorCornerKind): VectorAnchor {\n\tconst { corner, ...rest } = a;\n\tconst r = Number.isFinite(radius) ? Math.max(0, radius) : 0;\n\tconst k = kind ?? corner?.kind;\n\tif (r <= 0 && !kind) return rest;\n\treturn { ...rest, corner: { radius: r, ...(k && k !== 'round' ? { kind: k } : {}) } };\n}\n\n/** The next corner kind (Alt-clicking a corner widget cycles round → inverted → chamfer). */\nexport function nextVectorCornerKind(kind: VectorCornerKind | undefined): VectorCornerKind {\n\treturn kind === 'inverted' ? 'chamfer' : kind === 'chamfer' ? 'round' : 'inverted';\n}\n\n/** Every anchor of a subpath given the same live corner (radius 0 clears them). */\nexport function setSubpathCorners(sp: VectorSubpath, radius: number, kind?: VectorCornerKind): VectorSubpath {\n\treturn { closed: sp.closed, anchors: sp.anchors.map((a) => setAnchorCorner(a, radius, kind)) };\n}\n","/**\n * Variable-width stroke profiles: stroke widths at positions along a path (each subpath on its\n * own), interpolated smoothly and held flat before the first and after the last point. Each\n * point has a left and a right side scale (looking along the path on screen, y down), so a\n * stroke can grow on one side only.\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, see THIRD_PARTY_NOTICES.md):\n * - figcraft `crates/doc/src/props.rs` — `WidthProfile` / `WidthPoint`: sanitising, side\n * scales, inserting and moving points, and the monotone cubic (Fritsch–Carlson) interpolation\n * that never overshoots its neighbouring points.\n * - vectorcraft `crates/doc/src/appearance.rs` — `WidthProfile` as `(t, left, right)` points,\n * discontinuous points (two points at one `t` make a step) and the profile presets.\n * - effectcraft `crates/path/src/varstroke.rs` — `width_factor`: the parametric Taper (lengths,\n * end widths, ease) and Wave (amount, cycles, phase) shapes, used here as profile generators.\n */\nimport type { VectorWidthPoint } from './types.js';\n\n/** The most points a profile keeps. */\nexport const VECTOR_WIDTH_PROFILE_MAX_POINTS = 64;\n/** The widest a side can be, as a multiple of the stroke width. */\nexport const VECTOR_WIDTH_PROFILE_MAX_SCALE = 1000;\n/** Positions closer than this are the same place (the two sides of a discontinuous point). */\nexport const VECTOR_WIDTH_SAME_T = 1e-6;\n\n/** Built-in profiles. `uniform` is the plain stroke (no profile). */\nexport type VectorWidthPreset = 'uniform' | 'taperStart' | 'taperEnd' | 'taperBoth' | 'bulge' | 'pinch' | 'teardrop' | 'wave' | 'pressure';\n\n/** One preset as a menu shows it. */\nexport interface VectorWidthPresetInfo {\n\tid: VectorWidthPreset;\n\tlabel: string;\n\tpoints: readonly VectorWidthPoint[];\n}\n\nconst sym = (t: number, s: number): VectorWidthPoint => ({ t, left: s, right: s });\n\n/** The built-in profiles, in menu order. */\nexport const VECTOR_WIDTH_PRESETS: readonly VectorWidthPresetInfo[] = [\n\t{ id: 'uniform', label: 'Uniform', points: [] },\n\t{ id: 'taperStart', label: 'Taper start', points: [sym(0, 0), sym(1, 1)] },\n\t{ id: 'taperEnd', label: 'Taper end', points: [sym(0, 1), sym(1, 0)] },\n\t{ id: 'taperBoth', label: 'Taper both', points: [sym(0, 0), sym(0.5, 1), sym(1, 0)] },\n\t// Full width at the ends, swelling to twice the width in the middle.\n\t{ id: 'bulge', label: 'Bulge', points: [sym(0, 1), sym(0.5, 2), sym(1, 1)] },\n\t// Full width at the ends, pinched to a quarter in the middle.\n\t{ id: 'pinch', label: 'Pinch', points: [sym(0, 1), sym(0.5, 0.25), sym(1, 1)] },\n\t// A round head a fifth of the way along, then a long taper to the end.\n\t{ id: 'teardrop', label: 'Teardrop', points: [sym(0, 0), sym(0.2, 1), sym(1, 0)] },\n\t// Two swells between narrow necks.\n\t{ id: 'wave', label: 'Wave', points: [sym(0, 0.3), sym(0.25, 1), sym(0.5, 0.3), sym(0.75, 1), sym(1, 0.3)] },\n\t// A pen stroke: a quick press, a slow lift.\n\t{ id: 'pressure', label: 'Pressure', points: [sym(0, 0.15), sym(0.12, 0.85), sym(0.45, 1), sym(0.8, 0.7), sym(1, 0.05)] }\n];\n\nexport const VECTOR_WIDTH_PRESET_IDS: readonly VectorWidthPreset[] = VECTOR_WIDTH_PRESETS.map((p) => p.id);\n\nconst clean = (v: unknown, max: number) => (typeof v === 'number' && Number.isFinite(v) ? Math.min(Math.max(v, 0), max) : null);\n\n/**\n * A profile as the outline uses it: finite points only, `t` in 0–1, side scales in 0–1000,\n * sorted by `t` (stable, so a step keeps its order), at most 64 points. Points missing a side\n * take the other side's scale.\n */\nexport function sanitizeWidthProfile(points: readonly Partial<VectorWidthPoint>[] | null | undefined): VectorWidthPoint[] {\n\tif (!Array.isArray(points)) return [];\n\tconst out: VectorWidthPoint[] = [];\n\tfor (const p of points) {\n\t\tif (!p || typeof p !== 'object') continue;\n\t\tconst t = clean(p.t, 1);\n\t\tconst l = clean(p.left, VECTOR_WIDTH_PROFILE_MAX_SCALE);\n\t\tconst r = clean(p.right, VECTOR_WIDTH_PROFILE_MAX_SCALE);\n\t\tif (t === null || (l === null && r === null)) continue;\n\t\tout.push({ t, left: l ?? r!, right: r ?? l! });\n\t\tif (out.length >= VECTOR_WIDTH_PROFILE_MAX_POINTS) break;\n\t}\n\treturn out.map((p, i) => [p, i] as const).sort((a, b) => a[0].t - b[0].t || a[1] - b[1]).map(([p]) => p);\n}\n\n/** True when the profile draws a plain stroke: no points, or every side at scale 1. */\nexport function isUniformWidthProfile(points: readonly VectorWidthPoint[] | null | undefined): boolean {\n\treturn !points?.length || points.every((p) => p.left === 1 && p.right === 1);\n}\n\n/** Slope of side `k` from point `i` to `i + 1` (0 when they share a position). */\nfunction secant(pts: readonly VectorWidthPoint[], i: number, k: 'left' | 'right'): number {\n\tconst a = pts[i];\n\tconst b = pts[i + 1];\n\treturn a && b && b.t - a.t > 1e-12 ? (b[k] - a[k]) / (b.t - a.t) : 0;\n}\n\n/** Fritsch–Carlson tangent: one-sided at the ends, the harmonic mean of the slopes inside, flat at local extremes. */\nfunction tangent(pts: readonly VectorWidthPoint[], i: number, k: 'left' | 'right'): number {\n\tconst last = pts.length - 1;\n\tif (i <= 0) return secant(pts, 0, k);\n\tif (i >= last) return secant(pts, last - 1, k);\n\tconst d0 = secant(pts, i - 1, k);\n\tconst d1 = secant(pts, i, k);\n\treturn d0 * d1 <= 0 ? 0 : (2 * d0 * d1) / (d0 + d1);\n}\n\nfunction interp(pts: readonly VectorWidthPoint[], t: number, k: 'left' | 'right'): number {\n\tconst first = pts[0];\n\tconst last = pts[pts.length - 1];\n\tif (!(t > first.t)) return first[k];\n\tif (t >= last.t) return last[k];\n\t// The last point at or before t (the second of a step at exactly t).\n\tlet i = 0;\n\twhile (i + 1 < pts.length && pts[i + 1].t <= t) i++;\n\tconst a = pts[i];\n\tconst b = pts[i + 1];\n\tconst h = b.t - a.t;\n\tif (h <= 1e-12) return b[k];\n\tconst u = (t - a.t) / h;\n\tconst u2 = u * u;\n\tconst u3 = u2 * u;\n\tconst w = (2 * u3 - 3 * u2 + 1) * a[k] + (u3 - 2 * u2 + u) * h * tangent(pts, i, k) + (3 * u2 - 2 * u3) * b[k] + (u3 - u2) * h * tangent(pts, i + 1, k);\n\treturn Math.max(0, w);\n}\n\n/**\n * The left and right side scales at `t` (0–1 along the subpath by length). Each side is\n * interpolated on its own with a monotone cubic, so the width never overshoots its points;\n * a profile without points is uniform (1, 1).\n */\nexport function widthProfileAt(points: readonly VectorWidthPoint[] | null | undefined, t: number): { left: number; right: number } {\n\tif (!points?.length) return { left: 1, right: 1 };\n\treturn { left: interp(points, t, 'left'), right: interp(points, t, 'right') };\n}\n\n/** The largest side scale (the interpolation never exceeds its points); 1 without a profile. */\nexport function widthProfileMaxScale(points: readonly VectorWidthPoint[] | null | undefined): number {\n\tif (!points?.length) return 1;\n\treturn points.reduce((m, p) => Math.max(m, p.left, p.right), 0);\n}\n\n/** The points of a preset (empty for `uniform`), or null for an unknown id. */\nexport function widthProfilePreset(id: string): VectorWidthPoint[] | null {\n\tconst p = VECTOR_WIDTH_PRESETS.find((q) => q.id === id);\n\treturn p ? p.points.map((q) => ({ ...q })) : null;\n}\n\n/** The preset a profile matches: `uniform` without one (or all at scale 1), `custom` when none matches. */\nexport function widthProfilePresetId(points: readonly VectorWidthPoint[] | null | undefined): VectorWidthPreset | 'custom' {\n\tif (isUniformWidthProfile(points)) return 'uniform';\n\tconst same = (a: readonly VectorWidthPoint[], b: readonly VectorWidthPoint[]) =>\n\t\ta.length === b.length && a.every((p, i) => Math.abs(p.t - b[i].t) < 1e-9 && Math.abs(p.left - b[i].left) < 1e-9 && Math.abs(p.right - b[i].right) < 1e-9);\n\treturn VECTOR_WIDTH_PRESETS.find((p) => p.points.length && same(points!, p.points))?.id ?? 'custom';\n}\n\n/** The profile of the reversed path: positions mirrored and the sides swapped. */\nexport function reverseWidthProfile(points: readonly VectorWidthPoint[]): VectorWidthPoint[] {\n\treturn points.map((p) => ({ t: 1 - p.t, left: p.right, right: p.left })).reverse();\n}\n\n/** The profile of a mirrored path (it runs the same way, but its sides swap). */\nexport function mirrorWidthProfile(points: readonly VectorWidthPoint[]): VectorWidthPoint[] {\n\treturn points.map((p) => ({ t: p.t, left: p.right, right: p.left }));\n}\n\n/** The points a profile edit starts from: the profile, or a uniform one with a point at each end. */\nfunction editable(points: readonly VectorWidthPoint[] | null | undefined): VectorWidthPoint[] {\n\treturn points?.length ? points.map((p) => ({ ...p })) : [sym(0, 1), sym(1, 1)];\n}\n\n/**\n * Adds a width point at `t` (side scales `left` / `right`, default: as wide as the stroke is\n * there) and returns the new profile and the point's index. Inserting at the position of an\n * existing point replaces it, unless `step` is set (which makes a discontinuous point).\n */\nexport function insertWidthPoint(\n\tpoints: readonly VectorWidthPoint[] | null | undefined,\n\tt: number,\n\tsides: { left?: number; right?: number } = {},\n\toptions: { step?: boolean } = {}\n): { points: VectorWidthPoint[]; index: number } {\n\tconst pts = editable(points);\n\tconst tt = Math.min(Math.max(Number.isFinite(t) ? t : 0, 0), 1);\n\tconst here = widthProfileAt(points?.length ? points : null, tt);\n\tconst p: VectorWidthPoint = {\n\t\tt: tt,\n\t\tleft: clean(sides.left, VECTOR_WIDTH_PROFILE_MAX_SCALE) ?? here.left,\n\t\tright: clean(sides.right, VECTOR_WIDTH_PROFILE_MAX_SCALE) ?? here.right\n\t};\n\tconst same = pts.findIndex((q) => Math.abs(q.t - tt) <= VECTOR_WIDTH_SAME_T);\n\tif (same >= 0 && !options.step) {\n\t\tpts[same] = { ...p, t: pts[same].t };\n\t\treturn { points: pts, index: same };\n\t}\n\tlet i = 0;\n\twhile (i < pts.length && pts[i].t <= tt) i++;\n\tif (pts.length >= VECTOR_WIDTH_PROFILE_MAX_POINTS) return { points: pts, index: Math.max(0, i - 1) };\n\tpts.splice(i, 0, p);\n\treturn { points: pts, index: i };\n}\n\n/**\n * Changes point `index`: moves it to `t` (kept between its neighbours, so indices stay put)\n * and / or sets its side scales. Out-of-range indices leave the profile as it is.\n */\nexport function setWidthPoint(points: readonly VectorWidthPoint[], index: number, patch: Partial<VectorWidthPoint>): VectorWidthPoint[] {\n\tconst pts = points.map((p) => ({ ...p }));\n\tconst p = pts[index];\n\tif (!p) return pts;\n\tif (typeof patch.t === 'number' && Number.isFinite(patch.t)) {\n\t\tconst lo = index > 0 ? pts[index - 1].t : 0;\n\t\tconst hi = index < pts.length - 1 ? pts[index + 1].t : 1;\n\t\tp.t = Math.min(Math.max(patch.t, lo), Math.max(hi, lo));\n\t}\n\tconst l = clean(patch.left, VECTOR_WIDTH_PROFILE_MAX_SCALE);\n\tconst r = clean(patch.right, VECTOR_WIDTH_PROFILE_MAX_SCALE);\n\tif (l !== null) p.left = l;\n\tif (r !== null) p.right = r;\n\treturn pts;\n}\n\n/** Removes the points at `indices`. */\nexport function removeWidthPoints(points: readonly VectorWidthPoint[], indices: readonly number[]): VectorWidthPoint[] {\n\tconst drop = new Set(indices);\n\treturn points.filter((_, i) => !drop.has(i)).map((p) => ({ ...p }));\n}\n\n// ---------------------------------------------------------------------------\n// Generators\n// ---------------------------------------------------------------------------\n\n/** effectcraft's ease from the tip (`u = 0`) to full width (`u = 1`): linear at 0, a quarter circle at 1. */\nfunction ease(u: number, e: number): number {\n\tconst x = Math.min(Math.max(u, 0), 1);\n\tconst round = Math.sqrt(Math.max(0, 1 - (1 - x) * (1 - x)));\n\treturn x + (round - x) * Math.min(Math.max(e, 0), 1);\n}\n\n/** A parametric taper (effectcraft's Stroke Taper), lengths as fractions of the path. */\nexport interface VectorTaperOptions {\n\t/** Fraction of the path the start taper covers (default 0). */\n\tstartLength?: number;\n\t/** Fraction the end taper covers (default 0). */\n\tendLength?: number;\n\t/** Width at the start as a fraction of the stroke width (default 0: a point). */\n\tstartWidth?: number;\n\tendWidth?: number;\n\t/** 0 linear, 1 a quarter circle bulging outwards (default 0). */\n\tstartEase?: number;\n\tendEase?: number;\n}\n\n/** A width wave (effectcraft's Stroke Wave): the width swings between `1 − amount` and 1. */\nexport interface VectorWaveOptions {\n\t/** 0–1 (default 0.5). */\n\tamount?: number;\n\t/** Whole cycles along the path (default 4). */\n\tcycles?: number;\n\t/** Degrees (default 0). */\n\tphase?: number;\n}\n\n/** The width factor at fraction `t` of a taper and / or a wave (effectcraft `width_factor`). */\nexport function taperWaveFactor(t: number, taper?: VectorTaperOptions | null, wave?: VectorWaveOptions | null): number {\n\tlet k = 1;\n\tif (taper) {\n\t\tlet ls = Math.max(0, taper.startLength ?? 0);\n\t\tlet le = Math.max(0, taper.endLength ?? 0);\n\t\t// Overlapping tapers share the path in proportion.\n\t\tif (ls + le > 1) {\n\t\t\tconst f = 1 / (ls + le);\n\t\t\tls *= f;\n\t\t\tle *= f;\n\t\t}\n\t\tconst sw = Math.min(Math.max(taper.startWidth ?? 0, 0), 1);\n\t\tconst ew = Math.min(Math.max(taper.endWidth ?? 0, 0), 1);\n\t\tif (ls > 0 && t < ls) k = Math.min(k, sw + (1 - sw) * ease(t / ls, taper.startEase ?? 0));\n\t\tif (le > 0 && t > 1 - le) k = Math.min(k, ew + (1 - ew) * ease((1 - t) / le, taper.endEase ?? 0));\n\t}\n\tif (wave) {\n\t\tconst cycles = wave.cycles ?? 4;\n\t\tconst amount = Math.min(Math.max(wave.amount ?? 0.5, 0), 1);\n\t\tif (cycles > 0 && amount > 0) {\n\t\t\tconst ph = 2 * Math.PI * t * cycles + ((wave.phase ?? 0) * Math.PI) / 180;\n\t\t\tk *= 1 - amount * (0.5 - 0.5 * Math.cos(ph));\n\t\t}\n\t}\n\treturn k;\n}\n\n/**\n * Samples a taper and / or wave into profile points (symmetric), simplified to within\n * `tolerance` of the factor (default 0.01). The monotone interpolation draws them back smoothly.\n */\nexport function generateWidthProfile(options: { taper?: VectorTaperOptions | null; wave?: VectorWaveOptions | null; samples?: number; tolerance?: number }): VectorWidthPoint[] {\n\tconst cycles = options.wave ? Math.max(0, options.wave.cycles ?? 4) : 0;\n\tconst n = Math.max(8, Math.min(VECTOR_WIDTH_PROFILE_MAX_POINTS * 4, options.samples ?? Math.ceil(32 + cycles * 16)));\n\tconst raw: [number, number][] = [];\n\tfor (let i = 0; i <= n; i++) raw.push([i / n, taperWaveFactor(i / n, options.taper, options.wave)]);\n\t// Keep the taper ends exactly.\n\tconst ts = [options.taper?.startLength, options.taper?.endLength !== undefined ? 1 - options.taper.endLength : undefined];\n\tfor (const t of ts) if (typeof t === 'number' && t > 0 && t < 1) raw.push([t, taperWaveFactor(t, options.taper, options.wave)]);\n\traw.sort((a, b) => a[0] - b[0]);\n\tconst kept = simplifySamples(raw, options.tolerance ?? 0.01, VECTOR_WIDTH_PROFILE_MAX_POINTS);\n\treturn kept.map(([t, k]) => sym(t, k));\n}\n\n/** Douglas–Peucker on (t, value) samples (vertical distance), then thinned to at most `max`. */\nfunction simplifySamples(samples: readonly [number, number][], tolerance: number, max: number): [number, number][] {\n\tif (samples.length <= 2) return samples.slice();\n\tconst keep = new Array(samples.length).fill(false);\n\tkeep[0] = keep[samples.length - 1] = true;\n\tconst stack: [number, number][] = [[0, samples.length - 1]];\n\twhile (stack.length) {\n\t\tconst [a, b] = stack.pop()!;\n\t\tconst [ta, va] = samples[a];\n\t\tconst [tb, vb] = samples[b];\n\t\tlet worst = -1;\n\t\tlet err = tolerance;\n\t\tfor (let i = a + 1; i < b; i++) {\n\t\t\tconst [t, v] = samples[i];\n\t\t\tconst lin = tb - ta > 1e-12 ? va + ((vb - va) * (t - ta)) / (tb - ta) : va;\n\t\t\tconst e = Math.abs(v - lin);\n\t\t\tif (e > err) {\n\t\t\t\terr = e;\n\t\t\t\tworst = i;\n\t\t\t}\n\t\t}\n\t\tif (worst >= 0) {\n\t\t\tkeep[worst] = true;\n\t\t\tstack.push([a, worst], [worst, b]);\n\t\t}\n\t}\n\tlet out = samples.filter((_, i) => keep[i]);\n\twhile (out.length > max) out = out.filter((_, i) => i === 0 || i === out.length - 1 || i % 2 === 0);\n\treturn out;\n}\n\n/** Pen pressure that draws the stroke's own width (a mouse reports 0.5 while a button is down). */\nexport const VECTOR_PRESSURE_NOMINAL = 0.5;\n\n/**\n * A profile from pen pressure recorded along a stroke: `(t, pressure 0–1)` samples in order.\n * The width scale is pressure ÷ 0.5 (so half pressure draws the stroke's width, full pressure\n * twice it), at least 0.05; the samples are simplified to within `tolerance` (default 0.02).\n * Returns an empty (uniform) profile when every sample is the same.\n */\nexport function pressureWidthProfile(samples: readonly { t: number; pressure: number }[], options: { tolerance?: number } = {}): VectorWidthPoint[] {\n\tconst raw: [number, number][] = samples\n\t\t.filter((s) => Number.isFinite(s.t) && Number.isFinite(s.pressure))\n\t\t.map((s) => [Math.min(Math.max(s.t, 0), 1), Math.max(0.05, Math.min(1, Math.max(0, s.pressure)) / VECTOR_PRESSURE_NOMINAL)] as [number, number]);\n\tif (raw.length < 2) return [];\n\tif (raw.every((s) => Math.abs(s[1] - raw[0][1]) < 1e-6)) return [];\n\treturn simplifySamples(raw, options.tolerance ?? 0.02, VECTOR_WIDTH_PROFILE_MAX_POINTS).map(([t, k]) => sym(t, Math.round(k * 1000) / 1000));\n}\n","/**\n * The outline of a variable-width stroke, as a clean filled Bézier path.\n *\n * Each subpath is flattened (finely enough for the width to vary smoothly) and the stroke is\n * the union of positively wound pieces: one trapezoid per flattened segment (its ends at the\n * local side widths), a wedge on the outer side of every bend (the style's join at the path's\n * own corners, round inside curves) and the caps. Filled with the non-zero rule the union is\n * exact whatever the profile does; it is built as the boundary those pieces add up to (see\n * `variableStrokeRings`), normalised with the polygon boolean engine, and every ring is refitted\n * with cubics (`fitCubics`) to within the tolerance — a real Bézier outline, not a polyline.\n *\n * Ported from ArtCraft effectcraft `crates/path/src/varstroke.rs` (`outline`, `dash_intervals`)\n * (MIT OR Apache-2.0, see THIRD_PARTY_NOTICES.md), with one-sided widths after figcraft\n * `crates/pathops/src/width.rs` (`variable_outline`).\n */\nimport type { Point } from '../canvas/types.js';\nimport { fitCubics, isStraightCubic } from '../canvas/curveFit.js';\nimport { polygonBoolean } from '../canvas/polygonBoolean.js';\nimport {\n\tflattenChain,\n\tpathToContours,\n\tsegmentLength,\n\tsegmentNearest,\n\tsegmentTangent,\n\ttype BezierPath,\n\ttype BezierSegment\n} from '../canvas/pathops/bezier.js';\nimport type { StrokeCap, StrokeJoin } from '../canvas/pathops/stroke.js';\nimport type { VectorWidthPoint } from './types.js';\nimport { widthProfileAt } from './width.js';\n\nexport interface VariableStrokeOptions {\n\t/** Stroke width: a side scale of 1 reaches half of it from the centre line. */\n\twidth: number;\n\tprofile: readonly VectorWidthPoint[];\n\t/** Joins at the path's own corners (default `miter`); bends inside curves are always round. */\n\tjoin?: StrokeJoin;\n\t/** Default `butt`. */\n\tcap?: StrokeCap;\n\t/** Default 4 (as SVG). */\n\tmiterLimit?: number;\n\t/** Dash pattern (as SVG); the profile still runs along the whole subpath. */\n\tdash?: readonly number[];\n\tdashOffset?: number;\n\t/** Largest distance of the result from the exact outline (default 0.05). */\n\ttolerance?: number;\n}\n\n/** Width samples per subpath at least (so the width varies smoothly along long straight runs). */\nconst SAMPLES_PER_SUBPATH = 128;\n/** The most dashes one subpath makes. */\nconst MAX_DASHES = 5000;\n\ntype Vec = [number, number];\nconst sub = (a: Point, b: Point): Vec => [a[0] - b[0], a[1] - b[1]];\nconst along = (p: Point, v: Vec, k: number): Point => [p[0] + v[0] * k, p[1] + v[1] * k];\nconst lerp = (a: Point, b: Point, u: number): Point => [a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u];\nconst dist = (a: Point, b: Point) => Math.hypot(a[0] - b[0], a[1] - b[1]);\nconst unitOf = (v: Vec): Vec => {\n\tconst l = Math.hypot(v[0], v[1]);\n\treturn l > 0 ? [v[0] / l, v[1] / l] : [1, 0];\n};\n/** The left normal of a direction on screen (y down): `(dy, −dx)`. */\nconst leftNormal = (d: Vec): Vec => [d[1], -d[0]];\n\n/** A flattened subpath: points, their arc lengths, and which are the path's own vertices. */\ninterface Poly {\n\tpts: Point[];\n\ts: number[];\n\tcorner: boolean[];\n\tclosed: boolean;\n}\n\nfunction flatten(segments: readonly BezierSegment[], closed: boolean, tol: number): Poly | null {\n\tconst pts: Point[] = [];\n\tconst corner: boolean[] = [];\n\tconst push = (p: Point, isCorner: boolean) => {\n\t\tconst last = pts[pts.length - 1];\n\t\tif (last && dist(last, p) <= 1e-9) {\n\t\t\tcorner[corner.length - 1] ||= isCorner;\n\t\t\treturn;\n\t\t}\n\t\tpts.push(p);\n\t\tcorner.push(isCorner);\n\t};\n\tfor (const seg of segments) {\n\t\tconst flat = flattenChain([seg], tol);\n\t\t// flattenChain drops a closing duplicate; segments that end where they start keep it.\n\t\tif (dist(seg[0], seg[seg.length - 1]) <= 1e-12 && flat.length > 1) flat.push(seg[seg.length - 1]);\n\t\tflat.forEach((p, i) => push(p, i === 0 || i === flat.length - 1));\n\t}\n\tif (closed && pts.length > 2 && dist(pts[0], pts[pts.length - 1]) > 1e-9) push(pts[0], true);\n\tif (pts.length < 2) return null;\n\t// Subdivide so no piece is longer than the width sampling step.\n\tlet total = 0;\n\tfor (let i = 1; i < pts.length; i++) total += dist(pts[i - 1], pts[i]);\n\tif (!(total > 0)) return null;\n\tconst step = Math.max(total / SAMPLES_PER_SUBPATH, tol);\n\tconst fine: Point[] = [pts[0]];\n\tconst fineCorner: boolean[] = [corner[0]];\n\tfor (let i = 1; i < pts.length; i++) {\n\t\tconst n = Math.max(1, Math.ceil(dist(pts[i - 1], pts[i]) / step));\n\t\tfor (let k = 1; k <= n; k++) {\n\t\t\tfine.push(k === n ? pts[i] : lerp(pts[i - 1], pts[i], k / n));\n\t\t\tfineCorner.push(k === n ? corner[i] : false);\n\t\t}\n\t}\n\tconst s = [0];\n\tfor (let i = 1; i < fine.length; i++) s.push(s[i - 1] + dist(fine[i - 1], fine[i]));\n\treturn { pts: fine, s, corner: fineCorner, closed };\n}\n\n/** Arc-length intervals that are \"on\" for a dash pattern on a path `len` long (effectcraft `dash_intervals`). */\nexport function dashIntervals(pattern: readonly number[], offset: number, len: number): [number, number][] {\n\tlet pat = pattern.map((v) => (Number.isFinite(v) ? Math.max(0, v) : 0));\n\tif (pat.length % 2 === 1) pat = [...pat, ...pat];\n\tconst period = pat.reduce((a, b) => a + b, 0);\n\tif (pat.length < 2 || !(period > 1e-9) || !(len > 0)) return [[0, len]];\n\tlet pos = (((Number.isFinite(offset) ? offset : 0) % period) + period) % period;\n\tlet idx = 0;\n\twhile (pos >= pat[idx]) {\n\t\tpos -= pat[idx];\n\t\tidx = (idx + 1) % pat.length;\n\t}\n\tconst out: [number, number][] = [];\n\tlet s = 0;\n\tlet guard = 0;\n\twhile (s < len && guard++ < MAX_DASHES * pat.length) {\n\t\tconst e = Math.min(s + pat[idx] - pos, len);\n\t\tif (idx % 2 === 0 && e >= s) out.push([s, e]);\n\t\ts += pat[idx] - pos;\n\t\tpos = 0;\n\t\tidx = (idx + 1) % pat.length;\n\t}\n\treturn out;\n}\n\n/** The point at arc length `t` of a polyline and the index of the segment it lies on. */\nfunction at(poly: Poly, t: number): [Point, number] {\n\tlet i = 1;\n\twhile (i < poly.pts.length - 1 && poly.s[i] <= t) i++;\n\tconst a = poly.s[i - 1];\n\tconst b = poly.s[i];\n\tconst u = b > a ? Math.min(Math.max((t - a) / (b - a), 0), 1) : 0;\n\treturn [lerp(poly.pts[i - 1], poly.pts[i], u), i];\n}\n\n/** Points of an arc around `c` from angle `a0` turning by `sweep`, radius going from `r0` to `r1` (ends excluded). */\nfunction arcPoints(c: Point, a0: number, sweep: number, r0: number, r1: number, tol: number): Point[] {\n\tconst r = Math.max(r0, r1);\n\tif (!(r > tol * 0.5) || !Number.isFinite(sweep)) return [];\n\tconst stepAngle = 2 * Math.acos(Math.min(Math.max(1 - tol / r, -1), 1));\n\tconst n = Math.min(128, Math.max(2, Math.ceil(Math.abs(sweep) / Math.max(stepAngle, 1e-3))));\n\tconst out: Point[] = [];\n\tfor (let k = 1; k < n; k++) {\n\t\tconst f = k / n;\n\t\tconst a = a0 + sweep * f;\n\t\tconst rr = r0 + (r1 - r0) * f;\n\t\tout.push([c[0] + Math.cos(a) * rr, c[1] + Math.sin(a) * rr]);\n\t}\n\treturn out;\n}\n\n/** Where segments `a0 → a1` and `b0 → b1` cross, if they do (strictly inside `b`, anywhere past the start of `a`). */\nfunction crossing(a0: Point, a1: Point, b0: Point, b1: Point): Point | null {\n\tconst r = sub(a1, a0);\n\tconst q = sub(b1, b0);\n\tconst den = r[0] * q[1] - r[1] * q[0];\n\tif (Math.abs(den) < 1e-12) return null;\n\tconst w = sub(b0, a0);\n\tconst t = (w[0] * q[1] - w[1] * q[0]) / den;\n\tconst u = (w[0] * r[1] - w[1] * r[0]) / den;\n\treturn t > 1e-9 && t <= 1 && u >= 0 && u < 1 - 1e-9 ? [a0[0] + r[0] * t, a0[1] + r[1] * t] : null;\n}\n\n/**\n * The rings of a variable-width stroke in the path's own space; filled with the non-zero rule\n * they are the stroke.\n *\n * effectcraft builds the stroke as a union of positively wound pieces: a trapezoid per flattened\n * segment (its ends at the local side widths), a wedge on the outer side of every bend and the\n * caps. Unioning thousands of overlapping pieces is slow, so each run is emitted as the boundary\n * those pieces add up to instead (winding numbers add, so the non-zero fill is the same): the\n * offset sides with the outer join between them, and on the inner side of a bend either the point\n * where the two offsets cross (the region cut off is covered by both trapezoids) or, when they do\n * not cross, a detour through the centre point (which keeps the winding right when segments are\n * shorter than the width). A closed subpath gives two rings, an open run one.\n */\nexport function variableStrokeRings(path: BezierPath, options: VariableStrokeOptions): Point[][] {\n\tconst half = options.width / 2;\n\tif (!(half > 0) || !Number.isFinite(half)) return [];\n\tconst tol = options.tolerance && options.tolerance > 0 ? options.tolerance : 0.05;\n\tconst join = options.join ?? 'miter';\n\tconst cap = options.cap ?? 'butt';\n\tconst miterLimit = options.miterLimit && options.miterLimit >= 1 ? options.miterLimit : 4;\n\tconst rings: Point[][] = [];\n\tconst push = (out: Point[], p: Point) => {\n\t\tconst last = out[out.length - 1];\n\t\tif (!last || dist(last, p) > 1e-12) out.push(p);\n\t};\n\tfor (const contour of pathToContours(path)) {\n\t\tif (!contour.segments.length) continue;\n\t\t// Chords of the offsets lose area on the outer side of a curve; a quarter of the tolerance keeps that well inside it.\n\t\tconst poly = flatten(contour.segments, contour.closed, Math.min(tol, half) / 4);\n\t\tif (!poly) continue;\n\t\tconst len = poly.s[poly.s.length - 1];\n\t\tconst sides = (s: number): [number, number] => {\n\t\t\tconst w = widthProfileAt(options.profile, s / len);\n\t\t\treturn [w.left * half, w.right * half];\n\t\t};\n\t\tconst intervals = options.dash?.some((v) => v > 0) ? dashIntervals(options.dash, options.dashOffset ?? 0, len) : [[0, len] as [number, number]];\n\t\tconst whole = intervals.length === 1 && intervals[0][0] <= 0 && intervals[0][1] >= len;\n\t\tfor (const [a, b] of intervals) {\n\t\t\tconst [pa, ia] = at(poly, a);\n\t\t\tconst [pb, ib] = at(poly, b);\n\t\t\tconst pts: { p: Point; s: number; corner: boolean }[] = [{ p: pa, s: a, corner: poly.corner[0] && a <= 0 }];\n\t\t\tfor (let i = ia; i < ib; i++) pts.push({ p: poly.pts[i], s: poly.s[i], corner: poly.corner[i] });\n\t\t\tpts.push({ p: pb, s: b, corner: false });\n\t\t\tconst run = pts.filter((q, i) => i === 0 || dist(q.p, pts[i - 1].p) > 1e-9);\n\t\t\tif (run.length < 2) {\n\t\t\t\t// A zero-length dash: only its caps show.\n\t\t\t\tconst [l, r] = sides(a);\n\t\t\t\tconst w = (l + r) / 2;\n\t\t\t\tif (cap === 'round' && w > 0) rings.push([[pa[0] + w, pa[1]], ...arcPoints(pa, 0, 2 * Math.PI, w, w, tol)]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst closed = whole && poly.closed;\n\t\t\tconst m = run.length - 1;\n\t\t\tconst dirs: Vec[] = [];\n\t\t\tfor (let i = 0; i < m; i++) dirs.push(unitOf(sub(run[i + 1].p, run[i].p)));\n\t\t\tconst normals = dirs.map(leftNormal);\n\t\t\tconst w = run.map((q) => sides(q.s));\n\n\t\t\t/** One side (`sigma` +1 left, −1 right) along the run, joins included. */\n\t\t\tconst side = (sigma: 1 | -1): Point[] => {\n\t\t\t\tconst k = sigma > 0 ? 0 : 1;\n\t\t\t\tconst S = (i: number) => along(run[i].p, normals[i], sigma * w[i][k]);\n\t\t\t\tconst E = (i: number) => along(run[i + 1].p, normals[i], sigma * w[i + 1][k]);\n\t\t\t\tconst out: Point[] = [S(0)];\n\t\t\t\tfor (let i = 0; i < m; i++) {\n\t\t\t\t\tconst seam = i === m - 1;\n\t\t\t\t\tif (seam && !closed) {\n\t\t\t\t\t\tpush(out, E(i));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst j = seam ? 0 : i + 1;\n\t\t\t\t\tconst p = run[i + 1].p;\n\t\t\t\t\tconst d0 = dirs[i];\n\t\t\t\t\tconst d1 = dirs[j];\n\t\t\t\t\tconst cross = d0[0] * d1[1] - d0[1] * d1[0];\n\t\t\t\t\tconst dot = d0[0] * d1[0] + d0[1] * d1[1];\n\t\t\t\t\tconst r0 = w[i + 1][k];\n\t\t\t\t\tconst r1 = w[j][k];\n\t\t\t\t\tconst e = E(i);\n\t\t\t\t\tconst st = S(j);\n\t\t\t\t\tif (Math.abs(cross) < 1e-12 && dot > 0) {\n\t\t\t\t\t\tpush(out, e);\n\t\t\t\t\t\tif (!seam) push(out, st);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst uturn = Math.abs(cross) < 1e-12;\n\t\t\t\t\t// Turning right on screen puts the left side outside the bend (a U-turn: the left side).\n\t\t\t\t\tconst outer = uturn ? sigma > 0 : cross * sigma > 0;\n\t\t\t\t\tif (!outer) {\n\t\t\t\t\t\tconst x = seam ? null : crossing(out[out.length - 1], e, st, E(j));\n\t\t\t\t\t\tif (x) push(out, x);\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tpush(out, e);\n\t\t\t\t\t\t\tpush(out, p);\n\t\t\t\t\t\t\tif (!seam) push(out, st);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tpush(out, e);\n\t\t\t\t\tconst theta = uturn ? Math.PI : Math.atan2(cross, dot);\n\t\t\t\t\tconst r = (r0 + r1) / 2;\n\t\t\t\t\tconst kind: StrokeJoin = run[i + 1].corner || (seam && poly.corner[0]) ? join : 'round';\n\t\t\t\t\tif (r > 1e-9) {\n\t\t\t\t\t\tif (kind === 'round') {\n\t\t\t\t\t\t\tif (r * (1 - Math.cos(Math.abs(theta) / 2)) > tol * 0.25) {\n\t\t\t\t\t\t\t\tfor (const q of arcPoints(p, Math.atan2(e[1] - p[1], e[0] - p[0]), theta, r0, r1, tol)) push(out, q);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (kind === 'miter') {\n\t\t\t\t\t\t\tconst halfCos = Math.cos(theta / 2);\n\t\t\t\t\t\t\tconst bis: Vec = [normals[i][0] + normals[j][0], normals[i][1] + normals[j][1]];\n\t\t\t\t\t\t\tconst bl = Math.hypot(bis[0], bis[1]);\n\t\t\t\t\t\t\tif (halfCos > 1e-6 && 1 / halfCos <= miterLimit && bl > 1e-9) push(out, along(p, bis, (sigma * r) / halfCos / bl));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!seam) push(out, st);\n\t\t\t\t}\n\t\t\t\tif (closed && out.length > 1 && dist(out[0], out[out.length - 1]) <= 1e-12) out.pop();\n\t\t\t\treturn out;\n\t\t\t};\n\t\t\tconst left = side(1);\n\t\t\tconst right = side(-1);\n\t\t\tif (closed) {\n\t\t\t\trings.push(left, right.reverse());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Caps: round or square around each end, from one side to the other.\n\t\t\tconst capPoints = (atStart: boolean): Point[] => {\n\t\t\t\tif (cap === 'butt') return [];\n\t\t\t\tconst i = atStart ? 0 : m;\n\t\t\t\tconst d = atStart ? dirs[0] : dirs[m - 1];\n\t\t\t\tconst [l, r] = w[i];\n\t\t\t\tif (!(l + r > 1e-9)) return [];\n\t\t\t\tconst p = run[i].p;\n\t\t\t\tconst n = leftNormal(d);\n\t\t\t\tconst L = along(p, n, l);\n\t\t\t\tconst R = along(p, n, -r);\n\t\t\t\tif (cap === 'round') {\n\t\t\t\t\t// Half a turn around the outside: right side to left at the start, left to right at the end.\n\t\t\t\t\tconst a0 = Math.atan2(d[1], d[0]) + (atStart ? Math.PI / 2 : -Math.PI / 2);\n\t\t\t\t\treturn arcPoints(p, a0, Math.PI, atStart ? r : l, atStart ? l : r, tol);\n\t\t\t\t}\n\t\t\t\tconst ext = (l + r) / 2;\n\t\t\t\tconst o: Vec = atStart ? [-d[0], -d[1]] : d;\n\t\t\t\treturn atStart ? [along(R, o, ext), along(L, o, ext)] : [along(L, o, ext), along(R, o, ext)];\n\t\t\t};\n\t\t\tconst ring: Point[] = [];\n\t\t\tfor (const q of [...left, ...capPoints(false), ...right.reverse(), ...capPoints(true)]) push(ring, q);\n\t\t\tif (ring.length > 2) rings.push(ring);\n\t\t}\n\t}\n\treturn rings;\n}\n\n/**\n * The outline of a variable-width stroke of `path` (side widths from `profile`), as a clean\n * Bézier path: overlaps removed, outer rings and holes, each refitted with cubics to within\n * `tolerance` of the exact outline. Fill it with the non-zero rule (either rule works).\n */\nexport function variableStrokeOutline(path: BezierPath, options: VariableStrokeOptions): BezierPath {\n\tconst pieces = variableStrokeRings(path, options);\n\tif (!pieces.length) return [];\n\tconst tol = options.tolerance && options.tolerance > 0 ? options.tolerance : 0.05;\n\tlet polygons;\n\ttry {\n\t\tpolygons = polygonBoolean('union', [{ rings: pieces, fillRule: 'nonzero' }]);\n\t} catch {\n\t\treturn [];\n\t}\n\tconst out: BezierPath = [];\n\tfor (const polygon of polygons) {\n\t\tfor (const ring of polygon) {\n\t\t\tif (ring.length < 3) continue;\n\t\t\tconst cubics = fitCubics(ring, tol, { closed: true, cornerAngleDeg: 25 });\n\t\t\tif (!cubics.length) continue;\n\t\t\tout.push({ type: 'M', x: cubics[0].p0[0], y: cubics[0].p0[1] });\n\t\t\tcubics.forEach((c, i) => {\n\t\t\t\tif (isStraightCubic(c, tol * 0.02)) {\n\t\t\t\t\tif (i < cubics.length - 1) out.push({ type: 'L', x: c.p3[0], y: c.p3[1] });\n\t\t\t\t} else out.push({ type: 'C', x1: c.p1[0], y1: c.p1[1], x2: c.p2[0], y2: c.p2[1], x: c.p3[0], y: c.p3[1] });\n\t\t\t});\n\t\t\tout.push({ type: 'Z' });\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * Where point `p` lies relative to the stroke's centre line: the nearest point's contour,\n * its position `t` by length (0–1), the distance, and the side (`left` looking along the\n * path on screen) — what hit-testing and the width tool need.\n */\nexport function nearestStrokePosition(\n\tpath: BezierPath,\n\tp: Point,\n\t/** Only this contour (subpath) of the path. */\n\tonly?: number\n): { contour: number; t: number; distance: number; side: 'left' | 'right'; point: Point; tangent: Vec; length: number } | null {\n\tlet best: ReturnType<typeof nearestStrokePosition> = null;\n\tpathToContours(path).forEach((c, ci) => {\n\t\tif (!c.segments.length || (only !== undefined && ci !== only)) return;\n\t\tconst lengths = c.segments.map((s) => segmentLength(s));\n\t\tconst total = lengths.reduce((a, b) => a + b, 0);\n\t\tif (!(total > 0)) return;\n\t\tlet acc = 0;\n\t\tc.segments.forEach((seg, si) => {\n\t\t\tconst near = segmentNearest(seg, p);\n\t\t\tif (!best || near.distance < best.distance) {\n\t\t\t\tconst s = acc + segmentLength(seg, 0, near.t);\n\t\t\t\tconst tan = segmentTangent(seg, near.t);\n\t\t\t\tconst pt = seg.length === 2 ? lerp(seg[0], seg[1], near.t) : evalSeg(seg, near.t);\n\t\t\t\tconst n = leftNormal([tan[0], tan[1]]);\n\t\t\t\tconst side = (p[0] - pt[0]) * n[0] + (p[1] - pt[1]) * n[1] >= 0 ? 'left' : 'right';\n\t\t\t\tbest = { contour: ci, t: Math.min(Math.max(s / total, 0), 1), distance: near.distance, side, point: pt, tangent: [tan[0], tan[1]], length: total };\n\t\t\t}\n\t\t\tacc += lengths[si];\n\t\t});\n\t});\n\treturn best;\n}\n\nfunction evalSeg(seg: BezierSegment, t: number): Point {\n\t// de Casteljau\n\tlet pts = seg.map((q) => [q[0], q[1]] as Point);\n\twhile (pts.length > 1) pts = pts.slice(1).map((q, i) => lerp(pts[i], q, t));\n\treturn pts[0];\n}\n\n/** The point and unit tangent at position `t` (0–1 by length) of contour `index` of `path`. */\nexport function strokePositionPoint(path: BezierPath, index: number, t: number): { point: Point; tangent: Vec } | null {\n\tconst c = pathToContours(path)[index];\n\tif (!c?.segments.length) return null;\n\tconst lengths = c.segments.map((s) => segmentLength(s));\n\tconst total = lengths.reduce((a, b) => a + b, 0);\n\tlet want = Math.min(Math.max(t, 0), 1) * total;\n\tfor (let i = 0; i < c.segments.length; i++) {\n\t\tconst seg = c.segments[i];\n\t\tif (want <= lengths[i] + 1e-12 || i === c.segments.length - 1) {\n\t\t\t// Bisect the parameter for the remaining length.\n\t\t\tlet lo = 0;\n\t\t\tlet hi = 1;\n\t\t\tconst target = Math.min(want, lengths[i]);\n\t\t\tfor (let k = 0; k < 40; k++) {\n\t\t\t\tconst mid = (lo + hi) / 2;\n\t\t\t\tif (segmentLength(seg, 0, mid) < target) lo = mid;\n\t\t\t\telse hi = mid;\n\t\t\t}\n\t\t\tconst u = (lo + hi) / 2;\n\t\t\tconst tan = segmentTangent(seg, u);\n\t\t\treturn { point: evalSeg(seg, u), tangent: [tan[0], tan[1]] };\n\t\t}\n\t\twant -= lengths[i];\n\t}\n\treturn null;\n}\n","/**\n * Stroke options of vector paths: alignment (centre, inside, outside) and arrowheads at the\n * ends of open paths. Everything here works on a path's Bézier outline in one space (the\n * node's own, or the document's), so the canvases, hit-testing, SVG export and Outline Stroke\n * share it.\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, see THIRD_PARTY_NOTICES.md):\n * - figcraft `crates/pathops/src/lib.rs` — `stroke_outline_of`: an inside stroke is a stroke of\n * twice the width intersected with the fill, an outside one twice the width minus the fill,\n * and only closed shapes have an inside (open paths stroke centred).\n * - vectorcraft `crates/effects/src/stroke/arrow.rs` — arrowhead shapes, sizes and insets (where\n * the stroke stops under each head), `tip` vs `extend` alignment and trimming the stroke by\n * arc length under the head.\n */\nimport type { Point } from '../canvas/types.js';\nimport {\n\tcontoursToPath,\n\tdistanceToBezierPath,\n\tpathToContours,\n\tpointInBezierPath,\n\tsegmentLength,\n\tsegmentTangent,\n\ttrimSegments,\n\ttype BezierContour,\n\ttype BezierPath,\n\ttype BezierSegment\n} from '../canvas/pathops/bezier.js';\nimport { pathBoolean, type PathOperandInput } from '../canvas/pathops/boolean.js';\nimport { outlineStroke } from '../canvas/pathops/stroke.js';\nimport type { VectorArrowhead, VectorStrokeAlign, VectorStyle, VectorWidthPoint, Vec2 } from './types.js';\nimport { nearestStrokePosition, variableStrokeOutline } from './varstroke.js';\nimport { isUniformWidthProfile, sanitizeWidthProfile, widthProfileAt, widthProfileMaxScale } from './width.js';\n\n/** Handle length that makes a cubic approximate a quarter circle. */\nconst KAPPA = 0.5522847498307936;\n/** Where the notch of the (notched) arrow sits, as a fraction of the head's length. */\nconst NOTCH = 0.7;\n\n/** One arrowhead: a filled outline (nonzero) painted with the stroke's paint. */\nexport interface VectorArrowheadShape {\n\tend: 'start' | 'end';\n\tkind: VectorArrowhead;\n\ttip: Vec2;\n\t/** Unit direction the head points in. */\n\tdir: Vec2;\n\t/** Distance from the tip back to where the stroke ends under the head. */\n\tinset: number;\n\tpath: BezierPath;\n}\n\n/** What the stroke of a path draws. */\nexport interface VectorStrokeParts {\n\t/** Where the stroke sits (`center` for open shapes, whatever the style says). */\n\talign: VectorStrokeAlign;\n\t/** The line the stroke follows: the outline, shortened under `tip`-aligned heads. */\n\tline: BezierPath;\n\t/** The stroke width to draw `line` with: twice the style's width for inside / outside (half is clipped away). */\n\tdrawWidth: number;\n\theads: VectorArrowheadShape[];\n}\n\n/** True when the path has subpaths and all of them are closed (only such shapes have an inside). */\nexport function isClosedBezierShape(path: BezierPath): boolean {\n\tconst contours = pathToContours(path).filter((c) => c.segments.length > 0);\n\treturn contours.length > 0 && contours.every((c) => c.closed);\n}\n\n/** The alignment a stroke is drawn with: the style's, or `center` for open shapes. */\nexport function effectiveStrokeAlign(style: Pick<VectorStyle, 'strokeAlign'>, closedShape: boolean): VectorStrokeAlign {\n\tconst a = style.strokeAlign ?? 'center';\n\treturn closedShape ? a : 'center';\n}\n\n/** The style's width profile, sanitised, or null when the stroke is uniform. */\nexport function strokeWidthProfileOf(style: Pick<VectorStyle, 'strokeWidthProfile'>): VectorWidthPoint[] | null {\n\tif (!style.strokeWidthProfile?.length) return null;\n\tconst p = sanitizeWidthProfile(style.strokeWidthProfile);\n\treturn isUniformWidthProfile(p) ? null : p;\n}\n\n/** True when the style asks for more than a plain centred stroke (an alignment, arrowheads or a width profile). */\nexport function hasStrokeExtras(style: VectorStyle): boolean {\n\treturn (style.strokeAlign ?? 'center') !== 'center' || !!style.startArrow || !!style.endArrow || !!strokeWidthProfileOf(style);\n}\n\n/**\n * The area of the stroke along `parts.line` before alignment clipping: SVG's stroke for a\n * uniform width, the variable-width outline (`variableStrokeOutline`) for a profiled one.\n */\nexport function vectorStrokeLineArea(parts: Pick<VectorStrokeParts, 'line' | 'drawWidth'>, style: VectorStyle, tolerance?: number): BezierPath {\n\tconst profile = strokeWidthProfileOf(style);\n\tconst dash = style.strokeDasharray?.length ? { dash: style.strokeDasharray } : {};\n\tconst join = style.strokeLinejoin ?? 'miter';\n\tconst cap = style.strokeLinecap ?? 'butt';\n\tif (profile) return variableStrokeOutline(parts.line, { width: parts.drawWidth, profile, join, cap, ...dash, ...(tolerance ? { tolerance } : {}) });\n\treturn outlineStroke(parts.line, { width: parts.drawWidth, join, cap, ...dash, ...(tolerance ? { tolerance } : {}) });\n}\n\nconst capExtent = (style: VectorStyle, width: number) => (style.strokeLinecap === 'round' || style.strokeLinecap === 'square' ? width / 2 : 0);\n\n/** The weight of a head: the stroke width times its scale (at least 0.25). A head is 4 weights long and wide. */\nexport function arrowheadWeight(style: VectorStyle, end: 'start' | 'end'): number {\n\tconst scale = end === 'start' ? style.startArrowScale : style.endArrowScale;\n\tconst s = typeof scale === 'number' && scale > 0 && Number.isFinite(scale) ? scale : 1;\n\treturn Math.max(0.25, (style.strokeWidth ?? 1) * s);\n}\n\n/** Distance from the tip where the stroke ends, for a stroke whose cap reaches `cap` past its end. */\nexport function arrowheadInset(kind: VectorArrowhead, hw: number, cap: number): number {\n\tconst l = 4 * hw;\n\tconst solid = (back: number) => Math.max(back / 2, cap);\n\tswitch (kind) {\n\t\tcase 'triangle':\n\t\tcase 'circle':\n\t\tcase 'square':\n\t\t\treturn solid(l);\n\t\tcase 'arrow':\n\t\t\treturn solid(NOTCH * l);\n\t\tcase 'bar':\n\t\t\treturn solid(0.75 * hw);\n\t\tcase 'open':\n\t\t\t// The inner corner of the chevron: arm / sin(half angle).\n\t\t\treturn Math.max((hw * Math.sqrt(l * l + (l * l) / 4)) / (l / 2), cap);\n\t}\n}\n\nconst v = (x: number, y: number): Vec2 => ({ x, y });\nconst plus = (a: Vec2, b: Vec2, k = 1): Vec2 => ({ x: a.x + b.x * k, y: a.y + b.y * k });\nconst unit = (a: Vec2): Vec2 => {\n\tconst l = Math.hypot(a.x, a.y);\n\treturn l > 0 ? { x: a.x / l, y: a.y / l } : { x: 1, y: 0 };\n};\n\nfunction polygon(pts: Vec2[]): BezierPath {\n\treturn [{ type: 'M', x: pts[0].x, y: pts[0].y }, ...pts.slice(1).map((p) => ({ type: 'L' as const, x: p.x, y: p.y })), { type: 'Z' }];\n}\n\nfunction circle(c: Vec2, r: number): BezierPath {\n\tconst k = r * KAPPA;\n\tconst { x, y } = c;\n\treturn [\n\t\t{ type: 'M', x: x + r, y },\n\t\t{ type: 'C', x1: x + r, y1: y + k, x2: x + k, y2: y + r, x, y: y + r },\n\t\t{ type: 'C', x1: x - k, y1: y + r, x2: x - r, y2: y + k, x: x - r, y },\n\t\t{ type: 'C', x1: x - r, y1: y - k, x2: x - k, y2: y - r, x, y: y - r },\n\t\t{ type: 'C', x1: x + k, y1: y - r, x2: x + r, y2: y - k, x: x + r, y },\n\t\t{ type: 'Z' }\n\t];\n}\n\n/** The outline of a `kind` head of weight `hw` with its tip at `tip`, pointing along unit `dir`. */\nexport function arrowheadPath(kind: VectorArrowhead, tip: Vec2, dir: Vec2, hw: number): BezierPath {\n\tconst n = v(-dir.y, dir.x);\n\tconst l = 4 * hw;\n\tconst half = l / 2;\n\tconst base = plus(tip, dir, -l);\n\tswitch (kind) {\n\t\tcase 'triangle':\n\t\t\treturn polygon([tip, plus(base, n, half), plus(base, n, -half)]);\n\t\tcase 'arrow':\n\t\t\treturn polygon([tip, plus(base, n, half), plus(tip, dir, -NOTCH * l), plus(base, n, -half)]);\n\t\tcase 'open': {\n\t\t\t// Arms `hw` thick from the tip to the base corners, cut square at their ends.\n\t\t\tconst t = hw;\n\t\t\tconst a = plus(base, n, half);\n\t\t\tconst b = plus(base, n, -half);\n\t\t\tconst ua = unit(plus(a, tip, -1));\n\t\t\tconst ub = unit(plus(b, tip, -1));\n\t\t\tconst na = v(-ua.y, ua.x);\n\t\t\tconst nb = v(ub.y, -ub.x);\n\t\t\tconst inner = plus(tip, dir, -(t * Math.hypot(a.x - tip.x, a.y - tip.y)) / half);\n\t\t\treturn polygon([tip, a, plus(a, na, t), inner, plus(b, nb, t), b]);\n\t\t}\n\t\tcase 'circle':\n\t\t\treturn circle(plus(tip, dir, -half), half);\n\t\tcase 'square':\n\t\t\treturn polygon([plus(tip, n, half), plus(base, n, half), plus(base, n, -half), plus(tip, n, -half)]);\n\t\tcase 'bar': {\n\t\t\tconst t = 0.75 * hw;\n\t\t\treturn polygon([plus(tip, n, half), plus(plus(tip, n, half), dir, -t), plus(plus(tip, n, -half), dir, -t), plus(tip, n, -half)]);\n\t\t}\n\t}\n}\n\nconst toVec = (p: Point): Vec2 => ({ x: p[0], y: p[1] });\nconst segLen = (s: BezierSegment) => segmentLength(s);\n\n/** The end point of a contour and the unit direction pointing out of it there. */\nfunction endOf(segs: readonly BezierSegment[], atStart: boolean): { p: Vec2; out: Vec2 } {\n\tconst long = (s: BezierSegment) => segLen(s) > 1e-9;\n\tif (atStart) {\n\t\tconst s = segs.find(long) ?? segs[0];\n\t\tconst t = segmentTangent(s, 0);\n\t\treturn { p: toVec(segs[0][0]), out: v(-t[0], -t[1]) };\n\t}\n\tconst s = [...segs].reverse().find(long) ?? segs[segs.length - 1];\n\tconst t = segmentTangent(s, 1);\n\tconst last = segs[segs.length - 1];\n\treturn { p: toVec(last[last.length - 1]), out: v(t[0], t[1]) };\n}\n\n/** The point `dist` along the contour from its start (or back from its end), if it is that long. */\nfunction pointAlong(segs: readonly BezierSegment[], fromStart: boolean, dist: number): Vec2 | null {\n\tconst order = fromStart ? segs : [...segs].reverse();\n\tlet acc = 0;\n\tfor (const s of order) {\n\t\tconst l = segLen(s);\n\t\tif (acc + l >= dist) {\n\t\t\tconst want = fromStart ? dist - acc : l - (dist - acc);\n\t\t\tconst pts = trimSegments([s], 0, want);\n\t\t\tconst p = pts.length ? pts[0][pts[0].length - 1] : s[0];\n\t\t\treturn toVec(p);\n\t\t}\n\t\tacc += l;\n\t}\n\treturn null;\n}\n\n/**\n * The stroke of `path` as `style` draws it: its alignment, the line it follows (shortened under\n * `tip`-aligned heads) and its arrowheads. Heads go on the start of the first subpath and the\n * end of the last one, when those are open.\n */\nexport function vectorStrokeParts(path: BezierPath, style: VectorStyle): VectorStrokeParts {\n\tconst width = style.strokeWidth ?? 1;\n\tconst contours = pathToContours(path).filter((c) => c.segments.length > 0);\n\tconst closedShape = contours.length > 0 && contours.every((c) => c.closed);\n\tconst align = effectiveStrokeAlign(style, closedShape);\n\tconst drawWidth = align === 'center' ? width : width * 2;\n\tconst heads: VectorArrowheadShape[] = [];\n\tif (!contours.length || (!style.startArrow && !style.endArrow)) return { align, line: path, drawWidth, heads };\n\tconst first = contours[0];\n\tconst last = contours[contours.length - 1];\n\tconst cap = capExtent(style, width);\n\tconst tipMode = style.arrowAlign === 'tip';\n\tconst trims = contours.map(() => [0, 0]);\n\tconst place = (end: 'start' | 'end', contour: BezierContour, ci: number) => {\n\t\tconst kind = end === 'start' ? style.startArrow : style.endArrow;\n\t\tif (!kind || contour.closed) return;\n\t\tconst hw = arrowheadWeight(style, end);\n\t\tconst inset = arrowheadInset(kind, hw, cap);\n\t\tconst atStart = end === 'start';\n\t\tconst { p, out } = endOf(contour.segments, atStart);\n\t\tlet tip: Vec2;\n\t\tlet dir: Vec2;\n\t\tif (tipMode) {\n\t\t\t// Point along the chord from where the stroke now ends to the end point.\n\t\t\tconst q = pointAlong(contour.segments, atStart, inset);\n\t\t\tconst d = q ? v(p.x - q.x, p.y - q.y) : null;\n\t\t\tdir = d && Math.hypot(d.x, d.y) > 1e-9 ? unit(d) : out;\n\t\t\ttip = p;\n\t\t\ttrims[ci][atStart ? 0 : 1] = inset;\n\t\t} else {\n\t\t\ttip = plus(p, out, inset);\n\t\t\tdir = out;\n\t\t}\n\t\theads.push({ end, kind, tip, dir, inset, path: arrowheadPath(kind, tip, dir, hw) });\n\t};\n\tplace('start', first, 0);\n\tplace('end', last, contours.length - 1);\n\tif (!tipMode || !heads.length) return { align, line: path, drawWidth, heads };\n\tconst trimmed: BezierContour[] = contours.map((c, i) => {\n\t\tconst [s0, s1] = trims[i];\n\t\tif (!s0 && !s1) return c;\n\t\tconst lengths = c.segments.map(segLen);\n\t\tconst total = lengths.reduce((a, b) => a + b, 0);\n\t\treturn { closed: false, segments: total - s1 > s0 ? trimSegments(c.segments, s0, total - s1, lengths) : [] };\n\t});\n\treturn { align, line: contoursToPath(trimmed), drawWidth, heads };\n}\n\n/**\n * The area the stroke paints, as one filled path: the outlined stroke (joins, caps and dashes\n * as SVG) clipped by the alignment (against the fill, read with the style's `fillRule`), plus\n * the arrowheads.\n */\nexport function vectorStrokeOutlinePath(path: BezierPath, style: VectorStyle): BezierPath {\n\tconst parts = vectorStrokeParts(path, style);\n\tconst stroke = vectorStrokeLineArea(parts, style);\n\tconst fill: PathOperandInput = { path, fillRule: style.fillRule ?? 'nonzero' };\n\tlet area = stroke;\n\tif (parts.align === 'inside') area = pathBoolean('intersection', [stroke, fill]).path;\n\telse if (parts.align === 'outside') area = pathBoolean('difference', [stroke, fill]).path;\n\tif (!parts.heads.length) return area;\n\treturn pathBoolean('union', [area, ...parts.heads.map((h) => h.path)]).path;\n}\n\n/**\n * Whether point `p` hits the stroke of `path` (`tolerance` added on every side): within half\n * the width of the outline for a centred stroke, within the whole width on the inside or the\n * outside of the fill for an aligned one, or on an arrowhead.\n */\nexport function hitTestVectorStroke(path: BezierPath, p: Vec2, style: VectorStyle, tolerance = 0): boolean {\n\tconst parts = vectorStrokeParts(path, style);\n\tconst point: Point = [p.x, p.y];\n\tconst width = style.strokeWidth ?? 1;\n\tfor (const h of parts.heads) {\n\t\tif (pointInBezierPath(h.path, point) || (tolerance > 0 && distanceToBezierPath(h.path, point) <= tolerance)) return true;\n\t}\n\tif (!parts.line.length) return false;\n\tconst profile = strokeWidthProfileOf(style);\n\tlet d: number;\n\tlet reach = width / 2;\n\tif (profile) {\n\t\t// The side width at the nearest point of the centre line (twice it when aligned).\n\t\tconst near = nearestStrokePosition(parts.line, point);\n\t\tif (!near) return false;\n\t\td = near.distance;\n\t\tconst w = widthProfileAt(profile, near.t);\n\t\treach = (width / 2) * (near.side === 'left' ? w.left : w.right);\n\t\tif (parts.align !== 'center') reach *= 2;\n\t\tconst atEnd = near.t <= 1e-9 || near.t >= 1 - 1e-9;\n\t\tif (atEnd && (style.strokeLinecap === 'round' || style.strokeLinecap === 'square') && d > reach) {\n\t\t\t// Past an open end the cap reaches as far as the width there.\n\t\t\treach = Math.max(reach, ((width / 2) * (w.left + w.right)) / 2);\n\t\t}\n\t} else {\n\t\td = distanceToBezierPath(parts.line, point);\n\t\tif (parts.align !== 'center') reach = width;\n\t}\n\tif (parts.align === 'center') return d <= reach + tolerance;\n\tif (d > reach + tolerance) return false;\n\tif (d <= tolerance) return true;\n\tconst inside = pointInBezierPath(path, point, style.fillRule ?? 'nonzero');\n\treturn parts.align === 'inside' ? inside : !inside;\n}\n\n/** How far the stroke can reach past the outline (for padding bounds and masks). */\nexport function vectorStrokeReach(style: VectorStyle): number {\n\tconst width = (style.strokeWidth ?? 1) * widthProfileMaxScale(strokeWidthProfileOf(style));\n\tconst align = style.strokeAlign ?? 'center';\n\tlet reach = align === 'center' ? width / 2 : align === 'outside' ? width : 0;\n\tif (style.strokeLinejoin !== 'round' && style.strokeLinejoin !== 'bevel') reach *= 4;\n\tfor (const end of ['start', 'end'] as const) {\n\t\tif (end === 'start' ? style.startArrow : style.endArrow) reach = Math.max(reach, 8 * arrowheadWeight(style, end) + width);\n\t}\n\treturn reach;\n}\n","/**\n * Vector path geometry: anchors and handles to Bézier paths and back, bounds, hit-testing,\n * affine transforms, segment splitting, anchor-type conversion and shape factories.\n */\nimport type { Point } from '../canvas/types.js';\nimport {\n\tbezierPathBounds,\n\tbezierPathToSvg,\n\ttransformBezierPath,\n\tdistanceToBezierPath,\n\tpointInBezierPath,\n\tsegmentNearest,\n\tsegmentPoint,\n\tsplitSegment,\n\ttoBezierPath,\n\ttype AffineMatrix,\n\ttype BezierPath,\n\ttype BezierPathInput\n} from '../canvas/pathops/bezier.js';\nimport { expandVectorCorners, setSubpathCorners } from './corners.js';\nimport { hitTestVectorStroke, vectorStrokeOutlinePath } from './stroke.js';\nimport { mirrorWidthProfile } from './width.js';\nimport type {\n\tVectorAnchor,\n\tVectorAnchorType,\n\tVectorCornerKind,\n\tVectorBounds,\n\tVectorDocument,\n\tVectorGroupNode,\n\tVectorNode,\n\tVectorPaint,\n\tVectorPathNode,\n\tVectorSubpath,\n\tVec2\n} from './types.js';\n\nexport type { AffineMatrix };\n\nconst EPS = 1e-9;\n\n// ---------------------------------------------------------------------------\n// Small helpers\n// ---------------------------------------------------------------------------\n\nexport const cloneAnchor = (a: VectorAnchor): VectorAnchor => ({\n\tx: a.x,\n\ty: a.y,\n\t...(a.in ? { in: { x: a.in.x, y: a.in.y } } : {}),\n\t...(a.out ? { out: { x: a.out.x, y: a.out.y } } : {}),\n\t...(a.type && a.type !== 'corner' ? { type: a.type } : {}),\n\t...(a.corner ? { corner: { ...a.corner } } : {})\n});\n\nexport const cloneSubpath = (s: VectorSubpath): VectorSubpath => ({ anchors: s.anchors.map(cloneAnchor), closed: s.closed });\n\n/** A deep copy of a node (ids kept). */\nexport function cloneVectorNode<T extends VectorNode>(node: T): T {\n\treturn JSON.parse(JSON.stringify(node)) as T;\n}\n\nexport function cloneVectorDocument(doc: VectorDocument): VectorDocument {\n\treturn JSON.parse(JSON.stringify(doc)) as VectorDocument;\n}\n\n/** True when the paint draws something (not `null`, `'none'`, `'transparent'` or empty). */\nexport function hasPaint(paint: VectorPaint | undefined): boolean {\n\tif (paint === undefined || paint === null) return false;\n\tif (typeof paint === 'string') {\n\t\tconst p = paint.trim().toLowerCase();\n\t\treturn p !== '' && p !== 'none' && p !== 'transparent';\n\t}\n\treturn true;\n}\n\nconst handleOf = (a: VectorAnchor, side: 'in' | 'out'): Vec2 => a[side] ?? { x: a.x, y: a.y };\nconst isOnAnchor = (a: VectorAnchor, h: Vec2 | null | undefined) => !h || (Math.abs(h.x - a.x) < EPS && Math.abs(h.y - a.y) < EPS);\n\n// ---------------------------------------------------------------------------\n// Anchors ↔ Bézier\n// ---------------------------------------------------------------------------\n\n/** Number of segments of a subpath (a closed one has a segment from the last anchor back to the first). */\nexport function subpathSegmentCount(sp: VectorSubpath): number {\n\tconst n = sp.anchors.length;\n\tif (n < 2) return 0;\n\treturn sp.closed ? n : n - 1;\n}\n\n/** Control points of segment `i` of a subpath: 2 for a line, 4 for a cubic. */\nexport function subpathSegment(sp: VectorSubpath, i: number): Point[] {\n\tconst a = sp.anchors[i];\n\tconst b = sp.anchors[(i + 1) % sp.anchors.length];\n\tif (isOnAnchor(a, a.out) && isOnAnchor(b, b.in)) return [[a.x, a.y], [b.x, b.y]];\n\tconst c1 = handleOf(a, 'out');\n\tconst c2 = handleOf(b, 'in');\n\treturn [[a.x, a.y], [c1.x, c1.y], [c2.x, c2.y], [b.x, b.y]];\n}\n\n/**\n * Absolute `M` / `L` / `C` / `Z` commands of subpaths, with live corners cut\n * (`expandVectorCorners`). Pass `{ corners: false }` for the stored anchors as they are.\n */\nexport function subpathsToBezier(subpaths: readonly VectorSubpath[], options: { corners?: boolean } = {}): BezierPath {\n\tconst out: BezierPath = [];\n\tfor (const sp of options.corners === false ? subpaths : expandVectorCorners(subpaths)) {\n\t\tif (sp.anchors.length === 0) continue;\n\t\tconst first = sp.anchors[0];\n\t\tout.push({ type: 'M', x: first.x, y: first.y });\n\t\tconst count = subpathSegmentCount(sp);\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst seg = subpathSegment(sp, i);\n\t\t\tif (sp.closed && i === count - 1 && seg.length === 2) break; // `Z` draws the closing line.\n\t\t\tif (seg.length === 2) out.push({ type: 'L', x: seg[1][0], y: seg[1][1] });\n\t\t\telse out.push({ type: 'C', x1: seg[1][0], y1: seg[1][1], x2: seg[2][0], y2: seg[2][1], x: seg[3][0], y: seg[3][1] });\n\t\t}\n\t\tif (sp.closed) out.push({ type: 'Z' });\n\t}\n\treturn out;\n}\n\n/** The node's outline as Bézier commands. Groups have none. */\nexport function vectorNodeToBezier(node: VectorNode): BezierPath {\n\treturn node.type === 'path' ? subpathsToBezier(node.subpaths) : [];\n}\n\n/** SVG path data (`d`) of a path node or subpaths. */\nexport function vectorPathData(input: VectorPathNode | readonly VectorSubpath[], precision = 3): string {\n\tconst subpaths = Array.isArray(input) ? (input as readonly VectorSubpath[]) : (input as VectorPathNode).subpaths;\n\treturn bezierPathToSvg(subpathsToBezier(subpaths), { precision });\n}\n\n/** Infers the anchor type from its handles. */\nexport function inferAnchorType(a: VectorAnchor): VectorAnchorType {\n\tif (isOnAnchor(a, a.in) || isOnAnchor(a, a.out)) return 'corner';\n\tconst ix = a.in!.x - a.x;\n\tconst iy = a.in!.y - a.y;\n\tconst ox = a.out!.x - a.x;\n\tconst oy = a.out!.y - a.y;\n\tconst li = Math.hypot(ix, iy);\n\tconst lo = Math.hypot(ox, oy);\n\tconst cross = (ix * oy - iy * ox) / (li * lo);\n\tconst dot = (ix * ox + iy * oy) / (li * lo);\n\tif (Math.abs(cross) > 1e-3 || dot > 0) return 'corner';\n\treturn Math.abs(li - lo) <= 1e-3 * Math.max(li, lo) ? 'symmetric' : 'smooth';\n}\n\n/**\n * Converts SVG path data or Bézier commands to editable subpaths. Quadratics become cubics,\n * arcs become cubics, a closing anchor that repeats the first one is merged into it, and\n * each anchor's type is inferred from its handles.\n */\nexport function bezierToSubpaths(input: BezierPathInput): VectorSubpath[] {\n\tconst path = toBezierPath(input);\n\tconst out: VectorSubpath[] = [];\n\tlet current: VectorSubpath | null = null;\n\tconst last = () => current!.anchors[current!.anchors.length - 1];\n\tfor (const cmd of path) {\n\t\tswitch (cmd.type) {\n\t\t\tcase 'M':\n\t\t\t\tcurrent = { anchors: [{ x: cmd.x, y: cmd.y }], closed: false };\n\t\t\t\tout.push(current);\n\t\t\t\tbreak;\n\t\t\tcase 'L':\n\t\t\t\tcurrent!.anchors.push({ x: cmd.x, y: cmd.y });\n\t\t\t\tbreak;\n\t\t\tcase 'Q': {\n\t\t\t\tconst p0 = last();\n\t\t\t\tp0.out = { x: p0.x + (2 / 3) * (cmd.x1 - p0.x), y: p0.y + (2 / 3) * (cmd.y1 - p0.y) };\n\t\t\t\tcurrent!.anchors.push({ x: cmd.x, y: cmd.y, in: { x: cmd.x + (2 / 3) * (cmd.x1 - cmd.x), y: cmd.y + (2 / 3) * (cmd.y1 - cmd.y) } });\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'C':\n\t\t\t\tlast().out = { x: cmd.x1, y: cmd.y1 };\n\t\t\t\tcurrent!.anchors.push({ x: cmd.x, y: cmd.y, in: { x: cmd.x2, y: cmd.y2 } });\n\t\t\t\tbreak;\n\t\t\tcase 'Z': {\n\t\t\t\tif (!current) break;\n\t\t\t\tcurrent.closed = true;\n\t\t\t\tconst anchors = current.anchors;\n\t\t\t\tif (anchors.length > 1) {\n\t\t\t\t\tconst first = anchors[0];\n\t\t\t\t\tconst end = anchors[anchors.length - 1];\n\t\t\t\t\tif (Math.abs(end.x - first.x) < 1e-7 && Math.abs(end.y - first.y) < 1e-7) {\n\t\t\t\t\t\tif (end.in) first.in = end.in;\n\t\t\t\t\t\tanchors.pop();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrent = null;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tfor (const sp of out) {\n\t\tfor (const a of sp.anchors) {\n\t\t\tif (isOnAnchor(a, a.in)) delete a.in;\n\t\t\tif (isOnAnchor(a, a.out)) delete a.out;\n\t\t\tconst type = inferAnchorType(a);\n\t\t\tif (type !== 'corner') a.type = type;\n\t\t}\n\t}\n\treturn out.filter((sp) => sp.anchors.length > 0);\n}\n\n// ---------------------------------------------------------------------------\n// Tree helpers\n// ---------------------------------------------------------------------------\n\n/** Calls `fn` for every node, depth first, parents before children. */\nexport function walkVectorNodes(nodes: readonly VectorNode[], fn: (node: VectorNode, parent: VectorGroupNode | null, depth: number) => void): void {\n\tconst visit = (list: readonly VectorNode[], parent: VectorGroupNode | null, depth: number) => {\n\t\tfor (const node of list) {\n\t\t\tfn(node, parent, depth);\n\t\t\tif (node.type === 'group') visit(node.children, node, depth + 1);\n\t\t}\n\t};\n\tvisit(nodes, null, 0);\n}\n\n/** Finds a node by id anywhere in the tree. */\nexport function findVectorNode(nodes: readonly VectorNode[], id: string): VectorNode | undefined {\n\tfor (const node of nodes) {\n\t\tif (node.id === id) return node;\n\t\tif (node.type === 'group') {\n\t\t\tconst found = findVectorNode(node.children, id);\n\t\t\tif (found) return found;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** The list that contains node `id` (the root list or a group's children) and its index there. */\nexport function locateVectorNode(nodes: VectorNode[], id: string): { list: VectorNode[]; index: number; parent: VectorGroupNode | null } | null {\n\tconst search = (list: VectorNode[], parent: VectorGroupNode | null): ReturnType<typeof locateVectorNode> => {\n\t\tfor (let i = 0; i < list.length; i++) {\n\t\t\tconst node = list[i];\n\t\t\tif (node.id === id) return { list, index: i, parent };\n\t\t\tif (node.type === 'group') {\n\t\t\t\tconst found = search(node.children, node);\n\t\t\t\tif (found) return found;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t};\n\treturn search(nodes, null);\n}\n\n/** Every path node in the subtree (a path node itself, or a group's descendants). */\nexport function collectPathNodes(node: VectorNode): VectorPathNode[] {\n\tif (node.type === 'path') return [node];\n\tconst out: VectorPathNode[] = [];\n\twalkVectorNodes(node.children, (n) => {\n\t\tif (n.type === 'path') out.push(n);\n\t});\n\treturn out;\n}\n\n// ---------------------------------------------------------------------------\n// Bounds\n// ---------------------------------------------------------------------------\n\n/** The node's local → parent matrix (identity when it has no `transform`). */\nexport function nodeMatrix(node: VectorNode): AffineMatrix {\n\treturn node.transform ?? IDENTITY_MATRIX;\n}\n\n/** A path node's outline in the space `parent` maps to (default: its parent's space). */\nexport function vectorPathWorldBezier(node: VectorPathNode, parent: AffineMatrix = IDENTITY_MATRIX): BezierPath {\n\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\tconst path = subpathsToBezier(node.subpaths);\n\treturn isIdentityMatrix(m) ? path : transformBezierPath(path, m);\n}\n\n/**\n * Geometric bounds of a node (stroke width not included) in the space `parent` maps to —\n * by default the node's parent space, which for top-level nodes is the document. Null when\n * the node has no points.\n */\nexport function vectorNodeBounds(node: VectorNode, parent: AffineMatrix = IDENTITY_MATRIX): VectorBounds | null {\n\tif (node.type === 'group') {\n\t\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\t\treturn unionBounds(node.children.map((c) => vectorNodeBounds(c, m)));\n\t}\n\tconst b = bezierPathBounds(vectorPathWorldBezier(node, parent));\n\tif (!b) return null;\n\treturn { x: b.minX, y: b.minY, width: b.maxX - b.minX, height: b.maxY - b.minY };\n}\n\n/** The smallest box around all non-null boxes, or null. */\nexport function unionBounds(list: readonly (VectorBounds | null | undefined)[]): VectorBounds | null {\n\tlet minX = Infinity;\n\tlet minY = Infinity;\n\tlet maxX = -Infinity;\n\tlet maxY = -Infinity;\n\tfor (const b of list) {\n\t\tif (!b) continue;\n\t\tminX = Math.min(minX, b.x);\n\t\tminY = Math.min(minY, b.y);\n\t\tmaxX = Math.max(maxX, b.x + b.width);\n\t\tmaxY = Math.max(maxY, b.y + b.height);\n\t}\n\tif (minX === Infinity) return null;\n\treturn { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n}\n\n/** True when two boxes overlap (touching counts). */\nexport function boundsIntersect(a: VectorBounds, b: VectorBounds): boolean {\n\treturn a.x <= b.x + b.width && b.x <= a.x + a.width && a.y <= b.y + b.height && b.y <= a.y + a.height;\n}\n\n/** A box from two corners in any order. */\nexport function boundsFromPoints(a: Vec2, b: Vec2): VectorBounds {\n\treturn { x: Math.min(a.x, b.x), y: Math.min(a.y, b.y), width: Math.abs(b.x - a.x), height: Math.abs(b.y - a.y) };\n}\n\n// ---------------------------------------------------------------------------\n// Hit-testing\n// ---------------------------------------------------------------------------\n\n/**\n * Whether `p` hits a node: inside its fill (when it has one), on its stroke as drawn (its\n * alignment and arrowheads respected) or within `tolerance` of either. A group is hit when\n * any visible child is.\n */\nexport function hitTestVectorNode(node: VectorNode, p: Vec2, tolerance = 0, parent: AffineMatrix = IDENTITY_MATRIX): boolean {\n\tif (node.visible === false) return false;\n\tif (node.type === 'group') {\n\t\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\t\treturn node.children.some((c) => hitTestVectorNode(c, p, tolerance, m));\n\t}\n\tconst path = vectorPathWorldBezier(node, parent);\n\tif (path.length === 0) return false;\n\tconst point: Point = [p.x, p.y];\n\tif (hasPaint(node.fill) && pointInBezierPath(path, point, node.fillRule ?? 'nonzero')) return true;\n\tif (hasPaint(node.stroke)) return hitTestVectorStroke(path, p, node, tolerance);\n\treturn distanceToBezierPath(path, point) <= tolerance;\n}\n\n/**\n * The area a path node's stroke paints (alignment, caps, joins, dashes and arrowheads\n * included), as a filled path in the space `parent` maps to. Empty without a stroke.\n */\nexport function vectorStrokeOutline(node: VectorPathNode, parent: AffineMatrix = IDENTITY_MATRIX): BezierPath {\n\tif (!hasPaint(node.stroke) || !((node.strokeWidth ?? 1) > 0)) return [];\n\treturn vectorStrokeOutlinePath(vectorPathWorldBezier(node, parent), node);\n}\n\n/** The topmost node hit by `p` (skipping hidden and locked ones), or null. */\nexport function hitTestVectorNodes(nodes: readonly VectorNode[], p: Vec2, tolerance = 0): VectorNode | null {\n\tfor (let i = nodes.length - 1; i >= 0; i--) {\n\t\tconst node = nodes[i];\n\t\tif (node.visible === false || node.locked) continue;\n\t\tif (hitTestVectorNode(node, p, tolerance)) return node;\n\t}\n\treturn null;\n}\n\nexport interface NearestSegment {\n\tsubpath: number;\n\tsegment: number;\n\t/** Curve parameter 0–1 on the segment. */\n\tt: number;\n\tpoint: Vec2;\n\tdistance: number;\n}\n\n/** The closest point on any segment of a path node (`p` and the result are in the node's own space). */\nexport function nearestSegment(node: VectorPathNode, p: Vec2): NearestSegment | null {\n\tlet best: NearestSegment | null = null;\n\tnode.subpaths.forEach((sp, s) => {\n\t\tconst count = subpathSegmentCount(sp);\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst seg = subpathSegment(sp, i);\n\t\t\tconst hit = segmentNearest(seg, [p.x, p.y]);\n\t\t\tif (!best || hit.distance < best.distance) {\n\t\t\t\tconst pt = segmentPoint(seg, hit.t);\n\t\t\t\tbest = { subpath: s, segment: i, t: hit.t, point: { x: pt[0], y: pt[1] }, distance: hit.distance };\n\t\t\t}\n\t\t}\n\t});\n\treturn best;\n}\n\n// ---------------------------------------------------------------------------\n// Affine transforms\n// ---------------------------------------------------------------------------\n\nexport const IDENTITY_MATRIX: AffineMatrix = [1, 0, 0, 1, 0, 0];\n\n/** `a` then `b` (apply `a` first). */\nexport function multiplyMatrices(a: AffineMatrix, b: AffineMatrix): AffineMatrix {\n\tconst [a0, a1, a2, a3, a4, a5] = a;\n\tconst [b0, b1, b2, b3, b4, b5] = b;\n\treturn [b0 * a0 + b2 * a1, b1 * a0 + b3 * a1, b0 * a2 + b2 * a3, b1 * a2 + b3 * a3, b0 * a4 + b2 * a5 + b4, b1 * a4 + b3 * a5 + b5];\n}\n\nexport const translateMatrix = (dx: number, dy: number): AffineMatrix => [1, 0, 0, 1, dx, dy];\n\nexport function scaleMatrix(sx: number, sy: number, origin: Vec2 = { x: 0, y: 0 }): AffineMatrix {\n\treturn [sx, 0, 0, sy, origin.x - sx * origin.x, origin.y - sy * origin.y];\n}\n\n/** Rotation by `degrees` clockwise (y points down) around `origin`. */\nexport function rotateMatrix(degrees: number, origin: Vec2 = { x: 0, y: 0 }): AffineMatrix {\n\tconst r = (degrees * Math.PI) / 180;\n\tconst cos = Math.cos(r);\n\tconst sin = Math.sin(r);\n\treturn [cos, sin, -sin, cos, origin.x - cos * origin.x + sin * origin.y, origin.y - sin * origin.x - cos * origin.y];\n}\n\nexport function applyMatrix(m: AffineMatrix, p: Vec2): Vec2 {\n\treturn { x: m[0] * p.x + m[2] * p.y + m[4], y: m[1] * p.x + m[3] * p.y + m[5] };\n}\n\nexport function isIdentityMatrix(m: AffineMatrix, eps = 1e-12): boolean {\n\treturn Math.abs(m[0] - 1) < eps && Math.abs(m[1]) < eps && Math.abs(m[2]) < eps && Math.abs(m[3] - 1) < eps && Math.abs(m[4]) < eps && Math.abs(m[5]) < eps;\n}\n\n/** The inverse matrix (the identity for a singular one). */\nexport function invertMatrix(m: AffineMatrix): AffineMatrix {\n\tconst [a, b, c, d, e, f] = m;\n\tconst det = a * d - b * c;\n\tif (!det || !Number.isFinite(det)) return IDENTITY_MATRIX;\n\treturn [d / det, -b / det, -c / det, a / det, (c * f - d * e) / det, (b * e - a * f) / det];\n}\n\n/** Applies only the linear part (for directions and offsets). */\nexport function applyMatrixLinear(m: AffineMatrix, v: Vec2): Vec2 {\n\treturn { x: m[0] * v.x + m[2] * v.y, y: m[1] * v.x + m[3] * v.y };\n}\n\n/**\n * The rotation of a matrix in degrees, clockwise (y down), in (−180, 180]. For a mirrored\n * matrix it is the rotation left after undoing a horizontal flip, so a flipped rotated shape\n * keeps its angle.\n */\nexport function matrixRotation(m: AffineMatrix): number {\n\tconst [a, b, c, d] = m;\n\tconst mirrored = a * d - b * c < 0;\n\tconst deg = ((mirrored ? Math.atan2(-b - c, d - a) : Math.atan2(b - c, a + d)) * 180) / Math.PI;\n\treturn Math.abs(deg) < 1e-9 ? 0 : deg;\n}\n\n/**\n * Splits `m` into `residual` then `rigid` (`m = residual × rigid` in apply order): `rigid` is\n * the nearest rotation plus the translation, `residual` the linear rest (scale, skew,\n * reflection). An unrotated `m` gives an identity `rigid` and everything in `residual`.\n */\nexport function decomposeRigid(m: AffineMatrix): { rigid: AffineMatrix; residual: AffineMatrix } {\n\tconst [a, b, c, d, e, f] = m;\n\tconst deg = matrixRotation(m);\n\tif (deg === 0) return { rigid: IDENTITY_MATRIX, residual: m };\n\tconst r = (deg * Math.PI) / 180;\n\tconst cos = Math.cos(r);\n\tconst sin = Math.sin(r);\n\treturn {\n\t\trigid: [cos, sin, -sin, cos, e, f],\n\t\tresidual: [cos * a + sin * b, -sin * a + cos * b, cos * c + sin * d, -sin * c + cos * d, 0, 0]\n\t};\n}\n\n/** Every anchor and handle mapped through `m` (the node's own `transform` is untouched). */\nfunction bakeIntoGeometry<T extends VectorNode>(node: T, m: AffineMatrix): T {\n\tif (isIdentityMatrix(m)) return node;\n\tif (node.type === 'group') return { ...node, children: node.children.map((c) => transformVectorNode(c, m)) };\n\tconst path = node as VectorPathNode;\n\t// A mirror swaps the sides of a variable-width stroke (the path still runs the same way).\n\tconst mirrored = m[0] * m[3] - m[1] * m[2] < 0 && path.strokeWidthProfile?.length;\n\treturn {\n\t\t...path,\n\t\t...(mirrored ? { strokeWidthProfile: mirrorWidthProfile(path.strokeWidthProfile!) } : {}),\n\t\tsubpaths: path.subpaths.map((sp) => ({\n\t\t\tclosed: sp.closed,\n\t\t\tanchors: sp.anchors.map((a) => {\n\t\t\t\tconst p = applyMatrix(m, a);\n\t\t\t\tconst next: VectorAnchor = { x: p.x, y: p.y };\n\t\t\t\tif (a.in) next.in = applyMatrix(m, a.in);\n\t\t\t\tif (a.out) next.out = applyMatrix(m, a.out);\n\t\t\t\tif (a.type) next.type = a.type;\n\t\t\t\tif (a.corner) next.corner = { ...a.corner };\n\t\t\t\treturn next;\n\t\t\t})\n\t\t}))\n\t} as T;\n}\n\n/**\n * A copy of the node moved by `m`, given in its parent's space. The node's rotation and\n * translation go to its rigid `transform`; scale and skew are baked into its anchors (or its\n * children), so the result draws exactly as `m` says. Stroke widths are kept.\n */\nexport function transformVectorNode<T extends VectorNode>(node: T, m: AffineMatrix): T {\n\tconst total = multiplyMatrices(nodeMatrix(node), m);\n\tconst { rigid, residual } = decomposeRigid(total);\n\tconst { transform: _old, ...rest } = node as VectorNode;\n\tconst baked = bakeIntoGeometry(rest as T, residual);\n\treturn isIdentityMatrix(rigid) ? baked : ({ ...baked, transform: rigid } as T);\n}\n\n/** The node's rotation in degrees (from its `transform` and its ancestors' when `parent` is given). */\nexport function vectorNodeRotation(node: VectorNode, parent: AffineMatrix = IDENTITY_MATRIX): number {\n\treturn matrixRotation(multiplyMatrices(nodeMatrix(node), parent));\n}\n\n/** The local → document matrix of node `id` (ancestors' transforms included), or null. */\nexport function vectorWorldMatrix(nodes: readonly VectorNode[], id: string): AffineMatrix | null {\n\tconst search = (list: readonly VectorNode[], parent: AffineMatrix): AffineMatrix | null => {\n\t\tfor (const n of list) {\n\t\t\tconst m = multiplyMatrices(nodeMatrix(n), parent);\n\t\t\tif (n.id === id) return m;\n\t\t\tif (n.type === 'group') {\n\t\t\t\tconst found = search(n.children, m);\n\t\t\t\tif (found) return found;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t};\n\treturn search(nodes, IDENTITY_MATRIX);\n}\n\n/** The parent space → document matrix of node `id` (identity for top-level nodes), or null. */\nexport function vectorParentMatrix(nodes: readonly VectorNode[], id: string): AffineMatrix | null {\n\tconst node = findVectorNode(nodes, id);\n\tconst world = vectorWorldMatrix(nodes, id);\n\tif (!node || !world) return null;\n\treturn multiplyMatrices(invertMatrix(nodeMatrix(node)), world);\n}\n\n// ---------------------------------------------------------------------------\n// Anchor editing\n// ---------------------------------------------------------------------------\n\n/** Moves an anchor and its handles by (dx, dy). */\nexport function translateAnchor(a: VectorAnchor, dx: number, dy: number): VectorAnchor {\n\tconst next = cloneAnchor(a);\n\tnext.x += dx;\n\tnext.y += dy;\n\tif (next.in) next.in = { x: next.in.x + dx, y: next.in.y + dy };\n\tif (next.out) next.out = { x: next.out.x + dx, y: next.out.y + dy };\n\treturn next;\n}\n\n/**\n * Moves one handle to `pos`, keeping the other in line for `smooth` anchors and mirrored for\n * `symmetric` ones. With `breakHandles` the anchor becomes a `corner` and only this handle moves.\n */\nexport function moveAnchorHandle(a: VectorAnchor, side: 'in' | 'out', pos: Vec2, breakHandles = false): VectorAnchor {\n\tconst next = cloneAnchor(a);\n\tnext[side] = { x: pos.x, y: pos.y };\n\tconst other = side === 'in' ? 'out' : 'in';\n\tconst type = breakHandles ? 'corner' : (a.type ?? 'corner');\n\tif (breakHandles) delete next.type;\n\tconst dx = pos.x - a.x;\n\tconst dy = pos.y - a.y;\n\tconst len = Math.hypot(dx, dy);\n\tif (type === 'symmetric') next[other] = { x: a.x - dx, y: a.y - dy };\n\telse if (type === 'smooth' && len > EPS) {\n\t\tconst o = a[other];\n\t\tconst olen = o ? Math.hypot(o.x - a.x, o.y - a.y) : len;\n\t\tnext[other] = { x: a.x - (dx / len) * olen, y: a.y - (dy / len) * olen };\n\t}\n\tif (isOnAnchor(next, next.in)) delete next.in;\n\tif (isOnAnchor(next, next.out)) delete next.out;\n\treturn next;\n}\n\n/**\n * Converts anchor `index` of a subpath. `corner` removes both handles; `smooth` and\n * `symmetric` keep existing handles in line, or add handles a third of the way to the\n * neighbours along the line between them.\n */\nexport function convertAnchor(sp: VectorSubpath, index: number, type: VectorAnchorType): VectorSubpath {\n\tconst anchors = sp.anchors.map(cloneAnchor);\n\tconst a = anchors[index];\n\tif (!a) return { anchors, closed: sp.closed };\n\tif (type === 'corner') {\n\t\tdelete a.in;\n\t\tdelete a.out;\n\t\tdelete a.type;\n\t\treturn { anchors, closed: sp.closed };\n\t}\n\tconst n = anchors.length;\n\tconst prev = index > 0 ? anchors[index - 1] : sp.closed ? anchors[n - 1] : null;\n\tconst next = index < n - 1 ? anchors[index + 1] : sp.closed ? anchors[0] : null;\n\tlet dir: Vec2 | null = null;\n\tlet lenIn = 0;\n\tlet lenOut = 0;\n\tif (!isOnAnchor(a, a.out)) dir = { x: a.out!.x - a.x, y: a.out!.y - a.y };\n\telse if (!isOnAnchor(a, a.in)) dir = { x: a.x - a.in!.x, y: a.y - a.in!.y };\n\telse if (prev && next) dir = { x: next.x - prev.x, y: next.y - prev.y };\n\telse if (next) dir = { x: next.x - a.x, y: next.y - a.y };\n\telse if (prev) dir = { x: a.x - prev.x, y: a.y - prev.y };\n\tif (!dir || Math.hypot(dir.x, dir.y) < EPS) return { anchors, closed: sp.closed };\n\tconst dl = Math.hypot(dir.x, dir.y);\n\tconst ux = dir.x / dl;\n\tconst uy = dir.y / dl;\n\tlenIn = a.in && !isOnAnchor(a, a.in) ? Math.hypot(a.in.x - a.x, a.in.y - a.y) : prev ? Math.hypot(prev.x - a.x, prev.y - a.y) / 3 : 0;\n\tlenOut = a.out && !isOnAnchor(a, a.out) ? Math.hypot(a.out.x - a.x, a.out.y - a.y) : next ? Math.hypot(next.x - a.x, next.y - a.y) / 3 : 0;\n\tif (type === 'symmetric') lenIn = lenOut = (lenIn + lenOut) / 2 || Math.max(lenIn, lenOut);\n\tif (lenIn > EPS) a.in = { x: a.x - ux * lenIn, y: a.y - uy * lenIn };\n\tif (lenOut > EPS) a.out = { x: a.x + ux * lenOut, y: a.y + uy * lenOut };\n\ta.type = type;\n\treturn { anchors, closed: sp.closed };\n}\n\n/**\n * Inserts an anchor on segment `segment` at parameter `t` without changing the curve's\n * shape (de Casteljau split). Returns the new subpath and the new anchor's index.\n */\nexport function insertAnchor(sp: VectorSubpath, segment: number, t: number): { subpath: VectorSubpath; index: number } {\n\tconst anchors = sp.anchors.map(cloneAnchor);\n\tconst n = anchors.length;\n\tconst ia = segment;\n\tconst ib = (segment + 1) % n;\n\tconst seg = subpathSegment(sp, segment);\n\tconst [left, right] = splitSegment(seg, t);\n\tconst mid = left[left.length - 1];\n\tconst anchor: VectorAnchor = { x: mid[0], y: mid[1] };\n\tif (seg.length === 4) {\n\t\tanchors[ia].out = { x: left[1][0], y: left[1][1] };\n\t\tanchor.in = { x: left[2][0], y: left[2][1] };\n\t\tanchor.out = { x: right[1][0], y: right[1][1] };\n\t\tanchor.type = 'smooth';\n\t\tanchors[ib].in = { x: right[2][0], y: right[2][1] };\n\t\tfor (const k of [ia, ib]) if (isOnAnchor(anchors[k], anchors[k].in)) delete anchors[k].in;\n\t\tfor (const k of [ia, ib]) if (isOnAnchor(anchors[k], anchors[k].out)) delete anchors[k].out;\n\t}\n\tconst index = segment + 1;\n\tanchors.splice(index, 0, anchor);\n\treturn { subpath: { anchors, closed: sp.closed }, index };\n}\n\n/**\n * Removes anchors from a subpath. An open subpath with fewer than 2 anchors left, or a\n * closed one with fewer than 2, is returned with whatever remains (callers drop empty ones).\n */\nexport function removeAnchors(sp: VectorSubpath, indices: readonly number[]): VectorSubpath {\n\tconst drop = new Set(indices);\n\treturn { anchors: sp.anchors.filter((_, i) => !drop.has(i)).map(cloneAnchor), closed: sp.closed };\n}\n\n/** Reverses a subpath's direction (handles swap sides). */\nexport function reverseSubpath(sp: VectorSubpath): VectorSubpath {\n\tconst anchors = sp.anchors\n\t\t.slice()\n\t\t.reverse()\n\t\t.map((a) => {\n\t\t\tconst next: VectorAnchor = { x: a.x, y: a.y };\n\t\t\tif (a.out) next.in = { ...a.out };\n\t\t\tif (a.in) next.out = { ...a.in };\n\t\t\tif (a.type) next.type = a.type;\n\t\t\tif (a.corner) next.corner = { ...a.corner };\n\t\t\treturn next;\n\t\t});\n\treturn { anchors, closed: sp.closed };\n}\n\n// ---------------------------------------------------------------------------\n// Shape factories\n// ---------------------------------------------------------------------------\n\n/** Handle length that makes a cubic approximate a quarter circle. */\nexport const KAPPA = 0.5522847498307936;\n\n/**\n * A rectangle. A `radius` becomes a live corner on each of its four anchors (drawn round, and\n * clamped to half the shorter side, when the path is turned into curves).\n */\nexport function rectSubpath(b: VectorBounds, radius = 0, kind?: VectorCornerKind): VectorSubpath {\n\tconst { x, y, width: w, height: h } = b;\n\tconst sp: VectorSubpath = { anchors: [{ x, y }, { x: x + w, y }, { x: x + w, y: y + h }, { x, y: y + h }], closed: true };\n\treturn radius > 0 ? setSubpathCorners(sp, radius, kind) : sp;\n}\n\n/** An ellipse inscribed in a box (four smooth anchors). */\nexport function ellipseSubpath(b: VectorBounds): VectorSubpath {\n\tconst rx = b.width / 2;\n\tconst ry = b.height / 2;\n\tconst cx = b.x + rx;\n\tconst cy = b.y + ry;\n\tconst kx = rx * KAPPA;\n\tconst ky = ry * KAPPA;\n\treturn {\n\t\tclosed: true,\n\t\tanchors: [\n\t\t\t{ x: cx, y: cy - ry, in: { x: cx - kx, y: cy - ry }, out: { x: cx + kx, y: cy - ry }, type: 'symmetric' },\n\t\t\t{ x: cx + rx, y: cy, in: { x: cx + rx, y: cy - ky }, out: { x: cx + rx, y: cy + ky }, type: 'symmetric' },\n\t\t\t{ x: cx, y: cy + ry, in: { x: cx + kx, y: cy + ry }, out: { x: cx - kx, y: cy + ry }, type: 'symmetric' },\n\t\t\t{ x: cx - rx, y: cy, in: { x: cx - rx, y: cy + ky }, out: { x: cx - rx, y: cy - ky }, type: 'symmetric' }\n\t\t]\n\t};\n}\n\n/** A regular polygon inscribed in a box, first vertex at the top. */\nexport function polygonSubpath(b: VectorBounds, sides = 6): VectorSubpath {\n\tconst n = Math.max(3, Math.round(sides));\n\tconst cx = b.x + b.width / 2;\n\tconst cy = b.y + b.height / 2;\n\tconst anchors: VectorAnchor[] = [];\n\tfor (let i = 0; i < n; i++) {\n\t\tconst t = -Math.PI / 2 + (i * 2 * Math.PI) / n;\n\t\tanchors.push({ x: cx + (Math.cos(t) * b.width) / 2, y: cy + (Math.sin(t) * b.height) / 2 });\n\t}\n\treturn { anchors, closed: true };\n}\n\n/** A star inscribed in a box, first point at the top. `innerRatio` is inner / outer radius. */\nexport function starSubpath(b: VectorBounds, points = 5, innerRatio = 0.5): VectorSubpath {\n\tconst n = Math.max(3, Math.round(points));\n\tconst cx = b.x + b.width / 2;\n\tconst cy = b.y + b.height / 2;\n\tconst anchors: VectorAnchor[] = [];\n\tfor (let i = 0; i < n * 2; i++) {\n\t\tconst t = -Math.PI / 2 + (i * Math.PI) / n;\n\t\tconst r = i % 2 === 0 ? 1 : innerRatio;\n\t\tanchors.push({ x: cx + (Math.cos(t) * r * b.width) / 2, y: cy + (Math.sin(t) * r * b.height) / 2 });\n\t}\n\treturn { anchors, closed: true };\n}\n\n/** A straight open line. */\nexport function lineSubpath(a: Vec2, b: Vec2): VectorSubpath {\n\treturn { anchors: [{ x: a.x, y: a.y }, { x: b.x, y: b.y }], closed: false };\n}\n\n/** Rounds every coordinate to `precision` decimals (stable JSON and SVG output). */\nexport function roundSubpaths(subpaths: readonly VectorSubpath[], precision = 3): VectorSubpath[] {\n\tconst f = 10 ** precision;\n\tconst r = (n: number) => Math.round(n * f) / f;\n\tconst rp = (p: Vec2) => ({ x: r(p.x), y: r(p.y) });\n\treturn subpaths.map((sp) => ({\n\t\tclosed: sp.closed,\n\t\tanchors: sp.anchors.map((a) => ({ ...cloneAnchor(a), x: r(a.x), y: r(a.y), ...(a.in ? { in: rp(a.in) } : {}), ...(a.out ? { out: rp(a.out) } : {}) }))\n\t}));\n}\n","/**\n * SVG export and import for vector documents. Import is DOM-free (works in Node and\n * workers): it reads `<svg>`, `<g>`, `<path>`, `<rect>`, `<circle>`, `<ellipse>`, `<line>`,\n * `<polyline>`, `<polygon>`, linear / radial gradients, presentation attributes, `style`\n * declarations and `transform`s. Text, images, clip paths, masks, filters and `<use>` are\n * skipped.\n *\n * Live corners export as their cut outline plus `data-vector-d` (the sharp path) and\n * `data-vector-corners` (the radii), so the editor's own SVG imports with editable corners.\n * Inside / outside strokes, which SVG cannot express, export (after vectorcraft\n * `crates/svg/src/lib.rs`, MIT OR Apache-2.0) as a `<g data-vector-path>` holding the fill, a\n * stroke of twice the width clipped to the shape (inside) or masked by it (outside), and the\n * arrowheads as filled outlines; import merges such a group back into one path. A variable-width\n * stroke exports as its filled outline (`data-vector-part=\"stroke-outline\"`) with the profile\n * and line style kept in `data-vector-width-profile` / `data-vector-stroke-*` attributes.\n */\nimport { bezierPathToSvg } from '../canvas/pathops/bezier.js';\nimport { bezierPathBounds } from '../canvas/pathops/bezier.js';\nimport { hasStrokeExtras, strokeWidthProfileOf, vectorStrokeLineArea, vectorStrokeOutlinePath, vectorStrokeParts, vectorStrokeReach } from './stroke.js';\nimport { sanitizeWidthProfile } from './width.js';\nimport { gradientToSvgDef, type CanvasGradientDef, type GradientStop, type SvgGradientDef } from '../canvas/gradient.js';\nimport { formatNumber } from '../canvas/shapeGeometry.js';\nimport {\n\tbezierToSubpaths,\n\tellipseSubpath,\n\thasPaint,\n\tIDENTITY_MATRIX,\n\tlineSubpath,\n\tmultiplyMatrices,\n\trectSubpath,\n\trotateMatrix,\n\tscaleMatrix,\n\tsubpathsToBezier,\n\ttransformVectorNode,\n\ttranslateMatrix,\n\tvectorPathData,\n\ttype AffineMatrix\n} from './geometry.js';\nimport {\n\tVECTOR_ARROWHEADS,\n\tVECTOR_CORNER_KINDS,\n\ttype VectorArrowhead,\n\ttype VectorCornerKind,\n\ttype VectorDocument,\n\ttype VectorFillRule,\n\ttype VectorGroupNode,\n\ttype VectorLineCap,\n\ttype VectorLineJoin,\n\ttype VectorWidthPoint,\n\ttype VectorNode,\n\ttype VectorPaint,\n\ttype VectorBounds,\n\ttype VectorPathNode,\n\ttype VectorStrokeAlign,\n\ttype VectorSubpath\n} from './types.js';\n\n// ---------------------------------------------------------------------------\n// Export\n// ---------------------------------------------------------------------------\n\nexport interface VectorSvgExportOptions {\n\t/** Decimal places for coordinates (default 3). */\n\tprecision?: number;\n\t/** Draw `document.background` as a full-size rect (default true). */\n\tbackground?: boolean;\n\t/** Include hidden nodes with `display=\"none\"` instead of leaving them out (default false). */\n\tincludeHidden?: boolean;\n\t/** Prefix for gradient ids (default `vg-`), to keep ids unique when several SVGs share a page. */\n\tidPrefix?: string;\n\t/** Indent nested elements (default true). */\n\tpretty?: boolean;\n\t/**\n\t * How strokes with an inside / outside alignment or arrowheads are written: `clip` (default)\n\t * as a double-width stroke clipped or masked by the shape plus filled heads, `outline` as\n\t * one filled path of the area the stroke paints.\n\t */\n\tstrokes?: 'clip' | 'outline';\n}\n\n/** `data-vector-corners`: the live corners of subpaths as `subpath.index:radius[:kind]`, space separated. */\nexport function vectorCornersAttribute(subpaths: readonly VectorSubpath[], precision = 3): string {\n\tconst out: string[] = [];\n\tsubpaths.forEach((sp, s) =>\n\t\tsp.anchors.forEach((a, i) => {\n\t\t\tif (!a.corner || !(a.corner.radius > 0)) return;\n\t\t\tout.push(`${s}.${i}:${formatNumber(a.corner.radius, precision)}${a.corner.kind && a.corner.kind !== 'round' ? `:${a.corner.kind}` : ''}`);\n\t\t})\n\t);\n\treturn out.join(' ');\n}\n\n/** Puts `data-vector-corners` back on subpaths (malformed entries are ignored). */\nexport function applyVectorCornersAttribute(subpaths: VectorSubpath[], value: string): VectorSubpath[] {\n\tfor (const item of value.trim().split(/\\s+/)) {\n\t\tconst m = /^(\\d+)\\.(\\d+):([\\d.eE+-]+)(?::([a-z]+))?$/.exec(item);\n\t\tif (!m) continue;\n\t\tconst a = subpaths[+m[1]]?.anchors[+m[2]];\n\t\tconst radius = parseFloat(m[3]);\n\t\tif (!a || !(radius > 0)) continue;\n\t\tconst kind = VECTOR_CORNER_KINDS.includes(m[4] as VectorCornerKind) ? (m[4] as VectorCornerKind) : undefined;\n\t\ta.corner = { radius, ...(kind && kind !== 'round' ? { kind } : {}) };\n\t}\n\treturn subpaths;\n}\n\nconst escapeAttr = (value: string) => value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n\n/** A paint as an SVG attribute value plus the gradient def it needs (if any). */\nexport function vectorPaintToSvg(paint: VectorPaint | undefined, gradientId: string): { value: string; gradient: SvgGradientDef | null } {\n\tif (!hasPaint(paint)) return { value: 'none', gradient: null };\n\tif (typeof paint === 'string') return { value: paint, gradient: null };\n\treturn { value: `url(#${gradientId})`, gradient: gradientToSvgDef(paint as CanvasGradientDef, gradientId) };\n}\n\n/** The parts of an aligned or arrowed stroke (see `VectorRenderPath.strokeParts`). */\nexport interface VectorRenderStrokeParts {\n\talign: VectorStrokeAlign;\n\t/** The line the stroke follows (shortened under `tip`-aligned heads). */\n\td: string;\n\t/** Width to draw it with: twice the stroke width when aligned, half of it being clipped away. */\n\twidth: number;\n\t/**\n\t * A variable-width stroke: the area to fill with `stroke` (nonzero) instead of stroking `d`,\n\t * clipped or masked like the stroke would be.\n\t */\n\toutline?: string;\n\t/**\n\t * Inside: a `<clipPath id>` holding the shape (`d`, `clip-rule` = `fillRule`). Outside: a\n\t * `<mask id>` in user space over `bounds`, white with the shape (`d`) in black.\n\t */\n\tclip: { kind: 'clip' | 'mask'; id: string; bounds: VectorBounds } | null;\n\t/** Arrowhead outlines (fill with `stroke`, nonzero). */\n\theads: string[];\n}\n\n/** Stroke parts are recomputed only when the node (or the id / precision asked for) changes. */\nconst partsCache = new WeakMap<VectorPathNode, { clipId: string; precision: number; parts: VectorRenderStrokeParts | undefined }>();\n\n/** The stroke parts of a path whose stroke needs more than one element, in its own space (undefined otherwise). */\nexport function vectorStrokeSvgParts(node: VectorPathNode, clipId: string, precision = 3): VectorRenderStrokeParts | undefined {\n\tif (!hasPaint(node.stroke) || !hasStrokeExtras(node)) return undefined;\n\tconst hit = partsCache.get(node);\n\tif (hit && hit.clipId === clipId && hit.precision === precision) return hit.parts;\n\tconst parts = computeStrokeSvgParts(node, clipId, precision);\n\tpartsCache.set(node, { clipId, precision, parts });\n\treturn parts;\n}\n\nfunction computeStrokeSvgParts(node: VectorPathNode, clipId: string, precision: number): VectorRenderStrokeParts | undefined {\n\tconst path = subpathsToBezier(node.subpaths);\n\tconst parts = vectorStrokeParts(path, node);\n\tconst profiled = !!strokeWidthProfileOf(node);\n\tif (parts.align === 'center' && !parts.heads.length && !profiled) return undefined;\n\tlet clip: VectorRenderStrokeParts['clip'] = null;\n\tif (parts.align !== 'center') {\n\t\tconst b = bezierPathBounds(path);\n\t\tconst pad = vectorStrokeReach(node) + 1;\n\t\tconst bounds = b ? { x: round2(b.minX - pad), y: round2(b.minY - pad), width: round2(b.maxX - b.minX + 2 * pad), height: round2(b.maxY - b.minY + 2 * pad) } : { x: 0, y: 0, width: 0, height: 0 };\n\t\tclip = { kind: parts.align === 'inside' ? 'clip' : 'mask', id: clipId, bounds };\n\t}\n\treturn {\n\t\talign: parts.align,\n\t\td: bezierPathToSvg(parts.line, { precision }),\n\t\twidth: parts.drawWidth,\n\t\t...(profiled && (node.strokeWidth ?? 1) > 0 ? { outline: bezierPathToSvg(vectorStrokeLineArea(parts, node), { precision }) } : {}),\n\t\tclip,\n\t\theads: parts.heads.map((h) => bezierPathToSvg(h.path, { precision }))\n\t};\n}\n\n/** A width profile as a data attribute: `t,left,right` points separated by `;`. */\nexport function widthProfileToAttribute(points: readonly VectorWidthPoint[], precision = 4): string {\n\treturn points.map((p) => [p.t, p.left, p.right].map((n) => formatNumber(n, precision)).join(',')).join(';');\n}\n\n/** Reads `widthProfileToAttribute` output (invalid points are dropped). */\nexport function widthProfileFromAttribute(value: string | undefined): VectorWidthPoint[] {\n\tif (!value) return [];\n\treturn sanitizeWidthProfile(\n\t\tvalue.split(';').map((part) => {\n\t\t\tconst [t, left, right] = part.split(',').map((n) => parseFloat(n));\n\t\t\treturn { t, left, right: Number.isFinite(right) ? right : left };\n\t\t})\n\t);\n}\n\nconst round2 = (n: number) => Math.round(n * 100) / 100;\n\nfunction gradientMarkup(def: SvgGradientDef): string {\n\tconst tag = def.type === 'radial' ? 'radialGradient' : 'linearGradient';\n\tconst attrs = Object.entries(def.attrs)\n\t\t.map(([k, v]) => ` ${k}=\"${escapeAttr(String(v))}\"`)\n\t\t.join('');\n\tconst stops = def.stops\n\t\t.map((s) => `<stop offset=\"${s.offset}\" stop-color=\"${escapeAttr(s.stopColor)}\"${s.stopOpacity !== undefined ? ` stop-opacity=\"${s.stopOpacity}\"` : ''}/>`)\n\t\t.join('');\n\treturn `<${tag} id=\"${escapeAttr(def.id)}\"${attrs}>${stops}</${tag}>`;\n}\n\n/** Serializes a vector document as a standalone SVG string. */\nexport function vectorDocumentToSvg(doc: VectorDocument, options: VectorSvgExportOptions = {}): string {\n\tconst precision = options.precision ?? 3;\n\tconst prefix = options.idPrefix ?? 'vg-';\n\tconst pretty = options.pretty !== false;\n\tconst defs: string[] = [];\n\tconst lines: string[] = [];\n\tconst num = (n: number) => formatNumber(n, precision);\n\tconst indent = (depth: number) => (pretty ? ' '.repeat(depth) : '');\n\n\tconst common = (node: VectorNode) => {\n\t\tlet out = ` id=\"${escapeAttr(node.id)}\"`;\n\t\tif (node.transform) out += ` transform=\"matrix(${node.transform.map((n) => formatNumber(n, 6)).join(' ')})\"`;\n\t\tif (node.opacity !== undefined && node.opacity < 1) out += ` opacity=\"${num(node.opacity)}\"`;\n\t\tif (node.visible === false) out += ` display=\"none\"`;\n\t\treturn out;\n\t};\n\n\tconst emit = (node: VectorNode, depth: number) => {\n\t\tif (node.visible === false && !options.includeHidden) return;\n\t\tif (node.type === 'group') {\n\t\t\tlines.push(`${indent(depth)}<g${common(node)}>`);\n\t\t\tfor (const child of node.children) emit(child, depth + 1);\n\t\t\tlines.push(`${indent(depth)}</g>`);\n\t\t\treturn;\n\t\t}\n\t\tconst fill = vectorPaintToSvg(node.fill, `${prefix}fill-${node.id}`);\n\t\tconst stroke = vectorPaintToSvg(node.stroke, `${prefix}stroke-${node.id}`);\n\t\tif (fill.gradient) defs.push(gradientMarkup(fill.gradient));\n\t\tif (stroke.gradient) defs.push(gradientMarkup(stroke.gradient));\n\t\tconst d = vectorPathData(node, precision);\n\t\tconst corners = vectorCornersAttribute(node.subpaths, precision);\n\t\tconst live = corners ? ` data-vector-d=\"${bezierPathToSvg(subpathsToBezier(node.subpaths, { corners: false }), { precision })}\" data-vector-corners=\"${corners}\"` : '';\n\t\tconst fillAttrs = ` fill=\"${escapeAttr(fill.value)}\"${node.fillRule === 'evenodd' ? ` fill-rule=\"evenodd\"` : ''}`;\n\t\tconst lineAttrs = (width: number) => {\n\t\t\tlet out = ` stroke=\"${escapeAttr(stroke.value)}\" stroke-width=\"${num(width)}\"`;\n\t\t\tif (node.strokeLinecap && node.strokeLinecap !== 'butt') out += ` stroke-linecap=\"${node.strokeLinecap}\"`;\n\t\t\tif (node.strokeLinejoin && node.strokeLinejoin !== 'miter') out += ` stroke-linejoin=\"${node.strokeLinejoin}\"`;\n\t\t\tif (node.strokeDasharray?.length) out += ` stroke-dasharray=\"${node.strokeDasharray.map(num).join(' ')}\"`;\n\t\t\treturn out;\n\t\t};\n\t\tconst parts = stroke.value !== 'none' ? vectorStrokeSvgParts(node, `${prefix}clip-${node.id}`, precision) : undefined;\n\t\tif (!parts) {\n\t\t\tlines.push(`${indent(depth)}<path${common(node)} d=\"${d}\"${fillAttrs}${stroke.value !== 'none' ? lineAttrs(node.strokeWidth ?? 1) : ''}${live}/>`);\n\t\t\treturn;\n\t\t}\n\t\t// The stroke options SVG has no attribute for, kept for import.\n\t\tlet data = ` data-vector-path=\"\" data-vector-stroke-width=\"${num(node.strokeWidth ?? 1)}\"`;\n\t\tif (parts.align !== 'center') data += ` data-vector-stroke-align=\"${parts.align}\"`;\n\t\tif (node.startArrow) data += ` data-vector-start-arrow=\"${node.startArrow}\"`;\n\t\tif (node.endArrow) data += ` data-vector-end-arrow=\"${node.endArrow}\"`;\n\t\tif (node.arrowAlign && node.arrowAlign !== 'extend') data += ` data-vector-arrow-align=\"${node.arrowAlign}\"`;\n\t\tif (node.startArrowScale !== undefined && node.startArrowScale !== 1) data += ` data-vector-start-arrow-scale=\"${num(node.startArrowScale)}\"`;\n\t\tif (node.endArrowScale !== undefined && node.endArrowScale !== 1) data += ` data-vector-end-arrow-scale=\"${num(node.endArrowScale)}\"`;\n\t\tconst profile = strokeWidthProfileOf(node);\n\t\tif (profile) {\n\t\t\t// Drawn as a filled outline: keep the line style the outline was built with.\n\t\t\tdata += ` data-vector-width-profile=\"${widthProfileToAttribute(profile)}\"`;\n\t\t\tif (node.strokeLinecap && node.strokeLinecap !== 'butt') data += ` data-vector-stroke-linecap=\"${node.strokeLinecap}\"`;\n\t\t\tif (node.strokeLinejoin && node.strokeLinejoin !== 'miter') data += ` data-vector-stroke-linejoin=\"${node.strokeLinejoin}\"`;\n\t\t\tif (node.strokeDasharray?.length) data += ` data-vector-stroke-dasharray=\"${node.strokeDasharray.map(num).join(' ')}\"`;\n\t\t}\n\t\tlines.push(`${indent(depth)}<g${common(node)}${data}>`);\n\t\tlines.push(`${indent(depth + 1)}<path data-vector-part=\"fill\" d=\"${d}\"${fillAttrs}${live}/>`);\n\t\tif (options.strokes === 'outline') {\n\t\t\tconst area = bezierPathToSvg(vectorStrokeOutlinePath(subpathsToBezier(node.subpaths), node), { precision });\n\t\t\tlines.push(`${indent(depth + 1)}<path data-vector-part=\"stroke-outline\" d=\"${area}\" fill=\"${escapeAttr(stroke.value)}\"/>`);\n\t\t} else {\n\t\t\tlet clip = '';\n\t\t\tif (parts.clip) {\n\t\t\t\tconst rule = node.fillRule === 'evenodd' ? 'evenodd' : 'nonzero';\n\t\t\t\tconst id = escapeAttr(parts.clip.id);\n\t\t\t\tif (parts.clip.kind === 'clip') {\n\t\t\t\t\tdefs.push(`<clipPath id=\"${id}\"><path d=\"${d}\" clip-rule=\"${rule}\"/></clipPath>`);\n\t\t\t\t\tclip = ` clip-path=\"url(#${id})\"`;\n\t\t\t\t} else {\n\t\t\t\t\tconst b = parts.clip.bounds;\n\t\t\t\t\tconst box = `x=\"${num(b.x)}\" y=\"${num(b.y)}\" width=\"${num(b.width)}\" height=\"${num(b.height)}\"`;\n\t\t\t\t\tdefs.push(`<mask id=\"${id}\" maskUnits=\"userSpaceOnUse\" ${box}><rect ${box} fill=\"#fff\"/><path d=\"${d}\" fill=\"#000\" fill-rule=\"${rule}\"/></mask>`);\n\t\t\t\t\tclip = ` mask=\"url(#${id})\"`;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (parts.outline !== undefined) lines.push(`${indent(depth + 1)}<path data-vector-part=\"stroke-outline\" d=\"${parts.outline}\" fill=\"${escapeAttr(stroke.value)}\"${clip}/>`);\n\t\t\telse lines.push(`${indent(depth + 1)}<path data-vector-part=\"stroke\" d=\"${parts.d}\" fill=\"none\"${lineAttrs(parts.width)}${clip}/>`);\n\t\t\tfor (const h of parts.heads) lines.push(`${indent(depth + 1)}<path data-vector-part=\"head\" d=\"${h}\" fill=\"${escapeAttr(stroke.value)}\"/>`);\n\t\t}\n\t\tlines.push(`${indent(depth)}</g>`);\n\t};\n\n\tfor (const node of doc.nodes) emit(node, 1);\n\tconst w = num(doc.width);\n\tconst h = num(doc.height);\n\tconst nl = pretty ? '\\n' : '';\n\tconst out = [`<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${w}\" height=\"${h}\" viewBox=\"0 0 ${w} ${h}\">`];\n\tif (defs.length) out.push(`${indent(1)}<defs>${defs.join('')}</defs>`);\n\tif (doc.background && options.background !== false && hasPaint(doc.background)) {\n\t\tout.push(`${indent(1)}<rect width=\"${w}\" height=\"${h}\" fill=\"${escapeAttr(doc.background)}\"/>`);\n\t}\n\tout.push(...lines, '</svg>');\n\treturn out.join(nl);\n}\n\n// ---------------------------------------------------------------------------\n// Import\n// ---------------------------------------------------------------------------\n\nexport interface VectorSvgImportOptions {\n\t/** Makes ids for elements without a usable `id` (default `node-1`, `node-2`, …). */\n\tcreateId?: () => string;\n}\n\ninterface Element {\n\tname: string;\n\tattrs: Record<string, string>;\n\tchildren: Element[];\n}\n\n/** A tiny non-validating XML reader: elements and attributes only. */\nfunction parseXml(source: string): Element | null {\n\tconst text = source\n\t\t.replace(/<!--[\\s\\S]*?-->/g, '')\n\t\t.replace(/<\\?[\\s\\S]*?\\?>/g, '')\n\t\t.replace(/<!\\[CDATA\\[[\\s\\S]*?\\]\\]>/g, '')\n\t\t.replace(/<!DOCTYPE[^>[]*(\\[[\\s\\S]*?\\])?\\s*>/gi, '');\n\tconst root: Element = { name: '#root', attrs: {}, children: [] };\n\tconst stack: Element[] = [root];\n\tconst tag = /<(\\/?)([A-Za-z_][\\w:.-]*)((?:\\s+[^\\s=/>]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s>]+))?)*)\\s*(\\/?)>/g;\n\tconst attr = /([^\\s=/>]+)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s>]+)))?/g;\n\tlet m: RegExpExecArray | null;\n\twhile ((m = tag.exec(text))) {\n\t\tconst [, closing, rawName, rawAttrs, selfClosing] = m;\n\t\tconst name = rawName.replace(/^svg:/, '');\n\t\tif (closing) {\n\t\t\tfor (let i = stack.length - 1; i > 0; i--) {\n\t\t\t\tif (stack[i].name === name) {\n\t\t\t\t\tstack.length = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst attrs: Record<string, string> = {};\n\t\tlet a: RegExpExecArray | null;\n\t\tattr.lastIndex = 0;\n\t\twhile ((a = attr.exec(rawAttrs))) attrs[a[1]] = decodeEntities(a[2] ?? a[3] ?? a[4] ?? '');\n\t\tconst el: Element = { name, attrs, children: [] };\n\t\tstack[stack.length - 1].children.push(el);\n\t\tif (!selfClosing) stack.push(el);\n\t}\n\tconst find = (el: Element): Element | null => {\n\t\tif (el.name === 'svg') return el;\n\t\tfor (const c of el.children) {\n\t\t\tconst f = find(c);\n\t\t\tif (f) return f;\n\t\t}\n\t\treturn null;\n\t};\n\treturn find(root);\n}\n\nfunction decodeEntities(s: string): string {\n\treturn s\n\t\t.replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCodePoint(parseInt(h, 16)))\n\t\t.replace(/&#(\\d+);/g, (_, d) => String.fromCodePoint(parseInt(d, 10)))\n\t\t.replace(/&quot;/g, '\"')\n\t\t.replace(/&apos;/g, \"'\")\n\t\t.replace(/&lt;/g, '<')\n\t\t.replace(/&gt;/g, '>')\n\t\t.replace(/&amp;/g, '&');\n}\n\nconst numberList = (s: string | undefined): number[] =>\n\t(s ?? '')\n\t\t.trim()\n\t\t.split(/[\\s,]+|(?=-)(?<![eE])/)\n\t\t.filter(Boolean)\n\t\t.map(Number)\n\t\t.filter((n) => Number.isFinite(n));\n\nconst length = (s: string | undefined, fallback = 0): number => {\n\tif (s === undefined) return fallback;\n\tconst n = parseFloat(s);\n\treturn Number.isFinite(n) ? n : fallback;\n};\n\n/** Parses an SVG `transform` attribute into one matrix. */\nexport function parseSvgTransform(value: string | undefined): AffineMatrix {\n\tlet m: AffineMatrix = IDENTITY_MATRIX;\n\tif (!value) return m;\n\tconst re = /(matrix|translate|scale|rotate|skewX|skewY)\\s*\\(([^)]*)\\)/g;\n\tlet t: RegExpExecArray | null;\n\twhile ((t = re.exec(value))) {\n\t\tconst n = numberList(t[2]);\n\t\tlet step: AffineMatrix = IDENTITY_MATRIX;\n\t\tswitch (t[1]) {\n\t\t\tcase 'matrix':\n\t\t\t\tif (n.length >= 6) step = [n[0], n[1], n[2], n[3], n[4], n[5]];\n\t\t\t\tbreak;\n\t\t\tcase 'translate':\n\t\t\t\tstep = translateMatrix(n[0] ?? 0, n[1] ?? 0);\n\t\t\t\tbreak;\n\t\t\tcase 'scale':\n\t\t\t\tstep = scaleMatrix(n[0] ?? 1, n[1] ?? n[0] ?? 1);\n\t\t\t\tbreak;\n\t\t\tcase 'rotate':\n\t\t\t\tstep = rotateMatrix(n[0] ?? 0, { x: n[1] ?? 0, y: n[2] ?? 0 });\n\t\t\t\tbreak;\n\t\t\tcase 'skewX':\n\t\t\t\tstep = [1, 0, Math.tan(((n[0] ?? 0) * Math.PI) / 180), 1, 0, 0];\n\t\t\t\tbreak;\n\t\t\tcase 'skewY':\n\t\t\t\tstep = [1, Math.tan(((n[0] ?? 0) * Math.PI) / 180), 0, 1, 0, 0];\n\t\t\t\tbreak;\n\t\t}\n\t\t// SVG lists apply right to left: `translate(…) rotate(…)` rotates first.\n\t\tm = multiplyMatrices(step, m);\n\t}\n\treturn m;\n}\n\ninterface InheritedStyle {\n\tfill: string;\n\tstroke: string;\n\tstrokeWidth: string;\n\tstrokeLinecap?: string;\n\tstrokeLinejoin?: string;\n\tstrokeDasharray?: string;\n\tfillRule?: string;\n}\n\nconst STYLE_KEYS: Record<string, keyof InheritedStyle> = {\n\tfill: 'fill',\n\tstroke: 'stroke',\n\t'stroke-width': 'strokeWidth',\n\t'stroke-linecap': 'strokeLinecap',\n\t'stroke-linejoin': 'strokeLinejoin',\n\t'stroke-dasharray': 'strokeDasharray',\n\t'fill-rule': 'fillRule'\n};\n\nfunction readStyle(el: Element, parent: InheritedStyle): InheritedStyle {\n\tconst out = { ...parent };\n\tfor (const [attr, key] of Object.entries(STYLE_KEYS)) if (el.attrs[attr] !== undefined) out[key] = el.attrs[attr].trim();\n\tfor (const decl of (el.attrs.style ?? '').split(';')) {\n\t\tconst i = decl.indexOf(':');\n\t\tif (i < 0) continue;\n\t\tconst key = STYLE_KEYS[decl.slice(0, i).trim()];\n\t\tif (key) out[key] = decl.slice(i + 1).replace(/!important/, '').trim();\n\t}\n\treturn out;\n}\n\nfunction readStops(el: Element): GradientStop[] {\n\treturn el.children\n\t\t.filter((c) => c.name === 'stop')\n\t\t.map((c) => {\n\t\t\tconst style = Object.fromEntries(\n\t\t\t\t(c.attrs.style ?? '')\n\t\t\t\t\t.split(';')\n\t\t\t\t\t.map((d) => d.split(':').map((s) => s.trim()))\n\t\t\t\t\t.filter((d) => d.length === 2)\n\t\t\t);\n\t\t\tconst raw = c.attrs.offset ?? '0';\n\t\t\tconst offset = raw.endsWith('%') ? parseFloat(raw) / 100 : parseFloat(raw);\n\t\t\tconst opacity = style['stop-opacity'] ?? c.attrs['stop-opacity'];\n\t\t\treturn {\n\t\t\t\toffset: Number.isFinite(offset) ? Math.max(0, Math.min(1, offset)) : 0,\n\t\t\t\tcolor: style['stop-color'] ?? c.attrs['stop-color'] ?? '#000',\n\t\t\t\t...(opacity !== undefined ? { opacity: parseFloat(opacity) } : {})\n\t\t\t};\n\t\t});\n}\n\nconst fraction = (s: string | undefined, fallback: number) => {\n\tif (s === undefined) return fallback;\n\tconst n = parseFloat(s);\n\tif (!Number.isFinite(n)) return fallback;\n\treturn s.trim().endsWith('%') ? n / 100 : n;\n};\n\nfunction collectGradients(el: Element, raw: Map<string, Element>) {\n\tif ((el.name === 'linearGradient' || el.name === 'radialGradient') && el.attrs.id) raw.set(el.attrs.id, el);\n\tfor (const c of el.children) collectGradients(c, raw);\n}\n\nfunction resolveGradient(id: string, raw: Map<string, Element>, seen = new Set<string>()): CanvasGradientDef | null {\n\tconst el = raw.get(id);\n\tif (!el || seen.has(id)) return null;\n\tseen.add(id);\n\tlet stops = readStops(el);\n\tconst href = el.attrs.href ?? el.attrs['xlink:href'];\n\tif (!stops.length && href?.startsWith('#')) stops = resolveGradient(href.slice(1), raw, seen)?.stops ?? [];\n\tif (!stops.length) return null;\n\tif (el.name === 'radialGradient') {\n\t\treturn { type: 'radial', cx: fraction(el.attrs.cx, 0.5), cy: fraction(el.attrs.cy, 0.5), r: fraction(el.attrs.r, 0.5), stops };\n\t}\n\tconst x1 = fraction(el.attrs.x1, 0);\n\tconst y1 = fraction(el.attrs.y1, 0);\n\tconst x2 = fraction(el.attrs.x2, 1);\n\tconst y2 = fraction(el.attrs.y2, 0);\n\t// CSS angle: 0° points up, clockwise.\n\tconst angle = Math.round(((Math.atan2(x2 - x1, -(y2 - y1)) * 180) / Math.PI + 360) % 360);\n\treturn { type: 'linear', angle, stops };\n}\n\n/** Parses SVG markup into a vector document. Throws when there is no `<svg>` element. */\nexport function parseVectorSvg(svg: string, options: VectorSvgImportOptions = {}): VectorDocument {\n\tconst root = parseXml(svg);\n\tif (!root) throw new Error('The markup has no <svg> element.');\n\tlet counter = 0;\n\tconst usedIds = new Set<string>();\n\tconst createId = options.createId ?? (() => `node-${++counter}`);\n\tconst idFor = (el: Element) => {\n\t\tconst id = el.attrs.id;\n\t\tif (id && !usedIds.has(id)) {\n\t\t\tusedIds.add(id);\n\t\t\treturn id;\n\t\t}\n\t\tlet next = createId();\n\t\twhile (usedIds.has(next)) next = createId();\n\t\tusedIds.add(next);\n\t\treturn next;\n\t};\n\n\tconst rawGradients = new Map<string, Element>();\n\tcollectGradients(root, rawGradients);\n\tconst paint = (value: string): VectorPaint => {\n\t\tconst v = value.trim();\n\t\tconst url = /^url\\(\\s*['\"]?#([^'\")\\s]+)['\"]?\\s*\\)/.exec(v);\n\t\tif (url) return resolveGradient(url[1], rawGradients) ?? null;\n\t\tif (v === 'none' || v === '') return null;\n\t\treturn v;\n\t};\n\n\tconst viewBox = numberList(root.attrs.viewBox);\n\tconst width = viewBox.length === 4 ? viewBox[2] : length(root.attrs.width, 300);\n\tconst height = viewBox.length === 4 ? viewBox[3] : length(root.attrs.height, 150);\n\tconst rootMatrix: AffineMatrix = viewBox.length === 4 ? translateMatrix(-viewBox[0], -viewBox[1]) : IDENTITY_MATRIX;\n\n\tconst SKIP = new Set(['defs', 'clipPath', 'mask', 'symbol', 'style', 'title', 'desc', 'metadata', 'pattern', 'marker', 'filter', 'text', 'image', 'use', 'linearGradient', 'radialGradient', 'script', 'foreignObject']);\n\n\tconst shapeOf = (el: Element): VectorSubpath[] | null => {\n\t\tconst a = el.attrs;\n\t\tswitch (el.name) {\n\t\t\tcase 'path': {\n\t\t\t\t// Our own export: the sharp path and its live corners.\n\t\t\t\tif (a['data-vector-d'] && a['data-vector-corners']) {\n\t\t\t\t\tconst sharp = bezierToSubpaths(a['data-vector-d']);\n\t\t\t\t\tif (sharp.length) return applyVectorCornersAttribute(sharp, a['data-vector-corners']);\n\t\t\t\t}\n\t\t\t\treturn a.d ? bezierToSubpaths(a.d) : null;\n\t\t\t}\n\t\t\tcase 'rect': {\n\t\t\t\tconst w = length(a.width);\n\t\t\t\tconst h = length(a.height);\n\t\t\t\tif (w <= 0 || h <= 0) return null;\n\t\t\t\tconst r = length(a.rx ?? a.ry, 0);\n\t\t\t\treturn [rectSubpath({ x: length(a.x), y: length(a.y), width: w, height: h }, r)];\n\t\t\t}\n\t\t\tcase 'circle': {\n\t\t\t\tconst r = length(a.r);\n\t\t\t\tif (r <= 0) return null;\n\t\t\t\tconst cx = length(a.cx);\n\t\t\t\tconst cy = length(a.cy);\n\t\t\t\treturn [ellipseSubpath({ x: cx - r, y: cy - r, width: 2 * r, height: 2 * r })];\n\t\t\t}\n\t\t\tcase 'ellipse': {\n\t\t\t\tconst rx = length(a.rx);\n\t\t\t\tconst ry = length(a.ry);\n\t\t\t\tif (rx <= 0 || ry <= 0) return null;\n\t\t\t\treturn [ellipseSubpath({ x: length(a.cx) - rx, y: length(a.cy) - ry, width: 2 * rx, height: 2 * ry })];\n\t\t\t}\n\t\t\tcase 'line':\n\t\t\t\treturn [lineSubpath({ x: length(a.x1), y: length(a.y1) }, { x: length(a.x2), y: length(a.y2) })];\n\t\t\tcase 'polyline':\n\t\t\tcase 'polygon': {\n\t\t\t\tconst n = numberList(a.points);\n\t\t\t\tif (n.length < 4) return null;\n\t\t\t\tconst anchors = [];\n\t\t\t\tfor (let i = 0; i + 1 < n.length; i += 2) anchors.push({ x: n[i], y: n[i + 1] });\n\t\t\t\treturn [{ anchors, closed: el.name === 'polygon' }];\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t};\n\n\tconst strokeStyle = (s: InheritedStyle): Partial<VectorPathNode> => ({\n\t\t...(s.strokeWidth ? { strokeWidth: length(s.strokeWidth, 1) } : {}),\n\t\t...(s.strokeLinecap ? { strokeLinecap: s.strokeLinecap as VectorLineCap } : {}),\n\t\t...(s.strokeLinejoin ? { strokeLinejoin: s.strokeLinejoin as VectorLineJoin } : {}),\n\t\t...(s.strokeDasharray && s.strokeDasharray !== 'none' ? { strokeDasharray: numberList(s.strokeDasharray) } : {}),\n\t\t...(s.fillRule === 'evenodd' ? { fillRule: 'evenodd' as VectorFillRule } : {})\n\t});\n\n\t/** A node mapped by `m` (scale and skew baked in, stroke width scaled). */\n\tconst placed = (node: VectorPathNode, m: AffineMatrix): VectorPathNode => {\n\t\tif (m === IDENTITY_MATRIX) return node;\n\t\tconst next = transformVectorNode(node, m);\n\t\tconst strokeScale = Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]));\n\t\tif (hasPaint(next.stroke) && strokeScale > 0 && Math.abs(strokeScale - 1) > 1e-9) next.strokeWidth = (next.strokeWidth ?? 1) * strokeScale;\n\t\treturn next;\n\t};\n\n\t/**\n\t * A `<g data-vector-path>` from our own export (an aligned or arrowed stroke drawn in parts)\n\t * as the one path it came from: the fill part's outline and fill, the stroke part's paint and\n\t * line style, and the options the group's data attributes keep.\n\t */\n\tconst mergedPath = (g: Element, style: InheritedStyle, m: AffineMatrix, meta: Partial<VectorPathNode>): VectorPathNode | null => {\n\t\tconst part = (name: string) => g.children.find((c) => c.name === 'path' && c.attrs['data-vector-part'] === name);\n\t\tconst fillEl = part('fill');\n\t\tconst subpaths = fillEl ? shapeOf(fillEl) : null;\n\t\tif (!fillEl || !subpaths?.length) return null;\n\t\tconst a = g.attrs;\n\t\tconst fs = readStyle(fillEl, style);\n\t\tconst strokeEl = part('stroke');\n\t\tconst outlineEl = part('stroke-outline');\n\t\tconst ss = strokeEl ? readStyle(strokeEl, style) : null;\n\t\tconst width = length(a['data-vector-stroke-width'], ss ? length(ss.strokeWidth, 1) : 1);\n\t\tconst arrow = (v: string | undefined) => (VECTOR_ARROWHEADS.includes(v as VectorArrowhead) ? (v as VectorArrowhead) : undefined);\n\t\tconst scale = (v: string | undefined) => {\n\t\t\tconst n = v === undefined ? NaN : parseFloat(v);\n\t\t\treturn n > 0 ? n : undefined;\n\t\t};\n\t\tconst align = a['data-vector-stroke-align'];\n\t\tconst profile = widthProfileFromAttribute(a['data-vector-width-profile']);\n\t\tconst kept = (key: string, values: readonly string[]) => (values.includes(a[key]) ? a[key] : undefined);\n\t\tconst keptCap = kept('data-vector-stroke-linecap', ['round', 'square']) as VectorLineCap | undefined;\n\t\tconst keptJoin = kept('data-vector-stroke-linejoin', ['round', 'bevel']) as VectorLineJoin | undefined;\n\t\tconst keptDash = a['data-vector-stroke-dasharray'] ? numberList(a['data-vector-stroke-dasharray']) : undefined;\n\t\tconst node: VectorPathNode = {\n\t\t\tid: idFor(g),\n\t\t\ttype: 'path',\n\t\t\t...meta,\n\t\t\tsubpaths,\n\t\t\tfill: paint(fs.fill),\n\t\t\tstroke: ss ? paint(ss.stroke) : outlineEl ? paint(readStyle(outlineEl, style).fill) : null,\n\t\t\t...(ss ? strokeStyle(ss) : {}),\n\t\t\t...(fs.fillRule === 'evenodd' ? { fillRule: 'evenodd' as VectorFillRule } : {}),\n\t\t\tstrokeWidth: width,\n\t\t\t...(align === 'inside' || align === 'outside' ? { strokeAlign: align } : {}),\n\t\t\t...(arrow(a['data-vector-start-arrow']) ? { startArrow: arrow(a['data-vector-start-arrow']) } : {}),\n\t\t\t...(arrow(a['data-vector-end-arrow']) ? { endArrow: arrow(a['data-vector-end-arrow']) } : {}),\n\t\t\t...(a['data-vector-arrow-align'] === 'tip' ? { arrowAlign: 'tip' as const } : {}),\n\t\t\t...(scale(a['data-vector-start-arrow-scale']) ? { startArrowScale: scale(a['data-vector-start-arrow-scale']) } : {}),\n\t\t\t...(scale(a['data-vector-end-arrow-scale']) ? { endArrowScale: scale(a['data-vector-end-arrow-scale']) } : {}),\n\t\t\t...(profile.length ? { strokeWidthProfile: profile } : {}),\n\t\t\t...(keptCap ? { strokeLinecap: keptCap } : {}),\n\t\t\t...(keptJoin ? { strokeLinejoin: keptJoin } : {}),\n\t\t\t...(keptDash?.length ? { strokeDasharray: keptDash } : {})\n\t\t};\n\t\treturn placed(node, m);\n\t};\n\n\tconst visit = (el: Element, style: InheritedStyle, matrix: AffineMatrix): VectorNode[] => {\n\t\tconst out: VectorNode[] = [];\n\t\tfor (const child of el.children) {\n\t\t\tif (SKIP.has(child.name)) continue;\n\t\t\tconst m = multiplyMatrices(parseSvgTransform(child.attrs.transform), matrix);\n\t\t\tconst s = readStyle(child, style);\n\t\t\tconst opacity = child.attrs.opacity !== undefined ? parseFloat(child.attrs.opacity) : undefined;\n\t\t\tconst hidden = child.attrs.display === 'none' || child.attrs.visibility === 'hidden';\n\t\t\tconst meta = {\n\t\t\t\t...(child.attrs['inkscape:label'] || child.attrs['data-name'] ? { name: child.attrs['inkscape:label'] ?? child.attrs['data-name'] } : {}),\n\t\t\t\t...(opacity !== undefined && Number.isFinite(opacity) && opacity < 1 ? { opacity } : {}),\n\t\t\t\t...(hidden ? { visible: false } : {})\n\t\t\t};\n\t\t\tif (child.name === 'g' && child.attrs['data-vector-path'] !== undefined) {\n\t\t\t\tconst node = mergedPath(child, s, m, meta);\n\t\t\t\tif (node) out.push(node);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (child.name === 'g' || child.name === 'svg' || child.name === 'a' || child.name === 'switch') {\n\t\t\t\tconst children = visit(child, s, m);\n\t\t\t\tif (!children.length) continue;\n\t\t\t\tconst group: VectorGroupNode = { id: idFor(child), type: 'group', ...meta, children };\n\t\t\t\tout.push(group);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst subpaths = shapeOf(child);\n\t\t\tif (!subpaths || !subpaths.length) continue;\n\t\t\tconst node = placed(\n\t\t\t\t{\n\t\t\t\t\tid: idFor(child),\n\t\t\t\t\ttype: 'path',\n\t\t\t\t\t...meta,\n\t\t\t\t\tsubpaths,\n\t\t\t\t\tfill: child.name === 'line' ? null : paint(s.fill),\n\t\t\t\t\tstroke: paint(s.stroke),\n\t\t\t\t\t...strokeStyle(s)\n\t\t\t\t},\n\t\t\t\tm\n\t\t\t);\n\t\t\tout.push(node);\n\t\t}\n\t\treturn out;\n\t};\n\n\tconst nodes = visit(root, readStyle(root, { fill: '#000', stroke: 'none', strokeWidth: '' }), rootMatrix);\n\treturn { width, height, nodes };\n}\n","/**\n * Smart guides and object snapping for the vector editor. Targets — anchors, bounding-box\n * edges and centres, path segments and the artboard — are gathered once per gesture in\n * document space (rotated nodes included) and kept sorted by x and y, so each pointer move\n * finds the few near the pointer by bisection. A point snaps, in this order of priority: kept\n * to its Shift angle and slid into line with a target, onto an anchor or centre, onto an\n * intersection of two paths, onto the perpendicular foot or tangent point from where it\n * leaves, onto a path, onto a construction angle, then into line with targets on x and y. A\n * moved box lines its edges and centre up with targets, or spaces itself evenly in its row\n * and column; a resized box lands its moving edges on targets, or matches another object's\n * width or height. Every snap reports labelled guide lines in document units.\n *\n * Portions ported from vectorcraft-main/crates/tools/src/guides.rs (`Targets`, `within`,\n * `for_move`, `for_drawing`, `for_handle`, `for_anchor_drag`, `push_segments`, `snap_from`,\n * `slide`, `lined_up`, `on_segment`, `crossing`, `align_rects`, `snap_rects`, `even_spacing`,\n * `gap_marks`, `snap_scale`, `Leave`), figcraft-main/crates/engine/src/snap.rs (`spacings`,\n * `equal_spacing`, `spacing_guides`: equal-spacing cases and gap labels),\n * designcraft-main/crates/tools/src/snap.rs (`pass_dimensions`: matching other objects'\n * sizes) and cadcraft-main/crates/engine/src/snap/curves.rs (`Param::solve`: perpendicular and\n * tangent points by sign-change sampling and bisection) (MIT OR Apache-2.0, © ArtCraft Team\n * and contributors). See THIRD_PARTY_NOTICES.md.\n */\nimport type { Point } from '../canvas/types.js';\nimport { segmentDerivative, segmentNearest, segmentPoint, type BezierSegment } from '../canvas/pathops/bezier.js';\nimport { segmentIntersections } from '../canvas/pathops/boolean.js';\nimport {\n\tapplyMatrix,\n\tIDENTITY_MATRIX,\n\tmatrixRotation,\n\tmultiplyMatrices,\n\tnodeMatrix,\n\trotateMatrix,\n\tsubpathSegment,\n\tsubpathSegmentCount,\n\tvectorNodeBounds,\n\ttype AffineMatrix\n} from './geometry.js';\nimport type { VectorAnchorRef, VectorBounds, VectorDocument, VectorNode, VectorSubpath, VectorTransformHandle, Vec2 } from './types.js';\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * What a guide line shows: `align` lines run from a target through the snapped point or box,\n * `construction` lines from where a drawn point leaves, `spacing` marks equal gaps and `size`\n * the side whose length matches another object's.\n */\nexport type VectorGuideKind = 'align' | 'construction' | 'spacing' | 'size';\n\n/** A guide line in document units. */\nexport interface VectorGuideLine {\n\tkind: VectorGuideKind;\n\tx1: number;\n\ty1: number;\n\tx2: number;\n\ty2: number;\n}\n\n/** What a point or box snapped to. */\nexport type VectorSnapKind = 'anchor' | 'centre' | 'intersect' | 'perpendicular' | 'tangent' | 'path' | 'construction' | 'align' | 'spacing' | 'size';\n\n/** A guide label in document units: the snap kind's name, or a distance for gaps and sizes. */\nexport interface VectorGuideLabel {\n\tkind: VectorSnapKind;\n\tx: number;\n\ty: number;\n\ttext: string;\n}\n\nexport interface VectorSnapGuides {\n\tlines: VectorGuideLine[];\n\tlabels: VectorGuideLabel[];\n}\n\nexport interface VectorPointSnap extends VectorSnapGuides {\n\tpoint: Vec2;\n\t/** The rule that placed the point, or null when nothing was in reach. */\n\tkind: VectorSnapKind | null;\n\t/** Whether x / y were set by a target (for falling back to the grid on the other axis). */\n\tx: boolean;\n\ty: boolean;\n}\n\nexport interface VectorRectSnap extends VectorSnapGuides {\n\t/** Correction to add to the move. */\n\tdx: number;\n\tdy: number;\n\tx: boolean;\n\ty: boolean;\n}\n\nexport interface VectorScaleSnap extends VectorSnapGuides {\n\tsx: number;\n\tsy: number;\n\tsnapped: boolean;\n}\n\n/**\n * The point a drawn point leaves from (the anchor before it, a shape's start, a handle's\n * anchor) and how it keeps to it.\n */\nexport interface VectorSnapLeave {\n\tat: Vec2;\n\t/**\n\t * Shift held: keep to 45° steps round `at` (`angle`), to a diagonal (`square`, a box's\n\t * corner) or to the nearer axis (`axis`, a dragged point).\n\t */\n\tconstrain?: 'angle' | 'square' | 'axis' | null;\n\t/** Construction guide angles through `at`, degrees counter-clockwise on screen. */\n\tangles?: readonly number[];\n\t/** Snap to the perpendicular foot and tangent points from `at` on paths (default true). */\n\tcurves?: boolean;\n}\n\n/** The construction guide angles new editors start with. */\nexport const VECTOR_CONSTRUCTION_ANGLES: readonly number[] = [0, 45, 90, 135];\n\n/** Where `constrain` puts `p` (unchanged without one). */\nexport function constrainToLeave(leave: VectorSnapLeave | null | undefined, p: Vec2): Vec2 {\n\tif (!leave?.constrain) return p;\n\tconst dx = p.x - leave.at.x;\n\tconst dy = p.y - leave.at.y;\n\tswitch (leave.constrain) {\n\t\tcase 'axis':\n\t\t\treturn Math.abs(dx) > Math.abs(dy) ? { x: p.x, y: leave.at.y } : { x: leave.at.x, y: p.y };\n\t\tcase 'square': {\n\t\t\tconst s = Math.max(Math.abs(dx), Math.abs(dy));\n\t\t\treturn { x: leave.at.x + Math.sign(dx || 1) * s, y: leave.at.y + Math.sign(dy || 1) * s };\n\t\t}\n\t\tdefault: {\n\t\t\tconst len = Math.hypot(dx, dy);\n\t\t\tconst a = Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * (Math.PI / 4);\n\t\t\treturn { x: leave.at.x + Math.cos(a) * len, y: leave.at.y + Math.sin(a) * len };\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Targets\n// ---------------------------------------------------------------------------\n\ntype TargetKind = 'anchor' | 'centre' | 'edge' | 'artboard';\n\ninterface PointTarget {\n\tp: Vec2;\n\tkind: 'anchor' | 'centre';\n}\n\n/** A line to line up with: where it runs on its axis and the target point it comes from. */\ninterface LineTarget {\n\tv: number;\n\tfrom: Vec2;\n\tkind: TargetKind;\n}\n\ninterface SegmentTarget {\n\tseg: Point[];\n\tminX: number;\n\tminY: number;\n\tmaxX: number;\n\tmaxY: number;\n}\n\n/** How many anchors, and how many segments, the targets gather at most. */\nconst BUDGET = 20_000;\n/** The first near segments paired up when looking for intersections. */\nconst CROSSING_PAIRS = 32;\n/** Parameter samples per segment for perpendicular / tangent roots, and bisection steps. */\nconst CURVE_SAMPLES = 48;\nconst BISECT = 50;\nconst EQUAL = 1e-6;\n\n/** First index of `sorted` whose key is not below `v` (`strict`: above `v`). */\nfunction bound<T>(sorted: readonly T[], key: (e: T) => number, v: number, strict: boolean): number {\n\tlet lo = 0;\n\tlet hi = sorted.length;\n\twhile (lo < hi) {\n\t\tconst mid = (lo + hi) >>> 1;\n\t\tconst k = key(sorted[mid]);\n\t\tif (strict ? k <= v : k < v) lo = mid + 1;\n\t\telse hi = mid;\n\t}\n\treturn lo;\n}\n\n/** The entries of `sorted` (ascending by `key`) whose key is within `tol` of `v`, by bisection. */\nfunction within<T>(sorted: readonly T[], key: (e: T) => number, v: number, tol: number): readonly T[] {\n\treturn sorted.slice(bound(sorted, key, v - tol, false), bound(sorted, key, v + tol, true));\n}\n\nconst linesNear = (lines: readonly LineTarget[], v: number, tol: number) => within(lines, (l) => l.v, v, tol);\n\nconst distance = (a: Vec2, b: Vec2) => Math.hypot(a.x - b.x, a.y - b.y);\nconst toPoint = (p: Vec2): Point => [p.x, p.y];\nconst toVec = (p: Point): Vec2 => ({ x: p[0], y: p[1] });\n\n/** What `collect` gathers from each path besides its anchors and bounds. */\ntype Gather = 'bounds' | 'segments' | 'drawing';\n\nconst LABELS: Record<VectorSnapKind, string> = {\n\tanchor: 'anchor',\n\tcentre: 'centre',\n\tintersect: 'intersect',\n\tperpendicular: 'perpendicular',\n\ttangent: 'tangent',\n\tpath: 'path',\n\tconstruction: 'angle',\n\talign: 'align',\n\tspacing: 'spacing',\n\tsize: 'size'\n};\n\nconst fmtLength = (n: number) => String(Math.round(n * 100) / 100);\n\n/** A node's own (possibly rotated) frame: its size there and its centre in document space. */\nfunction nodeFrame(node: VectorNode, parent: AffineMatrix, aabb?: VectorBounds | null): { width: number; height: number; centre: Vec2 } | null {\n\tconst angle = matrixRotation(multiplyMatrices(nodeMatrix(node), parent));\n\tconst b = angle ? vectorNodeBounds(node, multiplyMatrices(parent, rotateMatrix(-angle))) : aabb !== undefined ? aabb : vectorNodeBounds(node, parent);\n\tif (!b) return null;\n\tconst c = { x: b.x + b.width / 2, y: b.y + b.height / 2 };\n\treturn { width: b.width, height: b.height, centre: angle ? applyMatrix(rotateMatrix(angle), c) : c };\n}\n\n/** True when `id` is `node` or inside it. */\nfunction contains(node: VectorNode, ids: ReadonlySet<string>): boolean {\n\tif (ids.has(node.id)) return true;\n\treturn node.type === 'group' && node.children.some((c) => contains(c, ids));\n}\n\n/**\n * Snap targets in document space, gathered once per gesture. Build them with `forMove`,\n * `forResize`, `forDrawing`, `forAnchorDrag` or `forHandle`, then call `snapFrom`,\n * `snapRect` or `snapScale` on every pointer move. Tolerances are in document units (screen\n * pixels divided by the zoom).\n */\nexport class VectorSnapTargets {\n\tprivate readonly points: PointTarget[] = [];\n\tprivate readonly xs: LineTarget[] = [];\n\tprivate readonly ys: LineTarget[] = [];\n\tprivate readonly segments: SegmentTarget[] = [];\n\t/** Bounds of the objects a moved box spaces itself evenly with. */\n\tprivate readonly boxes: VectorBounds[] = [];\n\t/** Side lengths of the other objects (in their own frames), which a resize may match. */\n\tprivate readonly sizes: number[] = [];\n\n\tprivate constructor() {}\n\n\t/** How many targets of each sort were gathered. */\n\tget counts(): { points: number; lines: number; segments: number; boxes: number } {\n\t\treturn { points: this.points.length, lines: this.xs.length + this.ys.length, segments: this.segments.length, boxes: this.boxes.length };\n\t}\n\n\t/** Targets for moving nodes `ids`: the other art's anchors, bounds and centres, the artboard, and boxes to space evenly with. */\n\tstatic forMove(doc: VectorDocument, ids: readonly string[]): VectorSnapTargets {\n\t\treturn VectorSnapTargets.collect(doc, new Set(ids), 'bounds');\n\t}\n\n\t/** Targets for resizing nodes `ids`: as for a move, plus the other objects' sizes. */\n\tstatic forResize(doc: VectorDocument, ids: readonly string[]): VectorSnapTargets {\n\t\treturn VectorSnapTargets.collect(doc, new Set(ids), 'bounds');\n\t}\n\n\t/**\n\t * Targets for a drawn point (pen, shape tools): the art but `exclude`, its anchors (as\n\t * points and in line), centres, edges and segments. The anchors and segments of `exclude`\n\t * (the path being drawn, whose bounds grow with it) stay targets.\n\t */\n\tstatic forDrawing(doc: VectorDocument, exclude: readonly string[] = []): VectorSnapTargets {\n\t\tconst skip = new Set(exclude);\n\t\tconst t = VectorSnapTargets.collect(doc, skip, 'drawing', false);\n\t\tt.pushPaths(doc, skip, () => false, true);\n\t\treturn t.index();\n\t}\n\n\t/**\n\t * Targets for dragging anchors: the other art with its segments, and the anchors and\n\t * segments that stay put on the paths being reshaped (their bounds move along, so they are\n\t * no targets). The moving anchors are left out.\n\t */\n\tstatic forAnchorDrag(doc: VectorDocument, anchors: readonly VectorAnchorRef[]): VectorSnapTargets {\n\t\tconst moving = new Map<string, Set<string>>();\n\t\tfor (const r of anchors) {\n\t\t\tconst set = moving.get(r.nodeId) ?? new Set<string>();\n\t\t\tset.add(`${r.subpath}:${r.index}`);\n\t\t\tmoving.set(r.nodeId, set);\n\t\t}\n\t\tconst t = VectorSnapTargets.collect(doc, new Set(moving.keys()), 'segments', false);\n\t\tt.pushPaths(doc, new Set(moving.keys()), (id, s, i) => !!moving.get(id)?.has(`${s}:${i}`), true);\n\t\treturn t.index();\n\t}\n\n\t/**\n\t * Targets for dragging a handle of path `nodeId`: the other art and that path's anchors\n\t * (its bounds and the segments through the handle move with it, so they would chase it).\n\t */\n\tstatic forHandle(doc: VectorDocument, nodeId: string): VectorSnapTargets {\n\t\tconst skip = new Set([nodeId]);\n\t\tconst t = VectorSnapTargets.collect(doc, skip, 'bounds', false);\n\t\tt.pushPaths(doc, skip, () => false, false);\n\t\treturn t.index();\n\t}\n\n\t/** The anchors of the paths `ids` as targets (on them and in line), and their segments when `segments`. */\n\tprivate pushPaths(doc: VectorDocument, ids: ReadonlySet<string>, moving: (id: string, subpath: number, index: number) => boolean, segments: boolean) {\n\t\tlet anchors = BUDGET;\n\t\tlet segmentBudget = segments ? BUDGET : 0;\n\t\tconst visit = (list: readonly VectorNode[], parent: AffineMatrix) => {\n\t\t\tfor (const n of list) {\n\t\t\t\tconst m = multiplyMatrices(nodeMatrix(n), parent);\n\t\t\t\tif (n.type === 'group') visit(n.children, m);\n\t\t\t\telse if (ids.has(n.id) && n.visible !== false) {\n\t\t\t\t\tn.subpaths.forEach((sp, s) => {\n\t\t\t\t\t\tsp.anchors.forEach((a, i) => {\n\t\t\t\t\t\t\tif (anchors <= 0 || moving(n.id, s, i)) return;\n\t\t\t\t\t\t\tthis.pushAnchor(applyMatrix(m, a));\n\t\t\t\t\t\t\tanchors--;\n\t\t\t\t\t\t});\n\t\t\t\t\t\tsegmentBudget = this.pushSegments(sp, m, (i) => moving(n.id, s, i), segmentBudget);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tvisit(doc.nodes, IDENTITY_MATRIX);\n\t}\n\n\tprivate pushAnchor(p: Vec2) {\n\t\tthis.points.push({ p, kind: 'anchor' });\n\t\tthis.xs.push({ v: p.x, from: p, kind: 'anchor' });\n\t\tthis.ys.push({ v: p.y, from: p, kind: 'anchor' });\n\t}\n\n\t/** The segments of `sp` (mapped by `m`) that stay put while the anchors `moving` accepts move. */\n\tprivate pushSegments(sp: VectorSubpath, m: AffineMatrix, moving: (index: number) => boolean, budget: number): number {\n\t\tconst n = sp.anchors.length;\n\t\tconst count = subpathSegmentCount(sp);\n\t\tfor (let i = 0; i < count && budget > 0; i++) {\n\t\t\tif (moving(i) || moving((i + 1) % n)) continue;\n\t\t\tconst seg = subpathSegment(sp, i).map((q) => toPoint(applyMatrix(m, toVec(q))));\n\t\t\tlet minX = Infinity;\n\t\t\tlet minY = Infinity;\n\t\t\tlet maxX = -Infinity;\n\t\t\tlet maxY = -Infinity;\n\t\t\tfor (const [x, y] of seg) {\n\t\t\t\tminX = Math.min(minX, x);\n\t\t\t\tminY = Math.min(minY, y);\n\t\t\t\tmaxX = Math.max(maxX, x);\n\t\t\t\tmaxY = Math.max(maxY, y);\n\t\t\t}\n\t\t\tthis.segments.push({ seg, minX, minY, maxX, maxY });\n\t\t\tbudget--;\n\t\t}\n\t\treturn budget;\n\t}\n\n\tprivate pushRect(r: VectorBounds, kind: TargetKind, centre: Vec2 | null) {\n\t\tconst corners = [\n\t\t\t{ x: r.x, y: r.y },\n\t\t\t{ x: r.x + r.width, y: r.y },\n\t\t\t{ x: r.x + r.width, y: r.y + r.height },\n\t\t\t{ x: r.x, y: r.y + r.height }\n\t\t];\n\t\tfor (const p of corners) {\n\t\t\tthis.xs.push({ v: p.x, from: p, kind });\n\t\t\tthis.ys.push({ v: p.y, from: p, kind });\n\t\t}\n\t\tif (centre) {\n\t\t\tthis.points.push({ p: centre, kind: 'centre' });\n\t\t\tthis.xs.push({ v: centre.x, from: centre, kind: 'centre' });\n\t\t\tthis.ys.push({ v: centre.y, from: centre, kind: 'centre' });\n\t\t}\n\t}\n\n\t/** Sorts the targets for `within` (stable: of targets alike, the first gathered wins). */\n\tprivate index(): this {\n\t\tthis.points.sort((a, b) => a.p.x - b.p.x);\n\t\tthis.xs.sort((a, b) => a.v - b.v);\n\t\tthis.ys.sort((a, b) => a.v - b.v);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Gathers targets from the artboard and every visible node but `exclude` (and what is inside\n\t * those): each leaf's anchors (also as lines for `drawing`), its segments (`segments`,\n\t * `drawing`), its bounds' corners as lines and its centre; and the top-level objects' boxes and\n\t * sizes (inside a group holding an excluded node, that group's other members).\n\t */\n\tprivate static collect(doc: VectorDocument, exclude: ReadonlySet<string>, gather: Gather, sort = true): VectorSnapTargets {\n\t\tconst self = new VectorSnapTargets();\n\t\tconst artboard = { x: 0, y: 0, width: doc.width, height: doc.height };\n\t\tself.pushRect(artboard, 'artboard', { x: doc.width / 2, y: doc.height / 2 });\n\t\tlet anchors = BUDGET;\n\t\tlet segments = BUDGET;\n\t\tconst visit = (list: readonly VectorNode[], parent: AffineMatrix) => {\n\t\t\tfor (const n of list) {\n\t\t\t\tif (exclude.has(n.id) || n.visible === false) continue;\n\t\t\t\tconst m = multiplyMatrices(nodeMatrix(n), parent);\n\t\t\t\tif (n.type === 'group') {\n\t\t\t\t\tvisit(n.children, m);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (anchors <= 0) continue;\n\t\t\t\tfor (const sp of n.subpaths) {\n\t\t\t\t\tfor (const a of sp.anchors) {\n\t\t\t\t\t\tif (anchors-- <= 0) break;\n\t\t\t\t\t\tconst p = applyMatrix(m, a);\n\t\t\t\t\t\tif (gather === 'drawing') self.pushAnchor(p);\n\t\t\t\t\t\telse self.points.push({ p, kind: 'anchor' });\n\t\t\t\t\t}\n\t\t\t\t\tif (gather !== 'bounds') segments = self.pushSegments(sp, m, () => false, segments);\n\t\t\t\t}\n\t\t\t\tconst b = vectorNodeBounds(n, parent);\n\t\t\t\tconst f = nodeFrame(n, parent, b);\n\t\t\t\tif (b) self.pushRect(b, 'edge', f?.centre ?? null);\n\t\t\t}\n\t\t};\n\t\tvisit(doc.nodes, IDENTITY_MATRIX);\n\t\t// Boxes to space evenly with and sizes to match: whole objects, opening groups that hold an excluded node.\n\t\tconst objects = (list: readonly VectorNode[], parent: AffineMatrix) => {\n\t\t\tfor (const n of list) {\n\t\t\t\tif (exclude.has(n.id) || n.visible === false || self.boxes.length >= BUDGET) continue;\n\t\t\t\tif (n.type === 'group' && contains(n, exclude)) {\n\t\t\t\t\tobjects(n.children, multiplyMatrices(nodeMatrix(n), parent));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst b = vectorNodeBounds(n, parent);\n\t\t\t\tif (b) self.boxes.push(b);\n\t\t\t\tconst f = nodeFrame(n, parent, b);\n\t\t\t\tif (f) self.sizes.push(f.width, f.height);\n\t\t\t}\n\t\t};\n\t\tobjects(doc.nodes, IDENTITY_MATRIX);\n\t\treturn sort ? self.index() : self;\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Points\n\t// -------------------------------------------------------------------------\n\n\t/** Snaps a single point (see `snapFrom`). */\n\tsnapPoint(p: Vec2, tol: number): VectorPointSnap {\n\t\treturn this.snapFrom(p, null, tol);\n\t}\n\n\t/**\n\t * Snaps a point `p`, drawn or dragged from `leave` when given. With `leave.constrain` it keeps\n\t * to its angle round `leave.at`, sliding along that way into line with the nearest target.\n\t * Otherwise it lands, in order, on an anchor or centre, an intersection of two paths, the\n\t * perpendicular foot or a tangent point from `leave.at`, a path, a construction guide\n\t * through `leave.at` (where a target's line crosses it if one does nearby), or else lines up\n\t * with targets on x and y.\n\t */\n\tsnapFrom(p: Vec2, leave: VectorSnapLeave | null | undefined, tol: number): VectorPointSnap {\n\t\tconst none = (q: Vec2): VectorPointSnap => ({ point: q, kind: null, x: false, y: false, lines: [], labels: [] });\n\t\tconst at = (q: Vec2, kind: VectorSnapKind, lines: VectorGuideLine[] = []): VectorPointSnap => ({\n\t\t\tpoint: q,\n\t\t\tkind,\n\t\t\tx: true,\n\t\t\ty: true,\n\t\t\tlines,\n\t\t\tlabels: [this.label(q, kind)]\n\t\t});\n\t\tif (leave?.constrain) {\n\t\t\tconst q = constrainToLeave(leave, p);\n\t\t\tconst hit = this.slide(leave.at, { x: q.x - leave.at.x, y: q.y - leave.at.y }, q, tol, true);\n\t\t\treturn hit ? { point: hit.point, x: true, y: true, ...this.linedUp(hit.point, hit.from) } : none(q);\n\t\t}\n\t\tconst point = this.nearestPoint(p, tol);\n\t\tif (point) return at(point.p, point.kind);\n\t\tconst near = this.segmentsNear(p, tol);\n\t\tconst crossing = this.crossing(near, p, tol);\n\t\tif (crossing) return at(crossing, 'intersect');\n\t\tif (leave && leave.curves !== false) {\n\t\t\tconst foot = this.curvePoint(near, leave.at, p, tol);\n\t\t\tif (foot) return at(foot.point, foot.kind, [line('construction', leave.at, foot.point)]);\n\t\t}\n\t\tconst on = this.onSegment(near);\n\t\tif (on) return at(on, 'path');\n\t\tif (leave?.angles?.length) {\n\t\t\tconst c = construction(leave, p, tol);\n\t\t\tif (c) {\n\t\t\t\tconst hit = this.slide(leave.at, c.dir, c.point, tol, false);\n\t\t\t\tif (hit) {\n\t\t\t\t\tconst lined = this.linedUp(hit.point, hit.from);\n\t\t\t\t\treturn { point: hit.point, x: true, y: true, kind: lined.kind, lines: [line('construction', leave.at, hit.point), ...lined.lines], labels: lined.labels };\n\t\t\t\t}\n\t\t\t\treturn { point: c.point, kind: 'construction', x: true, y: true, lines: [line('construction', leave.at, c.point)], labels: [] };\n\t\t\t}\n\t\t}\n\t\tconst nearest = (lines: readonly LineTarget[], v: number) => {\n\t\t\tlet best: LineTarget | null = null;\n\t\t\tfor (const l of linesNear(lines, v, tol)) if (!best || Math.abs(l.v - v) < Math.abs(best.v - v)) best = l;\n\t\t\treturn best;\n\t\t};\n\t\tconst bx = nearest(this.xs, p.x);\n\t\tconst by = nearest(this.ys, p.y);\n\t\tif (!bx && !by) return none(p);\n\t\tconst out = { x: bx ? bx.v : p.x, y: by ? by.v : p.y };\n\t\tconst lines: VectorGuideLine[] = [];\n\t\tif (bx) lines.push(line('align', bx.from, { x: out.x, y: out.y }));\n\t\tif (by) lines.push(line('align', by.from, { x: out.x, y: out.y }));\n\t\treturn { point: out, kind: 'align', x: !!bx, y: !!by, lines, labels: [this.label(out, 'align')] };\n\t}\n\n\tprivate label(p: Vec2, kind: VectorSnapKind, text = LABELS[kind]): VectorGuideLabel {\n\t\treturn { kind, x: p.x, y: p.y, text };\n\t}\n\n\t/** The anchor or centre nearest `p`, within `tol`. */\n\tprivate nearestPoint(p: Vec2, tol: number): PointTarget | null {\n\t\tlet best: PointTarget | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (const t of within(this.points, (e) => e.p.x, p.x, tol)) {\n\t\t\tconst d = distance(t.p, p);\n\t\t\tif (d <= tol && d < bestD) {\n\t\t\t\tbest = t;\n\t\t\t\tbestD = d;\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t}\n\n\t/**\n\t * Slides `q`, on the line through `at` along `dir` (beyond `at` only for a `ray`), to where\n\t * the nearest target line crosses it, at most twice `tol` away: where it lands and the\n\t * target point that line comes from.\n\t */\n\tprivate slide(at: Vec2, dir: Vec2, q: Vec2, tol: number, ray: boolean): { point: Vec2; from: Vec2 } | null {\n\t\tconst len2 = dir.x * dir.x + dir.y * dir.y;\n\t\tif (!Number.isFinite(len2) || len2 <= 1e-18) return null;\n\t\tconst reach = 2 * tol;\n\t\tlet best: { moved: number; point: Vec2; from: Vec2 } | null = null;\n\t\tfor (const vertical of [true, false]) {\n\t\t\tconst d = vertical ? dir.x : dir.y;\n\t\t\tif (Math.abs(d) <= 1e-9) continue;\n\t\t\tconst a = vertical ? at.x : at.y;\n\t\t\tfor (const l of linesNear(vertical ? this.xs : this.ys, vertical ? q.x : q.y, reach)) {\n\t\t\t\tconst s = (l.v - a) / d;\n\t\t\t\t// Exactly on the line, whatever the rounding along the way.\n\t\t\t\tconst hit = vertical ? { x: l.v, y: at.y + dir.y * s } : { x: at.x + dir.x * s, y: l.v };\n\t\t\t\tconst moved = distance(hit, q);\n\t\t\t\tif (moved <= reach && (!ray || s > 0) && (!best || moved < best.moved)) best = { moved, point: hit, from: l.from };\n\t\t\t}\n\t\t}\n\t\treturn best && { point: best.point, from: best.from };\n\t}\n\n\t/** The guides of a point `q` slid into line with the target at `from`: the line and \"align\", or the target's own label when `q` sits on it. */\n\tprivate linedUp(q: Vec2, from: Vec2): { kind: VectorSnapKind } & VectorSnapGuides {\n\t\tconst on = this.nearestPoint(q, 1e-9);\n\t\tif (on) return { kind: on.kind, lines: [], labels: [this.label(on.p, on.kind)] };\n\t\treturn { kind: 'align', lines: [line('align', from, q)], labels: [this.label(q, 'align')] };\n\t}\n\n\t/** Target segments whose control box reaches `p` and which pass within `tol` of it, nearest first. */\n\tprivate segmentsNear(p: Vec2, tol: number): { seg: Point[]; t: number; distance: number }[] {\n\t\tconst out: { seg: Point[]; t: number; distance: number }[] = [];\n\t\tconst pt = toPoint(p);\n\t\tfor (const s of this.segments) {\n\t\t\tif (p.x < s.minX - tol || p.x > s.maxX + tol || p.y < s.minY - tol || p.y > s.maxY + tol) continue;\n\t\t\tconst hit = segmentNearest(s.seg, pt);\n\t\t\tif (hit.distance <= tol) out.push({ seg: s.seg, t: hit.t, distance: hit.distance });\n\t\t}\n\t\treturn out.sort((a, b) => a.distance - b.distance);\n\t}\n\n\tprivate onSegment(near: readonly { seg: Point[]; t: number }[]): Vec2 | null {\n\t\treturn near.length ? toVec(segmentPoint(near[0].seg, near[0].t)) : null;\n\t}\n\n\t/** Where two of the target segments near `p` cross, the crossing nearest `p` within `tol`. */\n\tprivate crossing(near: readonly { seg: Point[] }[], p: Vec2, tol: number): Vec2 | null {\n\t\tconst list = near.slice(0, CROSSING_PAIRS);\n\t\tlet best: Vec2 | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (let i = 0; i < list.length; i++) {\n\t\t\tfor (let j = i + 1; j < list.length; j++) {\n\t\t\t\tfor (const hit of segmentIntersections(list[i].seg as BezierSegment, list[j].seg as BezierSegment)) {\n\t\t\t\t\tconst q = toVec(hit.point);\n\t\t\t\t\tconst d = distance(q, p);\n\t\t\t\t\tif (d <= tol && d < bestD) {\n\t\t\t\t\t\tbest = q;\n\t\t\t\t\t\tbestD = d;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t}\n\n\t/**\n\t * The foot of a perpendicular, or a tangent point, from `base` on a target segment near `p`\n\t * (within `tol` of it): roots of `(B(t) − base) · B′(t)` and `(B(t) − base) × B′(t)`\n\t * bracketed by sign changes of samples and narrowed by bisection.\n\t */\n\tprivate curvePoint(near: readonly { seg: Point[] }[], base: Vec2, p: Vec2, tol: number): { point: Vec2; kind: 'perpendicular' | 'tangent' } | null {\n\t\tlet best: { point: Vec2; kind: 'perpendicular' | 'tangent'; d: number } | null = null;\n\t\tfor (const { seg } of near) {\n\t\t\tfor (const kind of ['perpendicular', 'tangent'] as const) {\n\t\t\t\tif (kind === 'tangent' && seg.length === 2) continue;\n\t\t\t\tfor (const q of solveOnSegment(seg, base, kind === 'perpendicular' ? dotCondition : crossCondition)) {\n\t\t\t\t\tconst d = distance(q, p);\n\t\t\t\t\tif (d <= tol && (!best || d < best.d)) best = { point: q, kind, d };\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn best && { point: best.point, kind: best.kind };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Boxes\n\t// -------------------------------------------------------------------------\n\n\t/**\n\t * Snaps a moving box `r` (the moved selection's bounds): its edge or centre nearest a target\n\t * line on each axis (`axes` limits which may move). With `spacing`, an axis that lines up\n\t * with nothing spaces the box evenly in its row or column. Returns the correction and guides.\n\t */\n\tsnapRect(r: VectorBounds, tol: number, options: { spacing?: boolean; axes?: { x?: boolean; y?: boolean } } = {}): VectorRectSnap {\n\t\tconst axes = { x: options.axes?.x !== false, y: options.axes?.y !== false };\n\t\tconst nearest = (lines: readonly LineTarget[], values: number[]) => {\n\t\t\tlet best: { d: number; from: Vec2 } | null = null;\n\t\t\tfor (const v of values) for (const l of linesNear(lines, v, tol)) if (!best || Math.abs(l.v - v) < Math.abs(best.d)) best = { d: l.v - v, from: l.from };\n\t\t\treturn best;\n\t\t};\n\t\tconst bx = axes.x ? nearest(this.xs, [r.x, r.x + r.width / 2, r.x + r.width]) : null;\n\t\tconst by = axes.y ? nearest(this.ys, [r.y, r.y + r.height / 2, r.y + r.height]) : null;\n\t\tconst out: VectorRectSnap = { dx: bx?.d ?? 0, dy: by?.d ?? 0, x: !!bx, y: !!by, lines: [], labels: [] };\n\t\tconst done = { ...r, x: r.x + out.dx, y: r.y + out.dy };\n\t\tif (bx) {\n\t\t\tconst x = bx.from.x;\n\t\t\tout.lines.push({ kind: 'align', x1: x, y1: Math.min(bx.from.y, done.y), x2: x, y2: Math.max(bx.from.y, done.y + done.height) });\n\t\t}\n\t\tif (by) {\n\t\t\tconst y = by.from.y;\n\t\t\tout.lines.push({ kind: 'align', x1: Math.min(by.from.x, done.x), y1: y, x2: Math.max(by.from.x, done.x + done.width), y2: y });\n\t\t}\n\t\tif (options.spacing && this.boxes.length) {\n\t\t\tfor (const horizontal of [true, false]) {\n\t\t\t\tif (horizontal ? out.x || !axes.x : out.y || !axes.y) continue;\n\t\t\t\tconst moved = { ...r, x: r.x + out.dx, y: r.y + out.dy };\n\t\t\t\tconst even = this.evenSpacing(moved, horizontal, tol);\n\t\t\t\tif (!even) continue;\n\t\t\t\tif (horizontal) {\n\t\t\t\t\tout.dx += even.shift;\n\t\t\t\t\tout.x = true;\n\t\t\t\t} else {\n\t\t\t\t\tout.dy += even.shift;\n\t\t\t\t\tout.y = true;\n\t\t\t\t}\n\t\t\t\tfor (const gap of even.gaps) this.gapMarks(gap, horizontal, tol, out);\n\t\t\t}\n\t\t}\n\t\tif (bx || by) out.labels.unshift(this.label({ x: r.x + out.dx + r.width / 2, y: r.y + out.dy + r.height / 2 }, 'align'));\n\t\treturn out;\n\t}\n\n\t/**\n\t * Equal spacing along x (`horizontal`) or y for the moved box `r`, among the objects of its\n\t * row (column): the shift within `tol` that centres it between its neighbours, or leaves it\n\t * as far from the neighbour before or after it as two other objects of the row are apart;\n\t * and the gaps that are equal then, as (start, end, where across).\n\t */\n\tprivate evenSpacing(r: VectorBounds, horizontal: boolean, tol: number): { shift: number; gaps: [number, number, number][] } | null {\n\t\tconst span = (b: VectorBounds, x: boolean): [number, number] => (x ? [b.x, b.x + b.width] : [b.y, b.y + b.height]);\n\t\tconst [r0, r1] = span(r, horizontal);\n\t\tconst len = r1 - r0;\n\t\tconst [c0, c1] = span(r, !horizontal);\n\t\tconst row = this.boxes\n\t\t\t.map((b) => ({ b, a0: span(b, horizontal)[0], a1: span(b, horizontal)[1] }))\n\t\t\t.filter((e) => span(e.b, !horizontal)[0] < c1 && span(e.b, !horizontal)[1] > c0 && (e.a1 <= r0 + tol || e.a0 >= r1 - tol))\n\t\t\t.sort((a, b) => a.a0 - b.a0);\n\t\tif (!row.length) return null;\n\t\t// Across the middle of what two boxes share (or of the space between them).\n\t\tconst mid = (a: VectorBounds, b: VectorBounds) => (Math.max(span(a, !horizontal)[0], span(b, !horizontal)[0]) + Math.min(span(a, !horizontal)[1], span(b, !horizontal)[1])) / 2;\n\t\tconst pairs: { g: number; gap: [number, number, number] }[] = [];\n\t\tfor (const p of row) {\n\t\t\tconst next = bound(row, (e) => e.a0, p.a1, false);\n\t\t\tconst q = row[next];\n\t\t\tif (!q) continue;\n\t\t\tconst straddles = p.a1 <= r0 + tol && q.a0 >= r1 - tol;\n\t\t\tif (q.a0 > p.a1 && !straddles) pairs.push({ g: q.a0 - p.a1, gap: [p.a1, q.a0, mid(p.b, q.b)] });\n\t\t}\n\t\tlet before: (typeof row)[number] | null = null;\n\t\tlet after: (typeof row)[number] | null = null;\n\t\tfor (const e of row) {\n\t\t\tif (e.a1 <= r0 + tol && (!before || e.a1 > before.a1)) before = e;\n\t\t\tif (e.a0 >= r1 - tol && (!after || e.a0 < after.a0)) after = e;\n\t\t}\n\t\tconst starts: { start: number; repeats: number | null }[] = [];\n\t\tif (before && after && after.a0 - before.a1 > len) starts.push({ start: (before.a1 + after.a0 - len) / 2, repeats: null });\n\t\tfor (const { g } of pairs) {\n\t\t\tif (before) starts.push({ start: before.a1 + g, repeats: g });\n\t\t\tif (after) starts.push({ start: after.a0 - g - len, repeats: g });\n\t\t}\n\t\tlet pick: { start: number; repeats: number | null } | null = null;\n\t\tfor (const s of starts) if (Math.abs(s.start - r0) <= tol && (!pick || Math.abs(s.start - r0) < Math.abs(pick.start - r0))) pick = s;\n\t\tif (!pick) return null;\n\t\tconst { start, repeats } = pick;\n\t\tconst at = horizontal ? { ...r, x: start } : { ...r, y: start };\n\t\tconst end = start + len;\n\t\tconst gaps: [number, number, number][] = [];\n\t\tif (before && (repeats === null || Math.abs(start - before.a1 - repeats) <= EQUAL)) gaps.push([before.a1, start, mid(before.b, at)]);\n\t\tif (after && (repeats === null || Math.abs(after.a0 - end - repeats) <= EQUAL)) gaps.push([end, after.a0, mid(after.b, at)]);\n\t\tif (repeats !== null) for (const p of pairs) if (Math.abs(p.g - repeats) <= EQUAL) gaps.push(p.gap);\n\t\treturn { shift: start - r0, gaps };\n\t}\n\n\t/** A gap mark: a line across the gap with a tick at each end, and its length as a label. */\n\tprivate gapMarks([u0, u1, c]: [number, number, number], horizontal: boolean, tick: number, out: VectorSnapGuides) {\n\t\tconst pt = (u: number, v: number): Vec2 => (horizontal ? { x: u, y: v } : { x: v, y: u });\n\t\tout.lines.push(line('spacing', pt(u0, c), pt(u1, c)), line('spacing', pt(u0, c - tick), pt(u0, c + tick)), line('spacing', pt(u1, c - tick), pt(u1, c + tick)));\n\t\tout.labels.push(this.label(pt((u0 + u1) / 2, c), 'spacing', fmtLength(u1 - u0)));\n\t}\n\n\t/** The other objects' side length nearest `length`, within `tol`, or null. */\n\tmatchSize(length: number, tol: number): number | null {\n\t\tlet best: number | null = null;\n\t\tfor (const s of this.sizes) if (Math.abs(s - length) <= tol && (best === null || Math.abs(s - length) < Math.abs(best - length))) best = s;\n\t\treturn best;\n\t}\n\n\t/**\n\t * Snaps a selection-box resize. `sx / sy` are the scale `scaleFor` gave for dragging\n\t * `handle` of `frame` (in the box's own, possibly rotated frame), `mods.shift` keeps the\n\t * proportions and `mods.alt` scales about the centre. The handle lands on an anchor or\n\t * centre within `tol`, else the corner or the side it moves lines up with the nearest\n\t * target, whatever the box's angle; a handle with one way to go (a side, or a proportional\n\t * corner) slides along it until one of them is on a target. An axis that snaps to nothing\n\t * may match another object's width or height instead.\n\t */\n\tsnapScale(\n\t\tframe: VectorBounds & { angle: number },\n\t\thandle: Exclude<VectorTransformHandle, 'rotate'>,\n\t\tsx: number,\n\t\tsy: number,\n\t\tmods: { shift?: boolean; alt?: boolean },\n\t\ttol: number\n\t): VectorScaleSnap {\n\t\tconst toDoc = frame.angle ? rotateMatrix(frame.angle) : IDENTITY_MATRIX;\n\t\tconst toLocal = frame.angle ? rotateMatrix(-frame.angle) : IDENTITY_MATRIX;\n\t\tconst corner = handle.length === 2;\n\t\tconst proportional = !!mods.shift;\n\t\tconst centre = { x: frame.x + frame.width / 2, y: frame.y + frame.height / 2 };\n\t\tconst origin = mods.alt ? centre : handlePos(opposite(handle), frame);\n\t\tconst hp = handlePos(handle, frame);\n\t\tconst d0 = { x: hp.x - origin.x, y: hp.y - origin.y };\n\t\tconst valid = (n: number, s: number) => Number.isFinite(n) && n * s > 0;\n\t\tconst nearest = (v: number, lines: readonly LineTarget[]) => {\n\t\t\tlet best: LineTarget | null = null;\n\t\t\tfor (const l of linesNear(lines, v, tol)) if (!best || Math.abs(l.v - v) < Math.abs(best.v - v)) best = l;\n\t\t\treturn best;\n\t\t};\n\t\ttype Snap = { hx: LineTarget | null; hy: LineTarget | null; on: PointTarget | null };\n\t\tlet nx = sx;\n\t\tlet ny = sy;\n\t\tlet snap: Snap = { hx: null, hy: null, on: null };\n\t\tif (corner && !proportional) {\n\t\t\t// The corner goes anywhere: onto an anchor or centre, else it takes a target's x, its y, or both.\n\t\t\tconst p = applyMatrix(toDoc, { x: origin.x + d0.x * sx, y: origin.y + d0.y * sy });\n\t\t\tconst hx = nearest(p.x, this.xs);\n\t\t\tconst hy = nearest(p.y, this.ys);\n\t\t\tconst on = this.nearestPoint(p, tol);\n\t\t\tconst tries: { tx: number | null; ty: number | null; s: Snap }[] = [];\n\t\t\tif (on) tries.push({ tx: on.p.x, ty: on.p.y, s: { hx: null, hy: null, on } });\n\t\t\ttries.push({ tx: hx?.v ?? null, ty: hy?.v ?? null, s: { hx, hy, on: null } });\n\t\t\ttries.push({ tx: hx?.v ?? null, ty: null, s: { hx, hy: null, on: null } });\n\t\t\ttries.push({ tx: null, ty: hy?.v ?? null, s: { hx: null, hy, on: null } });\n\t\t\tfor (const { tx, ty, s } of tries) {\n\t\t\t\tif (tx === null && ty === null) continue;\n\t\t\t\tconst q = applyMatrix(toLocal, { x: tx ?? p.x, y: ty ?? p.y });\n\t\t\t\tlet cx = (q.x - origin.x) / d0.x;\n\t\t\t\tlet cy = (q.y - origin.y) / d0.y;\n\t\t\t\t// Square to the page, the axis without a target stays exactly where it was.\n\t\t\t\tif (!frame.angle) {\n\t\t\t\t\tif (tx === null) cx = sx;\n\t\t\t\t\tif (ty === null) cy = sy;\n\t\t\t\t}\n\t\t\t\tif (valid(cx, sx) && valid(cy, sy)) {\n\t\t\t\t\tnx = cx;\n\t\t\t\t\tny = cy;\n\t\t\t\t\tsnap = s;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// One parameter `s`: the scale is `c + s·e` on each axis.\n\t\t\tconst movesX = handle === 'e' || handle === 'w';\n\t\t\tlet e: Vec2;\n\t\t\tlet c: Vec2;\n\t\t\tlet s0: number;\n\t\t\tif (corner) [e, c, s0] = [{ x: Math.sign(sx), y: Math.sign(sy) }, { x: 0, y: 0 }, Math.abs(sx)];\n\t\t\telse if (movesX) [e, c, s0] = proportional ? [{ x: 1, y: Math.sign(sx) }, { x: 0, y: 0 }, sx] : [{ x: 1, y: 0 }, { x: 0, y: 1 }, sx];\n\t\t\telse [e, c, s0] = proportional ? [{ x: Math.sign(sy), y: 1 }, { x: 0, y: 0 }, sy] : [{ x: 0, y: 1 }, { x: 1, y: 0 }, sy];\n\t\t\t// The points that may land on a target: the handle, and the two ends of its side.\n\t\t\tconst i = RING.indexOf(handle);\n\t\t\tconst ends = corner ? [] : [RING[(i + 1) % 8], RING[(i + 7) % 8]];\n\t\t\t// How far the handle travels per unit of `s`: a snap may not drag it far from the pointer.\n\t\t\tconst travel = Math.hypot(e.x * d0.x, e.y * d0.y);\n\t\t\tlet best: { s: number; inLine: boolean; moved: number; snap: Snap } | null = null;\n\t\t\tconst consider = (s: number, inLine: boolean, found: Snap) => {\n\t\t\t\tconst moved = Math.abs(s - s0) * travel;\n\t\t\t\tif (!valid(s, s0) || moved > 2 * tol) return;\n\t\t\t\tif (!best || (inLine === best.inLine ? moved < best.moved : !inLine)) best = { s, inLine, moved, snap: found };\n\t\t\t};\n\t\t\tfor (const h of [handle, ...ends]) {\n\t\t\t\tconst hv = handlePos(h, frame);\n\t\t\t\tconst v = { x: hv.x - origin.x, y: hv.y - origin.y };\n\t\t\t\tconst base = applyMatrix(toDoc, { x: origin.x + c.x * v.x, y: origin.y + c.y * v.y });\n\t\t\t\tconst dir = applyMatrix(toDoc, { x: e.x * v.x, y: e.y * v.y });\n\t\t\t\tconst p = { x: base.x + dir.x * s0, y: base.y + dir.y * s0 };\n\t\t\t\tconst l2 = dir.x * dir.x + dir.y * dir.y;\n\t\t\t\tconst on = l2 > 1e-18 ? this.nearestPoint(p, tol) : null;\n\t\t\t\t// An anchor or centre beside its way: it stops at the nearest point of the way.\n\t\t\t\tif (on) consider(((on.p.x - base.x) * dir.x + (on.p.y - base.y) * dir.y) / l2, false, { hx: null, hy: null, on });\n\t\t\t\tif (Math.abs(dir.x) > 1e-9) {\n\t\t\t\t\tconst hit = nearest(p.x, this.xs);\n\t\t\t\t\tif (hit) consider((hit.v - base.x) / dir.x, true, { hx: hit, hy: null, on: null });\n\t\t\t\t}\n\t\t\t\tif (Math.abs(dir.y) > 1e-9) {\n\t\t\t\t\tconst hit = nearest(p.y, this.ys);\n\t\t\t\t\tif (hit) consider((hit.v - base.y) / dir.y, true, { hx: null, hy: hit, on: null });\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst found = best as { s: number; snap: Snap } | null;\n\t\t\tif (found) {\n\t\t\t\tnx = c.x + found.s * e.x;\n\t\t\t\tny = c.y + found.s * e.y;\n\t\t\t\tsnap = found.snap;\n\t\t\t}\n\t\t}\n\t\tconst out: VectorScaleSnap = { sx: nx, sy: ny, snapped: false, lines: [], labels: [] };\n\t\tconst handleAt = () => applyMatrix(toDoc, { x: origin.x + d0.x * out.sx, y: origin.y + d0.y * out.sy });\n\t\tif (snap.on) {\n\t\t\tout.snapped = true;\n\t\t\tout.labels.push(this.label(snap.on.p, snap.on.kind));\n\t\t\treturn out;\n\t\t}\n\t\t// Sides that line up with nothing may match another object's width or height.\n\t\tconst movesX = handle !== 'n' && handle !== 's';\n\t\tconst movesY = handle !== 'e' && handle !== 'w';\n\t\tconst sized: ('x' | 'y')[] = [];\n\t\tif (!proportional) {\n\t\t\tif (movesX && !snap.hx && !(frame.angle && snap.hy) && frame.width > 1e-9) {\n\t\t\t\tconst len = this.matchSize(Math.abs(out.sx) * frame.width, tol);\n\t\t\t\tif (len !== null && len > 0) {\n\t\t\t\t\tout.sx = Math.sign(out.sx || 1) * (len / frame.width);\n\t\t\t\t\tsized.push('x');\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (movesY && !snap.hy && !(frame.angle && snap.hx) && frame.height > 1e-9) {\n\t\t\t\tconst len = this.matchSize(Math.abs(out.sy) * frame.height, tol);\n\t\t\t\tif (len !== null && len > 0) {\n\t\t\t\t\tout.sy = Math.sign(out.sy || 1) * (len / frame.height);\n\t\t\t\t\tsized.push('y');\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// The resized box in its frame, and its corners on the page.\n\t\tconst x0 = origin.x + (frame.x - origin.x) * out.sx;\n\t\tconst x1 = origin.x + (frame.x + frame.width - origin.x) * out.sx;\n\t\tconst y0 = origin.y + (frame.y - origin.y) * out.sy;\n\t\tconst y1 = origin.y + (frame.y + frame.height - origin.y) * out.sy;\n\t\tconst box = { x0: Math.min(x0, x1), x1: Math.max(x0, x1), y0: Math.min(y0, y1), y1: Math.max(y0, y1) };\n\t\tconst page = [\n\t\t\t{ x: box.x0, y: box.y0 },\n\t\t\t{ x: box.x1, y: box.y0 },\n\t\t\t{ x: box.x1, y: box.y1 },\n\t\t\t{ x: box.x0, y: box.y1 }\n\t\t].map((q) => applyMatrix(toDoc, q));\n\t\tconst pminY = Math.min(...page.map((q) => q.y));\n\t\tconst pmaxY = Math.max(...page.map((q) => q.y));\n\t\tconst pminX = Math.min(...page.map((q) => q.x));\n\t\tconst pmaxX = Math.max(...page.map((q) => q.x));\n\t\tif (snap.hx) out.lines.push({ kind: 'align', x1: snap.hx.v, y1: Math.min(snap.hx.from.y, pminY), x2: snap.hx.v, y2: Math.max(snap.hx.from.y, pmaxY) });\n\t\tif (snap.hy) out.lines.push({ kind: 'align', x1: Math.min(snap.hy.from.x, pminX), y1: snap.hy.v, x2: Math.max(snap.hy.from.x, pmaxX), y2: snap.hy.v });\n\t\tif (snap.hx || snap.hy) {\n\t\t\tout.snapped = true;\n\t\t\tout.labels.push(this.label(handleAt(), 'align'));\n\t\t}\n\t\tfor (const axis of sized) {\n\t\t\tout.snapped = true;\n\t\t\t// Along the matched side, just outside the box.\n\t\t\tconst off = tol * 2;\n\t\t\tconst [a, b] = axis === 'x' ? [{ x: box.x0, y: box.y1 + off }, { x: box.x1, y: box.y1 + off }] : [{ x: box.x1 + off, y: box.y0 }, { x: box.x1 + off, y: box.y1 }];\n\t\t\tconst pa = applyMatrix(toDoc, a);\n\t\t\tconst pb = applyMatrix(toDoc, b);\n\t\t\tout.lines.push(line('size', pa, pb));\n\t\t\tout.labels.push(this.label({ x: (pa.x + pb.x) / 2, y: (pa.y + pb.y) / 2 }, 'size', `${axis === 'x' ? 'W' : 'H'} ${fmtLength(axis === 'x' ? box.x1 - box.x0 : box.y1 - box.y0)}`));\n\t\t}\n\t\treturn out;\n\t}\n}\n\n/** The eight resize handles clockwise from the top left (each side sits between its two corners). */\nconst RING: readonly Exclude<VectorTransformHandle, 'rotate'>[] = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'];\n\nfunction opposite(h: Exclude<VectorTransformHandle, 'rotate'>): Exclude<VectorTransformHandle, 'rotate'> {\n\treturn RING[(RING.indexOf(h) + 4) % 8];\n}\n\nfunction handlePos(h: Exclude<VectorTransformHandle, 'rotate'>, r: VectorBounds): Vec2 {\n\tconst x = h.includes('w') ? r.x : h.includes('e') ? r.x + r.width : r.x + r.width / 2;\n\tconst y = h.startsWith('n') ? r.y : h.startsWith('s') ? r.y + r.height : r.y + r.height / 2;\n\treturn { x, y };\n}\n\nfunction line(kind: VectorGuideKind, a: Vec2, b: Vec2): VectorGuideLine {\n\treturn { kind, x1: a.x, y1: a.y, x2: b.x, y2: b.y };\n}\n\n/** The construction guide through `leave.at` nearest `p`, within `tol` (and `p` farther than that from `at`): its direction and where `p` lands. */\nfunction construction(leave: VectorSnapLeave, p: Vec2, tol: number): { dir: Vec2; point: Vec2 } | null {\n\tconst v = { x: p.x - leave.at.x, y: p.y - leave.at.y };\n\tif (Math.hypot(v.x, v.y) <= tol) return null;\n\tlet best: { dir: Vec2; point: Vec2; d: number } | null = null;\n\tfor (const a of leave.angles ?? []) {\n\t\t// Counter-clockwise as seen on the y-down page.\n\t\tconst r = (a * Math.PI) / 180;\n\t\t// Exactly along an axis for multiples of 90°.\n\t\tconst exact = (n: number) => (Math.abs(n) < 1e-12 ? 0 : n);\n\t\tconst dir = { x: exact(Math.cos(r)), y: exact(-Math.sin(r)) };\n\t\tconst k = v.x * dir.x + v.y * dir.y;\n\t\tconst point = { x: leave.at.x + dir.x * k, y: leave.at.y + dir.y * k };\n\t\tconst d = distance(point, p);\n\t\tif (d <= tol && (!best || d < best.d)) best = { dir, point, d };\n\t}\n\treturn best && { dir: best.dir, point: best.point };\n}\n\nconst dotCondition = (r: Point, d: Point) => r[0] * d[0] + r[1] * d[1];\nconst crossCondition = (r: Point, d: Point) => r[0] * d[1] - r[1] * d[0];\n\n/**\n * The points of a segment where `cond(B(t) − base, B′(t))` is zero: sign changes of samples,\n * narrowed by bisection, kept when the normalised condition is (nearly) zero there.\n */\nfunction solveOnSegment(seg: readonly Point[], base: Vec2, cond: (r: Point, d: Point) => number): Vec2[] {\n\tconst b: Point = [base.x, base.y];\n\tconst g = (t: number) => {\n\t\tconst p = segmentPoint(seg, t);\n\t\treturn cond([p[0] - b[0], p[1] - b[1]], segmentDerivative(seg, t));\n\t};\n\tconst vals: number[] = [];\n\tlet scale = 0;\n\tfor (let i = 0; i <= CURVE_SAMPLES; i++) {\n\t\tconst t = i / CURVE_SAMPLES;\n\t\tconst p = segmentPoint(seg, t);\n\t\tconst d = segmentDerivative(seg, t);\n\t\tconst r: Point = [p[0] - b[0], p[1] - b[1]];\n\t\tvals.push(cond(r, d));\n\t\tscale = Math.max(scale, Math.hypot(r[0], r[1]) * Math.hypot(d[0], d[1]));\n\t}\n\t// Every point qualifies (a line seen from a point on it): no particular solution.\n\tif (!(scale > 0) || vals.every((v) => Math.abs(v) <= scale * 1e-12)) return [];\n\tconst out: Vec2[] = [];\n\tfor (let i = 0; i < CURVE_SAMPLES; i++) {\n\t\tconst ga = vals[i];\n\t\tconst gb = vals[i + 1];\n\t\tif (!(Number.isFinite(ga) && Number.isFinite(gb)) || (ga > 0 === gb > 0 && ga !== 0)) continue;\n\t\tlet lo = i / CURVE_SAMPLES;\n\t\tlet hi = (i + 1) / CURVE_SAMPLES;\n\t\tlet flo = ga;\n\t\tfor (let k = 0; k < BISECT; k++) {\n\t\t\tconst m = (lo + hi) / 2;\n\t\t\tconst fm = g(m);\n\t\t\tif (fm === 0) {\n\t\t\t\tlo = hi = m;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (fm > 0 === flo > 0) {\n\t\t\t\tlo = m;\n\t\t\t\tflo = fm;\n\t\t\t} else hi = m;\n\t\t}\n\t\tconst t = (lo + hi) / 2;\n\t\tconst p = segmentPoint(seg, t);\n\t\tconst dv = segmentDerivative(seg, t);\n\t\tconst r = Math.hypot(p[0] - b[0], p[1] - b[1]);\n\t\tconst dl = Math.hypot(dv[0], dv[1]);\n\t\tif (!(r > 1e-9 && dl > 0) || Math.abs(cond([p[0] - b[0], p[1] - b[1]], dv)) > 1e-6 * r * dl) continue;\n\t\tif (!out.some((q) => Math.hypot(q.x - p[0], q.y - p[1]) <= 1e-9 * (1 + r))) out.push({ x: p[0], y: p[1] });\n\t}\n\treturn out;\n}\n","/**\n * Path editing on subpaths in a node's own space: anchor deletion that keeps the shape,\n * segment bending, Curvature-tool anchor moves, cutting at anchors (Scissors), Join, Average,\n * Remove Redundant Points and Smooth.\n *\n * Portions ported from (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md):\n * - vectorcraft-main/crates/pathops/src/edit.rs (`remove_anchor`, `golden_min`, `smooth`,\n * `remove_redundant_points`, `merge_pair`, `average`, `join`)\n * - vectorcraft-main/crates/geom/src/path.rs (`SubPath::cut_at`)\n * - vectorcraft-main/crates/tools/src/draw2/curvature.rs (`curvature_move`)\n * - figcraft-main/crates/engine/src/vectoredit/ops.rs (`bend`)\n */\nimport type { Point } from '../canvas/types.js';\nimport { fitCubicWithTangents } from '../canvas/curveFit.js';\nimport { segmentPoint } from '../canvas/pathops/bezier.js';\nimport { cloneAnchor, inferAnchorType, insertAnchor, moveAnchorHandle, subpathSegment, subpathSegmentCount } from './geometry.js';\nimport type { VectorAnchor, VectorSubpath, Vec2 } from './types.js';\n\nconst EPS = 1e-9;\n\n// ---------------------------------------------------------------------------\n// Small helpers\n// ---------------------------------------------------------------------------\n\nconst unit = (x: number, y: number): Point | null => {\n\tconst l = Math.hypot(x, y);\n\treturn l > 1e-12 && Number.isFinite(l) ? [x / l, y / l] : null;\n};\n\n/** Segment `i` as four control points (a line has its controls at the thirds of its chord). */\nfunction cubicOf(sp: VectorSubpath, i: number): Point[] {\n\tconst s = subpathSegment(sp, i);\n\tif (s.length === 4) return s;\n\tconst [a, b] = s;\n\treturn [a, [a[0] + (b[0] - a[0]) / 3, a[1] + (b[1] - a[1]) / 3], [a[0] + (2 * (b[0] - a[0])) / 3, a[1] + (2 * (b[1] - a[1])) / 3], b];\n}\n\nconst isLine = (sp: VectorSubpath, i: number) => subpathSegment(sp, i).length === 2;\n\n/** Direction the curve leaves `c[0]`. */\nfunction startTangent(c: readonly Point[]): Point {\n\tfor (let k = 1; k < 4; k++) {\n\t\tconst u = unit(c[k][0] - c[0][0], c[k][1] - c[0][1]);\n\t\tif (u) return u;\n\t}\n\treturn [1, 0];\n}\n\n/** Direction the curve arrives at `c[3]` (forward along the curve). */\nfunction endTangent(c: readonly Point[]): Point {\n\tfor (let k = 2; k >= 0; k--) {\n\t\tconst u = unit(c[3][0] - c[k][0], c[3][1] - c[k][1]);\n\t\tif (u) return u;\n\t}\n\treturn [1, 0];\n}\n\n/** `n + 1` points of a cubic at even parameters (`withStart` false skips the first). */\nfunction sample(c: readonly Point[], n: number, out: Point[], withStart: boolean) {\n\tfor (let i = withStart ? 0 : 1; i <= n; i++) out.push(segmentPoint(c, i / n));\n}\n\nconst onAnchor = (a: VectorAnchor, h: Vec2 | null | undefined) => !h || (Math.abs(h.x - a.x) < EPS && Math.abs(h.y - a.y) < EPS);\n\n/** Drops handles that sit on their anchor and sets the type the handles show (a symmetric pair that is no longer equal becomes smooth). */\nfunction tidy(a: VectorAnchor, keepType = true): VectorAnchor {\n\tconst next = cloneAnchor(a);\n\tif (onAnchor(next, next.in)) delete next.in;\n\tif (onAnchor(next, next.out)) delete next.out;\n\tconst shown = inferAnchorType(next);\n\tconst type = keepType && a.type ? (a.type === 'symmetric' && shown !== 'symmetric' ? (shown === 'corner' ? 'corner' : 'smooth') : a.type === 'smooth' && shown === 'corner' ? 'corner' : a.type) : shown;\n\tif (type === 'corner') delete next.type;\n\telse next.type = type;\n\treturn next;\n}\n\n/** Index of the anchor before / after `i` (round the start of a closed subpath), or -1. */\nfunction neighbours(sp: VectorSubpath, i: number): [number, number] {\n\tconst n = sp.anchors.length;\n\tconst wrap = sp.closed && n > 1;\n\treturn [i > 0 ? i - 1 : wrap ? n - 1 : -1, i < n - 1 ? i + 1 : wrap ? 0 : -1];\n}\n\n// ---------------------------------------------------------------------------\n// Deleting anchors without changing the shape\n// ---------------------------------------------------------------------------\n\n/**\n * The value of `f` with the least error for an argument in [a, b], by a golden-section search\n * (a fixed number of steps). An error that is not a number never wins.\n */\nfunction goldenMin<T extends { error: number }>(f: (x: number) => T, a: number, b: number): T {\n\tconst R = 0.618033988749895;\n\tlet x1 = b - R * (b - a);\n\tlet x2 = a + R * (b - a);\n\tlet f1 = f(x1);\n\tlet f2 = f(x2);\n\tfor (let i = 0; i < 40; i++) {\n\t\tif (f1.error < f2.error || Number.isNaN(f2.error)) {\n\t\t\tb = x2;\n\t\t\tx2 = x1;\n\t\t\tf2 = f1;\n\t\t\tx1 = b - R * (b - a);\n\t\t\tf1 = f(x1);\n\t\t} else {\n\t\t\ta = x1;\n\t\t\tx1 = x2;\n\t\t\tf1 = f2;\n\t\t\tx2 = a + R * (b - a);\n\t\t\tf2 = f(x2);\n\t\t}\n\t}\n\treturn f1.error <= f2.error ? f1 : f2;\n}\n\n/**\n * One cubic through `pts`: `N + 1` samples of a left curve then `N` of a right one. The new\n * curve passes their joint at some parameter k: the left samples sit at k·i/N, the right ones\n * at k + (1 − k)·i/N. Searches k for the closest fit.\n */\nfunction fitAcross(pts: Point[], N: number, t0: Point, t1: Point) {\n\tconst fit = (k: number) => {\n\t\tconst u: number[] = [];\n\t\tfor (let i = 0; i <= N; i++) u.push((k * i) / N);\n\t\tfor (let i = 1; i <= N; i++) u.push(k + ((1 - k) * i) / N);\n\t\treturn fitCubicWithTangents(pts, u, t0, t1);\n\t};\n\treturn goldenMin(fit, 0, 1);\n}\n\n/**\n * Removes anchor `index` without opening the path: its neighbours keep their handle directions\n * and their facing handles are refitted so one cubic follows the two segments that met there\n * as closely as possible (least maximum error over where the new curve passes the removed\n * point). Two straight segments become one; removing an end of an open subpath drops its\n * segment. Returns the subpath unchanged (a copy) when `index` is out of range.\n */\nexport function removeAnchorKeepingShape(sp: VectorSubpath, index: number): VectorSubpath {\n\tconst anchors = sp.anchors.map(cloneAnchor);\n\tconst n = anchors.length;\n\tif (index < 0 || index >= n) return { anchors, closed: sp.closed };\n\tif ((sp.closed || (index > 0 && index < n - 1)) && n >= 3) {\n\t\tconst pi = (index + n - 1) % n;\n\t\tconst ni = (index + 1) % n;\n\t\tif (!(isLine(sp, pi) && isLine(sp, index))) {\n\t\t\tconst left = cubicOf(sp, pi);\n\t\t\tconst right = cubicOf(sp, index);\n\t\t\tconst N = 16;\n\t\t\tconst pts: Point[] = [];\n\t\t\tsample(left, N, pts, true);\n\t\t\tsample(right, N, pts, false);\n\t\t\tconst t0 = startTangent(left);\n\t\t\tconst t1 = endTangent(right);\n\t\t\tconst { curve } = fitAcross(pts, N, t0, t1);\n\t\t\tif ([curve.p1, curve.p2].every((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]))) {\n\t\t\t\tanchors[pi] = tidy({ ...anchors[pi], out: { x: curve.p1[0], y: curve.p1[1] } });\n\t\t\t\tanchors[ni] = tidy({ ...anchors[ni], in: { x: curve.p2[0], y: curve.p2[1] } });\n\t\t\t}\n\t\t}\n\t}\n\tanchors.splice(index, 1);\n\tlet closed = sp.closed;\n\tif (!closed && anchors.length) {\n\t\t// A new end has nothing beyond it.\n\t\tanchors[0] = tidy({ ...anchors[0], in: null });\n\t\tconst last = anchors.length - 1;\n\t\tanchors[last] = tidy({ ...anchors[last], out: null });\n\t}\n\tif (anchors.length < 3) closed = closed && anchors.length === 2 && anchors.some((a) => a.in || a.out);\n\treturn { anchors, closed };\n}\n\n/** Removes several anchors of a subpath, keeping the shape (see `removeAnchorKeepingShape`). */\nexport function removeAnchorsKeepingShape(sp: VectorSubpath, indices: readonly number[]): VectorSubpath {\n\tconst order = [...new Set(indices)].filter((i) => i >= 0 && i < sp.anchors.length).sort((a, b) => b - a);\n\treturn order.reduce((acc, i) => removeAnchorKeepingShape(acc, i), { anchors: sp.anchors.map(cloneAnchor), closed: sp.closed });\n}\n\n// ---------------------------------------------------------------------------\n// Bending a segment\n// ---------------------------------------------------------------------------\n\n/**\n * Bends segment `segment` so the curve passes through `p` at parameter `t` (clamped to\n * 0.05–0.95): its handles go to the thirds of the chord plus one shared offset, so\n * `B(t) = L(t) + 3t(1 − t)·offset` exactly. The end anchors keep their types (a smooth or\n * symmetric end turns its other handle to stay in line).\n */\nexport function bendSegment(sp: VectorSubpath, segment: number, t: number, p: Vec2): VectorSubpath {\n\tconst anchors = sp.anchors.map(cloneAnchor);\n\tconst n = anchors.length;\n\tif (segment < 0 || segment >= subpathSegmentCount(sp) || !Number.isFinite(t) || !Number.isFinite(p.x) || !Number.isFinite(p.y)) return { anchors, closed: sp.closed };\n\tconst tc = Math.min(0.95, Math.max(0.05, t));\n\tconst ia = segment;\n\tconst ib = (segment + 1) % n;\n\tconst a = anchors[ia];\n\tconst b = anchors[ib];\n\tconst k = 3 * tc * (1 - tc);\n\tconst ox = (p.x - (a.x + (b.x - a.x) * tc)) / k;\n\tconst oy = (p.y - (a.y + (b.y - a.y) * tc)) / k;\n\tconst c1 = { x: a.x + (b.x - a.x) / 3 + ox, y: a.y + (b.y - a.y) / 3 + oy };\n\tconst c2 = { x: b.x + (a.x - b.x) / 3 + ox, y: b.y + (a.y - b.y) / 3 + oy };\n\tanchors[ia] = moveAnchorHandle(a, 'out', c1);\n\tanchors[ib] = moveAnchorHandle(b, 'in', c2);\n\treturn { anchors, closed: sp.closed };\n}\n\n/** The point at parameter `t` of segment `segment` (for tests and previews). */\nexport function subpathPointAt(sp: VectorSubpath, segment: number, t: number): Vec2 {\n\tconst [x, y] = segmentPoint(subpathSegment(sp, segment), t);\n\treturn { x, y };\n}\n\n// ---------------------------------------------------------------------------\n// Curvature-tool anchor move\n// ---------------------------------------------------------------------------\n\n/**\n * Moves anchor `index` to `q` the way the Curvature tool drags a point: only the two segments\n * at it change. A smooth or symmetric anchor turns its handles along the line through its\n * neighbours; the neighbours' handles on those segments, and a corner's own handles, keep\n * their directions while their lengths scale with their segment's chord, so the segments\n * beyond don't move and a corner without handles keeps none.\n */\nexport function curvatureMoveAnchor(sp: VectorSubpath, index: number, q: Vec2): VectorSubpath {\n\tconst anchors = sp.anchors.map(cloneAnchor);\n\tconst a = sp.anchors[index];\n\tif (!a) return { anchors, closed: sp.closed };\n\tconst own: [Vec2 | null, Vec2 | null] = [\n\t\ta.in && !onAnchor(a, a.in) ? { x: a.in.x - a.x, y: a.in.y - a.y } : null,\n\t\ta.out && !onAnchor(a, a.out) ? { x: a.out.x - a.x, y: a.out.y - a.y } : null\n\t];\n\tconst ends: [Vec2 | null, Vec2 | null] = [null, null];\n\tneighbours(sp, index).forEach((j, side) => {\n\t\tif (j < 0 || j === index) return;\n\t\tconst b = anchors[j];\n\t\tconst old = Math.hypot(a.x - b.x, a.y - b.y);\n\t\tconst s = old > 1e-9 ? Math.hypot(q.x - b.x, q.y - b.y) / old : 1;\n\t\tconst key = side === 0 ? 'out' : 'in';\n\t\tconst h = b[key];\n\t\tif (h) b[key] = { x: b.x + (h.x - b.x) * s, y: b.y + (h.y - b.y) * s };\n\t\tconst o = own[side];\n\t\tif (o) own[side] = { x: o.x * s, y: o.y * s };\n\t\tends[side] = { x: b.x, y: b.y };\n\t});\n\tconst moved: VectorAnchor = { x: q.x, y: q.y };\n\tif (own[0]) moved.in = { x: q.x + own[0].x, y: q.y + own[0].y };\n\tif (own[1]) moved.out = { x: q.x + own[1].x, y: q.y + own[1].y };\n\tif (a.type) moved.type = a.type;\n\tif (a.corner) moved.corner = { ...a.corner };\n\tconst [prev, next] = ends;\n\tif (a.type && a.type !== 'corner' && prev && next) {\n\t\tconst dx = next.x - prev.x;\n\t\tconst dy = next.y - prev.y;\n\t\tconst l = Math.hypot(dx, dy);\n\t\tif (l > 1e-9) {\n\t\t\t// A handle it lacks comes out a third of the way to that side's neighbour.\n\t\t\tconst len = (h: Vec2 | null, to: Vec2) => (h ? Math.hypot(h.x, h.y) : Math.hypot(q.x - to.x, q.y - to.y) / 3);\n\t\t\tlet li = len(own[0], prev);\n\t\t\tlet lo = len(own[1], next);\n\t\t\tif (a.type === 'symmetric') li = lo = (li + lo) / 2;\n\t\t\tmoved.in = { x: q.x - (dx * li) / l, y: q.y - (dy * li) / l };\n\t\t\tmoved.out = { x: q.x + (dx * lo) / l, y: q.y + (dy * lo) / l };\n\t\t}\n\t}\n\tanchors[index] = moved;\n\treturn { anchors, closed: sp.closed };\n}\n\n// ---------------------------------------------------------------------------\n// Scissors\n// ---------------------------------------------------------------------------\n\n/**\n * Cuts a subpath at the anchors `at`: each becomes the end of one open piece and the start of\n * the next, its handle off each piece dropped (the shape doesn't change). A closed subpath\n * opens at its first cut, so one cut leaves one piece whose ends coincide. The ends of an open\n * subpath and indices out of range don't cut; with no cut left the subpath comes back as it is.\n */\nexport function cutSubpathAt(sp: VectorSubpath, at: readonly number[]): VectorSubpath[] {\n\tconst n = sp.anchors.length;\n\tconst cuts = [...new Set(at)].filter((i) => Number.isInteger(i) && i >= 0 && i < n && (sp.closed || (i > 0 && i < n - 1))).sort((a, b) => a - b);\n\tif (!cuts.length || n < 2) return [{ anchors: sp.anchors.map(cloneAnchor), closed: sp.closed }];\n\tconst first = cuts[0];\n\t// A closed subpath's anchors from the first cut round to it again; an open one's as they are.\n\tconst run = sp.closed ? Array.from({ length: n + 1 }, (_, i) => sp.anchors[(first + i) % n]) : sp.anchors;\n\tconst cutSet = new Set(sp.closed ? [...cuts.map((c) => (c - first + n) % n), n] : cuts);\n\tconst pieces: VectorSubpath[] = [];\n\tlet cur: VectorAnchor[] = [];\n\trun.forEach((a, i) => {\n\t\tif (!cutSet.has(i)) {\n\t\t\tcur.push(cloneAnchor(a));\n\t\t\treturn;\n\t\t}\n\t\tif (cur.length) {\n\t\t\tcur.push(tidy({ ...a, out: null }, false));\n\t\t\tpieces.push({ anchors: cur, closed: false });\n\t\t\tcur = [];\n\t\t}\n\t\tif (i < n) cur.push(tidy({ ...a, in: null }, false));\n\t});\n\tif (cur.length > 1) pieces.push({ anchors: cur, closed: false });\n\treturn pieces;\n}\n\n/**\n * Cuts a subpath at parameter `t` of segment `segment` (Scissors on a segment): an anchor is\n * inserted there without changing the shape, then cut. Within `endTolerance` of the segment's\n * ends (in parameter) the existing anchor is cut instead.\n */\nexport function splitSubpathAt(sp: VectorSubpath, segment: number, t: number, endTolerance = 1e-6): VectorSubpath[] {\n\tconst n = sp.anchors.length;\n\tif (segment < 0 || segment >= subpathSegmentCount(sp)) return [{ anchors: sp.anchors.map(cloneAnchor), closed: sp.closed }];\n\tif (t <= endTolerance) return cutSubpathAt(sp, [segment]);\n\tif (t >= 1 - endTolerance) return cutSubpathAt(sp, [(segment + 1) % n]);\n\tconst { subpath, index } = insertAnchor(sp, segment, t);\n\treturn cutSubpathAt(subpath, [index]);\n}\n\n// ---------------------------------------------------------------------------\n// Join\n// ---------------------------------------------------------------------------\n\nconst endOf = (sp: VectorSubpath, last: boolean): VectorAnchor => sp.anchors[last ? sp.anchors.length - 1 : 0];\nconst dist = (a: Vec2, b: Vec2) => Math.hypot(a.x - b.x, a.y - b.y);\n\nfunction reverse(sp: VectorSubpath): VectorSubpath {\n\treturn {\n\t\tclosed: sp.closed,\n\t\tanchors: sp.anchors\n\t\t\t.slice()\n\t\t\t.reverse()\n\t\t\t.map((a) => {\n\t\t\t\tconst next: VectorAnchor = { x: a.x, y: a.y };\n\t\t\t\tif (a.out) next.in = { ...a.out };\n\t\t\t\tif (a.in) next.out = { ...a.in };\n\t\t\t\tif (a.type) next.type = a.type;\n\t\t\t\tif (a.corner) next.corner = { ...a.corner };\n\t\t\t\treturn next;\n\t\t\t})\n\t};\n}\n\n/**\n * Join: open subpaths are joined nearest-endpoints-first into one open subpath (endpoints\n * within `tolerance` merge into one anchor, otherwise a straight segment connects them). A\n * single open subpath is closed instead (its ends merged when they meet). Closed subpaths and\n * lone anchors pass through unchanged, before the joined one.\n */\nexport function joinSubpaths(subpaths: readonly VectorSubpath[], tolerance: number): VectorSubpath[] {\n\tconst closed: VectorSubpath[] = [];\n\tlet open: VectorSubpath[] = [];\n\tfor (const sp of subpaths) {\n\t\tconst copy = { anchors: sp.anchors.map(cloneAnchor), closed: sp.closed };\n\t\tif (sp.closed || sp.anchors.length < 2) {\n\t\t\tif (sp.anchors.length) closed.push(copy);\n\t\t} else open.push(copy);\n\t}\n\tif (open.length === 1) {\n\t\tconst sp = open[0];\n\t\tconst first = sp.anchors[0];\n\t\tconst last = sp.anchors[sp.anchors.length - 1];\n\t\tif (sp.anchors.length > 2 && dist(first, last) <= tolerance) {\n\t\t\tsp.anchors.pop();\n\t\t\tsp.anchors[0] = tidy({ ...first, in: last.in ?? null }, false);\n\t\t} else {\n\t\t\tsp.anchors[0] = tidy({ ...first, in: null }, false);\n\t\t\tsp.anchors[sp.anchors.length - 1] = tidy({ ...sp.anchors[sp.anchors.length - 1], out: null }, false);\n\t\t}\n\t\tsp.closed = true;\n\t\treturn [...closed, sp];\n\t}\n\twhile (open.length > 1) {\n\t\t// The closest pair of endpoints on different subpaths.\n\t\tlet best = { d: Infinity, i: 0, j: 1, ei: true, ej: false };\n\t\tfor (let i = 0; i < open.length; i++) {\n\t\t\tfor (let j = i + 1; j < open.length; j++) {\n\t\t\t\tfor (const ei of [false, true]) {\n\t\t\t\t\tfor (const ej of [false, true]) {\n\t\t\t\t\t\tconst d = dist(endOf(open[i], ei), endOf(open[j], ej));\n\t\t\t\t\t\tif (d < best.d) best = { d, i, j, ei, ej };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tlet a = open[best.i];\n\t\tlet b = open[best.j];\n\t\topen = open.filter((_, k) => k !== best.j);\n\t\t// `a` ends at the meeting point, `b` starts there.\n\t\tif (!best.ei) a = reverse(a);\n\t\tif (best.ej) b = reverse(b);\n\t\tconst anchors = a.anchors;\n\t\tif (best.d <= tolerance) {\n\t\t\tconst [head, ...rest] = b.anchors;\n\t\t\tconst l = anchors[anchors.length - 1];\n\t\t\tanchors[anchors.length - 1] = tidy({ ...l, out: head.out ?? null }, false);\n\t\t\tanchors.push(...rest);\n\t\t} else {\n\t\t\tconst l = anchors[anchors.length - 1];\n\t\t\tanchors[anchors.length - 1] = tidy({ ...l, out: null }, false);\n\t\t\tanchors.push(tidy({ ...b.anchors[0], in: null }, false), ...b.anchors.slice(1));\n\t\t}\n\t\topen[best.i > best.j ? best.i - 1 : best.i] = { anchors, closed: false };\n\t}\n\treturn [...closed, ...open];\n}\n\n// ---------------------------------------------------------------------------\n// Smooth and Remove Redundant Points\n// ---------------------------------------------------------------------------\n\n/**\n * Smooth: pulls handles towards Catmull-Rom-like tangents (a third of the way to each\n * neighbour along the line through both). `amount` 0–1 (0 = unchanged, 1 = fully smooth).\n * Only the anchors in `only` change when it is given; endpoints of open subpaths keep their\n * handles. Subpaths of fewer than three anchors are unchanged.\n */\nexport function smoothSubpath(sp: VectorSubpath, amount = 1, only?: ReadonlySet<number>): VectorSubpath {\n\tconst t = Math.min(1, Math.max(0, amount));\n\tconst orig = sp.anchors;\n\tconst n = orig.length;\n\tconst anchors = orig.map(cloneAnchor);\n\tif (n < 3 || t === 0) return { anchors, closed: sp.closed };\n\tfor (let i = 0; i < n; i++) {\n\t\tif (!sp.closed && (i === 0 || i === n - 1)) continue;\n\t\tif (only && !only.has(i)) continue;\n\t\tconst prev = orig[(i + n - 1) % n];\n\t\tconst next = orig[(i + 1) % n];\n\t\tconst p = orig[i];\n\t\tconst dir = unit(next.x - prev.x, next.y - prev.y);\n\t\tif (!dir) continue;\n\t\tconst li = dist(p, prev) / 3;\n\t\tconst lo = dist(p, next) / 3;\n\t\tconst hin = p.in ?? p;\n\t\tconst hout = p.out ?? p;\n\t\tconst target = (h: Vec2, x: number, y: number) => ({ x: h.x + (x - h.x) * t, y: h.y + (y - h.y) * t });\n\t\tanchors[i] = tidy(\n\t\t\t{\n\t\t\t\tx: p.x,\n\t\t\t\ty: p.y,\n\t\t\t\tin: target(hin, p.x - dir[0] * li, p.y - dir[1] * li),\n\t\t\t\tout: target(hout, p.x + dir[0] * lo, p.y + dir[1] * lo)\n\t\t\t},\n\t\t\tfalse\n\t\t);\n\t}\n\treturn { anchors, closed: sp.closed };\n}\n\ninterface Seg {\n\tc: Point[];\n\tline: boolean;\n}\n\nfunction segsOf(sp: VectorSubpath): Seg[] {\n\tconst out: Seg[] = [];\n\tfor (let i = 0; i < subpathSegmentCount(sp); i++) {\n\t\tconst s = subpathSegment(sp, i);\n\t\tout.push(s.length === 2 ? { c: s, line: true } : { c: s, line: false });\n\t}\n\treturn out;\n}\n\n/** A subpath from consecutive segments (anchor types inferred; original types kept where they still hold). */\nfunction segsToSubpath(segs: readonly Seg[], closed: boolean, types: Map<string, VectorAnchor['type']>): VectorSubpath | null {\n\tif (!segs.length) return null;\n\tconst anchors: VectorAnchor[] = [];\n\tconst at = (p: Point): VectorAnchor => ({ x: p[0], y: p[1] });\n\tanchors.push(at(segs[0].c[0]));\n\tfor (const s of segs) {\n\t\tconst end = s.c[s.c.length - 1];\n\t\tif (!s.line) anchors[anchors.length - 1].out = { x: s.c[1][0], y: s.c[1][1] };\n\t\tconst next = at(end);\n\t\tif (!s.line) next.in = { x: s.c[2][0], y: s.c[2][1] };\n\t\tanchors.push(next);\n\t}\n\tif (closed) {\n\t\tconst last = anchors.pop()!;\n\t\tif (last.in) anchors[0].in = last.in;\n\t}\n\tconst typed = anchors.map((a) => {\n\t\tconst type = types.get(`${a.x},${a.y}`);\n\t\treturn tidy(type ? { ...a, type } : a, !!type);\n\t});\n\treturn { anchors: typed, closed };\n}\n\nconst isZeroSeg = (s: Seg) => s.c.every((p) => Math.abs(p[0] - s.c[0][0]) < 1e-9 && Math.abs(p[1] - s.c[0][1]) < 1e-9);\n\n/** One segment replacing `a` then `b` within `tol`, or null. */\nfunction mergePair(a: Seg, b: Seg, tol: number): Seg | null {\n\tconst a0 = a.c[0];\n\tconst a3 = a.c[a.c.length - 1];\n\tconst b3 = b.c[b.c.length - 1];\n\tif (a.line && b.line) {\n\t\tconst cx = b3[0] - a0[0];\n\t\tconst cy = b3[1] - a0[1];\n\t\tconst len = Math.hypot(cx, cy);\n\t\tif (len < 1e-12) return null;\n\t\tconst mx = a3[0] - a0[0];\n\t\tconst my = a3[1] - a0[1];\n\t\tconst along = (mx * cx + my * cy) / len;\n\t\treturn Math.abs((mx * cy - my * cx) / len) <= tol && along >= 0 && along <= len ? { c: [a0, b3], line: true } : null;\n\t}\n\tconst ca = a.line ? [a0, a0, a3, a3] : a.c;\n\tconst cb = b.line ? [a3, a3, b3, b3] : b.c;\n\tconst ta = endTangent(ca);\n\tconst tb = startTangent(cb);\n\t// Only merge across (near-)smooth joints.\n\tif (ta[0] * tb[0] + ta[1] * tb[1] < 0.99) return null;\n\tconst pts: Point[] = [];\n\tsample(ca, 16, pts, true);\n\tsample(cb, 16, pts, false);\n\tconst { curve, error } = fitAcross(pts, 16, startTangent(ca), endTangent(cb));\n\treturn error <= tol ? { c: [curve.p0, curve.p1, curve.p2, curve.p3], line: false } : null;\n}\n\n/**\n * Remove Redundant Points: drops anchors that can go without changing the shape by more than\n * `tolerance` (collinear corners, duplicate points, and smooth joints that one cubic can\n * replace).\n */\nexport function removeRedundantPoints(sp: VectorSubpath, tolerance: number): VectorSubpath {\n\tconst tol = Math.max(tolerance, 1e-9);\n\tconst types = new Map(sp.anchors.filter((a) => a.type).map((a) => [`${a.x},${a.y}`, a.type] as const));\n\tconst segs = segsOf(sp).filter((s) => !isZeroSeg(s));\n\tif (!segs.length) return { anchors: sp.anchors.map(cloneAnchor), closed: sp.closed };\n\tconst minSegs = sp.closed ? 2 : 1;\n\tlet changed = true;\n\twhile (changed && segs.length > minSegs) {\n\t\tchanged = false;\n\t\tconst n = segs.length;\n\t\tconst joints = sp.closed ? n : n - 1;\n\t\tfor (let j = 0; j < joints; j++) {\n\t\t\tconst [i0, i1] = sp.closed ? [(j + n - 1) % n, j] : [j, j + 1];\n\t\t\tconst m = mergePair(segs[i0], segs[i1], tol);\n\t\t\tif (!m) continue;\n\t\t\tsegs[i0] = m;\n\t\t\tsegs.splice(i1, 1);\n\t\t\t// The merged segment now starts the loop.\n\t\t\tif (sp.closed && i1 === 0) segs.unshift(segs.pop()!);\n\t\t\tchanged = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn segsToSubpath(segs, sp.closed, types) ?? { anchors: sp.anchors.map(cloneAnchor), closed: sp.closed };\n}\n","/**\n * Knife and eraser on Bézier paths, built on the curve booleans and `outlineStroke`.\n *\n * The knife cuts filled regions along a polyline with no gap: each stretch of the polyline\n * that crosses a region from boundary to boundary (a chord) splits the boundary loop it starts\n * and ends on into two loops sharing that chord, or, when it joins two loops (an outline and a\n * hole), merges them into one. Crossings are exact (line–cubic roots), and the pieces share\n * the cut edge exactly.\n *\n * The eraser removes the area of a round-capped stroke along a polyline: filled shapes lose it\n * by a boolean difference; outlines are cut where they cross the stroke's outline (exact\n * curve–curve intersections) and keep the parts outside it.\n *\n * Modelled on vectorcraft-main/crates/engine/src/cmd/draw2.rs (`knife`, `erase_region`,\n * `erase_outline`, `cut_subpath`; MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md), without its fixed knife slit and its sampled crossing search.\n */\nimport type { Point } from '../canvas/types.js';\nimport {\n\tbezierPathBounds,\n\tcloseContour,\n\tcontourSignedArea,\n\tcontoursToPath,\n\tpathToContours,\n\tpointInBezierPath,\n\tsegmentBounds,\n\tsegmentPoint,\n\tsubSegment,\n\twindingNumber,\n\ttype BezierPath,\n\ttype BezierPathInput\n} from '../canvas/pathops/bezier.js';\nimport { normalizeBezierPath, pathBoolean, segmentIntersections } from '../canvas/pathops/boolean.js';\nimport { outlineStroke } from '../canvas/pathops/stroke.js';\nimport { inferAnchorType, subpathSegment, subpathSegmentCount } from './geometry.js';\nimport type { VectorAnchor, VectorSubpath } from './types.js';\n\ntype FillRule = 'nonzero' | 'evenodd';\n\n// ---------------------------------------------------------------------------\n// Faces: an outer loop with its holes\n// ---------------------------------------------------------------------------\n\ninterface Loop {\n\tsegs: Point[][];\n\t/** Which segments came from a knife chord (not sampled for containment). */\n\tchord: boolean[];\n}\n\ninterface Face {\n\tloops: Loop[];\n}\n\nconst loopArea = (l: Loop) => contourSignedArea(l.segs);\n\n/** A point on the loop that is not on a chord (chords are shared with a neighbouring piece). */\nfunction loopSample(l: Loop): Point {\n\tconst k = l.chord.findIndex((c) => !c);\n\treturn segmentPoint(l.segs[k >= 0 ? k : 0], 0.5);\n}\n\nconst contains = (l: Loop, p: Point) => windingNumber([l.segs], p) !== 0;\n\n/**\n * Groups non-crossing loops into faces: loops turning like the largest one are outlines, the\n * others holes of the smallest outline around them.\n */\nfunction groupFaces(loops: Loop[]): Face[] {\n\tconst usable = loops.filter((l) => l.segs.length && Math.abs(loopArea(l)) > 1e-12);\n\tif (!usable.length) return [];\n\tconst largest = usable.reduce((a, b) => (Math.abs(loopArea(b)) > Math.abs(loopArea(a)) ? b : a));\n\tconst sign = Math.sign(loopArea(largest));\n\tconst outers = usable.filter((l) => Math.sign(loopArea(l)) === sign).sort((a, b) => Math.abs(loopArea(a)) - Math.abs(loopArea(b)));\n\tconst faces = new Map<Loop, Face>(outers.map((o) => [o, { loops: [o] }]));\n\tfor (const hole of usable.filter((l) => Math.sign(loopArea(l)) !== sign)) {\n\t\tconst p = loopSample(hole);\n\t\tconst parent = outers.find((o) => Math.abs(loopArea(o)) > Math.abs(loopArea(hole)) && contains(o, p));\n\t\tif (parent) faces.get(parent)!.loops.push(hole);\n\t}\n\treturn outers.reverse().map((o) => faces.get(o)!);\n}\n\nfunction faceToPath(face: Face): BezierPath {\n\treturn contoursToPath(face.loops.map((l) => ({ segments: l.segs, closed: true })));\n}\n\n/** Simple, consistently oriented faces of a filled path. */\nfunction facesOf(path: BezierPathInput, fillRule: FillRule): Face[] {\n\tconst normalized = normalizeBezierPath(path, fillRule);\n\tconst loops = pathToContours(normalized).map((c) => {\n\t\tconst segs = closeContour(c, true).map((s) => s.slice());\n\t\treturn { segs, chord: segs.map(() => false) };\n\t});\n\treturn groupFaces(loops);\n}\n\n/** One path per face (an outline with its holes) of a filled path, largest first. */\nexport function splitIntoFaces(path: BezierPathInput, fillRule: FillRule = 'nonzero'): BezierPath[] {\n\treturn facesOf(path, fillRule).map(faceToPath);\n}\n\n// ---------------------------------------------------------------------------\n// Line × segment crossings\n// ---------------------------------------------------------------------------\n\n/** Real roots in [0, 1] of `a·t³ + b·t² + c·t + d` (monotone pieces, bisection). */\nfunction rootsInUnit(a: number, b: number, c: number, d: number, scale: number): number[] {\n\tconst f = (t: number) => ((a * t + b) * t + c) * t + d;\n\tconst tol = 1e-12 * Math.max(1, scale);\n\t// Critical points split [0, 1] into monotone pieces.\n\tconst cuts = [0];\n\tconst qa = 3 * a;\n\tconst qb = 2 * b;\n\tif (Math.abs(qa) > 1e-18) {\n\t\tconst disc = qb * qb - 4 * qa * c;\n\t\tif (disc >= 0) {\n\t\t\tconst r = Math.sqrt(disc);\n\t\t\tfor (const t of [(-qb - r) / (2 * qa), (-qb + r) / (2 * qa)].sort((x, y) => x - y)) if (t > 0 && t < 1) cuts.push(t);\n\t\t}\n\t} else if (Math.abs(qb) > 1e-18) {\n\t\tconst t = -c / qb;\n\t\tif (t > 0 && t < 1) cuts.push(t);\n\t}\n\tcuts.push(1);\n\tconst roots: number[] = [];\n\tconst push = (t: number) => {\n\t\tif (!roots.some((r) => Math.abs(r - t) < 1e-9)) roots.push(t);\n\t};\n\tfor (let i = 0; i < cuts.length - 1; i++) {\n\t\tlet lo = cuts[i];\n\t\tlet hi = cuts[i + 1];\n\t\tlet flo = f(lo);\n\t\tconst fhi = f(hi);\n\t\tif (Math.abs(flo) <= tol) push(lo);\n\t\tif (Math.abs(fhi) <= tol) push(hi);\n\t\tif (flo * fhi >= 0) continue;\n\t\tfor (let k = 0; k < 80; k++) {\n\t\t\tconst m = (lo + hi) / 2;\n\t\t\tconst fm = f(m);\n\t\t\tif (fm === 0) {\n\t\t\t\tlo = hi = m;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (fm * flo < 0) hi = m;\n\t\t\telse {\n\t\t\t\tlo = m;\n\t\t\t\tflo = fm;\n\t\t\t}\n\t\t}\n\t\tpush((lo + hi) / 2);\n\t}\n\treturn roots.sort((x, y) => x - y);\n}\n\n/** Where the line `p → q` crosses a segment: `s` on the line (0–1), `t` on the segment. Parallel overlaps are not crossings. */\nfunction lineHits(p: Point, q: Point, seg: readonly Point[]): { s: number; t: number; point: Point }[] {\n\tconst dx = q[0] - p[0];\n\tconst dy = q[1] - p[1];\n\tconst len2 = dx * dx + dy * dy;\n\tif (len2 < 1e-24) return [];\n\t// Signed distance (times |d|) of the segment from the line, as a polynomial in t.\n\tconst h = (pt: Point) => (pt[0] - p[0]) * -dy + (pt[1] - p[1]) * dx;\n\tlet coeffs: [number, number, number, number];\n\tif (seg.length === 2) coeffs = [0, 0, h(seg[1]) - h(seg[0]), h(seg[0])];\n\telse {\n\t\tconst [h0, h1, h2, h3] = seg.map(h);\n\t\tcoeffs = [-h0 + 3 * h1 - 3 * h2 + h3, 3 * h0 - 6 * h1 + 3 * h2, -3 * h0 + 3 * h1, h0];\n\t}\n\tif (coeffs.every((c) => Math.abs(c) < 1e-12 * Math.max(1, len2))) return [];\n\tconst scale = Math.sqrt(len2) * Math.max(1, ...seg.map((pt) => Math.abs(pt[0]) + Math.abs(pt[1])));\n\tconst out: { s: number; t: number; point: Point }[] = [];\n\tfor (const t of rootsInUnit(...coeffs, scale)) {\n\t\tconst point = segmentPoint(seg, t);\n\t\tconst s = ((point[0] - p[0]) * dx + (point[1] - p[1]) * dy) / len2;\n\t\tif (s >= -1e-9 && s <= 1 + 1e-9) out.push({ s: Math.min(1, Math.max(0, s)), t, point });\n\t}\n\treturn out;\n}\n\n// ---------------------------------------------------------------------------\n// Knife\n// ---------------------------------------------------------------------------\n\ninterface Hit {\n\t/** Knife position: segment index + parameter. */\n\ts: number;\n\tloop: number;\n\tseg: number;\n\tt: number;\n\tpoint: Point;\n}\n\nconst near = (a: Point, b: Point, eps: number) => Math.abs(a[0] - b[0]) <= eps && Math.abs(a[1] - b[1]) <= eps;\nconst degenerate = (seg: readonly Point[], eps: number) => seg.every((p) => near(p, seg[0], eps));\n\n/** The loop's pieces from (seg a, t a) forward to (seg b, t b); `full` goes all the way round when they coincide. */\nfunction arc(l: Loop, a: { seg: number; t: number }, b: { seg: number; t: number }, eps: number): { segs: Point[][]; chord: boolean[] } {\n\tconst n = l.segs.length;\n\tconst segs: Point[][] = [];\n\tconst chord: boolean[] = [];\n\tconst push = (k: number, t0: number, t1: number) => {\n\t\tconst piece = t0 <= 0 && t1 >= 1 ? l.segs[k].slice() : subSegment(l.segs[k], t0, t1);\n\t\tif (!degenerate(piece, eps)) {\n\t\t\tsegs.push(piece);\n\t\t\tchord.push(l.chord[k]);\n\t\t}\n\t};\n\tif (a.seg === b.seg && b.t >= a.t + 1e-12) {\n\t\tpush(a.seg, a.t, b.t);\n\t\treturn { segs, chord };\n\t}\n\tpush(a.seg, a.t, 1);\n\tfor (let k = (a.seg + 1) % n; k !== b.seg; k = (k + 1) % n) push(k, 0, 1);\n\tpush(b.seg, 0, b.t);\n\treturn { segs, chord };\n}\n\n/** Line segments through `points`. */\nfunction polySegs(points: readonly Point[], eps: number): Point[][] {\n\tconst out: Point[][] = [];\n\tfor (let i = 1; i < points.length; i++) if (!near(points[i - 1], points[i], eps)) out.push([points[i - 1], points[i]]);\n\treturn out;\n}\n\n/**\n * Cuts the filled path along the open polyline `knife`. Returns one path per resulting face\n * (an outline with its holes), or null when the knife crossed nothing from edge to edge. A\n * stretch of the knife that starts or ends inside the shape does not cut.\n */\nexport function knifePath(path: BezierPathInput, fillRule: FillRule, knife: readonly Point[]): BezierPath[] | null {\n\tconst pts = knife.filter((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]));\n\tif (pts.length < 2) return null;\n\tlet faces = facesOf(path, fillRule);\n\tif (!faces.length) return null;\n\tconst b = bezierPathBounds(path);\n\tconst size = b ? Math.max(b.maxX - b.minX, b.maxY - b.minY, 1) : 1;\n\tconst eps = size * 1e-9;\n\tlet cursor = -Infinity;\n\tlet cuts = 0;\n\tfor (let guard = 0; guard < 512; guard++) {\n\t\tlet best: { face: number; from: Hit; to: Hit } | null = null;\n\t\tfaces.forEach((face, fi) => {\n\t\t\tconst hits: Hit[] = [];\n\t\t\tfor (let m = 0; m < pts.length - 1; m++) {\n\t\t\t\tif (m + 1 < cursor - 1e-9) continue;\n\t\t\t\tconst kb = { minX: Math.min(pts[m][0], pts[m + 1][0]), maxX: Math.max(pts[m][0], pts[m + 1][0]), minY: Math.min(pts[m][1], pts[m + 1][1]), maxY: Math.max(pts[m][1], pts[m + 1][1]) };\n\t\t\t\tface.loops.forEach((l, li) =>\n\t\t\t\t\tl.segs.forEach((seg, si) => {\n\t\t\t\t\t\tconst sb = segmentBounds(seg);\n\t\t\t\t\t\tif (sb.maxX < kb.minX - eps || sb.minX > kb.maxX + eps || sb.maxY < kb.minY - eps || sb.minY > kb.maxY + eps) return;\n\t\t\t\t\t\tfor (const h of lineHits(pts[m], pts[m + 1], seg)) {\n\t\t\t\t\t\t\tconst s = m + h.s;\n\t\t\t\t\t\t\tif (s >= cursor - 1e-9) hits.push({ s, loop: li, seg: si, t: h.t, point: h.point });\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\t}\n\t\t\thits.sort((x, y) => x.s - y.s);\n\t\t\tconst unique = hits.filter((h, i) => i === 0 || h.s - hits[i - 1].s > 1e-9 || !near(h.point, hits[i - 1].point, eps * 10));\n\t\t\tconst inside = (s: number) => {\n\t\t\t\tconst m = Math.min(pts.length - 2, Math.floor(s));\n\t\t\t\tconst u = s - m;\n\t\t\t\tconst q: Point = [pts[m][0] + (pts[m + 1][0] - pts[m][0]) * u, pts[m][1] + (pts[m + 1][1] - pts[m][1]) * u];\n\t\t\t\treturn windingNumber(face.loops.map((l) => l.segs), q) !== 0;\n\t\t\t};\n\t\t\tfor (let i = 0; i < unique.length - 1; i++) {\n\t\t\t\tconst from = unique[i];\n\t\t\t\tconst to = unique[i + 1];\n\t\t\t\tif (near(from.point, to.point, eps * 10) || !inside((from.s + to.s) / 2)) continue;\n\t\t\t\tif (!best || from.s < best.from.s) best = { face: fi, from, to };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t\tif (!best) break;\n\t\tconst { face: fi, from, to } = best as { face: number; from: Hit; to: Hit };\n\t\tconst face = faces[fi];\n\t\t// The chord: the crossing points with the knife's corners between them.\n\t\tconst corners: Point[] = [from.point];\n\t\tfor (let m = Math.floor(from.s) + 1; m <= to.s - 1e-12 && m < pts.length; m++) if (m > from.s) corners.push(pts[m]);\n\t\tcorners.push(to.point);\n\t\tconst forward = polySegs(corners, eps);\n\t\tconst back = polySegs(corners.slice().reverse(), eps);\n\t\tconst la = face.loops[from.loop];\n\t\tconst loops = face.loops.filter((_, i) => i !== from.loop && i !== to.loop);\n\t\tif (from.loop === to.loop) {\n\t\t\tconst ab = arc(la, from, to, eps);\n\t\t\tconst ba = arc(la, to, from, eps);\n\t\t\tloops.push(\n\t\t\t\t{ segs: [...ab.segs, ...back], chord: [...ab.chord, ...back.map(() => true)] },\n\t\t\t\t{ segs: [...ba.segs, ...forward], chord: [...ba.chord, ...forward.map(() => true)] }\n\t\t\t);\n\t\t} else {\n\t\t\t// The chord joins two loops into one, with the chord on both sides of a zero-width slit.\n\t\t\tconst lb = face.loops[to.loop];\n\t\t\tconst roundA = arc(la, from, from, eps);\n\t\t\tconst roundB = arc(lb, to, to, eps);\n\t\t\tloops.push({\n\t\t\t\tsegs: [...roundA.segs, ...forward, ...roundB.segs, ...back],\n\t\t\t\tchord: [...roundA.chord, ...forward.map(() => true), ...roundB.chord, ...back.map(() => true)]\n\t\t\t});\n\t\t}\n\t\tfaces = [...faces.slice(0, fi), ...groupFaces(loops), ...faces.slice(fi + 1)];\n\t\tcursor = to.s;\n\t\tcuts++;\n\t}\n\treturn cuts ? faces.map(faceToPath) : null;\n}\n\n// ---------------------------------------------------------------------------\n// Eraser\n// ---------------------------------------------------------------------------\n\n/** The area a round eraser of diameter `width` covers along `points` (a disc for one point). */\nexport function eraserRegion(points: readonly Point[], width: number): BezierPath {\n\tconst pts = points.filter((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]));\n\tconst r = width / 2;\n\tif (!pts.length || !(r > 0)) return [];\n\tconst moved = pts.some((p) => !near(p, pts[0], 1e-9));\n\tif (!moved) {\n\t\tconst [cx, cy] = pts[0];\n\t\tconst k = r * 0.5522847498307936;\n\t\treturn [\n\t\t\t{ type: 'M', x: cx, y: cy - r },\n\t\t\t{ type: 'C', x1: cx + k, y1: cy - r, x2: cx + r, y2: cy - k, x: cx + r, y: cy },\n\t\t\t{ type: 'C', x1: cx + r, y1: cy + k, x2: cx + k, y2: cy + r, x: cx, y: cy + r },\n\t\t\t{ type: 'C', x1: cx - k, y1: cy + r, x2: cx - r, y2: cy + k, x: cx - r, y: cy },\n\t\t\t{ type: 'C', x1: cx - r, y1: cy - k, x2: cx - k, y2: cy - r, x: cx, y: cy - r },\n\t\t\t{ type: 'Z' }\n\t\t];\n\t}\n\tconst line: BezierPath = [{ type: 'M', x: pts[0][0], y: pts[0][1] }, ...pts.slice(1).map((p) => ({ type: 'L' as const, x: p[0], y: p[1] }))];\n\treturn outlineStroke(line, { width, cap: 'round', join: 'round' });\n}\n\n/**\n * A filled path with `region` removed: one path per remaining face, or null when the region\n * does not overlap the fill.\n */\nexport function eraseFromFill(path: BezierPathInput, fillRule: FillRule, region: BezierPathInput): BezierPath[] | null {\n\tconst overlap = pathBoolean('intersection', [{ path, fillRule }, { path: region }]).path;\n\tif (!pathToContours(overlap).some((c) => Math.abs(contourSignedArea(closeContour(c, true))) > 1e-9)) return null;\n\tconst rest = pathBoolean('difference', [{ path, fillRule }, { path: region }]).path;\n\treturn splitIntoFaces(rest);\n}\n\n/**\n * The parts of a subpath's outline outside `region`, as open subpaths that keep the original\n * curves exactly; null when the outline does not enter the region. A closed subpath's last\n * and first parts join at its first anchor.\n */\nexport function eraseFromOutline(sp: VectorSubpath, region: BezierPathInput): VectorSubpath[] | null {\n\tconst regionSegs = pathToContours(region).flatMap((c) => closeContour(c, true));\n\tif (!regionSegs.length) return null;\n\tconst rb = bezierPathBounds(region);\n\tconst count = subpathSegmentCount(sp);\n\tif (!rb || count === 0) return null;\n\tconst removed = (p: Point) => pointInBezierPath(region, p, 'nonzero');\n\ttype Piece = { seg: number; t0: number; t1: number };\n\tconst runs: Piece[][] = [];\n\tlet cur: Piece[] = [];\n\tlet any = false;\n\tfor (let i = 0; i < count; i++) {\n\t\tconst seg = subpathSegment(sp, i);\n\t\tconst sb = segmentBounds(seg);\n\t\tconst ts = [0, 1];\n\t\tif (!(sb.maxX < rb.minX || sb.minX > rb.maxX || sb.maxY < rb.minY || sb.minY > rb.maxY)) {\n\t\t\tfor (const r of regionSegs) {\n\t\t\t\tconst b = segmentBounds(r);\n\t\t\t\tif (b.maxX < sb.minX || b.minX > sb.maxX || b.maxY < sb.minY || b.minY > sb.maxY) continue;\n\t\t\t\tfor (const hit of segmentIntersections(seg, r)) if (hit.ta > 1e-9 && hit.ta < 1 - 1e-9) ts.push(hit.ta);\n\t\t\t}\n\t\t}\n\t\tts.sort((a, b) => a - b);\n\t\tfor (let k = 0; k < ts.length - 1; k++) {\n\t\t\tconst t0 = ts[k];\n\t\t\tconst t1 = ts[k + 1];\n\t\t\tif (t1 - t0 < 1e-9) continue;\n\t\t\tif (removed(segmentPoint(seg, (t0 + t1) / 2))) {\n\t\t\t\tany = true;\n\t\t\t\tif (cur.length) runs.push(cur);\n\t\t\t\tcur = [];\n\t\t\t} else cur.push({ seg: i, t0, t1 });\n\t\t}\n\t}\n\tif (cur.length) runs.push(cur);\n\tif (!any) return null;\n\t// A closed path's last and first runs meet at anchor 0.\n\tif (sp.closed && runs.length >= 2) {\n\t\tconst first = runs[0][0];\n\t\tconst lastRun = runs[runs.length - 1];\n\t\tconst last = lastRun[lastRun.length - 1];\n\t\tif (first.seg === 0 && first.t0 === 0 && last.seg === count - 1 && last.t1 === 1) lastRun.push(...runs.shift()!);\n\t}\n\tconst out: VectorSubpath[] = [];\n\tfor (const run of runs) {\n\t\tconst anchors: VectorAnchor[] = [];\n\t\tfor (const { seg, t0, t1 } of run) {\n\t\t\tconst c = subSegment(subpathSegment(sp, seg), t0, t1);\n\t\t\tconst line = c.length === 2;\n\t\t\tconst start = c[0];\n\t\t\tconst end = c[c.length - 1];\n\t\t\tif (!anchors.length) anchors.push({ x: start[0], y: start[1] });\n\t\t\tif (!line) anchors[anchors.length - 1].out = { x: c[1][0], y: c[1][1] };\n\t\t\tconst next: VectorAnchor = { x: end[0], y: end[1] };\n\t\t\tif (!line) next.in = { x: c[2][0], y: c[2][1] };\n\t\t\tanchors.push(next);\n\t\t}\n\t\tif (anchors.length < 2) continue;\n\t\tfor (const a of anchors) {\n\t\t\tconst type = inferAnchorType(a);\n\t\t\tif (type !== 'corner') a.type = type;\n\t\t}\n\t\tout.push({ anchors, closed: false });\n\t}\n\treturn out;\n}\n\n/** Bounds of a point list (for picking the paths a knife or eraser stroke can reach). */\nexport function polylineBounds(points: readonly Point[], pad = 0): { x: number; y: number; width: number; height: number } | null {\n\tif (!points.length) return null;\n\tlet minX = Infinity;\n\tlet minY = Infinity;\n\tlet maxX = -Infinity;\n\tlet maxY = -Infinity;\n\tfor (const [x, y] of points) {\n\t\tminX = Math.min(minX, x);\n\t\tminY = Math.min(minY, y);\n\t\tmaxX = Math.max(maxX, x);\n\t\tmaxY = Math.max(maxY, y);\n\t}\n\treturn { x: minX - pad, y: minY - pad, width: maxX - minX + 2 * pad, height: maxY - minY + 2 * pad };\n}\n\n/** Ramer–Douglas–Peucker reduction of a polyline (keeps both ends). */\nexport function simplifyPolyline(points: readonly Point[], tolerance: number): Point[] {\n\tconst n = points.length;\n\tif (n < 3) return points.slice();\n\tconst keep = new Array<boolean>(n).fill(false);\n\tkeep[0] = keep[n - 1] = true;\n\tconst stack: [number, number][] = [[0, n - 1]];\n\twhile (stack.length) {\n\t\tconst [a, b] = stack.pop()!;\n\t\tconst [ax, ay] = points[a];\n\t\tconst dx = points[b][0] - ax;\n\t\tconst dy = points[b][1] - ay;\n\t\tconst len = Math.hypot(dx, dy);\n\t\tlet far = -1;\n\t\tlet farD = 0;\n\t\tfor (let i = a + 1; i < b; i++) {\n\t\t\tconst [px, py] = points[i];\n\t\t\tconst d = len < 1e-12 ? Math.hypot(px - ax, py - ay) : Math.abs((px - ax) * dy - (py - ay) * dx) / len;\n\t\t\tif (d > farD) {\n\t\t\t\tfarD = d;\n\t\t\t\tfar = i;\n\t\t\t}\n\t\t}\n\t\tif (far >= 0 && farD > tolerance) {\n\t\t\tkeep[far] = true;\n\t\t\tstack.push([a, far], [far, b]);\n\t\t}\n\t}\n\treturn points.filter((_, i) => keep[i]);\n}\n\n","/**\n * Pencil helpers: lazy-mouse smoothing (a pulled string between the pointer and the pen) and\n * ink-to-shape recognition (a hand-drawn stroke that is a line, rectangle, ellipse or polygon).\n *\n * Portions ported from (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md):\n * - photocraft-main/crates/paint/src/dynamics.rs (`Smoother`: pulled-string mode, `string`,\n * `finish` with catch-up on stroke end)\n * - wordcraft-main/crates/engine/src/cmd/ink_shape.rs (`recognise`, `ellipse_rms`,\n * `snap_square`, `corners`, `turning`, `rdp`, `upright`)\n */\nimport type { Point } from '../canvas/types.js';\n\n// ---------------------------------------------------------------------------\n// Lazy mouse\n// ---------------------------------------------------------------------------\n\n/**\n * Pulled-string smoothing: the pen stays put until the pointer is more than `length` away,\n * then follows it at that distance, so small wobbles never reach the stroke. Feed pointer\n * positions to `push`; it returns the pen positions to draw through (possibly none).\n */\nexport class LazyMouse {\n\tprivate pos: Point | null = null;\n\tprivate last: Point | null = null;\n\n\t/** `length` is the string length in the units of the points (0 turns smoothing off). */\n\tconstructor(readonly length: number) {}\n\n\tpush(p: Point): Point[] {\n\t\tthis.last = p;\n\t\tif (!(this.length > 0)) return [p];\n\t\tconst pos = this.pos;\n\t\tif (!pos) {\n\t\t\tthis.pos = p;\n\t\t\treturn [p];\n\t\t}\n\t\tconst dx = p[0] - pos[0];\n\t\tconst dy = p[1] - pos[1];\n\t\tconst d = Math.hypot(dx, dy);\n\t\tif (d <= this.length) return [];\n\t\tconst k = (d - this.length) / d;\n\t\tconst next: Point = [pos[0] + dx * k, pos[1] + dy * k];\n\t\tthis.pos = next;\n\t\treturn [next];\n\t}\n\n\t/** The string from the pen to the pointer while they are apart, else null. */\n\tstring(): [Point, Point] | null {\n\t\tconst { pos, last } = this;\n\t\tif (!(this.length > 0) || !pos || !last || (pos[0] === last[0] && pos[1] === last[1])) return null;\n\t\treturn [pos, last];\n\t}\n\n\t/** End of stroke: the pen catches up with the pointer (the point to add, if it lagged). */\n\tfinish(): Point[] {\n\t\tconst { pos, last } = this;\n\t\tif (!(this.length > 0) || !pos || !last || (pos[0] === last[0] && pos[1] === last[1])) return [];\n\t\tthis.pos = last;\n\t\treturn [last];\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Ink to shape\n// ---------------------------------------------------------------------------\n\n/** A shape recognised in a stroke, in the stroke's coordinates. */\nexport type VectorInkShape =\n\t| { kind: 'line'; a: Point; b: Point }\n\t| { kind: 'rect'; x: number; y: number; width: number; height: number }\n\t| { kind: 'ellipse'; x: number; y: number; width: number; height: number }\n\t| { kind: 'polygon'; points: Point[] };\n\nexport interface RecognizeInkOptions {\n\t/** Strokes whose longer side is smaller than this stay ink (default 6). */\n\tminSize?: number;\n}\n\n/** Most corners a recognised polygon may have. */\nexport const VECTOR_INK_MAX_CORNERS = 8;\nconst MAX_POINTS = 100_000;\n\n/** \"line\", \"square\", \"rectangle\", \"circle\", \"ellipse\", \"triangle\" or \"polygon\". */\nexport function vectorInkShapeName(shape: VectorInkShape): string {\n\tswitch (shape.kind) {\n\t\tcase 'line':\n\t\t\treturn 'line';\n\t\tcase 'rect':\n\t\t\treturn shape.width === shape.height ? 'square' : 'rectangle';\n\t\tcase 'ellipse':\n\t\t\treturn shape.width === shape.height ? 'circle' : 'ellipse';\n\t\tcase 'polygon':\n\t\t\treturn shape.points.length === 3 ? 'triangle' : 'polygon';\n\t}\n}\n\nconst dist = (a: Point, b: Point) => Math.hypot(b[0] - a[0], b[1] - a[1]);\n\nfunction bbox(pts: readonly Point[]): [number, number, number, number] {\n\tif (!pts.length) return [0, 0, 0, 0];\n\tlet [x0, y0] = pts[0];\n\tlet [x1, y1] = pts[0];\n\tfor (const [x, y] of pts) {\n\t\tx0 = Math.min(x0, x);\n\t\ty0 = Math.min(y0, y);\n\t\tx1 = Math.max(x1, x);\n\t\ty1 = Math.max(y1, y);\n\t}\n\treturn [x0, y0, x1 - x0, y1 - y0];\n}\n\nfunction segDistance(a: Point, b: Point, p: Point): number {\n\tconst dx = b[0] - a[0];\n\tconst dy = b[1] - a[1];\n\tconst len2 = dx * dx + dy * dy;\n\tconst t = len2 > 0 ? Math.min(1, Math.max(0, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / len2)) : 0;\n\treturn dist([a[0] + t * dx, a[1] + t * dy], p);\n}\n\nfunction polygonDistance(c: readonly Point[], p: Point): number {\n\tlet best = Infinity;\n\tfor (let i = 0; i < c.length; i++) best = Math.min(best, segDistance(c[i], c[(i + 1) % c.length], p));\n\treturn best;\n}\n\n/** RMS of each point's normalised radius minus one on the ellipse inscribed in the box (0 on it). */\nfunction ellipseRms(p: readonly Point[], x0: number, y0: number, w: number, h: number): number {\n\tconst rx = w / 2;\n\tconst ry = h / 2;\n\tif (rx <= 0 || ry <= 0 || !p.length) return Infinity;\n\tconst cx = x0 + rx;\n\tconst cy = y0 + ry;\n\tlet sum = 0;\n\tfor (const [x, y] of p) sum += (Math.hypot((x - cx) / rx, (y - cy) / ry) - 1) ** 2;\n\treturn Math.sqrt(sum / p.length);\n}\n\n/** A box drawn nearly square made square (same centre). */\nfunction snapSquare(x: number, y: number, w: number, h: number): [number, number, number, number] {\n\tif (Math.abs(w - h) <= 0.12 * Math.max(w, h)) {\n\t\tconst s = (w + h) / 2;\n\t\treturn [x + (w - s) / 2, y + (h - s) / 2, s, s];\n\t}\n\treturn [x, y, w, h];\n}\n\n/** How far the path turns at `b` coming from `a` towards `c`, in degrees (0 = straight on). */\nfunction turning(a: Point, b: Point, c: Point): number {\n\tconst u = [b[0] - a[0], b[1] - a[1]];\n\tconst v = [c[0] - b[0], c[1] - b[1]];\n\tconst lu = Math.hypot(u[0], u[1]);\n\tconst lv = Math.hypot(v[0], v[1]);\n\tif (lu <= 0 || lv <= 0) return 0;\n\treturn (Math.acos(Math.min(1, Math.max(-1, (u[0] * v[0] + u[1] * v[1]) / (lu * lv)))) * 180) / Math.PI;\n}\n\n/** Ramer–Douglas–Peucker reduction of an open polyline (iterative), keeping both ends. */\nfunction rdp(p: readonly Point[], eps: number): Point[] {\n\tconst n = p.length;\n\tif (n < 3) return p.slice();\n\tconst keep = new Array<boolean>(n).fill(false);\n\tkeep[0] = keep[n - 1] = true;\n\tconst stack: [number, number][] = [[0, n - 1]];\n\twhile (stack.length) {\n\t\tconst [a, b] = stack.pop()!;\n\t\tlet far = a;\n\t\tlet farD = 0;\n\t\tfor (let i = a + 1; i < b; i++) {\n\t\t\tconst d = segDistance(p[a], p[b], p[i]);\n\t\t\tif (d > farD) {\n\t\t\t\tfarD = d;\n\t\t\t\tfar = i;\n\t\t\t}\n\t\t}\n\t\tif (farD > eps) {\n\t\t\tkeep[far] = true;\n\t\t\tstack.push([a, far], [far, b]);\n\t\t}\n\t}\n\treturn p.filter((_, i) => keep[i]);\n}\n\n/** Corners of the closed path through `p`: RDP split at the point farthest from the start, then flat and crowded corners merged away. */\nfunction corners(p: readonly Point[], diag: number): Point[] {\n\tconst eps = 0.05 * diag;\n\tconst start = p[0];\n\tlet far = 0;\n\tlet farD = 0;\n\tp.forEach((q, i) => {\n\t\tconst d = dist(start, q);\n\t\tif (d > farD) {\n\t\t\tfarD = d;\n\t\t\tfar = i;\n\t\t}\n\t});\n\tconst a = p.slice(0, far);\n\tconst b = p.slice(far);\n\tconst ring = rdp([...a, ...b.slice(0, 1)], eps);\n\tconst back = rdp([...b, start], eps);\n\t// The halves share the far point and the start.\n\tring.pop();\n\tback.pop();\n\tring.push(...back);\n\twhile (ring.length > 3) {\n\t\tconst n = ring.length;\n\t\tconst turn = (i: number) => turning(ring[(i + n - 1) % n], ring[i], ring[(i + 1) % n]);\n\t\tlet flat = 0;\n\t\tlet flatT = Infinity;\n\t\tfor (let i = 0; i < n; i++) {\n\t\t\tconst t = turn(i);\n\t\t\tif (t < flatT) {\n\t\t\t\tflatT = t;\n\t\t\t\tflat = i;\n\t\t\t}\n\t\t}\n\t\tlet short = -1;\n\t\tfor (let j = 0; j < n; j++) {\n\t\t\tif (dist(ring[j], ring[(j + 1) % n]) < 0.1 * diag) {\n\t\t\t\tshort = j;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (flatT < 30) ring.splice(flat, 1);\n\t\telse if (short >= 0) {\n\t\t\t// Of the two crowded corners keep the sharper.\n\t\t\tconst k = turn(short) < turn((short + 1) % n) ? short : (short + 1) % n;\n\t\t\tring.splice(k, 1);\n\t\t} else break;\n\t}\n\treturn ring;\n}\n\n/** A quadrilateral whose sides run (nearly) across and down, alternately. */\nfunction upright(c: readonly Point[]): boolean {\n\tconst n = c.length;\n\tconst dirs = c.map((a, i) => {\n\t\tconst b = c[(i + 1) % n];\n\t\tconst deg = ((((Math.atan2(b[1] - a[1], b[0] - a[0]) * 180) / Math.PI) % 180) + 180) % 180;\n\t\tif (deg <= 15 || deg >= 165) return 'across';\n\t\tif (deg >= 75 && deg <= 105) return 'down';\n\t\treturn null;\n\t});\n\treturn dirs.every((d) => d !== null) && dirs.every((d, i) => d !== dirs[(i + 1) % n]);\n}\n\n/**\n * The shape a hand-drawn stroke draws, if it is one: an open stroke is a line when it stays\n * close to the chord between its ends; a closed one is an ellipse when its points sit on the\n * ellipse inscribed in their bounds, else a polygon of 3–8 corners when that polygon stays\n * close to every point (an upright four-cornered one is a rectangle). Nearly square boxes\n * become squares and circles. Anything else (scribbles, curves, letters) is null.\n */\nexport function recognizeInkShape(points: readonly Point[], options: RecognizeInkOptions = {}): VectorInkShape | null {\n\tconst minSize = options.minSize ?? 6;\n\tconst p: Point[] = [];\n\tfor (const q of points.slice(0, MAX_POINTS)) {\n\t\tif (!Number.isFinite(q[0]) || !Number.isFinite(q[1]) || Math.abs(q[0]) >= 1e9 || Math.abs(q[1]) >= 1e9) continue;\n\t\tconst last = p[p.length - 1];\n\t\tif (!last || last[0] !== q[0] || last[1] !== q[1]) p.push([q[0], q[1]]);\n\t}\n\tif (p.length < 2) return null;\n\tconst first = p[0];\n\tconst last = p[p.length - 1];\n\tconst [x0, y0, w, h] = bbox(p);\n\tconst size = Math.max(w, h);\n\tconst diag = Math.hypot(w, h);\n\tif (size < minSize) return null;\n\tlet length = 0;\n\tfor (let i = 1; i < p.length; i++) length += dist(p[i - 1], p[i]);\n\tconst gap = dist(first, last);\n\t// A line: the stroke barely leaves the chord between its ends and doesn't double back.\n\tif (gap > 0.85 * length && gap >= minSize) {\n\t\tconst off = Math.max(...p.map((q) => segDistance(first, last, q)));\n\t\tif (off <= Math.max(0.06 * gap, (1.5 * minSize) / 6)) return { kind: 'line', a: first, b: last };\n\t}\n\t// Other shapes are closed: the stroke ends near where it began and goes around.\n\tif (gap > 0.2 * size || length < 2 * size) return null;\n\tconst rms = ellipseRms(p, x0, y0, w, h);\n\tconst roundish = w > 0.2 * size && h > 0.2 * size;\n\tconst ellipse = (): VectorInkShape => {\n\t\tconst [x, y, sw, sh] = snapSquare(x0, y0, w, h);\n\t\treturn { kind: 'ellipse', x, y, width: sw, height: sh };\n\t};\n\tif (roundish && rms < 0.06) return ellipse();\n\tconst c = corners(p, diag);\n\tconst fits = c.length >= 3 && p.every((q) => polygonDistance(c, q) <= 0.08 * diag);\n\tif (fits && c.length === 4 && upright(c)) {\n\t\tconst [bx, by, bw, bh] = bbox(c);\n\t\tconst [x, y, sw, sh] = snapSquare(bx, by, bw, bh);\n\t\treturn { kind: 'rect', x, y, width: sw, height: sh };\n\t}\n\tif (fits && c.length <= VECTOR_INK_MAX_CORNERS) return { kind: 'polygon', points: c };\n\t// A wobbly round stroke is still an ellipse.\n\treturn roundish && rms < 0.1 ? ellipse() : null;\n}\n","import { HistoryManager } from '../history/HistoryManager.js';\nimport type { Command } from '../history/types.js';\nimport { fitCubics } from '../canvas/curveFit.js';\nimport { pathBoolean } from '../canvas/pathops/boolean.js';\nimport { bezierPathBounds, transformBezierPath, type BezierPath } from '../canvas/pathops/bezier.js';\nimport type { Point } from '../canvas/types.js';\nimport {\n\tbezierToSubpaths,\n\tboundsFromPoints,\n\tboundsIntersect,\n\tcloneVectorDocument,\n\tcloneVectorNode,\n\tcollectPathNodes,\n\tconvertAnchor,\n\tellipseSubpath,\n\tfindVectorNode,\n\thitTestVectorNode,\n\thitTestVectorNodes,\n\tinsertAnchor,\n\tlineSubpath,\n\tlocateVectorNode,\n\tmoveAnchorHandle,\n\tnearestSegment,\n\thasPaint,\n\tnodeMatrix,\n\tinvertMatrix,\n\tapplyMatrix,\n\tapplyMatrixLinear,\n\tmultiplyMatrices,\n\tmatrixRotation,\n\tvectorWorldMatrix,\n\tvectorParentMatrix,\n\tvectorPathWorldBezier,\n\tIDENTITY_MATRIX,\n\tpolygonSubpath,\n\trectSubpath,\n\tremoveAnchors,\n\treverseSubpath,\n\trotateMatrix,\n\tscaleMatrix,\n\tstarSubpath,\n\tsubpathsToBezier,\n\ttransformVectorNode,\n\ttranslateAnchor,\n\ttranslateMatrix,\n\tunionBounds,\n\tvectorNodeBounds,\n\twalkVectorNodes,\n\ttype AffineMatrix\n} from './geometry.js';\nimport {\n\tcornerBisectorPoint,\n\tcornerRadiusChange,\n\tfitCornerRadius,\n\tnextVectorCornerKind,\n\tsetAnchorCorner,\n\tsetSubpathCorners,\n\tvectorCorners,\n\ttype VectorCornerInfo\n} from './corners.js';\nimport { strokeWidthProfileOf, vectorStrokeOutlinePath, vectorStrokeParts } from './stroke.js';\nimport { nearestStrokePosition, strokePositionPoint } from './varstroke.js';\nimport {\n\tgenerateWidthProfile,\n\tinsertWidthPoint,\n\tpressureWidthProfile,\n\tremoveWidthPoints,\n\treverseWidthProfile,\n\tsanitizeWidthProfile,\n\tsetWidthPoint,\n\twidthProfileAt,\n\twidthProfileMaxScale,\n\twidthProfilePreset,\n\ttype VectorTaperOptions,\n\ttype VectorWaveOptions,\n\ttype VectorWidthPreset\n} from './width.js';\nimport { parseVectorSvg, vectorDocumentToSvg, type VectorSvgExportOptions } from './svg.js';\nimport { constrainToLeave, VECTOR_CONSTRUCTION_ANGLES, VectorSnapTargets, type VectorSnapGuides, type VectorSnapLeave } from './snap.js';\nimport {\n\tbendSegment as bendSubpathSegment,\n\tcurvatureMoveAnchor,\n\tcutSubpathAt,\n\tjoinSubpaths,\n\tremoveAnchorsKeepingShape,\n\tremoveRedundantPoints as removeRedundantSubpathPoints,\n\tsmoothSubpath,\n\tsplitSubpathAt\n} from './pathEdit.js';\nimport { eraseFromFill, eraseFromOutline, eraserRegion, knifePath, polylineBounds, simplifyPolyline } from './pathCut.js';\nimport { LazyMouse, recognizeInkShape, vectorInkShapeName, type VectorInkShape } from './ink.js';\nimport type {\n\tVec2,\n\tVectorAlign,\n\tVectorAnchor,\n\tVectorAnchorRef,\n\tVectorAnchorType,\n\tVectorArrange,\n\tVectorAverageAxis,\n\tVectorBooleanOperation,\n\tVectorBounds,\n\tVectorCornerKind,\n\tVectorDefaults,\n\tVectorDistribute,\n\tVectorDocument,\n\tVectorGroupNode,\n\tVectorHandleRef,\n\tVectorModifiers,\n\tVectorNode,\n\tVectorPathNode,\n\tVectorSegmentRef,\n\tVectorStyle,\n\tVectorSubpath,\n\tVectorTool,\n\tVectorTransformHandle,\n\tVectorViewport,\n\tVectorWidthPoint\n} from './types.js';\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport interface VectorSnapOptions {\n\t/** Grid size in document units (0 = off, default 0). Points and boxes that snap to no object snap to it. */\n\tgrid: number;\n\t/**\n\t * Snap to other objects (default true): anchors, paths and their intersections, bounding-box\n\t * edges and centres, the artboard, construction angles, equal spacing and matching sizes.\n\t */\n\tobjects: boolean;\n\t/** Show smart guide lines and labels while snapping (default true). */\n\tguides: boolean;\n\t/** How near a target pulls, in screen pixels (default 5). */\n\tthreshold: number;\n\t/** Construction guide angles through the point a drawn point leaves from, in degrees (default 0, 45, 90, 135). */\n\tangles: readonly number[];\n}\n\n/** Snap options new editors start with. Hold Cmd / Ctrl (`mod`) during a drag to bypass snapping. */\nexport const DEFAULT_VECTOR_SNAP: Readonly<VectorSnapOptions> = { grid: 0, objects: true, guides: true, threshold: 5, angles: VECTOR_CONSTRUCTION_ANGLES };\n\n/** How path-editing gestures and the pencil, knife and eraser behave. */\nexport interface VectorPathEditOptions {\n\t/**\n\t * Deleting anchors refits the neighbouring handles so the shape stays (default true). Off,\n\t * the neighbours are joined with their handles as they are.\n\t */\n\tkeepShapeOnDelete: boolean;\n\t/**\n\t * Dragging one anchor with the direct tool bends its two segments like the Curvature tool,\n\t * keeping the segments beyond still (default false). Alt held during the drag flips it.\n\t */\n\tcurvatureMoves: boolean;\n\t/** Pencil lazy-mouse smoothing, 0–1: the pulled string is up to 100 screen pixels long (default 0, off). */\n\tpencilSmoothing: number;\n\t/** Pencil strokes that look like a line, rectangle, ellipse or polygon become that shape (default false). */\n\trecognizeShapes: boolean;\n\t/** Eraser diameter in document units (default 10). */\n\teraserSize: number;\n\t/**\n\t * Record pointer pressure on pencil strokes as a width profile: `pen` (default) for pen input\n\t * only, `all` for any pointer that reports pressure, `off` never.\n\t */\n\tpencilPressure: 'pen' | 'all' | 'off';\n}\n\n/** Path-editing options new editors start with. */\nexport const DEFAULT_VECTOR_PATH_EDIT: Readonly<VectorPathEditOptions> = {\n\tkeepShapeOnDelete: true,\n\tcurvatureMoves: false,\n\tpencilSmoothing: 0,\n\trecognizeShapes: false,\n\teraserSize: 10,\n\tpencilPressure: 'pen'\n};\n\n/** Longest pencil lazy-mouse string (at smoothing 1), in screen pixels. */\nexport const VECTOR_PENCIL_STRING_PX = 100;\n\nexport interface VectorEditorOptions {\n\tdocument?: VectorDocument;\n\t/** History to record into, e.g. one shared with the rest of the app (default: a new one). */\n\thistory?: HistoryManager;\n\t/** Starting tool (default `select`). */\n\ttool?: VectorTool;\n\t/** Style and settings for new shapes and paths. */\n\tdefaults?: VectorDefaults;\n\tviewport?: Partial<VectorViewport>;\n\tsnap?: Partial<VectorSnapOptions>;\n\tediting?: Partial<VectorPathEditOptions>;\n\t/** Pick distance for anchors, handles and outlines in screen pixels (default 6). */\n\thitRadius?: number;\n\t/** Id factory for new nodes. */\n\tcreateId?: () => string;\n\t/** Called after the document changes (edits, undo, redo, load). */\n\tonChange?: (document: VectorDocument) => void;\n}\n\n/** A pointer event as the controller needs it. Positions are in screen pixels relative to the canvas. */\nexport interface VectorPointerInput extends VectorModifiers {\n\t/** 0 = primary, 1 = middle (pans), 2 = secondary. Default 0. */\n\tbutton?: number;\n\t/** `PointerEvent.pressure` (0–1), recorded on pencil strokes. */\n\tpressure?: number;\n\t/** `PointerEvent.pointerType` (`mouse`, `pen`, `touch`). */\n\tpointerType?: string;\n}\n\n/** One width point of a path's stroke profile; `subpath` is the subpath it is shown on. */\nexport interface VectorWidthPointRef {\n\tnodeId: string;\n\tindex: number;\n\tsubpath: number;\n}\n\n/** A spot on a stroke (width tool): where a drag would add a width point. Positions in document units. */\nexport interface VectorStrokeSpot {\n\tnodeId: string;\n\tsubpath: number;\n\t/** Position along the subpath by length, 0–1. */\n\tt: number;\n\tpoint: Vec2;\n\t/** Ends of the stroke's width across the path there. */\n\tleft: Vec2;\n\tright: Vec2;\n}\n\n/** A key press as the controller needs it. */\nexport interface VectorKeyInput extends VectorModifiers {\n\t/** `KeyboardEvent.key`. */\n\tkey: string;\n}\n\n/** What the pointer is over. */\nexport interface VectorHover {\n\tnodeId: string | null;\n\tanchor?: VectorAnchorRef;\n\thandle?: VectorHandleRef;\n\t/** A segment under the pointer (direct tool and scissors); `point` is in document space. */\n\tsegment?: { nodeId: string; subpath: number; segment: number; t: number; point: Vec2 };\n\ttransformHandle?: VectorTransformHandle;\n\t/** A live corner widget (direct tool): the corner's anchor. */\n\tcorner?: VectorAnchorRef;\n\t/** A width point (width tool): its centre or the end of its left / right side. */\n\twidthPoint?: VectorWidthPointRef & { part: 'center' | 'left' | 'right' };\n\t/** A spot on a stroke away from its width points (width tool). */\n\tstrokeSpot?: VectorStrokeSpot;\n}\n\n/** The drag in progress, for overlays and status text. */\nexport type VectorInteraction =\n\t| { type: 'marquee'; bounds: VectorBounds }\n\t| { type: 'move'; dx: number; dy: number }\n\t| { type: 'scale'; handle: VectorTransformHandle; sx: number; sy: number }\n\t| { type: 'rotate'; angle: number }\n\t| { type: 'anchors'; dx: number; dy: number }\n\t| { type: 'handle'; ref: VectorHandleRef }\n\t| { type: 'bend'; ref: VectorSegmentRef }\n\t| { type: 'corner'; ref: VectorAnchorRef; radius: number }\n\t| { type: 'draw'; tool: VectorTool; nodeId: string; bounds: VectorBounds; string?: [Vec2, Vec2] }\n\t| { type: 'stroke'; tool: 'knife' | 'eraser'; points: Vec2[]; width: number }\n\t| { type: 'width'; ref: VectorWidthPointRef; mode: 'width' | 'move'; width: number }\n\t| { type: 'pen'; nodeId: string }\n\t| { type: 'pan' };\n\n/** A snapshot of the editor. The same object is returned until something changes. */\nexport interface VectorEditorState {\n\tdocument: VectorDocument;\n\ttool: VectorTool;\n\t/** Selected node ids (top-level nodes or group members picked with the direct tool). */\n\tselection: readonly string[];\n\t/** Selected anchors (direct tool). */\n\tselectedAnchors: readonly VectorAnchorRef[];\n\t/** The selected width point (width tool); Delete removes it. */\n\tselectedWidthPoint: VectorWidthPointRef | null;\n\t/** The path whose anchors are being edited, if any. */\n\teditingId: string | null;\n\t/** Axis-aligned bounds of the selected nodes in document units. */\n\tselectionBounds: VectorBounds | null;\n\t/** The selection box, rotated with the selection when its nodes share a rotation. */\n\tselectionFrame: VectorSelectionFrame | null;\n\tviewport: VectorViewport;\n\tdefaults: Readonly<Required<Pick<VectorDefaults, 'polygonSides' | 'starPoints' | 'starInnerRatio' | 'cornerRadius'>> & Pick<VectorDefaults, 'cornerKind'> & VectorStyle>;\n\tsnap: VectorSnapOptions;\n\tediting: VectorPathEditOptions;\n\t/** Smart guides of the snap in progress, in document units (null when there are none). */\n\tguides: VectorSnapGuides | null;\n\thitRadius: number;\n\thover: VectorHover | null;\n\t/** A CSS cursor for the canvas. */\n\tcursor: string;\n\tinteraction: VectorInteraction | null;\n\t/** The path the pen tool is adding to. */\n\tpen: { nodeId: string; subpath: number } | null;\n\t/** Last pointer position in document units (for the pen preview), or null when outside. */\n\tpointer: Vec2 | null;\n\tcanUndo: boolean;\n\tcanRedo: boolean;\n\tundoLabel: string;\n\tredoLabel: string;\n\t/** Bumped on every change. */\n\trevision: number;\n}\n\nexport type VectorActionResult = { ok: true } | { ok: false; message: string };\n\nexport interface AddVectorNodeOptions {\n\t/** Group to add into (default: the root). */\n\tparentId?: string;\n\t/** Position in the parent's list (default: on top). */\n\tindex?: number;\n\t/** Select the new node (default true). */\n\tselect?: boolean;\n\t/** Undo step label. */\n\tlabel?: string;\n}\n\n/** A shape description for `addShape` (and the agent command of the same name). */\nexport interface VectorShapeInput extends VectorStyle {\n\tkind: 'rect' | 'ellipse' | 'polygon' | 'star' | 'line';\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n\t/** Live corner radius of a rectangle, polygon or star (default: the editor default). */\n\tcornerRadius?: number;\n\tcornerKind?: VectorCornerKind;\n\tsides?: number;\n\tpoints?: number;\n\tinnerRatio?: number;\n\tname?: string;\n}\n\n/** Every field of `VectorStyle`, in the order style panels and commands list them. */\nexport const VECTOR_STYLE_KEYS = [\n\t'fill',\n\t'stroke',\n\t'strokeWidth',\n\t'strokeLinecap',\n\t'strokeLinejoin',\n\t'strokeDasharray',\n\t'fillRule',\n\t'strokeAlign',\n\t'startArrow',\n\t'endArrow',\n\t'arrowAlign',\n\t'startArrowScale',\n\t'endArrowScale',\n\t'strokeWidthProfile'\n] as const satisfies readonly (keyof VectorStyle)[];\n\n/** Clipboard payload type written by `copy()`. */\nexport const VECTOR_CLIPBOARD_TYPE = 'pixerate/vector';\n\nconst DEFAULT_DEFAULTS = {\n\tfill: '#d4d4d8',\n\tstroke: '#18181b',\n\tstrokeWidth: 2,\n\tpolygonSides: 6,\n\tstarPoints: 5,\n\tstarInnerRatio: 0.5,\n\tcornerRadius: 0\n};\n\nconst MIN_ZOOM = 0.05;\nconst MAX_ZOOM = 64;\n/** Screen distance of the rotation handle above the selection box. */\nexport const VECTOR_ROTATE_HANDLE_OFFSET = 24;\n\n// ---------------------------------------------------------------------------\n// Helpers shared with the render module\n// ---------------------------------------------------------------------------\n\nconst sameRef = (a: VectorAnchorRef, b: VectorAnchorRef) => a.nodeId === b.nodeId && a.subpath === b.subpath && a.index === b.index;\n\n/** Ids of the path nodes whose anchors are shown (the edited path plus selected paths). */\nexport function getEditablePathIds(state: Pick<VectorEditorState, 'document' | 'selection' | 'editingId' | 'tool' | 'pen'>): string[] {\n\tif (state.tool !== 'direct' && state.tool !== 'pen') return [];\n\tconst ids = new Set<string>();\n\tif (state.pen) ids.add(state.pen.nodeId);\n\tif (state.tool === 'direct') {\n\t\tif (state.editingId) ids.add(state.editingId);\n\t\tfor (const id of state.selection) {\n\t\t\tconst node = findVectorNode(state.document.nodes, id);\n\t\t\tif (node && !node.locked) for (const p of collectPathNodes(node)) if (!p.locked) ids.add(p.id);\n\t\t}\n\t}\n\treturn [...ids].filter((id) => findVectorNode(state.document.nodes, id)?.type === 'path');\n}\n\n/** Every anchor drawn on the canvas. */\nexport function getVisibleAnchors(state: Pick<VectorEditorState, 'document' | 'selection' | 'editingId' | 'tool' | 'pen'>): VectorAnchorRef[] {\n\tconst out: VectorAnchorRef[] = [];\n\tfor (const id of getEditablePathIds(state)) {\n\t\tconst node = findVectorNode(state.document.nodes, id) as VectorPathNode;\n\t\tnode.subpaths.forEach((sp, s) => sp.anchors.forEach((_, i) => out.push({ nodeId: id, subpath: s, index: i })));\n\t}\n\treturn out;\n}\n\n/**\n * Handles drawn on the canvas: those of selected anchors and of the segments next to them\n * (direct tool), or of the last anchor of the pen path.\n */\nexport function getVisibleHandles(\n\tstate: Pick<VectorEditorState, 'document' | 'selection' | 'editingId' | 'tool' | 'pen' | 'selectedAnchors'>\n): VectorHandleRef[] {\n\tconst out: VectorHandleRef[] = [];\n\tconst seen = new Set<string>();\n\tconst push = (node: VectorPathNode, s: number, i: number, handle: 'in' | 'out') => {\n\t\tconst sp = node.subpaths[s];\n\t\tconst a = sp?.anchors[i];\n\t\tif (!a || !a[handle]) return;\n\t\tconst key = `${node.id}:${s}:${i}:${handle}`;\n\t\tif (seen.has(key)) return;\n\t\tseen.add(key);\n\t\tout.push({ nodeId: node.id, subpath: s, index: i, handle });\n\t};\n\tif (state.tool === 'pen' && state.pen) {\n\t\tconst node = findVectorNode(state.document.nodes, state.pen.nodeId);\n\t\tconst sp = node?.type === 'path' ? node.subpaths[state.pen.subpath] : undefined;\n\t\tif (node?.type === 'path' && sp) {\n\t\t\tconst last = sp.anchors.length - 1;\n\t\t\tpush(node, state.pen.subpath, last, 'in');\n\t\t\tpush(node, state.pen.subpath, last, 'out');\n\t\t}\n\t\treturn out;\n\t}\n\tif (state.tool !== 'direct') return out;\n\tconst editable = new Set(getEditablePathIds(state));\n\tfor (const ref of state.selectedAnchors) {\n\t\tif (!editable.has(ref.nodeId)) continue;\n\t\tconst node = findVectorNode(state.document.nodes, ref.nodeId) as VectorPathNode;\n\t\tconst sp = node.subpaths[ref.subpath];\n\t\tif (!sp) continue;\n\t\tconst n = sp.anchors.length;\n\t\tpush(node, ref.subpath, ref.index, 'in');\n\t\tpush(node, ref.subpath, ref.index, 'out');\n\t\tconst prev = ref.index > 0 ? ref.index - 1 : sp.closed ? n - 1 : -1;\n\t\tconst next = ref.index < n - 1 ? ref.index + 1 : sp.closed ? 0 : -1;\n\t\tif (prev >= 0) push(node, ref.subpath, prev, 'out');\n\t\tif (next >= 0) push(node, ref.subpath, next, 'in');\n\t}\n\treturn out;\n}\n\n/** Live corner widgets sit at least this far inside their corner (screen px along each side of a right angle). */\nexport const VECTOR_CORNER_WIDGET_INSET = 10;\n\n/** A live corner widget of the direct tool: drag it to round the corners, Alt-click to change their kind. */\nexport interface VectorCornerWidget {\n\tref: VectorAnchorRef;\n\t/** Document position of the widget. */\n\tx: number;\n\ty: number;\n\t/** The radius stored on the anchor and the radius drawn (no larger than fits). */\n\tradius: number;\n\tdrawnRadius: number;\n\tkind: VectorCornerKind;\n\t/** The corner in its node's own space. */\n\tcorner: VectorCornerInfo;\n}\n\n/**\n * The live corner widgets the direct tool shows: on each editable path, at its selected corner\n * anchors (or at every corner when none of its anchors is selected). Corners whose sides are\n * shorter than three insets on screen hide theirs. Dragging one sets the radius of all of them.\n * Ported from ArtCraft vectorcraft `crates/tools/src/corners.rs` (MIT OR Apache-2.0, see\n * THIRD_PARTY_NOTICES.md), as is the `corner` drag below.\n */\nexport function getVectorCornerWidgets(\n\tstate: Pick<VectorEditorState, 'document' | 'selection' | 'editingId' | 'tool' | 'pen' | 'selectedAnchors' | 'viewport'>\n): VectorCornerWidget[] {\n\tif (state.tool !== 'direct' || state.pen) return [];\n\tconst zoom = state.viewport.zoom;\n\tconst out: VectorCornerWidget[] = [];\n\tfor (const id of getEditablePathIds(state)) {\n\t\tconst node = findVectorNode(state.document.nodes, id) as VectorPathNode;\n\t\tconst picked = state.selectedAnchors.filter((r) => r.nodeId === id);\n\t\tconst m = vectorWorldMatrix(state.document.nodes, id) ?? IDENTITY_MATRIX;\n\t\tfor (const c of vectorCorners(node.subpaths)) {\n\t\t\tif (picked.length && !picked.some((r) => r.subpath === c.subpath && r.index === c.index)) continue;\n\t\t\tconst side = Math.min(c.lu, c.lv);\n\t\t\tif (side * zoom < 3 * VECTOR_CORNER_WIDGET_INSET) continue;\n\t\t\tconst a = node.subpaths[c.subpath].anchors[c.index];\n\t\t\tconst radius = a.corner?.radius ?? 0;\n\t\t\tconst drawn = fitCornerRadius(c, radius);\n\t\t\t// On the bisector at the centre of the arc as drawn, at least the inset in and at most half the shorter side.\n\t\t\tconst k = Math.min(Math.max(drawn / c.sin, VECTOR_CORNER_WIDGET_INSET / (zoom * Math.sqrt(1 + c.cos))), side / 2);\n\t\t\tconst p = applyMatrix(m, cornerBisectorPoint(c, k));\n\t\t\tout.push({ ref: { nodeId: id, subpath: c.subpath, index: c.index }, x: p.x, y: p.y, radius, drawnRadius: drawn, kind: a.corner?.kind ?? 'round', corner: c });\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * The line a path's stroke follows (node space; shortened under `tip` arrowheads) and the\n * distance a side scale of 1 reaches from it (half the drawn width: twice the stroke width for\n * inside / outside strokes). Null for paths without a visible stroke.\n */\nexport function vectorStrokeWidthGeometry(node: VectorPathNode): { line: BezierPath; unit: number } | null {\n\tif (!hasPaint(node.stroke) || !((node.strokeWidth ?? 1) > 0)) return null;\n\tconst parts = vectorStrokeParts(subpathsToBezier(node.subpaths), node);\n\treturn parts.line.length ? { line: parts.line, unit: parts.drawWidth / 2 } : null;\n}\n\n/** A width point of the width tool, in document units. */\nexport interface VectorWidthHandle {\n\tref: VectorWidthPointRef;\n\t/** The point on the path. */\n\tx: number;\n\ty: number;\n\t/** Ends of its left and right sides. */\n\tleft: Vec2;\n\tright: Vec2;\n\tt: number;\n\t/** Side scales (multiples of half the stroke width). */\n\tleftScale: number;\n\trightScale: number;\n\tselected: boolean;\n}\n\n/**\n * The width points the width tool shows: every profile point on every subpath of the stroke\n * under the pointer, the selected paths and the stroke being edited. Ported from ArtCraft\n * vectorcraft `crates/tools/src/distort/width.rs` (MIT OR Apache-2.0, see\n * THIRD_PARTY_NOTICES.md), as are the `width` drag and hover below.\n */\nexport function getVectorWidthHandles(\n\tstate: Pick<VectorEditorState, 'document' | 'selection' | 'tool' | 'hover' | 'interaction' | 'selectedWidthPoint'>\n): VectorWidthHandle[] {\n\tif (state.tool !== 'width') return [];\n\tconst ids = new Set<string>();\n\tfor (const id of state.selection) {\n\t\tconst n = findVectorNode(state.document.nodes, id);\n\t\tif (n) for (const p of collectPathNodes(n)) ids.add(p.id);\n\t}\n\tif (state.hover?.nodeId) ids.add(state.hover.nodeId);\n\tif (state.interaction?.type === 'width') ids.add(state.interaction.ref.nodeId);\n\tif (state.selectedWidthPoint) ids.add(state.selectedWidthPoint.nodeId);\n\tconst out: VectorWidthHandle[] = [];\n\tfor (const id of ids) {\n\t\tconst node = findVectorNode(state.document.nodes, id);\n\t\tif (node?.type !== 'path' || node.visible === false || !node.strokeWidthProfile?.length) continue;\n\t\tconst g = vectorStrokeWidthGeometry(node);\n\t\tif (!g) continue;\n\t\tconst profile = sanitizeWidthProfile(node.strokeWidthProfile);\n\t\tconst m = vectorWorldMatrix(state.document.nodes, id) ?? IDENTITY_MATRIX;\n\t\tconst contours = node.subpaths.length;\n\t\tfor (let sp = 0; sp < contours; sp++) {\n\t\t\tprofile.forEach((w, index) => {\n\t\t\t\tconst at = strokePositionPoint(g.line, sp, w.t);\n\t\t\t\tif (!at) return;\n\t\t\t\tconst n = { x: at.tangent[1], y: -at.tangent[0] };\n\t\t\t\tconst c = { x: at.point[0], y: at.point[1] };\n\t\t\t\tconst p = applyMatrix(m, c);\n\t\t\t\tconst l = applyMatrix(m, { x: c.x + n.x * w.left * g.unit, y: c.y + n.y * w.left * g.unit });\n\t\t\t\tconst r = applyMatrix(m, { x: c.x - n.x * w.right * g.unit, y: c.y - n.y * w.right * g.unit });\n\t\t\t\tconst sel = state.selectedWidthPoint;\n\t\t\t\tout.push({\n\t\t\t\t\tref: { nodeId: id, index, subpath: sp },\n\t\t\t\t\tx: p.x,\n\t\t\t\t\ty: p.y,\n\t\t\t\t\tleft: l,\n\t\t\t\t\tright: r,\n\t\t\t\t\tt: w.t,\n\t\t\t\t\tleftScale: w.left,\n\t\t\t\t\trightScale: w.right,\n\t\t\t\t\tselected: !!sel && sel.nodeId === id && sel.index === index\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t}\n\treturn out;\n}\n\n/** Looks up an anchor (positions in its node's own space). */\nexport function getAnchor(doc: VectorDocument, ref: VectorAnchorRef): VectorAnchor | undefined {\n\tconst node = findVectorNode(doc.nodes, ref.nodeId);\n\treturn node?.type === 'path' ? node.subpaths[ref.subpath]?.anchors[ref.index] : undefined;\n}\n\n/** An anchor with its position and handles in document space (its node's transforms applied). */\nexport function getAnchorWorld(doc: VectorDocument, ref: VectorAnchorRef): { x: number; y: number; in?: Vec2; out?: Vec2; type?: VectorAnchorType } | undefined {\n\tconst a = getAnchor(doc, ref);\n\tif (!a) return undefined;\n\tconst m = vectorWorldMatrix(doc.nodes, ref.nodeId) ?? IDENTITY_MATRIX;\n\tconst p = applyMatrix(m, a);\n\treturn { x: p.x, y: p.y, ...(a.in ? { in: applyMatrix(m, a.in) } : {}), ...(a.out ? { out: applyMatrix(m, a.out) } : {}), ...(a.type ? { type: a.type } : {}) };\n}\n\n/**\n * The selection box: `angle` is the shared rotation of the selected nodes (0 when they\n * differ), `x / y / width / height` the bounds in the box's own frame (document space\n * rotated by −angle). A frame point `q` is at `rotateMatrix(angle)` applied to `q`.\n */\nexport interface VectorSelectionFrame {\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n\tangle: number;\n}\n\n/** The selection frame of nodes `ids` (see `VectorSelectionFrame`), or null when they have no points. */\nexport function getVectorSelectionFrame(doc: VectorDocument, ids: readonly string[]): VectorSelectionFrame | null {\n\tconst nodes = ids.map((id) => ({ node: findVectorNode(doc.nodes, id), parent: vectorParentMatrix(doc.nodes, id) ?? IDENTITY_MATRIX })).filter((n) => n.node);\n\tif (!nodes.length) return null;\n\tconst angles = nodes.map((n) => matrixRotation(multiplyMatrices(nodeMatrix(n.node!), n.parent)));\n\tconst same = angles.every((a) => Math.abs(normalizeAngle(a - angles[0])) < 1e-6);\n\tconst angle = same ? angles[0] : 0;\n\tconst unrotate = rotateMatrix(-angle);\n\tconst b = unionBounds(nodes.map((n) => vectorNodeBounds(n.node!, multiplyMatrices(n.parent, unrotate))));\n\treturn b ? { ...b, angle } : null;\n}\n\nconst normalizeAngle = (a: number) => ((((a + 180) % 360) + 360) % 360) - 180;\n\n/** Screen positions of the selection box handles for a box given in screen pixels. */\nexport function getTransformHandlePositions(box: VectorBounds): { handle: VectorTransformHandle; x: number; y: number }[] {\n\tconst { x, y, width: w, height: h } = box;\n\treturn [\n\t\t{ handle: 'nw', x, y },\n\t\t{ handle: 'n', x: x + w / 2, y },\n\t\t{ handle: 'ne', x: x + w, y },\n\t\t{ handle: 'e', x: x + w, y: y + h / 2 },\n\t\t{ handle: 'se', x: x + w, y: y + h },\n\t\t{ handle: 's', x: x + w / 2, y: y + h },\n\t\t{ handle: 'sw', x, y: y + h },\n\t\t{ handle: 'w', x, y: y + h / 2 },\n\t\t{ handle: 'rotate', x: x + w / 2, y: y - VECTOR_ROTATE_HANDLE_OFFSET }\n\t];\n}\n\n/**\n * Screen geometry of a selection box. `box` and each handle's `x / y` are the unrotated box\n * in screen pixels; draw them inside a group with `transform` (a `rotate(angle cx cy)`),\n * or use `screen` for the true on-screen positions (hit-testing).\n */\nexport interface VectorSelectionBoxGeometry {\n\tbox: VectorBounds;\n\tangle: number;\n\ttransform: string;\n\thandles: { handle: VectorTransformHandle; x: number; y: number; screen: Vec2 }[];\n\t/** The four corners on screen, clockwise from the top left. */\n\tcorners: Vec2[];\n}\n\nexport function getVectorSelectionBoxGeometry(frame: VectorSelectionFrame, viewport: VectorViewport): VectorSelectionBoxGeometry {\n\tconst z = viewport.zoom;\n\tconst box = { x: frame.x * z + viewport.x, y: frame.y * z + viewport.y, width: frame.width * z, height: frame.height * z };\n\tconst rot = rotateMatrix(frame.angle, { x: viewport.x, y: viewport.y });\n\tconst toScreen = (p: Vec2): Vec2 => (frame.angle ? applyMatrix(rot, p) : { x: p.x, y: p.y });\n\tconst handles = getTransformHandlePositions(box).map((h) => ({ ...h, screen: toScreen(h) }));\n\tconst corners = [\n\t\t{ x: box.x, y: box.y },\n\t\t{ x: box.x + box.width, y: box.y },\n\t\t{ x: box.x + box.width, y: box.y + box.height },\n\t\t{ x: box.x, y: box.y + box.height }\n\t].map(toScreen);\n\tconst r = (n: number) => Math.round(n * 1000) / 1000;\n\treturn { box, angle: frame.angle, transform: frame.angle ? `rotate(${r(frame.angle)} ${r(viewport.x)} ${r(viewport.y)})` : '', handles, corners };\n}\n\nconst RESIZE_CURSOR_ORDER = ['ew-resize', 'nwse-resize', 'ns-resize', 'nesw-resize'];\nconst HANDLE_ANGLES: Partial<Record<VectorTransformHandle, number>> = { e: 0, se: 45, s: 90, sw: 135, w: 180, nw: 225, n: 270, ne: 315 };\n\n/** The resize cursor for a handle of a box rotated by `angle` degrees. */\nexport function vectorResizeCursor(handle: VectorTransformHandle, angle = 0): string {\n\tif (handle === 'rotate') return 'grab';\n\tconst a = (((HANDLE_ANGLES[handle]! + angle) % 180) + 180) % 180;\n\treturn RESIZE_CURSOR_ORDER[Math.round(a / 45) % 4];\n}\n\n\nconst TOOL_LABELS: Record<VectorTool, string> = {\n\tselect: 'Select',\n\tdirect: 'Direct Select',\n\tpen: 'Pen',\n\tpencil: 'Pencil',\n\trect: 'Rectangle',\n\tellipse: 'Ellipse',\n\tpolygon: 'Polygon',\n\tstar: 'Star',\n\tline: 'Line',\n\tscissors: 'Scissors',\n\tknife: 'Knife',\n\teraser: 'Eraser',\n\twidth: 'Width'\n};\n\nconst TOOL_KEYS: Record<string, VectorTool> = { v: 'select', a: 'direct', p: 'pen', n: 'pencil', r: 'rect', o: 'ellipse', y: 'polygon', s: 'star', l: 'line', c: 'scissors', k: 'knife', e: 'eraser', w: 'width' };\n\nexport function vectorToolLabel(tool: VectorTool): string {\n\treturn TOOL_LABELS[tool];\n}\n\n/** Keyboard shortcut of each tool (single letters, no modifiers). */\nexport const VECTOR_TOOL_SHORTCUTS: Readonly<Record<VectorTool, string>> = {\n\tselect: 'V',\n\tdirect: 'A',\n\tpen: 'P',\n\tpencil: 'N',\n\trect: 'R',\n\tellipse: 'O',\n\tpolygon: 'Y',\n\tstar: 'S',\n\tline: 'L',\n\tscissors: 'C',\n\tknife: 'K',\n\teraser: 'E',\n\twidth: 'W'\n};\n\n/** Short glyphs for tool buttons (pair them with `vectorToolLabel` for the accessible name). */\nexport const VECTOR_TOOL_GLYPHS: Readonly<Record<VectorTool, string>> = {\n\tselect: '↖',\n\tdirect: '⌖',\n\tpen: '✒',\n\tpencil: '✎',\n\trect: '▭',\n\tellipse: '◯',\n\tpolygon: '⬡',\n\tstar: '☆',\n\tline: '╱',\n\tscissors: '✂',\n\tknife: '⟋',\n\teraser: '⌫',\n\twidth: '⇹'\n};\n\n/** Tools that drag out a shape (they snap while hovering). */\nconst SHAPE_TOOLS: ReadonlySet<VectorTool> = new Set(['rect', 'ellipse', 'polygon', 'star', 'line']);\n\nconst BOOLEAN_OPS: Record<VectorBooleanOperation, 'union' | 'difference' | 'intersection' | 'xor'> = {\n\tunion: 'union',\n\tsubtract: 'difference',\n\tintersect: 'intersection',\n\texclude: 'xor'\n};\n\nconst BOOLEAN_LABELS: Record<VectorBooleanOperation, string> = { union: 'Union', subtract: 'Subtract', intersect: 'Intersect', exclude: 'Exclude' };\n\n/** Replaces nodes by id anywhere in the tree (structural sharing for untouched branches). */\nfunction mapTree(nodes: readonly VectorNode[], fn: (node: VectorNode) => VectorNode | null): VectorNode[] {\n\tlet changed = false;\n\tconst out: VectorNode[] = [];\n\tfor (const node of nodes) {\n\t\tlet next = fn(node);\n\t\tif (next && next.type === 'group') {\n\t\t\tconst children = mapTree(next.children, fn);\n\t\t\tif (children !== next.children) next = { ...next, children };\n\t\t}\n\t\tif (next !== node) changed = true;\n\t\tif (next) out.push(next);\n\t}\n\treturn changed ? out : (nodes as VectorNode[]);\n}\n\n/** Replaces node `id` anywhere in the tree with `replacements` (none removes it). */\nfunction spliceTree(nodes: readonly VectorNode[], id: string, replacements: readonly VectorNode[]): VectorNode[] {\n\tlet changed = false;\n\tconst out: VectorNode[] = [];\n\tfor (const node of nodes) {\n\t\tif (node.id === id) {\n\t\t\tchanged = true;\n\t\t\tout.push(...replacements);\n\t\t\tcontinue;\n\t\t}\n\t\tif (node.type === 'group') {\n\t\t\tconst children = spliceTree(node.children, id, replacements);\n\t\t\tif (children !== node.children) {\n\t\t\t\tchanged = true;\n\t\t\t\tout.push({ ...node, children });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tout.push(node);\n\t}\n\treturn changed ? out : (nodes as VectorNode[]);\n}\n\nconst toPoint = (p: Vec2): Point => [p.x, p.y];\n\nconst isRoot = (m: AffineMatrix) => m === IDENTITY_MATRIX || (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1 && m[4] === 0 && m[5] === 0);\n\nlet idCounter = 0;\nconst defaultCreateId = () => `vn-${Date.now().toString(36)}${(++idCounter).toString(36)}`;\n\n// ---------------------------------------------------------------------------\n// Controller\n// ---------------------------------------------------------------------------\n\ninterface Snapshot {\n\tdoc: VectorDocument;\n\tselection: string[];\n\tanchors: VectorAnchorRef[];\n\teditingId: string | null;\n\tpen: { nodeId: string; subpath: number } | null;\n}\n\n/** Snap targets of a drag, gathered on its first move that needs them. */\ntype DragTargets = { targets?: VectorSnapTargets };\n\ntype Drag =\n\t| ({ kind: 'move'; start: Vec2; origin: VectorBounds | null; before: Snapshot; base: VectorDocument; moved: boolean; duplicated: boolean; clickId: string | null } & DragTargets)\n\t| ({ kind: 'scale'; handle: VectorTransformHandle; start: Vec2; frame: VectorSelectionFrame; before: Snapshot; base: VectorDocument } & DragTargets)\n\t| { kind: 'rotate'; start: Vec2; center: Vec2; before: Snapshot; base: VectorDocument }\n\t| { kind: 'marquee'; start: Vec2; base: string[]; baseAnchors: VectorAnchorRef[]; anchorsMode: boolean }\n\t| ({ kind: 'anchors'; start: Vec2; before: Snapshot; base: VectorDocument; moved: boolean; clickRef: VectorAnchorRef | null; lead: VectorAnchorRef | null } & DragTargets)\n\t| ({ kind: 'handle'; ref: VectorHandleRef; before: Snapshot; base: VectorDocument } & DragTargets)\n\t| { kind: 'bend'; ref: VectorSegmentRef; t: number; start: Vec2; before: Snapshot; base: VectorDocument; moved: boolean }\n\t| { kind: 'corner'; widget: VectorCornerWidget; refs: VectorAnchorRef[]; start: Vec2; before: Snapshot; base: VectorDocument; moved: boolean; alt: boolean; shift: boolean }\n\t| { kind: 'stroke'; tool: 'knife' | 'eraser'; points: Vec2[]; before: Snapshot }\n\t| { kind: 'pull'; ref: VectorAnchorRef; before: Snapshot; base: VectorDocument; label: string; outOnly: boolean; closing: boolean; altBreaks: boolean }\n\t| ({ kind: 'shape'; tool: VectorTool; start: Vec2; nodeId: string; before: Snapshot } & DragTargets)\n\t| { kind: 'pencil'; nodeId: string; points: Point[]; before: Snapshot; lazy: LazyMouse; pressures: number[] | null; pressure: number }\n\t| {\n\t\t\tkind: 'width';\n\t\t\tref: VectorWidthPointRef;\n\t\t\tmode: 'width' | 'move';\n\t\t\tside: 'both' | 'left' | 'right';\n\t\t\t/** The stroke line's point and left normal where the drag started (node space). */\n\t\t\torigin: Vec2;\n\t\t\tnormal: Vec2;\n\t\t\t/** Half the drawn stroke width: side scale 1 reaches this far. */\n\t\t\tunit: number;\n\t\t\tprofile: VectorWidthPoint[];\n\t\t\tbefore: Snapshot;\n\t\t\tbase: VectorDocument;\n\t\t\tstart: Vec2;\n\t\t\tmoved: boolean;\n\t\t\tcreated: boolean;\n\t }\n\t| { kind: 'pan'; start: Vec2; viewport: VectorViewport };\n\n/**\n * Headless state for a vector editor: a document of paths and groups, select / direct /\n * pen / pencil / shape tools driven by pointer and key events, undo, transforms, boolean\n * operations, alignment, grouping, SVG import / export and a viewport. Any UI forwards\n * pointer events (in canvas pixels) and renders `getState()`; `getState()` returns the same\n * object until something changes, so it works with `useSyncExternalStore` and Svelte runes.\n */\nexport class VectorEditorController {\n\treadonly history: HistoryManager;\n\tprivate doc: VectorDocument;\n\tprivate selection: string[] = [];\n\tprivate anchors: VectorAnchorRef[] = [];\n\tprivate widthPoint: VectorWidthPointRef | null = null;\n\tprivate editingId: string | null = null;\n\tprivate pen: { nodeId: string; subpath: number } | null = null;\n\tprivate tool: VectorTool;\n\tprivate defaults: VectorEditorState['defaults'];\n\tprivate viewport: VectorViewport;\n\tprivate snap: VectorSnapOptions;\n\tprivate editing: VectorPathEditOptions;\n\tprivate hitRadius: number;\n\tprivate hover: VectorHover | null = null;\n\tprivate pointer: Vec2 | null = null;\n\tprivate drag: Drag | null = null;\n\tprivate interaction: VectorInteraction | null = null;\n\tprivate guides: VectorSnapGuides | null = null;\n\t/** Whether the last `snapDrawn` landed on an object (guides may be hidden). */\n\tprivate snappedToObject = false;\n\t/** Drawing targets for hovering the pen and shape tools, kept while the document and the excluded path stay the same. */\n\tprivate hoverTargets: { doc: VectorDocument; exclude: string; targets: VectorSnapTargets } | null = null;\n\tprivate spaceHeld = false;\n\tprivate clipboard: VectorNode[] | null = null;\n\tprivate readonly createId: () => string;\n\tprivate readonly onChange?: (document: VectorDocument) => void;\n\tprivate readonly listeners = new Set<(state: VectorEditorState) => void>();\n\tprivate readonly cleanups: Array<() => void> = [];\n\tprivate applying = false;\n\t/** Set while a commit records a change that was already applied, so `restore` still reports it. */\n\tprivate committing = false;\n\tprivate revision = 0;\n\tprivate state!: VectorEditorState;\n\n\tconstructor(options: VectorEditorOptions = {}) {\n\t\tthis.history = options.history ?? new HistoryManager();\n\t\tthis.doc = options.document ? cloneVectorDocument(options.document) : { width: 800, height: 600, nodes: [] };\n\t\tthis.tool = options.tool ?? 'select';\n\t\tthis.defaults = { ...DEFAULT_DEFAULTS, ...(options.defaults ?? {}) } as VectorEditorState['defaults'];\n\t\tthis.viewport = { x: 0, y: 0, zoom: 1, ...(options.viewport ?? {}) };\n\t\tthis.snap = { ...DEFAULT_VECTOR_SNAP, ...(options.snap ?? {}) };\n\t\tthis.editing = { ...DEFAULT_VECTOR_PATH_EDIT, ...(options.editing ?? {}) };\n\t\tthis.hitRadius = options.hitRadius ?? 6;\n\t\tthis.createId = options.createId ?? defaultCreateId;\n\t\tthis.onChange = options.onChange;\n\t\tthis.state = this.computeState();\n\t\tthis.cleanups.push(\n\t\t\tthis.history.subscribe((h) => {\n\t\t\t\tconst s = this.state;\n\t\t\t\tif (this.applying || (s.canUndo === h.canUndo && s.canRedo === h.canRedo && s.undoLabel === h.undoName && s.redoLabel === h.redoName)) return;\n\t\t\t\tthis.notify();\n\t\t\t})\n\t\t);\n\t}\n\n\t/** Stops listening to the history. */\n\tdestroy(): void {\n\t\tthis.cleanups.splice(0).forEach((fn) => fn());\n\t\tthis.listeners.clear();\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// State\n\t// -------------------------------------------------------------------------\n\n\t/** The current snapshot (stable until the next change). */\n\tgetState = (): VectorEditorState => this.state;\n\n\t/** Calls `listener` after every change. Returns an unsubscribe function. */\n\tsubscribe = (listener: (state: VectorEditorState) => void): (() => void) => {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t};\n\n\tgetDocument(): VectorDocument {\n\t\treturn this.doc;\n\t}\n\n\tgetNode(id: string): VectorNode | undefined {\n\t\treturn findVectorNode(this.doc.nodes, id);\n\t}\n\n\tprivate computeState(): VectorEditorState {\n\t\tconst h = this.history.getState();\n\t\treturn {\n\t\t\tdocument: this.doc,\n\t\t\ttool: this.tool,\n\t\t\tselection: this.selection,\n\t\t\tselectedAnchors: this.anchors,\n\t\t\tselectedWidthPoint: this.widthPoint,\n\t\t\teditingId: this.editingId,\n\t\t\tselectionBounds: this.boundsOf(this.selection),\n\t\t\tselectionFrame: this.frameOf(this.selectedRoots()),\n\t\t\tviewport: this.viewport,\n\t\t\tdefaults: this.defaults,\n\t\t\tsnap: this.snap,\n\t\t\tediting: this.editing,\n\t\t\tguides: this.guides,\n\t\t\thitRadius: this.hitRadius,\n\t\t\thover: this.hover,\n\t\t\tcursor: this.cursorFor(),\n\t\t\tinteraction: this.interaction,\n\t\t\tpen: this.pen,\n\t\t\tpointer: this.pointer,\n\t\t\tcanUndo: h.canUndo,\n\t\t\tcanRedo: h.canRedo,\n\t\t\tundoLabel: h.undoName,\n\t\t\tredoLabel: h.redoName,\n\t\t\trevision: this.revision\n\t\t};\n\t}\n\n\tprivate notify(docChanged = false) {\n\t\tthis.revision++;\n\t\tthis.state = this.computeState();\n\t\tif (docChanged) this.onChange?.(this.doc);\n\t\tconst state = this.state;\n\t\tthis.listeners.forEach((listener) => {\n\t\t\ttry {\n\t\t\t\tlistener(state);\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error('[VectorEditorController] Error in state listener:', error);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate boundsOf(ids: readonly string[]): VectorBounds | null {\n\t\treturn unionBounds(\n\t\t\tids.map((id) => {\n\t\t\t\tconst n = this.getNode(id);\n\t\t\t\treturn n ? vectorNodeBounds(n, vectorParentMatrix(this.doc.nodes, id) ?? IDENTITY_MATRIX) : null;\n\t\t\t})\n\t\t);\n\t}\n\n\tprivate frameOf(ids: readonly string[]): VectorSelectionFrame | null {\n\t\treturn getVectorSelectionFrame(this.doc, ids);\n\t}\n\n\t/** Local → document matrix of a node in `doc` (default: the current document). */\n\tprivate worldOf(id: string, doc: VectorDocument = this.doc): AffineMatrix {\n\t\treturn vectorWorldMatrix(doc.nodes, id) ?? IDENTITY_MATRIX;\n\t}\n\n\t/** A document point in node `id`'s own space. */\n\tprivate toLocal(id: string, p: Vec2, doc: VectorDocument = this.doc): Vec2 {\n\t\treturn applyMatrix(invertMatrix(this.worldOf(id, doc)), p);\n\t}\n\n\tprivate cursorFor(): string {\n\t\tif (this.drag?.kind === 'pan' || this.spaceHeld) return this.drag ? 'grabbing' : 'grab';\n\t\tif (this.drag?.kind === 'rotate') return 'grabbing';\n\t\tif (this.drag?.kind === 'move') return 'move';\n\t\tconst h = this.hover;\n\t\tswitch (this.tool) {\n\t\t\tcase 'select':\n\t\t\t\tif (h?.transformHandle) return vectorResizeCursor(h.transformHandle, this.frameOf(this.selectedRoots())?.angle ?? 0);\n\t\t\t\treturn h?.nodeId ? 'move' : 'default';\n\t\t\tcase 'direct':\n\t\t\t\tif (h?.anchor || h?.handle || h?.corner) return 'pointer';\n\t\t\t\tif (h?.segment) return 'copy';\n\t\t\t\treturn h?.nodeId ? 'move' : 'default';\n\t\t\tcase 'pen':\n\t\t\t\treturn h?.anchor ? 'pointer' : 'crosshair';\n\t\t\tcase 'width':\n\t\t\t\tif (this.drag?.kind === 'width') return this.drag.mode === 'move' ? 'grabbing' : 'ew-resize';\n\t\t\t\tif (h?.widthPoint) return h.widthPoint.part === 'center' ? 'grab' : 'ew-resize';\n\t\t\t\treturn h?.strokeSpot ? 'copy' : 'default';\n\t\t\tdefault:\n\t\t\t\treturn 'crosshair';\n\t\t}\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Undoable changes\n\t// -------------------------------------------------------------------------\n\n\tprivate snapshot(): Snapshot {\n\t\treturn { doc: this.doc, selection: this.selection, anchors: this.anchors, editingId: this.editingId, pen: this.pen };\n\t}\n\n\tprivate restore(s: Snapshot) {\n\t\tconst docChanged = s.doc !== this.doc || this.committing;\n\t\tthis.committing = false;\n\t\tthis.applying = true;\n\t\ttry {\n\t\t\tthis.doc = s.doc;\n\t\t\tthis.selection = s.selection.filter((id) => this.getNode(id));\n\t\t\tthis.anchors = s.anchors.filter((r) => getAnchor(this.doc, r));\n\t\t\tthis.editingId = s.editingId && this.getNode(s.editingId) ? s.editingId : null;\n\t\t\tthis.pen = s.pen && (this.getNode(s.pen.nodeId) as VectorPathNode | undefined)?.subpaths?.[s.pen.subpath] ? s.pen : null;\n\t\t} finally {\n\t\t\tthis.applying = false;\n\t\t}\n\t\tthis.notify(docChanged);\n\t}\n\n\t/** Records the change from `before` to the current state as one undo step. */\n\tprivate commit(name: string, before: Snapshot) {\n\t\tconst after = this.snapshot();\n\t\tif (before.doc === after.doc) {\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst command: Command = {\n\t\t\tname,\n\t\t\texecute: () => this.restore(after),\n\t\t\tundo: () => this.restore(before),\n\t\t\tredo: () => this.restore(after)\n\t\t};\n\t\tthis.committing = true;\n\t\tthis.history.execute(command);\n\t\tthis.committing = false;\n\t}\n\n\t/** Runs `fn` (which updates fields) and records it as one undo step. */\n\tprivate change(name: string, fn: () => void): void {\n\t\tconst before = this.snapshot();\n\t\tfn();\n\t\tthis.commit(name, before);\n\t}\n\n\tprivate setDoc(nodes: VectorNode[]) {\n\t\tif (nodes !== this.doc.nodes) this.doc = { ...this.doc, nodes };\n\t}\n\n\tprivate replaceNode(id: string, next: VectorNode | null) {\n\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === id ? next : n)));\n\t}\n\n\tprivate freshIds<T extends VectorNode>(node: T): T {\n\t\tconst copy = cloneVectorNode(node);\n\t\tconst used = new Set<string>();\n\t\twalkVectorNodes(this.doc.nodes, (n) => used.add(n.id));\n\t\tconst next = () => {\n\t\t\tlet id = this.createId();\n\t\t\twhile (used.has(id)) id = this.createId();\n\t\t\tused.add(id);\n\t\t\treturn id;\n\t\t};\n\t\tconst assign = (n: VectorNode) => {\n\t\t\tn.id = next();\n\t\t\tif (n.type === 'group') n.children.forEach(assign);\n\t\t};\n\t\tassign(copy);\n\t\treturn copy;\n\t}\n\n\tprivate newId(): string {\n\t\tlet id = this.createId();\n\t\twhile (this.getNode(id)) id = this.createId();\n\t\treturn id;\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Viewport\n\t// -------------------------------------------------------------------------\n\n\tscreenToDocument(p: Vec2): Vec2 {\n\t\tconst v = this.viewport;\n\t\treturn { x: (p.x - v.x) / v.zoom, y: (p.y - v.y) / v.zoom };\n\t}\n\n\tdocumentToScreen(p: Vec2): Vec2 {\n\t\tconst v = this.viewport;\n\t\treturn { x: p.x * v.zoom + v.x, y: p.y * v.zoom + v.y };\n\t}\n\n\tsetViewport(viewport: Partial<VectorViewport>): void {\n\t\tconst next = { ...this.viewport, ...viewport };\n\t\tnext.zoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, next.zoom));\n\t\tif (next.x === this.viewport.x && next.y === this.viewport.y && next.zoom === this.viewport.zoom) return;\n\t\tthis.viewport = next;\n\t\tthis.notify();\n\t}\n\n\t/** Zooms by `factor` keeping the document point under `screen` in place. */\n\tzoomAt(screen: Vec2, factor: number): void {\n\t\tconst zoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, this.viewport.zoom * factor));\n\t\tconst doc = this.screenToDocument(screen);\n\t\tthis.setViewport({ zoom, x: screen.x - doc.x * zoom, y: screen.y - doc.y * zoom });\n\t}\n\n\tpanBy(dx: number, dy: number): void {\n\t\tthis.setViewport({ x: this.viewport.x + dx, y: this.viewport.y + dy });\n\t}\n\n\t/** Fits the artboard (or `bounds`) into a canvas of `size` screen pixels. */\n\tzoomToFit(size: { width: number; height: number }, options: { padding?: number; bounds?: VectorBounds } = {}): void {\n\t\tconst padding = options.padding ?? 40;\n\t\tconst b = options.bounds ?? { x: 0, y: 0, width: this.doc.width, height: this.doc.height };\n\t\tconst zoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, Math.min((size.width - padding * 2) / (b.width || 1), (size.height - padding * 2) / (b.height || 1))));\n\t\tthis.setViewport({ zoom, x: (size.width - b.width * zoom) / 2 - b.x * zoom, y: (size.height - b.height * zoom) / 2 - b.y * zoom });\n\t}\n\n\t/** Zoom at the canvas centre-ish: positive `delta` zooms out (wheel convention). Use with `wheel`. */\n\twheel(screen: Vec2, delta: { x: number; y: number }, mods: VectorModifiers = {}): void {\n\t\tif (mods.mod) this.zoomAt(screen, Math.exp(-delta.y * 0.01));\n\t\telse this.panBy(-(mods.shift ? delta.y : delta.x), -(mods.shift ? 0 : delta.y));\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Settings\n\t// -------------------------------------------------------------------------\n\n\tsetTool(tool: VectorTool): void {\n\t\tif (tool === this.tool) return;\n\t\tthis.finishPath();\n\t\tthis.cancelDrag();\n\t\tthis.tool = tool;\n\t\tthis.hover = null;\n\t\tthis.guides = null;\n\t\tthis.widthPoint = null;\n\t\tif (tool !== 'direct') {\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t}\n\t\tthis.notify();\n\t}\n\n\tsetDefaults(defaults: Partial<VectorDefaults>): void {\n\t\tthis.defaults = { ...this.defaults, ...defaults };\n\t\tthis.notify();\n\t}\n\n\tsetSnap(snap: Partial<VectorSnapOptions>): void {\n\t\tthis.snap = { ...this.snap, ...snap };\n\t\tif (!this.snap.guides || !this.snap.objects) this.guides = null;\n\t\tthis.notify();\n\t}\n\n\t/** Changes how deleting, dragging anchors, the pencil and the eraser behave. */\n\tsetEditing(editing: Partial<VectorPathEditOptions>): void {\n\t\tconst next = { ...this.editing, ...editing };\n\t\tnext.pencilSmoothing = Math.min(1, Math.max(0, Number.isFinite(next.pencilSmoothing) ? next.pencilSmoothing : 0));\n\t\tif (!(next.eraserSize > 0)) next.eraserSize = this.editing.eraserSize;\n\t\tthis.editing = next;\n\t\tthis.notify();\n\t}\n\n\t/** Turns object snapping on or off (the toolbar's snapping toggle). */\n\ttoggleSnapping(on: boolean = !this.snap.objects): void {\n\t\tthis.setSnap({ objects: on });\n\t}\n\n\tprivate gridValue(v: number): number {\n\t\tconst g = this.snap.grid;\n\t\treturn g > 0 ? Math.round(v / g) * g : v;\n\t}\n\n\tprivate snapPoint(p: Vec2): Vec2 {\n\t\treturn { x: this.gridValue(p.x), y: this.gridValue(p.y) };\n\t}\n\n\t/** The pull distance in document units. */\n\tprivate snapTolerance(): number {\n\t\treturn this.snap.threshold / this.viewport.zoom;\n\t}\n\n\tprivate setGuides(guides: VectorSnapGuides | null) {\n\t\tthis.guides = guides && this.snap.guides && (guides.lines.length || guides.labels.length) ? guides : null;\n\t}\n\n\t/**\n\t * Where a drawn or dragged point `p` goes: onto the smart guide `targets` (gathered by\n\t * `gather` when missing), else onto the grid, kept to `leave`'s constraint. Cmd / Ctrl\n\t * bypasses snapping.\n\t */\n\tprivate snapDrawn(p: Vec2, leave: VectorSnapLeave | null, input: VectorModifiers, targets: () => VectorSnapTargets): Vec2 {\n\t\tthis.snappedToObject = false;\n\t\tif (input.mod) {\n\t\t\tthis.setGuides(null);\n\t\t\treturn constrainToLeave(leave, p);\n\t\t}\n\t\tif (this.snap.objects) {\n\t\t\tconst withAngles = leave ? { ...leave, angles: this.snap.angles } : null;\n\t\t\tconst res = targets().snapFrom(p, withAngles, this.snapTolerance());\n\t\t\tif (res.kind) {\n\t\t\t\tthis.snappedToObject = true;\n\t\t\t\tthis.setGuides(res);\n\t\t\t\t// An axis lined up with nothing still goes to the grid.\n\t\t\t\treturn leave?.constrain ? res.point : { x: res.x ? res.point.x : this.gridValue(res.point.x), y: res.y ? res.point.y : this.gridValue(res.point.y) };\n\t\t\t}\n\t\t}\n\t\tthis.setGuides(null);\n\t\treturn constrainToLeave(leave, this.snapPoint(p));\n\t}\n\n\t/** Drawing targets for the pen and shape tools, reused while the document stays the same. */\n\tprivate drawingTargets(exclude: string | null): VectorSnapTargets {\n\t\tconst key = exclude ?? '';\n\t\tconst cached = this.hoverTargets;\n\t\tif (cached && cached.doc === this.doc && cached.exclude === key) return cached.targets;\n\t\tconst targets = VectorSnapTargets.forDrawing(this.doc, exclude ? [exclude] : []);\n\t\tthis.hoverTargets = { doc: this.doc, exclude: key, targets };\n\t\treturn targets;\n\t}\n\n\t/** Where the pointer at `p` would place a point with the pen or a shape tool (and the guides showing why). */\n\tprivate hoverSnap(p: Vec2, input: VectorModifiers): Vec2 {\n\t\tif (this.tool === 'pen') {\n\t\t\tconst sp = this.pen ? (this.getNode(this.pen.nodeId) as VectorPathNode | undefined)?.subpaths[this.pen.subpath] : undefined;\n\t\t\tif (this.pen && sp && this.hover?.anchor) {\n\t\t\t\tthis.setGuides(null);\n\t\t\t\treturn p;\n\t\t\t}\n\t\t\tconst last = this.pen && sp ? getAnchorWorld(this.doc, { nodeId: this.pen.nodeId, subpath: this.pen.subpath, index: sp.anchors.length - 1 }) : undefined;\n\t\t\tconst leave = last ? { at: { x: last.x, y: last.y }, constrain: input.shift ? ('angle' as const) : null } : null;\n\t\t\treturn this.snapDrawn(p, leave, input, () => this.drawingTargets(this.pen?.nodeId ?? null));\n\t\t}\n\t\tif (SHAPE_TOOLS.has(this.tool)) return this.snapDrawn(p, null, input, () => this.drawingTargets(null));\n\t\tthis.setGuides(null);\n\t\treturn p;\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Document\n\t// -------------------------------------------------------------------------\n\n\t/** Replaces the document. Undoable unless `{ history: false }` (then history is cleared). */\n\tsetDocument(doc: VectorDocument, options: { history?: boolean; label?: string } = {}): void {\n\t\tthis.cancelDrag();\n\t\tconst next = cloneVectorDocument(doc);\n\t\tif (options.history === false) {\n\t\t\tthis.doc = next;\n\t\t\tthis.selection = [];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t\tthis.pen = null;\n\t\t\tthis.history.clear();\n\t\t\tthis.notify(true);\n\t\t\treturn;\n\t\t}\n\t\tthis.change(options.label ?? 'Replace Document', () => {\n\t\t\tthis.doc = next;\n\t\t\tthis.selection = [];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t\tthis.pen = null;\n\t\t});\n\t}\n\n\t/** Changes the artboard size or background. */\n\tsetArtboard(patch: Partial<Pick<VectorDocument, 'width' | 'height' | 'background'>>): void {\n\t\tthis.change('Change Artboard', () => {\n\t\t\tthis.doc = { ...this.doc, ...patch };\n\t\t});\n\t}\n\n\t/** Replaces the document with parsed SVG markup (one undo step). */\n\tloadSvg(svg: string, options: { history?: boolean } = {}): VectorActionResult {\n\t\ttry {\n\t\t\tconst doc = parseVectorSvg(svg, { createId: () => this.createId() });\n\t\t\tthis.setDocument(doc, { history: options.history, label: 'Import SVG' });\n\t\t\treturn { ok: true };\n\t\t} catch (error) {\n\t\t\treturn { ok: false, message: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n\n\t/** Adds the nodes of SVG markup on top of the document, selected. */\n\timportSvg(svg: string): VectorActionResult {\n\t\ttry {\n\t\t\tconst parsed = parseVectorSvg(svg);\n\t\t\tconst nodes = parsed.nodes.map((n) => this.freshIds(n));\n\t\t\tif (!nodes.length) return { ok: false, message: 'The SVG has no shapes the editor can read.' };\n\t\t\tthis.change('Import SVG', () => {\n\t\t\t\tthis.setDoc([...this.doc.nodes, ...nodes]);\n\t\t\t\tthis.selection = nodes.map((n) => n.id);\n\t\t\t\tthis.anchors = [];\n\t\t\t});\n\t\t\treturn { ok: true };\n\t\t} catch (error) {\n\t\t\treturn { ok: false, message: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n\n\ttoSvg(options?: VectorSvgExportOptions): string {\n\t\treturn vectorDocumentToSvg(this.doc, options);\n\t}\n\n\ttoJSON(): VectorDocument {\n\t\treturn cloneVectorDocument(this.doc);\n\t}\n\n\t/** Adds a node (ids are kept unless taken). Returns its id. */\n\taddNode(node: VectorNode, options: AddVectorNodeOptions = {}): string {\n\t\tconst taken = (() => {\n\t\t\tlet clash = false;\n\t\t\twalkVectorNodes([node], (n) => {\n\t\t\t\tif (this.getNode(n.id)) clash = true;\n\t\t\t});\n\t\t\treturn clash;\n\t\t})();\n\t\tconst next = taken ? this.freshIds(node) : cloneVectorNode(node);\n\t\tthis.change(options.label ?? `Add ${next.type === 'group' ? 'Group' : (next.name ?? 'Path')}`, () => {\n\t\t\tconst insert = (list: VectorNode[]) => {\n\t\t\t\tconst copy = list.slice();\n\t\t\t\tcopy.splice(options.index ?? copy.length, 0, next);\n\t\t\t\treturn copy;\n\t\t\t};\n\t\t\tif (options.parentId) {\n\t\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === options.parentId && n.type === 'group' ? { ...n, children: insert(n.children) } : n)));\n\t\t\t} else this.setDoc(insert(this.doc.nodes));\n\t\t\tif (options.select !== false) {\n\t\t\t\tthis.selection = [next.id];\n\t\t\t\tthis.anchors = [];\n\t\t\t}\n\t\t});\n\t\treturn next.id;\n\t}\n\n\t/** Builds a path node for a shape with the current defaults (not added). */\n\tcreateShapeNode(input: VectorShapeInput): VectorPathNode {\n\t\tconst b = { x: input.x, y: input.y, width: input.width, height: input.height };\n\t\tconst d = this.defaults;\n\t\tlet subpath: VectorSubpath;\n\t\tswitch (input.kind) {\n\t\t\tcase 'rect':\n\t\t\t\tsubpath = rectSubpath(b);\n\t\t\t\tbreak;\n\t\t\tcase 'ellipse':\n\t\t\t\tsubpath = ellipseSubpath(b);\n\t\t\t\tbreak;\n\t\t\tcase 'polygon':\n\t\t\t\tsubpath = polygonSubpath(b, input.sides ?? d.polygonSides);\n\t\t\t\tbreak;\n\t\t\tcase 'star':\n\t\t\t\tsubpath = starSubpath(b, input.points ?? d.starPoints, input.innerRatio ?? d.starInnerRatio);\n\t\t\t\tbreak;\n\t\t\tcase 'line':\n\t\t\t\tsubpath = lineSubpath({ x: b.x, y: b.y }, { x: b.x + b.width, y: b.y + b.height });\n\t\t\t\tbreak;\n\t\t}\n\t\tconst radius = input.cornerRadius ?? d.cornerRadius;\n\t\tconst kind = input.cornerKind ?? d.cornerKind;\n\t\t// Live corners: the shape keeps its sharp anchors, so the radius stays editable.\n\t\tif ((input.kind === 'rect' || input.kind === 'polygon' || input.kind === 'star') && radius > 0) subpath = setSubpathCorners(subpath, radius, kind);\n\t\tconst names = { rect: 'Rectangle', ellipse: 'Ellipse', polygon: 'Polygon', star: 'Star', line: 'Line' };\n\t\tconst style = this.styleFor(input.kind === 'line');\n\t\tconst own: VectorStyle = {};\n\t\tfor (const key of VECTOR_STYLE_KEYS) {\n\t\t\tif (input[key] !== undefined) (own as any)[key] = input[key];\n\t\t}\n\t\treturn { id: this.newId(), type: 'path', name: input.name ?? names[input.kind], ...style, ...own, subpaths: [subpath] };\n\t}\n\n\t/** Adds a shape drawn with the current defaults. Returns its id. */\n\taddShape(input: VectorShapeInput, options: AddVectorNodeOptions = {}): string {\n\t\tconst node = this.createShapeNode(input);\n\t\treturn this.addNode(node, { label: `Add ${node.name}`, ...options });\n\t}\n\n\t/** Adds a path from SVG path data. Returns its id. */\n\taddPath(d: string, style: VectorStyle & { name?: string } = {}, options: AddVectorNodeOptions = {}): string {\n\t\tconst subpaths = bezierToSubpaths(d);\n\t\tconst node: VectorPathNode = { id: this.newId(), type: 'path', name: style.name ?? 'Path', ...this.styleFor(false), ...style, subpaths };\n\t\treturn this.addNode(node, { label: 'Add Path', ...options });\n\t}\n\n\tprivate styleFor(open: boolean): VectorStyle {\n\t\tconst d = this.defaults;\n\t\tconst out: VectorStyle = { fill: open ? null : (d.fill ?? null), stroke: d.stroke ?? null, strokeWidth: d.strokeWidth ?? 1 };\n\t\tif (d.strokeLinecap) out.strokeLinecap = d.strokeLinecap;\n\t\tif (d.strokeLinejoin) out.strokeLinejoin = d.strokeLinejoin;\n\t\tif (d.strokeDasharray) out.strokeDasharray = d.strokeDasharray;\n\t\tif (d.fillRule) out.fillRule = d.fillRule;\n\t\tif (d.strokeAlign && d.strokeAlign !== 'center') out.strokeAlign = d.strokeAlign;\n\t\tfor (const key of ['startArrow', 'endArrow', 'arrowAlign', 'startArrowScale', 'endArrowScale'] as const) if (d[key]) (out as any)[key] = d[key];\n\t\tif (d.strokeWidthProfile?.length) out.strokeWidthProfile = d.strokeWidthProfile.map((p) => ({ ...p }));\n\t\treturn out;\n\t}\n\n\t/** Merges `patch` into a node (paths take style and geometry; groups name / visibility / opacity). */\n\tupdateNode(id: string, patch: Partial<VectorPathNode> | Partial<VectorGroupNode>, options: { label?: string } = {}): VectorActionResult {\n\t\tconst node = this.getNode(id);\n\t\tif (!node) return { ok: false, message: `There is no node \"${id}\".` };\n\t\tconst { id: _id, type: _type, ...rest } = patch as any;\n\t\tthis.change(options.label ?? 'Edit Node', () => this.replaceNode(id, { ...node, ...rest } as VectorNode));\n\t\treturn { ok: true };\n\t}\n\n\t/** Applies style (and opacity) to the selected (or given) nodes; groups pass it to every path inside. */\n\tsetStyle(style: VectorStyle & { opacity?: number }, ids: readonly string[] = this.selection, options: { label?: string } = {}): VectorActionResult {\n\t\tconst targets = new Set<string>();\n\t\tfor (const id of ids) {\n\t\t\tconst node = this.getNode(id);\n\t\t\tif (!node) return { ok: false, message: `There is no node \"${id}\".` };\n\t\t\tfor (const p of collectPathNodes(node)) targets.add(p.id);\n\t\t}\n\t\tif (!targets.size) return { ok: false, message: 'Nothing is selected.' };\n\t\tthis.change(options.label ?? 'Change Style', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (targets.has(n.id) ? withStyle(n as VectorPathNode, style) : n)));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/**\n\t * Sets the variable-width profile of the selected (or given) paths: a preset id\n\t * (`uniform` removes the profile), points, or a parametric taper / wave. Returns an error for\n\t * an unknown preset.\n\t */\n\tsetWidthProfile(\n\t\tprofile: VectorWidthPreset | readonly VectorWidthPoint[] | { taper?: VectorTaperOptions; wave?: VectorWaveOptions } | null,\n\t\toptions: { ids?: readonly string[] } = {}\n\t): VectorActionResult {\n\t\tlet points: VectorWidthPoint[];\n\t\tif (profile === null) points = [];\n\t\telse if (typeof profile === 'string') {\n\t\t\tconst preset = widthProfilePreset(profile);\n\t\t\tif (!preset) return { ok: false, message: `There is no width profile \"${profile}\".` };\n\t\t\tpoints = preset;\n\t\t} else if (Array.isArray(profile)) points = sanitizeWidthProfile(profile);\n\t\telse {\n\t\t\tconst p = profile as { taper?: VectorTaperOptions; wave?: VectorWaveOptions };\n\t\t\tpoints = p.taper || p.wave ? generateWidthProfile(p) : [];\n\t\t}\n\t\tthis.widthPoint = null;\n\t\treturn this.setStyle({ strokeWidthProfile: points.length ? points : null }, options.ids ?? this.selection, { label: points.length ? 'Width Profile' : 'Uniform Width' });\n\t}\n\n\t/** Removes one width point of a path's profile (the width tool's Delete). */\n\tremoveWidthPoint(ref: Pick<VectorWidthPointRef, 'nodeId' | 'index'>): VectorActionResult {\n\t\tconst node = this.getNode(ref.nodeId);\n\t\tif (node?.type !== 'path' || !node.strokeWidthProfile?.[ref.index]) return { ok: false, message: 'There is no such width point.' };\n\t\tconst rest = removeWidthPoints(sanitizeWidthProfile(node.strokeWidthProfile), [ref.index]);\n\t\tthis.widthPoint = null;\n\t\tthis.change('Delete Width Point', () => this.replaceNode(node.id, withStyle(node, { strokeWidthProfile: rest.length ? rest : null })));\n\t\treturn { ok: true };\n\t}\n\n\t/**\n\t * Sets the live corner radius (and optionally the kind) of anchors: `refs`, else the selected\n\t * anchors (direct tool), else every anchor of the `ids` / selected paths. Radius 0 makes the\n\t * corners sharp again. Corners shrink to fit when drawn, so any radius is accepted.\n\t */\n\tsetCornerRadius(radius: number, options: { kind?: VectorCornerKind; refs?: readonly VectorAnchorRef[]; ids?: readonly string[] } = {}): VectorActionResult {\n\t\tif (!Number.isFinite(radius) || radius < 0) return { ok: false, message: 'The radius must be a number of at least 0.' };\n\t\tconst refs = this.cornerTargets(options);\n\t\tif (!refs.length) return { ok: false, message: 'Nothing is selected.' };\n\t\tthis.change(radius > 0 ? 'Corner Radius' : 'Sharpen Corners', () => {\n\t\t\tthis.doc = this.updateAnchors(this.doc, refs, (a) => setAnchorCorner(a, radius, options.kind));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Sets the live corner kind of the same anchors as `setCornerRadius`, keeping their radii. */\n\tsetCornerKind(kind: VectorCornerKind, options: { refs?: readonly VectorAnchorRef[]; ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst refs = this.cornerTargets(options);\n\t\tif (!refs.length) return { ok: false, message: 'Nothing is selected.' };\n\t\tthis.change('Corner Kind', () => {\n\t\t\tthis.doc = this.updateAnchors(this.doc, refs, (a) => setAnchorCorner(a, a.corner?.radius ?? 0, kind));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Anchors a corner change applies to (see `setCornerRadius`). */\n\tprivate cornerTargets(options: { refs?: readonly VectorAnchorRef[]; ids?: readonly string[] }): VectorAnchorRef[] {\n\t\tif (options.refs) return options.refs.filter((r) => getAnchor(this.doc, r));\n\t\tif (!options.ids && this.tool === 'direct' && this.anchors.length) return this.anchors.slice();\n\t\tconst out: VectorAnchorRef[] = [];\n\t\tfor (const id of options.ids ?? this.selection) {\n\t\t\tconst node = this.getNode(id);\n\t\t\tif (!node) continue;\n\t\t\tfor (const p of collectPathNodes(node)) {\n\t\t\t\tif (p.locked) continue;\n\t\t\t\tp.subpaths.forEach((sp, s) => sp.anchors.forEach((_, i) => out.push({ nodeId: p.id, subpath: s, index: i })));\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n\t/**\n\t * Outline Stroke: replaces each selected (or given) path's stroke with a filled path of the\n\t * area it paints (alignment, joins, caps, dashes and arrowheads included), placed above a copy\n\t * of the path that keeps the fill (left out when there is none). Returns the new paths' ids.\n\t */\n\toutlineStroke(options: { ids?: readonly string[] } = {}): string[] {\n\t\tconst roots = options.ids ?? this.selectedRoots();\n\t\tconst paths: VectorPathNode[] = [];\n\t\tfor (const id of roots) {\n\t\t\tconst node = this.getNode(id);\n\t\t\tif (node) for (const p of collectPathNodes(node)) if (!p.locked && hasPaint(p.stroke) && (p.strokeWidth ?? 1) > 0) paths.push(p);\n\t\t}\n\t\tif (!paths.length) return [];\n\t\tconst created: string[] = [];\n\t\tconst replace = new Map<string, VectorNode[]>();\n\t\tfor (const p of paths) {\n\t\t\t// In the node's own space: the new paths keep its transform.\n\t\t\tconst outline = bezierToSubpaths(vectorStrokeOutlinePath(subpathsToBezier(p.subpaths), p));\n\t\t\tif (!outline.length) continue;\n\t\t\tconst {\n\t\t\t\tstroke,\n\t\t\t\tstrokeWidth: _w,\n\t\t\t\tstrokeLinecap: _c,\n\t\t\t\tstrokeLinejoin: _j,\n\t\t\t\tstrokeDasharray: _d,\n\t\t\t\tstrokeAlign: _a,\n\t\t\t\tstartArrow: _s,\n\t\t\t\tendArrow: _e,\n\t\t\t\tarrowAlign: _al,\n\t\t\t\tstartArrowScale: _ss,\n\t\t\t\tendArrowScale: _es,\n\t\t\t\tstrokeWidthProfile: _wp,\n\t\t\t\t...rest\n\t\t\t} = cloneVectorNode(p);\n\t\t\tconst id = this.newId();\n\t\t\tconst strokeNode: VectorPathNode = { ...rest, id, name: `${p.name ?? 'Path'} Stroke`, subpaths: outline, fill: stroke ?? null, stroke: null, fillRule: 'nonzero' };\n\t\t\tconst list: VectorNode[] = hasPaint(p.fill) ? [{ ...rest, stroke: null }, strokeNode] : [strokeNode];\n\t\t\tcreated.push(id);\n\t\t\treplace.set(p.id, list);\n\t\t}\n\t\tif (!created.length) return [];\n\t\tthis.change('Outline Stroke', () => {\n\t\t\tlet nodes = this.doc.nodes;\n\t\t\tfor (const [id, list] of replace) nodes = spliceTree(nodes, id, list);\n\t\t\tthis.setDoc(nodes);\n\t\t\tthis.selection = created;\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn created;\n\t}\n\n\trename(id: string, name: string): VectorActionResult {\n\t\treturn this.updateNode(id, { name }, { label: 'Rename' });\n\t}\n\n\tsetVisible(id: string, visible: boolean): VectorActionResult {\n\t\treturn this.updateNode(id, { visible }, { label: visible ? 'Show' : 'Hide' });\n\t}\n\n\tsetLocked(id: string, locked: boolean): VectorActionResult {\n\t\tconst result = this.updateNode(id, { locked }, { label: locked ? 'Lock' : 'Unlock' });\n\t\tif (locked && result.ok && this.selection.includes(id)) {\n\t\t\tthis.selection = this.selection.filter((s) => s !== id);\n\t\t\tthis.notify();\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Removes nodes by id. */\n\tremoveNodes(ids: readonly string[], options: { label?: string } = {}): VectorActionResult {\n\t\tconst drop = new Set(ids.filter((id) => this.getNode(id)));\n\t\tif (!drop.size) return { ok: false, message: 'Nothing to delete.' };\n\t\tthis.change(options.label ?? 'Delete', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (drop.has(n.id) ? null : n)));\n\t\t\tthis.selection = this.selection.filter((id) => !drop.has(id) && this.getNode(id));\n\t\t\tthis.anchors = this.anchors.filter((r) => getAnchor(this.doc, r));\n\t\t\tif (this.editingId && !this.getNode(this.editingId)) this.editingId = null;\n\t\t\tif (this.pen && !this.getNode(this.pen.nodeId)) this.pen = null;\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Selection\n\t// -------------------------------------------------------------------------\n\n\tselect(ids: readonly string[], options: { add?: boolean; toggle?: boolean } = {}): void {\n\t\tconst valid = ids.filter((id) => this.getNode(id));\n\t\tlet next: string[];\n\t\tif (options.toggle) {\n\t\t\tconst set = new Set(this.selection);\n\t\t\tfor (const id of valid) set.has(id) ? set.delete(id) : set.add(id);\n\t\t\tnext = [...set];\n\t\t} else next = options.add ? [...new Set([...this.selection, ...valid])] : valid;\n\t\tthis.selection = next;\n\t\tif (!options.add && !options.toggle) this.anchors = this.anchors.filter((r) => next.includes(r.nodeId));\n\t\tthis.notify();\n\t}\n\n\tselectAll(): void {\n\t\tif (this.tool === 'direct' && this.editingId) {\n\t\t\tthis.anchors = getVisibleAnchors(this.view());\n\t\t} else {\n\t\t\tthis.selection = this.doc.nodes.filter((n) => !n.locked && n.visible !== false).map((n) => n.id);\n\t\t}\n\t\tthis.notify();\n\t}\n\n\tclearSelection(): void {\n\t\tif (!this.selection.length && !this.anchors.length && !this.editingId) return;\n\t\tthis.selection = [];\n\t\tthis.anchors = [];\n\t\tthis.editingId = null;\n\t\tthis.notify();\n\t}\n\n\tselectAnchors(refs: readonly VectorAnchorRef[], options: { add?: boolean } = {}): void {\n\t\tconst valid = refs.filter((r) => getAnchor(this.doc, r));\n\t\tthis.anchors = options.add ? [...this.anchors, ...valid.filter((r) => !this.anchors.some((a) => sameRef(a, r)))] : valid;\n\t\tif (valid.length && !this.editingId) this.editingId = valid[0].nodeId;\n\t\tthis.notify();\n\t}\n\n\t/** Top-level ids of the selection (members of selected groups are covered by the group). */\n\tprivate selectedRoots(): string[] {\n\t\treturn this.selection.filter((id) => {\n\t\t\tlet covered = false;\n\t\t\tconst loc = locateVectorNode(this.doc.nodes, id);\n\t\t\tlet parent = loc?.parent ?? null;\n\t\t\twhile (parent) {\n\t\t\t\tif (this.selection.includes(parent.id)) covered = true;\n\t\t\t\tparent = locateVectorNode(this.doc.nodes, parent.id)?.parent ?? null;\n\t\t\t}\n\t\t\treturn !covered;\n\t\t});\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Transforms\n\t// -------------------------------------------------------------------------\n\n\t/** `m`, given in a frame rotated by `angle`, as a document-space matrix. */\n\tprivate inFrame(angle: number, m: AffineMatrix): AffineMatrix {\n\t\tif (!angle) return m;\n\t\treturn multiplyMatrices(multiplyMatrices(rotateMatrix(-angle), m), rotateMatrix(angle));\n\t}\n\n\t/** Applies a matrix to the selected (or given) nodes as one undo step. */\n\ttransform(matrix: AffineMatrix, options: { ids?: readonly string[]; label?: string } = {}): VectorActionResult {\n\t\tconst ids = new Set(options.ids ?? this.selectedRoots());\n\t\tif (!ids.size) return { ok: false, message: 'Nothing is selected.' };\n\t\tthis.change(options.label ?? 'Transform', () => {\n\t\t\tthis.doc = this.transformed(this.doc, ids, matrix);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** `doc` with nodes `ids` moved by `m`, given in document space. */\n\tprivate transformed(doc: VectorDocument, ids: ReadonlySet<string>, m: AffineMatrix): VectorDocument {\n\t\tconst visit = (list: readonly VectorNode[], parent: AffineMatrix): VectorNode[] => {\n\t\t\tlet changed = false;\n\t\t\tconst out = list.map((n) => {\n\t\t\t\tlet next = n;\n\t\t\t\tif (ids.has(n.id) && !n.locked) {\n\t\t\t\t\t// `m` in the node's parent space: parent → document, m, document → parent.\n\t\t\t\t\tconst local = isRoot(parent) ? m : multiplyMatrices(multiplyMatrices(parent, m), invertMatrix(parent));\n\t\t\t\t\tnext = transformVectorNode(n, local);\n\t\t\t\t} else if (n.type === 'group') {\n\t\t\t\t\tconst children = visit(n.children, multiplyMatrices(nodeMatrix(n), parent));\n\t\t\t\t\tif (children !== n.children) next = { ...n, children };\n\t\t\t\t}\n\t\t\t\tif (next !== n) changed = true;\n\t\t\t\treturn next;\n\t\t\t});\n\t\t\treturn changed ? out : (list as VectorNode[]);\n\t\t};\n\t\tconst nodes = visit(doc.nodes, IDENTITY_MATRIX);\n\t\treturn nodes === doc.nodes ? doc : { ...doc, nodes };\n\t}\n\n\ttranslate(dx: number, dy: number, options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tif (this.tool === 'direct' && this.anchors.length && !options.ids) {\n\t\t\tthis.change('Move Points', () => {\n\t\t\t\tthis.doc = this.movedAnchors(this.doc, this.anchors, dx, dy);\n\t\t\t});\n\t\t\treturn { ok: true };\n\t\t}\n\t\treturn this.transform(translateMatrix(dx, dy), { ids: options.ids, label: 'Move' });\n\t}\n\n\t/** The selection frame's centre in document space. */\n\tprivate frameCenter(frame: VectorSelectionFrame): Vec2 {\n\t\treturn applyMatrix(rotateMatrix(frame.angle), { x: frame.x + frame.width / 2, y: frame.y + frame.height / 2 });\n\t}\n\n\t/**\n\t * Scales along the selection box's own axes (rotated with the selection when its nodes\n\t * share a rotation) around `origin` (default: the box centre, in document space).\n\t */\n\tscale(sx: number, sy: number = sx, options: { ids?: readonly string[]; origin?: Vec2 } = {}): VectorActionResult {\n\t\tconst frame = this.frameOf(options.ids ?? this.selectedRoots());\n\t\tif (!frame) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst origin = applyMatrix(rotateMatrix(-frame.angle), options.origin ?? this.frameCenter(frame));\n\t\treturn this.transform(this.inFrame(frame.angle, scaleMatrix(sx, sy, origin)), { ids: options.ids, label: 'Scale' });\n\t}\n\n\t/** Rotates clockwise by `degrees` around `origin` (default: the selection centre). */\n\trotate(degrees: number, options: { ids?: readonly string[]; origin?: Vec2 } = {}): VectorActionResult {\n\t\tconst frame = this.frameOf(options.ids ?? this.selectedRoots());\n\t\tif (!frame) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst origin = options.origin ?? this.frameCenter(frame);\n\t\treturn this.transform(rotateMatrix(degrees, origin), { ids: options.ids, label: 'Rotate' });\n\t}\n\n\t/** Sets each selected (or given) node's rotation to `degrees`, turning it around its own centre. */\n\tsetRotation(degrees: number, options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tif (!ids.length) return { ok: false, message: 'Nothing is selected.' };\n\t\tthis.change('Set Rotation', () => {\n\t\t\tfor (const id of ids) {\n\t\t\t\tconst frame = this.frameOf([id]);\n\t\t\t\tif (!frame) continue;\n\t\t\t\tconst delta = normalizeAngle(degrees - frame.angle);\n\t\t\t\tif (Math.abs(delta) > 1e-9) this.doc = this.transformed(this.doc, new Set([id]), rotateMatrix(delta, this.frameCenter(frame)));\n\t\t\t}\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Mirrors along the selection box's own axes. */\n\tflip(axis: 'horizontal' | 'vertical', options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst frame = this.frameOf(options.ids ?? this.selectedRoots());\n\t\tif (!frame) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst c = { x: frame.x + frame.width / 2, y: frame.y + frame.height / 2 };\n\t\tconst m = axis === 'horizontal' ? scaleMatrix(-1, 1, c) : scaleMatrix(1, -1, c);\n\t\treturn this.transform(this.inFrame(frame.angle, m), { ids: options.ids, label: axis === 'horizontal' ? 'Flip Horizontal' : 'Flip Vertical' });\n\t}\n\n\t/**\n\t * Aligns the selected nodes to their combined bounds, or to the artboard when one node is\n\t * selected (or `to: 'artboard'`).\n\t */\n\talign(edge: VectorAlign, options: { ids?: readonly string[]; to?: 'selection' | 'artboard' } = {}): VectorActionResult {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tif (!ids.length) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst target = options.to === 'artboard' || ids.length === 1 ? { x: 0, y: 0, width: this.doc.width, height: this.doc.height } : this.boundsOf(ids)!;\n\t\tthis.change(`Align ${edge[0].toUpperCase()}${edge.slice(1)}`, () => {\n\t\t\tfor (const id of ids) {\n\t\t\t\tconst b = this.boundsOf([id]);\n\t\t\t\tif (!b) continue;\n\t\t\t\tlet dx = 0;\n\t\t\t\tlet dy = 0;\n\t\t\t\tif (edge === 'left') dx = target.x - b.x;\n\t\t\t\tif (edge === 'center') dx = target.x + target.width / 2 - (b.x + b.width / 2);\n\t\t\t\tif (edge === 'right') dx = target.x + target.width - (b.x + b.width);\n\t\t\t\tif (edge === 'top') dy = target.y - b.y;\n\t\t\t\tif (edge === 'middle') dy = target.y + target.height / 2 - (b.y + b.height / 2);\n\t\t\t\tif (edge === 'bottom') dy = target.y + target.height - (b.y + b.height);\n\t\t\t\tif (dx || dy) this.doc = this.transformed(this.doc, new Set([id]), translateMatrix(dx, dy));\n\t\t\t}\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Spaces three or more selected nodes evenly (equal gaps). */\n\tdistribute(direction: VectorDistribute, options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tconst items = ids.map((id) => ({ id, b: this.boundsOf([id]) })).filter((i): i is { id: string; b: VectorBounds } => !!i.b);\n\t\tif (items.length < 3) return { ok: false, message: 'Select at least three objects to distribute.' };\n\t\tconst horizontal = direction === 'horizontal';\n\t\tconst pos = (b: VectorBounds) => (horizontal ? b.x : b.y);\n\t\tconst size = (b: VectorBounds) => (horizontal ? b.width : b.height);\n\t\titems.sort((a, b) => pos(a.b) - pos(b.b));\n\t\tconst first = items[0].b;\n\t\tconst last = items[items.length - 1].b;\n\t\tconst total = pos(last) + size(last) - pos(first);\n\t\tconst gap = (total - items.reduce((s, i) => s + size(i.b), 0)) / (items.length - 1);\n\t\tthis.change(horizontal ? 'Distribute Horizontally' : 'Distribute Vertically', () => {\n\t\t\tlet cursor = pos(first);\n\t\t\tfor (const item of items) {\n\t\t\t\tconst d = cursor - pos(item.b);\n\t\t\t\tif (Math.abs(d) > 1e-9) this.doc = this.transformed(this.doc, new Set([item.id]), horizontal ? translateMatrix(d, 0) : translateMatrix(0, d));\n\t\t\t\tcursor += size(item.b) + gap;\n\t\t\t}\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Structure\n\t// -------------------------------------------------------------------------\n\n\t/** Copies the selection (offset by `offset`, default 10, 10) on top of each original. */\n\tduplicate(options: { ids?: readonly string[]; offset?: Vec2 } = {}): string[] {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tconst offset = options.offset ?? { x: 10, y: 10 };\n\t\tconst created: string[] = [];\n\t\tif (!ids.length) return created;\n\t\tthis.change('Duplicate', () => {\n\t\t\tthis.doc = this.withDuplicates(this.doc, ids, offset, created);\n\t\t\tthis.selection = created;\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn created;\n\t}\n\n\tprivate withDuplicates(doc: VectorDocument, ids: readonly string[], offset: Vec2, created: string[]): VectorDocument {\n\t\tconst set = new Set(ids);\n\t\tconst m = translateMatrix(offset.x, offset.y);\n\t\tconst insert = (list: readonly VectorNode[]): VectorNode[] => {\n\t\t\tconst out: VectorNode[] = [];\n\t\t\tfor (const node of list) {\n\t\t\t\tconst n = node.type === 'group' ? { ...node, children: insert(node.children) } : node;\n\t\t\t\tout.push(n);\n\t\t\t\tif (set.has(node.id)) {\n\t\t\t\t\tconst copy = transformVectorNode(this.freshIds(node), m);\n\t\t\t\t\tcreated.push(copy.id);\n\t\t\t\t\tout.push(copy);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn out;\n\t\t};\n\t\treturn { ...doc, nodes: insert(doc.nodes) };\n\t}\n\n\t/** Groups the selected nodes (they must share a parent). Returns the group id. */\n\tgroup(options: { ids?: readonly string[]; name?: string } = {}): string | null {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tif (!ids.length) return null;\n\t\tconst locs = ids.map((id) => locateVectorNode(this.doc.nodes, id));\n\t\tif (locs.some((l) => !l)) return null;\n\t\tconst parent = locs[0]!.parent?.id ?? null;\n\t\tif (locs.some((l) => (l!.parent?.id ?? null) !== parent)) return null;\n\t\tconst id = this.newId();\n\t\tthis.change('Group', () => {\n\t\t\tconst set = new Set(ids);\n\t\t\tconst regroup = (list: readonly VectorNode[]): VectorNode[] => {\n\t\t\t\tconst members = list.filter((n) => set.has(n.id));\n\t\t\t\tconst top = Math.max(...members.map((m) => list.indexOf(m)));\n\t\t\t\tconst out: VectorNode[] = [];\n\t\t\t\tlist.forEach((n, i) => {\n\t\t\t\t\tif (i === top) out.push({ id, type: 'group', name: options.name ?? 'Group', children: members });\n\t\t\t\t\tif (!set.has(n.id)) out.push(n);\n\t\t\t\t});\n\t\t\t\treturn out;\n\t\t\t};\n\t\t\tif (parent === null) this.setDoc(regroup(this.doc.nodes));\n\t\t\telse this.setDoc(mapTree(this.doc.nodes, (n) => (n.id === parent && n.type === 'group' ? { ...n, children: regroup(n.children) } : n)));\n\t\t\tthis.selection = [id];\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn id;\n\t}\n\n\t/** Replaces selected groups with their children. */\n\tungroup(options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst groups = (options.ids ?? this.selection).map((id) => this.getNode(id)).filter((n): n is VectorGroupNode => n?.type === 'group');\n\t\tif (!groups.length) return { ok: false, message: 'Select a group to ungroup.' };\n\t\tconst set = new Set(groups.map((g) => g.id));\n\t\tthis.change('Ungroup', () => {\n\t\t\tconst flatten = (list: readonly VectorNode[]): VectorNode[] => {\n\t\t\t\tconst out: VectorNode[] = [];\n\t\t\t\tlet changed = false;\n\t\t\t\tfor (const n of list) {\n\t\t\t\t\tif (set.has(n.id) && n.type === 'group') {\n\t\t\t\t\t\tchanged = true;\n\t\t\t\t\t\tconst opacity = n.opacity;\n\t\t\t\t\t\tconst m = nodeMatrix(n);\n\t\t\t\t\t\tout.push(\n\t\t\t\t\t\t\t...n.children\n\t\t\t\t\t\t\t\t.map((c) => (n.transform ? transformVectorNode(c, m) : c))\n\t\t\t\t\t\t\t\t.map((c) => (opacity !== undefined && opacity < 1 ? { ...c, opacity: (c.opacity ?? 1) * opacity } : c))\n\t\t\t\t\t\t);\n\t\t\t\t\t} else if (n.type === 'group') {\n\t\t\t\t\t\tconst children = flatten(n.children);\n\t\t\t\t\t\tif (children !== n.children) changed = true;\n\t\t\t\t\t\tout.push(children !== n.children ? { ...n, children } : n);\n\t\t\t\t\t} else out.push(n);\n\t\t\t\t}\n\t\t\t\treturn changed ? out : (list as VectorNode[]);\n\t\t\t};\n\t\t\tthis.setDoc(flatten(this.doc.nodes));\n\t\t\tthis.selection = groups.flatMap((g) => g.children.map((c) => c.id));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Changes stacking order within each node's parent. */\n\tarrange(op: VectorArrange, options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst set = new Set(options.ids ?? this.selectedRoots());\n\t\tif (!set.size) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst reorder = (list: readonly VectorNode[]): VectorNode[] => {\n\t\t\tconst out = list.map((n) => (n.type === 'group' ? { ...n, children: reorder(n.children) } : n));\n\t\t\tif (op === 'front') return [...out.filter((n) => !set.has(n.id)), ...out.filter((n) => set.has(n.id))];\n\t\t\tif (op === 'back') return [...out.filter((n) => set.has(n.id)), ...out.filter((n) => !set.has(n.id))];\n\t\t\tif (op === 'forward') {\n\t\t\t\tfor (let i = out.length - 2; i >= 0; i--) if (set.has(out[i].id) && !set.has(out[i + 1].id)) [out[i], out[i + 1]] = [out[i + 1], out[i]];\n\t\t\t} else {\n\t\t\t\tfor (let i = 1; i < out.length; i++) if (set.has(out[i].id) && !set.has(out[i - 1].id)) [out[i], out[i - 1]] = [out[i - 1], out[i]];\n\t\t\t}\n\t\t\treturn out;\n\t\t};\n\t\tconst labels = { front: 'Bring to Front', forward: 'Bring Forward', backward: 'Send Backward', back: 'Send to Back' };\n\t\tthis.change(labels[op], () => this.setDoc(reorder(this.doc.nodes)));\n\t\treturn { ok: true };\n\t}\n\n\t/**\n\t * Combines the selected paths (two or more) into one with a boolean operation. `subtract`\n\t * removes the upper shapes from the lowest one. The result takes the lowest shape's style\n\t * and place.\n\t */\n\tbooleanOp(op: VectorBooleanOperation, options: { ids?: readonly string[] } = {}): string | null {\n\t\tconst roots = options.ids ?? this.selectedRoots();\n\t\tconst order: string[] = [];\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (roots.includes(n.id)) for (const p of collectPathNodes(n)) order.push(p.id);\n\t\t});\n\t\tconst paths = [...new Set(order)].map((id) => this.getNode(id) as VectorPathNode);\n\t\tif (paths.length < 2) return null;\n\t\tconst result = pathBoolean(\n\t\t\tBOOLEAN_OPS[op],\n\t\t\tpaths.map((p) => ({\n\t\t\t\tpath: vectorPathWorldBezier(\n\t\t\t\t\t{ ...p, subpaths: p.subpaths.filter((s) => s.anchors.length > 1).map((s) => ({ ...s, closed: true })) },\n\t\t\t\t\tvectorParentMatrix(this.doc.nodes, p.id) ?? IDENTITY_MATRIX\n\t\t\t\t),\n\t\t\t\tfillRule: p.fillRule ?? 'nonzero'\n\t\t\t}))\n\t\t);\n\t\tconst base = paths[0];\n\t\tconst anchorRoot = roots.find((r) => findVectorNode([this.getNode(r)!], base.id)) ?? base.id;\n\t\tconst subpaths = bezierToSubpaths(this.intoParentSpace(anchorRoot, result.path));\n\t\tif (result.error || !subpaths.length) return null;\n\t\tconst id = this.newId();\n\t\tconst { transform: _t, ...baseRest } = cloneVectorNode(base);\n\t\tconst node: VectorPathNode = { ...baseRest, id, name: BOOLEAN_LABELS[op], subpaths };\n\t\tconst drop = new Set([...paths.map((p) => p.id), ...roots]);\n\t\tthis.change(BOOLEAN_LABELS[op], () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === anchorRoot ? node : drop.has(n.id) ? null : n)));\n\t\t\tthis.selection = [id];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn id;\n\t}\n\n\t/** Joins the selected paths into one compound path (subpaths kept, lowest style). */\n\tcombine(options: { ids?: readonly string[] } = {}): string | null {\n\t\tconst roots = options.ids ?? this.selectedRoots();\n\t\tconst paths: VectorPathNode[] = [];\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (roots.includes(n.id)) paths.push(...collectPathNodes(n));\n\t\t});\n\t\tif (paths.length < 2) return null;\n\t\tconst id = this.newId();\n\t\tconst first = roots.find((r) => findVectorNode([this.getNode(r)!], paths[0].id)) ?? paths[0].id;\n\t\tconst subpaths = paths.flatMap((p) => bezierToSubpaths(this.intoParentSpace(first, vectorPathWorldBezier(p, vectorParentMatrix(this.doc.nodes, p.id) ?? IDENTITY_MATRIX))));\n\t\tconst { transform: _t, ...baseRest } = cloneVectorNode(paths[0]);\n\t\tconst node: VectorPathNode = { ...baseRest, id, name: 'Compound Path', subpaths };\n\t\tconst drop = new Set([...paths.map((p) => p.id), ...roots]);\n\t\tthis.change('Combine', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === first ? node : drop.has(n.id) ? null : n)));\n\t\t\tthis.selection = [id];\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn id;\n\t}\n\n\t/** A document-space path mapped into the parent space of node `id`. */\n\tprivate intoParentSpace(id: string, path: BezierPath): BezierPath {\n\t\tconst parent = vectorParentMatrix(this.doc.nodes, id) ?? IDENTITY_MATRIX;\n\t\treturn isRoot(parent) ? path : transformBezierPath(path, invertMatrix(parent));\n\t}\n\n\t/** Splits selected compound paths into one path per subpath. */\n\tbreakApart(options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst paths = (options.ids ?? this.selection).map((id) => this.getNode(id)).filter((n): n is VectorPathNode => n?.type === 'path' && n.subpaths.length > 1);\n\t\tif (!paths.length) return { ok: false, message: 'Select a compound path to break apart.' };\n\t\tconst created: string[] = [];\n\t\tconst set = new Set(paths.map((p) => p.id));\n\t\tthis.change('Break Apart', () => {\n\t\t\tconst split = (list: readonly VectorNode[]): VectorNode[] =>\n\t\t\t\tlist.flatMap((n): VectorNode[] => {\n\t\t\t\t\tif (n.type === 'group') return [{ ...n, children: split(n.children) }];\n\t\t\t\t\tif (!set.has(n.id)) return [n];\n\t\t\t\t\treturn n.subpaths.map((sp, i) => {\n\t\t\t\t\t\tconst id = i === 0 ? n.id : this.newId();\n\t\t\t\t\t\tcreated.push(id);\n\t\t\t\t\t\treturn { ...n, id, subpaths: [sp] };\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\tthis.setDoc(split(this.doc.nodes));\n\t\t\tthis.selection = created;\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Anchor editing\n\t// -------------------------------------------------------------------------\n\n\tprivate updateAnchors(doc: VectorDocument, refs: readonly VectorAnchorRef[], fn: (a: VectorAnchor, ref: VectorAnchorRef) => VectorAnchor): VectorDocument {\n\t\tconst byNode = new Map<string, VectorAnchorRef[]>();\n\t\tfor (const r of refs) byNode.set(r.nodeId, [...(byNode.get(r.nodeId) ?? []), r]);\n\t\tconst nodes = mapTree(doc.nodes, (n) => {\n\t\t\tconst list = byNode.get(n.id);\n\t\t\tif (!list || n.type !== 'path' || n.locked) return n;\n\t\t\tconst subpaths = n.subpaths.map((sp, s) => {\n\t\t\t\tconst hits = list.filter((r) => r.subpath === s);\n\t\t\t\tif (!hits.length) return sp;\n\t\t\t\treturn { closed: sp.closed, anchors: sp.anchors.map((a, i) => (hits.some((r) => r.index === i) ? fn(a, { nodeId: n.id, subpath: s, index: i }) : a)) };\n\t\t\t});\n\t\t\treturn { ...n, subpaths };\n\t\t});\n\t\treturn nodes === doc.nodes ? doc : { ...doc, nodes };\n\t}\n\n\t/** Moves anchors by a document-space offset (converted into each node's own space). */\n\tprivate movedAnchors(doc: VectorDocument, refs: readonly VectorAnchorRef[], dx: number, dy: number): VectorDocument {\n\t\tconst local = new Map<string, Vec2>();\n\t\tfor (const r of refs) if (!local.has(r.nodeId)) local.set(r.nodeId, applyMatrixLinear(invertMatrix(this.worldOf(r.nodeId, doc)), { x: dx, y: dy }));\n\t\treturn this.updateAnchors(doc, refs, (a, ref) => {\n\t\t\tconst d = local.get(ref.nodeId)!;\n\t\t\treturn translateAnchor(a, d.x, d.y);\n\t\t});\n\t}\n\n\t/**\n\t * Moves one anchor to a document position. Its handles follow; with `curvature` (default:\n\t * the `curvatureMoves` setting) its two segments bend instead, as the Curvature tool does.\n\t */\n\tmoveAnchor(ref: VectorAnchorRef, to: Vec2, options: { curvature?: boolean } = {}): VectorActionResult {\n\t\tconst a = getAnchorWorld(this.doc, ref);\n\t\tif (!a) return { ok: false, message: 'There is no such anchor.' };\n\t\tconst curvature = options.curvature ?? this.editing.curvatureMoves;\n\t\tthis.change('Move Point', () => {\n\t\t\tthis.doc = curvature ? this.curvatureMoved(this.doc, ref, to) : this.movedAnchors(this.doc, [ref], to.x - a.x, to.y - a.y);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** `doc` with anchor `ref` moved to document point `to` by a Curvature-tool move. */\n\tprivate curvatureMoved(doc: VectorDocument, ref: VectorAnchorRef, to: Vec2): VectorDocument {\n\t\tconst node = findVectorNode(doc.nodes, ref.nodeId);\n\t\tif (node?.type !== 'path' || node.locked || !node.subpaths[ref.subpath]) return doc;\n\t\tconst q = this.toLocal(ref.nodeId, to, doc);\n\t\tconst subpaths = node.subpaths.map((sp, i) => (i === ref.subpath ? curvatureMoveAnchor(sp, ref.index, q) : sp));\n\t\tconst nodes = mapTree(doc.nodes, (n) => (n.id === ref.nodeId ? { ...node, subpaths } : n));\n\t\treturn { ...doc, nodes };\n\t}\n\n\t/** `doc` with segment `ref` bent through document point `p` at parameter `t`. */\n\tprivate bent(doc: VectorDocument, ref: VectorSegmentRef, t: number, p: Vec2): VectorDocument {\n\t\tconst node = findVectorNode(doc.nodes, ref.nodeId);\n\t\tif (node?.type !== 'path' || node.locked || !node.subpaths[ref.subpath]) return doc;\n\t\tconst q = this.toLocal(ref.nodeId, p, doc);\n\t\tconst subpaths = node.subpaths.map((sp, i) => (i === ref.subpath ? bendSubpathSegment(sp, ref.segment, t, q) : sp));\n\t\treturn { ...doc, nodes: mapTree(doc.nodes, (n) => (n.id === ref.nodeId ? { ...node, subpaths } : n)) };\n\t}\n\n\t/**\n\t * Bends a segment so the curve passes through document point `to` at parameter `t`\n\t * (default 0.5, clamped to 0.05–0.95); see `bendSegment` in `pathEdit`.\n\t */\n\tbendSegment(ref: VectorSegmentRef, to: Vec2, t = 0.5): VectorActionResult {\n\t\tconst node = this.getNode(ref.nodeId);\n\t\tconst sp = node?.type === 'path' ? node.subpaths[ref.subpath] : undefined;\n\t\tif (!sp || ref.segment < 0 || ref.segment >= (sp.closed ? sp.anchors.length : sp.anchors.length - 1) || sp.anchors.length < 2) return { ok: false, message: 'There is no such segment.' };\n\t\tif (node!.locked) return { ok: false, message: 'The path is locked.' };\n\t\tthis.change('Bend Segment', () => {\n\t\t\tthis.doc = this.bent(this.doc, ref, t, to);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Moves one handle to a document position (see `moveAnchorHandle` for how the opposite handle follows). */\n\tmoveHandle(ref: VectorHandleRef, to: Vec2, options: { breakHandles?: boolean } = {}): VectorActionResult {\n\t\tif (!getAnchor(this.doc, ref)) return { ok: false, message: 'There is no such anchor.' };\n\t\tconst local = this.toLocal(ref.nodeId, to);\n\t\tthis.change('Move Handle', () => {\n\t\t\tthis.doc = this.updateAnchors(this.doc, [ref], (a) => moveAnchorHandle(a, ref.handle, local, options.breakHandles));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Converts the selected (or given) anchors between corner, smooth and symmetric. */\n\tconvertAnchors(type: VectorAnchorType, refs: readonly VectorAnchorRef[] = this.anchors): VectorActionResult {\n\t\tif (!refs.length) return { ok: false, message: 'Select points to convert.' };\n\t\tthis.change(type === 'corner' ? 'Make Corner' : 'Make Smooth', () => {\n\t\t\tconst nodes = mapTree(this.doc.nodes, (n) => {\n\t\t\t\tif (n.type !== 'path') return n;\n\t\t\t\tconst mine = refs.filter((r) => r.nodeId === n.id);\n\t\t\t\tif (!mine.length) return n;\n\t\t\t\tconst subpaths = n.subpaths.map((sp, s) => mine.filter((r) => r.subpath === s).reduce((acc, r) => convertAnchor(acc, r.index, type), sp));\n\t\t\t\treturn { ...n, subpaths };\n\t\t\t});\n\t\t\tthis.setDoc(nodes);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Adds an anchor on the nearest segment of `nodeId` to document point `point` (shape unchanged). */\n\tinsertAnchorAt(nodeId: string, point: Vec2): VectorAnchorRef | null {\n\t\tconst node = this.getNode(nodeId);\n\t\tif (node?.type !== 'path') return null;\n\t\tconst hit = nearestSegment(node, this.toLocal(nodeId, point));\n\t\tif (!hit) return null;\n\t\tconst { subpath, index } = insertAnchor(node.subpaths[hit.subpath], hit.segment, hit.t);\n\t\tconst ref = { nodeId, subpath: hit.subpath, index };\n\t\tthis.change('Add Point', () => {\n\t\t\tthis.replaceNode(nodeId, { ...node, subpaths: node.subpaths.map((sp, i) => (i === hit.subpath ? subpath : sp)) });\n\t\t\tthis.editingId = nodeId;\n\t\t\tthis.anchors = [ref];\n\t\t});\n\t\treturn ref;\n\t}\n\n\t/**\n\t * Deletes the selected (or given) anchors; subpaths left with one anchor and empty paths go\n\t * too. With `keepShape` (default: the `keepShapeOnDelete` setting, on) the neighbours'\n\t * handles are refitted so the path keeps its shape; off, the neighbours are joined as they are.\n\t */\n\tdeleteAnchors(refs: readonly VectorAnchorRef[] = this.anchors, options: { keepShape?: boolean } = {}): VectorActionResult {\n\t\tif (!refs.length) return { ok: false, message: 'Select points to delete.' };\n\t\tconst keepShape = options.keepShape ?? this.editing.keepShapeOnDelete;\n\t\tthis.change('Delete Points', () => {\n\t\t\tconst nodes = mapTree(this.doc.nodes, (n) => {\n\t\t\t\tif (n.type !== 'path' || n.locked) return n;\n\t\t\t\tconst mine = refs.filter((r) => r.nodeId === n.id);\n\t\t\t\tif (!mine.length) return n;\n\t\t\t\tconst subpaths = n.subpaths\n\t\t\t\t\t.map((sp, s) => {\n\t\t\t\t\t\tconst indices = mine.filter((r) => r.subpath === s).map((r) => r.index);\n\t\t\t\t\t\tif (!indices.length) return sp;\n\t\t\t\t\t\treturn keepShape ? removeAnchorsKeepingShape(sp, indices) : removeAnchors(sp, indices);\n\t\t\t\t\t})\n\t\t\t\t\t.filter((sp) => sp.anchors.length > 1);\n\t\t\t\treturn subpaths.length ? { ...n, subpaths } : null;\n\t\t\t});\n\t\t\tthis.setDoc(nodes);\n\t\t\tthis.anchors = [];\n\t\t\tthis.selection = this.selection.filter((id) => this.getNode(id));\n\t\t\tif (this.editingId && !this.getNode(this.editingId)) this.editingId = null;\n\t\t\tif (this.pen && !this.getNode(this.pen.nodeId)) this.pen = null;\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Opens or closes the subpaths that contain selected anchors (or all subpaths of `nodeId`). */\n\tsetClosed(closed: boolean, nodeId?: string): VectorActionResult {\n\t\tconst targets = nodeId\n\t\t\t? (() => {\n\t\t\t\t\tconst n = this.getNode(nodeId);\n\t\t\t\t\treturn n?.type === 'path' ? n.subpaths.map((_, s) => ({ nodeId, subpath: s })) : [];\n\t\t\t\t})()\n\t\t\t: this.anchors.map((r) => ({ nodeId: r.nodeId, subpath: r.subpath }));\n\t\tif (!targets.length) return { ok: false, message: 'Select a path or points.' };\n\t\tthis.change(closed ? 'Close Path' : 'Open Path', () => {\n\t\t\tthis.setDoc(\n\t\t\t\tmapTree(this.doc.nodes, (n) =>\n\t\t\t\t\tn.type === 'path' && targets.some((t) => t.nodeId === n.id)\n\t\t\t\t\t\t? { ...n, subpaths: n.subpaths.map((sp, s) => (targets.some((t) => t.nodeId === n.id && t.subpath === s) ? { ...sp, closed } : sp)) }\n\t\t\t\t\t\t: n\n\t\t\t\t)\n\t\t\t);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Reverses the direction of every subpath of the selected paths. */\n\treversePaths(ids: readonly string[] = this.selection): VectorActionResult {\n\t\tconst set = new Set(ids.flatMap((id) => (this.getNode(id) ? collectPathNodes(this.getNode(id)!) : [])).map((p) => p.id));\n\t\tif (!set.size) return { ok: false, message: 'Select a path.' };\n\t\tthis.change('Reverse Path', () => {\n\t\t\tthis.setDoc(\n\t\t\t\tmapTree(this.doc.nodes, (n) =>\n\t\t\t\t\tn.type === 'path' && set.has(n.id)\n\t\t\t\t\t\t? { ...n, subpaths: n.subpaths.map(reverseSubpath), ...(n.strokeWidthProfile?.length ? { strokeWidthProfile: reverseWidthProfile(n.strokeWidthProfile) } : {}) }\n\t\t\t\t\t\t: n\n\t\t\t\t)\n\t\t\t);\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Path clean-up, Scissors, Knife and Eraser\n\t// -------------------------------------------------------------------------\n\n\t/** Unlocked path nodes in the given roots (default: the paths being edited, else the selection). */\n\tprivate pathTargets(ids?: readonly string[]): VectorPathNode[] {\n\t\tconst roots = ids ?? (this.tool === 'direct' && this.anchors.length ? [...new Set(this.anchors.map((r) => r.nodeId))] : this.selection);\n\t\tconst out = new Map<string, VectorPathNode>();\n\t\tfor (const id of roots) {\n\t\t\tconst node = this.getNode(id);\n\t\t\tif (node && !node.locked) for (const p of collectPathNodes(node)) if (!p.locked) out.set(p.id, p);\n\t\t}\n\t\t// Document order, bottom to top.\n\t\tconst order: string[] = [];\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (out.has(n.id)) order.push(n.id);\n\t\t});\n\t\treturn order.map((id) => out.get(id)!);\n\t}\n\n\t/** Subpaths of node `from` mapped into node `to`'s own space. */\n\tprivate subpathsIn(from: VectorPathNode, to: string): VectorSubpath[] {\n\t\tconst m = multiplyMatrices(this.worldOf(from.id), invertMatrix(this.worldOf(to)));\n\t\tif (isRoot(m)) return from.subpaths;\n\t\tconst map = (p: Vec2) => applyMatrix(m, p);\n\t\treturn from.subpaths.map((sp) => ({\n\t\t\tclosed: sp.closed,\n\t\t\tanchors: sp.anchors.map((a) => ({ ...map(a), ...(a.in ? { in: map(a.in) } : {}), ...(a.out ? { out: map(a.out) } : {}), ...(a.type ? { type: a.type } : {}), ...(a.corner ? { corner: { ...a.corner } } : {}) }))\n\t\t}));\n\t}\n\n\t/**\n\t * Replaces a path with pieces: each entry becomes one path (the first keeps the node's id and\n\t * place, the others go just above it with the same style). No pieces removes the path.\n\t * Returns the ids of the paths now standing in for it.\n\t */\n\tprivate replaceWithPieces(node: VectorPathNode, pieces: readonly VectorSubpath[][]): string[] {\n\t\tconst nodes = pieces.filter((p) => p.length).map((subpaths, i) => ({ ...node, id: i === 0 ? node.id : this.newId(), subpaths }) as VectorPathNode);\n\t\tthis.setDoc(spliceTree(this.doc.nodes, node.id, nodes));\n\t\treturn nodes.map((n) => n.id);\n\t}\n\n\t/** Clears anchor selections, editing and pen state that no longer point at anything. */\n\tprivate dropStaleRefs() {\n\t\tthis.selection = this.selection.filter((id) => this.getNode(id));\n\t\tthis.anchors = this.anchors.filter((r) => getAnchor(this.doc, r));\n\t\tif (this.editingId && !this.getNode(this.editingId)) this.editingId = null;\n\t\tif (this.pen && !this.getNode(this.pen.nodeId)) this.pen = null;\n\t}\n\n\t/**\n\t * Join: the open subpaths of the selected (or given) paths become one open path, joined\n\t * nearest endpoints first (ends within `tolerance` document units merge into one anchor,\n\t * others get a straight segment); a single open subpath is closed. The result replaces the\n\t * lowest path, in its space and style. Default tolerance: the pick distance.\n\t */\n\tjoinPaths(options: { ids?: readonly string[]; tolerance?: number } = {}): VectorActionResult {\n\t\tconst paths = this.pathTargets(options.ids);\n\t\tif (!paths.length) return { ok: false, message: 'Select paths to join.' };\n\t\tconst base = paths[0];\n\t\tconst all = paths.flatMap((p) => this.subpathsIn(p, base.id));\n\t\tif (!all.some((sp) => !sp.closed && sp.anchors.length > 1)) return { ok: false, message: 'There are no open paths to join.' };\n\t\tconst subpaths = joinSubpaths(all, options.tolerance ?? this.tolerance());\n\t\tconst drop = new Set(paths.slice(1).map((p) => p.id));\n\t\tthis.change('Join', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === base.id ? { ...base, subpaths } : drop.has(n.id) ? null : n)));\n\t\t\tthis.selection = [base.id];\n\t\t\tthis.anchors = [];\n\t\t\tif (this.editingId && drop.has(this.editingId)) this.editingId = base.id;\n\t\t\tthis.dropStaleRefs();\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Average: moves the selected (or given) anchors onto their average position along `axis`, in document space. */\n\taverageAnchors(axis: VectorAverageAxis = 'both', refs: readonly VectorAnchorRef[] = this.anchors): VectorActionResult {\n\t\tconst points = refs.map((r) => ({ ref: r, at: getAnchorWorld(this.doc, r) })).filter((p): p is { ref: VectorAnchorRef; at: NonNullable<ReturnType<typeof getAnchorWorld>> } => !!p.at);\n\t\tif (points.length < 2) return { ok: false, message: 'Select at least two points to average.' };\n\t\tconst cx = points.reduce((s, p) => s + p.at.x, 0) / points.length;\n\t\tconst cy = points.reduce((s, p) => s + p.at.y, 0) / points.length;\n\t\tthis.change('Average', () => {\n\t\t\tfor (const { ref, at } of points) {\n\t\t\t\tconst dx = axis === 'horizontal' ? 0 : cx - at.x;\n\t\t\t\tconst dy = axis === 'vertical' ? 0 : cy - at.y;\n\t\t\t\tif (dx || dy) this.doc = this.movedAnchors(this.doc, [ref], dx, dy);\n\t\t\t}\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Applies `fn` to every subpath of the target paths as one undo step. */\n\tprivate editSubpaths(label: string, ids: readonly string[] | undefined, fn: (sp: VectorSubpath, node: VectorPathNode, index: number) => VectorSubpath): VectorActionResult {\n\t\tconst paths = this.pathTargets(ids);\n\t\tif (!paths.length) return { ok: false, message: 'Select a path.' };\n\t\tconst set = new Set(paths.map((p) => p.id));\n\t\tthis.change(label, () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.type === 'path' && set.has(n.id) ? { ...n, subpaths: n.subpaths.map((sp, i) => fn(sp, n, i)) } : n)));\n\t\t\tthis.dropStaleRefs();\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/**\n\t * Remove Redundant Points: drops anchors of the selected (or given) paths that can go\n\t * without moving the outline more than `tolerance` document units (default 0.5).\n\t */\n\tremoveRedundantPoints(options: { ids?: readonly string[]; tolerance?: number } = {}): VectorActionResult {\n\t\tconst tolerance = options.tolerance ?? 0.5;\n\t\treturn this.editSubpaths('Remove Redundant Points', options.ids, (sp) => removeRedundantSubpathPoints(sp, tolerance));\n\t}\n\n\t/**\n\t * Smooth: pulls handles towards smooth tangents by `amount` (0–1, default 1). With the direct\n\t * tool and points selected, only those points change.\n\t */\n\tsmoothPaths(options: { ids?: readonly string[]; amount?: number; refs?: readonly VectorAnchorRef[] } = {}): VectorActionResult {\n\t\tconst refs = options.refs ?? (!options.ids && this.tool === 'direct' && this.anchors.length ? this.anchors : null);\n\t\tconst ids = options.ids ?? (refs ? [...new Set(refs.map((r) => r.nodeId))] : undefined);\n\t\treturn this.editSubpaths('Smooth', ids, (sp, node, i) => {\n\t\t\tconst only = refs ? new Set(refs.filter((r) => r.nodeId === node.id && r.subpath === i).map((r) => r.index)) : undefined;\n\t\t\treturn only && !only.size ? sp : smoothSubpath(sp, options.amount ?? 1, only);\n\t\t});\n\t}\n\n\t/** Splits a cut subpath into pieces: separate paths for a one-subpath node, subpaths in place for a compound one. */\n\tprivate applyCuts(node: VectorPathNode, cut: (sp: VectorSubpath, index: number) => VectorSubpath[] | null): string[] | null {\n\t\tconst results = node.subpaths.map((sp, i) => cut(sp, i));\n\t\tif (results.every((r) => !r)) return null;\n\t\tconst subpaths = node.subpaths.flatMap((sp, i) => results[i] ?? [sp]);\n\t\tif (node.subpaths.length === 1) return this.replaceWithPieces(node, subpaths.map((sp) => [sp]));\n\t\tthis.replaceNode(node.id, { ...node, subpaths });\n\t\treturn [node.id];\n\t}\n\n\t/**\n\t * Scissors: cuts path `nodeId` at the outline point nearest document point `point` (at an\n\t * anchor when within the pick distance of one). A closed subpath opens there; an open one\n\t * splits in two (a one-subpath path becomes two paths). Returns the ids of the paths.\n\t */\n\tcutPathAt(nodeId: string, point: Vec2): string[] | null {\n\t\tconst node = this.getNode(nodeId);\n\t\tif (node?.type !== 'path' || node.locked) return null;\n\t\tconst local = this.toLocal(nodeId, point);\n\t\tconst hit = nearestSegment(node, local);\n\t\tif (!hit) return null;\n\t\tconst sp = node.subpaths[hit.subpath];\n\t\tconst n = sp.anchors.length;\n\t\tconst near = [hit.segment, (hit.segment + 1) % n].find((i) => Math.hypot(sp.anchors[i].x - hit.point.x, sp.anchors[i].y - hit.point.y) <= this.tolerance());\n\t\tif (!sp.closed && n > 1 && (near === 0 || near === n - 1) && !(hit.t > 1e-6 && hit.t < 1 - 1e-6)) return null;\n\t\tlet ids: string[] | null = null;\n\t\tthis.change('Cut Path', () => {\n\t\t\tids = this.applyCuts(node, (s, i) => (i !== hit.subpath ? null : near !== undefined ? cutSubpathAt(s, [near]) : splitSubpathAt(s, hit.segment, hit.t)));\n\t\t\tif (ids) {\n\t\t\t\tthis.selection = ids;\n\t\t\t\tthis.anchors = [];\n\t\t\t\tif (this.editingId === nodeId) this.editingId = null;\n\t\t\t}\n\t\t\tthis.dropStaleRefs();\n\t\t});\n\t\treturn ids;\n\t}\n\n\t/** Scissors on the selected (or given) anchors: each cuts its subpath there (see `cutPathAt`). */\n\tcutAtAnchors(refs: readonly VectorAnchorRef[] = this.anchors): VectorActionResult {\n\t\tconst byNode = new Map<string, VectorAnchorRef[]>();\n\t\tfor (const r of refs) if (getAnchor(this.doc, r)) byNode.set(r.nodeId, [...(byNode.get(r.nodeId) ?? []), r]);\n\t\tif (!byNode.size) return { ok: false, message: 'Select points to cut at.' };\n\t\tconst created: string[] = [];\n\t\tthis.change('Cut Path', () => {\n\t\t\tfor (const [id, list] of byNode) {\n\t\t\t\tconst node = this.getNode(id) as VectorPathNode;\n\t\t\t\tif (node.locked) continue;\n\t\t\t\tconst ids = this.applyCuts(node, (sp, i) => {\n\t\t\t\t\tconst at = list.filter((r) => r.subpath === i).map((r) => r.index);\n\t\t\t\t\tconst pieces = at.length ? cutSubpathAt(sp, at) : null;\n\t\t\t\t\treturn pieces && !(pieces.length === 1 && pieces[0].closed === sp.closed) ? pieces : null;\n\t\t\t\t});\n\t\t\t\tif (ids) created.push(...ids);\n\t\t\t}\n\t\t\tif (created.length) this.selection = created;\n\t\t\tthis.anchors = [];\n\t\t\tthis.dropStaleRefs();\n\t\t});\n\t\treturn created.length ? { ok: true } : { ok: false, message: 'Points at the ends of open paths do not cut.' };\n\t}\n\n\t/** Visible, unlocked paths a stroke over `points` can reach: in `ids`, the selection, or (with neither) any whose bounds it crosses. */\n\tprivate strokeTargets(points: readonly Vec2[], ids: readonly string[] | undefined, pad: number): VectorPathNode[] {\n\t\tconst blocked = new Set<string>();\n\t\twalkVectorNodes(this.doc.nodes, (n, parent) => {\n\t\t\tif (n.visible === false || n.locked || (parent && blocked.has(parent.id))) blocked.add(n.id);\n\t\t});\n\t\tconst visible = (p: VectorPathNode) => !blocked.has(p.id);\n\t\tif (ids?.length || this.selection.length) return this.pathTargets(ids ?? this.selection).filter(visible);\n\t\tconst box = polylineBounds(points.map(toPoint), pad);\n\t\tif (!box) return [];\n\t\tconst out: VectorPathNode[] = [];\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (n.type !== 'path' || !visible(n)) return;\n\t\t\tconst b = vectorNodeBounds(n, vectorParentMatrix(this.doc.nodes, n.id) ?? IDENTITY_MATRIX);\n\t\t\tif (b && boundsIntersect(b, box)) out.push(n);\n\t\t});\n\t\treturn out;\n\t}\n\n\t/** A stroke's points in node `id`'s own space. */\n\tprivate localPoints(id: string, points: readonly Vec2[]): Point[] {\n\t\tconst inv = invertMatrix(this.worldOf(id));\n\t\treturn points.map((p) => toPoint(applyMatrix(inv, p)));\n\t}\n\n\t/**\n\t * Knife: cuts closed paths along the polyline `points` (document space) wherever it crosses\n\t * them from edge to edge, with no gap between the pieces. It cuts the given paths, the\n\t * selection, or (with neither) every path it crosses. Returns the ids of the pieces (empty\n\t * when nothing was cut).\n\t */\n\tknife(points: readonly Vec2[], options: { ids?: readonly string[] } = {}): string[] {\n\t\tconst pts = simplifyPolyline(points.map(toPoint), 0.25 / this.viewport.zoom).map(([x, y]) => ({ x, y }));\n\t\tif (pts.length < 2) return [];\n\t\tconst plan: { node: VectorPathNode; pieces: VectorSubpath[][] }[] = [];\n\t\tfor (const node of this.strokeTargets(pts, options.ids, 0)) {\n\t\t\tconst closed = node.subpaths.filter((sp) => sp.anchors.length > 1);\n\t\t\tif (!closed.length || closed.some((sp) => !sp.closed)) continue;\n\t\t\tconst result = knifePath(subpathsToBezier(closed), node.fillRule ?? 'nonzero', this.localPoints(node.id, pts));\n\t\t\tif (result) plan.push({ node, pieces: result.map((path) => bezierToSubpaths(path)) });\n\t\t}\n\t\tif (!plan.length) return [];\n\t\tconst created: string[] = [];\n\t\tthis.change('Knife', () => {\n\t\t\tfor (const { node, pieces } of plan) created.push(...this.replaceWithPieces(node, pieces));\n\t\t\tthis.selection = created;\n\t\t\tthis.anchors = [];\n\t\t\tthis.dropStaleRefs();\n\t\t});\n\t\treturn created;\n\t}\n\n\t/**\n\t * Eraser: rubs out a round stroke of diameter `size` (default: the `eraserSize` setting)\n\t * along `points` (document space). Filled closed paths lose that area (pieces that come\n\t * apart become separate paths); outlines are cut where they pass under it. It erases from\n\t * the given paths, the selection, or (with neither) every path it reaches. Returns the ids\n\t * of the paths it changed or created.\n\t */\n\terase(points: readonly Vec2[], options: { ids?: readonly string[]; size?: number } = {}): string[] {\n\t\tconst width = options.size ?? this.editing.eraserSize;\n\t\tif (!(width > 0) || !points.length) return [];\n\t\tconst pts = simplifyPolyline(points.map(toPoint), Math.min(width * 0.05, 0.25 / this.viewport.zoom));\n\t\tconst region = eraserRegion(pts, width);\n\t\tif (!region.length) return [];\n\t\tconst plan: { node: VectorPathNode; pieces: VectorSubpath[][] }[] = [];\n\t\tconst rb = bezierPathBounds(region);\n\t\tconst reach = rb ? [{ x: rb.minX, y: rb.minY }, { x: rb.maxX, y: rb.maxY }] : points;\n\t\tfor (const node of this.strokeTargets(reach, options.ids, 0)) {\n\t\t\tconst local = transformBezierPath(region, invertMatrix(this.worldOf(node.id)));\n\t\t\tconst live = node.subpaths.filter((sp) => sp.anchors.length > 1);\n\t\t\tif (!live.length) continue;\n\t\t\tif (hasPaint(node.fill) && live.every((sp) => sp.closed)) {\n\t\t\t\tconst faces = eraseFromFill(subpathsToBezier(live), node.fillRule ?? 'nonzero', local);\n\t\t\t\tif (faces) plan.push({ node, pieces: faces.map((f) => bezierToSubpaths(f)) });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst results = live.map((sp) => eraseFromOutline(sp, local));\n\t\t\tif (results.every((r) => !r)) continue;\n\t\t\tconst subpaths = live.flatMap((sp, i) => results[i] ?? [sp]);\n\t\t\tplan.push({ node, pieces: live.length === 1 ? subpaths.map((sp) => [sp]) : [subpaths] });\n\t\t}\n\t\tif (!plan.length) return [];\n\t\tconst changed: string[] = [];\n\t\tthis.change('Erase', () => {\n\t\t\tfor (const { node, pieces } of plan) changed.push(...this.replaceWithPieces(node, pieces));\n\t\t\tthis.anchors = [];\n\t\t\tthis.dropStaleRefs();\n\t\t\tif (this.selection.length || options.ids) this.selection = [...new Set([...this.selection, ...changed.filter((id) => this.getNode(id))])];\n\t\t});\n\t\treturn changed;\n\t}\n\n\t/** Ends the pen path being drawn (a lone anchor is removed). */\n\tfinishPath(): void {\n\t\tif (!this.pen) return;\n\t\tconst node = this.getNode(this.pen.nodeId) as VectorPathNode | undefined;\n\t\tconst sp = node?.subpaths[this.pen.subpath];\n\t\tconst pen = this.pen;\n\t\tthis.pen = null;\n\t\tthis.pointer = null;\n\t\tif (node && sp && sp.anchors.length < 2) {\n\t\t\tconst subpaths = node.subpaths.filter((_, i) => i !== pen.subpath);\n\t\t\tthis.change('Delete Path', () => {\n\t\t\t\tthis.replaceNode(node.id, subpaths.length ? { ...node, subpaths } : null);\n\t\t\t\tif (!subpaths.length) {\n\t\t\t\t\tthis.selection = this.selection.filter((id) => id !== node.id);\n\t\t\t\t\tif (this.editingId === node.id) this.editingId = null;\n\t\t\t\t}\n\t\t\t\tthis.anchors = [];\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tthis.notify();\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Clipboard\n\t// -------------------------------------------------------------------------\n\n\t/** Copies the selection. Returns JSON text for the system clipboard (or null). */\n\tcopy(): string | null {\n\t\tconst nodes = this.selectedRoots()\n\t\t\t.map((id) => this.getNode(id))\n\t\t\t.filter((n): n is VectorNode => !!n)\n\t\t\t.map((n) => cloneVectorNode(n));\n\t\tif (!nodes.length) return null;\n\t\tthis.clipboard = nodes;\n\t\treturn JSON.stringify({ type: VECTOR_CLIPBOARD_TYPE, nodes });\n\t}\n\n\tcut(): string | null {\n\t\tconst text = this.copy();\n\t\tif (text) this.removeNodes(this.selectedRoots(), { label: 'Cut' });\n\t\treturn text;\n\t}\n\n\t/**\n\t * Pastes `text` (from `copy()`, or SVG markup) or the internal clipboard, offset by 10, 10.\n\t * Returns the new ids.\n\t */\n\tpaste(text?: string, options: { offset?: Vec2 } = {}): string[] {\n\t\tlet nodes: VectorNode[] | null = null;\n\t\tif (text) {\n\t\t\tconst trimmed = text.trim();\n\t\t\tif (trimmed.startsWith('{')) {\n\t\t\t\ttry {\n\t\t\t\t\tconst data = JSON.parse(trimmed);\n\t\t\t\t\tif (data?.type === VECTOR_CLIPBOARD_TYPE && Array.isArray(data.nodes)) nodes = data.nodes;\n\t\t\t\t} catch {\n\t\t\t\t\tnodes = null;\n\t\t\t\t}\n\t\t\t} else if (/<svg[\\s>]/i.test(trimmed)) {\n\t\t\t\ttry {\n\t\t\t\t\tnodes = parseVectorSvg(trimmed).nodes;\n\t\t\t\t} catch {\n\t\t\t\t\tnodes = null;\n\t\t\t\t}\n\t\t\t}\n\t\t} else nodes = this.clipboard;\n\t\tif (!nodes?.length) return [];\n\t\tconst offset = options.offset ?? (text && !text.trim().startsWith('{') ? { x: 0, y: 0 } : { x: 10, y: 10 });\n\t\tconst copies = nodes.map((n) => transformVectorNode(this.freshIds(n), translateMatrix(offset.x, offset.y)));\n\t\tthis.change('Paste', () => {\n\t\t\tthis.setDoc([...this.doc.nodes, ...copies]);\n\t\t\tthis.selection = copies.map((n) => n.id);\n\t\t\tthis.anchors = [];\n\t\t});\n\t\tif (!text) this.clipboard = copies.map((n) => cloneVectorNode(n));\n\t\treturn copies.map((n) => n.id);\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Undo\n\t// -------------------------------------------------------------------------\n\n\tundo(): boolean {\n\t\tthis.cancelDrag();\n\t\tthis.pen = null;\n\t\treturn this.history.undo();\n\t}\n\n\tredo(): boolean {\n\t\tthis.cancelDrag();\n\t\treturn this.history.redo();\n\t}\n\n\t/** Deletes selected anchors (direct tool) or nodes. */\n\tdeleteSelection(): VectorActionResult {\n\t\tif (this.tool === 'direct' && this.anchors.length) return this.deleteAnchors();\n\t\treturn this.removeNodes(this.selectedRoots());\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Pointer input\n\t// -------------------------------------------------------------------------\n\n\t/** The fields the anchor / handle helpers read, without building a full state. */\n\tprivate view() {\n\t\treturn { document: this.doc, selection: this.selection, editingId: this.editingId, tool: this.tool, pen: this.pen, selectedAnchors: this.anchors };\n\t}\n\n\tprivate tolerance() {\n\t\treturn this.hitRadius / this.viewport.zoom;\n\t}\n\n\tprivate hitTransformHandle(screen: Vec2): VectorTransformHandle | null {\n\t\tif (this.tool !== 'select' || !this.selection.length) return null;\n\t\tconst frame = this.frameOf(this.selectedRoots());\n\t\tif (!frame) return null;\n\t\tconst { box, handles } = getVectorSelectionBoxGeometry(frame, this.viewport);\n\t\tconst r = this.hitRadius + 2;\n\t\t// Tiny boxes: only corners and rotation, so the box can still be grabbed.\n\t\tconst usable = box.width < 2 * r || box.height < 2 * r ? handles.filter((h) => h.handle.length === 2 || h.handle === 'rotate') : handles;\n\t\tfor (const h of usable) if (Math.hypot(h.screen.x - screen.x, h.screen.y - screen.y) <= r * Math.SQRT2) return h.handle;\n\t\treturn null;\n\t}\n\n\tprivate hitHandle(screen: Vec2): VectorHandleRef | null {\n\t\tfor (const ref of getVisibleHandles(this.view()).reverse()) {\n\t\t\tconst a = getAnchorWorld(this.doc, ref);\n\t\t\tconst h = a?.[ref.handle];\n\t\t\tif (!h) continue;\n\t\t\tconst s = this.documentToScreen(h);\n\t\t\tif (Math.hypot(s.x - screen.x, s.y - screen.y) <= this.hitRadius) return ref;\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate cornerView() {\n\t\treturn { ...this.view(), viewport: this.viewport };\n\t}\n\n\tprivate hitCornerWidget(screen: Vec2): VectorCornerWidget | null {\n\t\tlet best: VectorCornerWidget | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (const w of getVectorCornerWidgets(this.cornerView())) {\n\t\t\tconst s = this.documentToScreen(w);\n\t\t\tconst d = Math.hypot(s.x - screen.x, s.y - screen.y);\n\t\t\tif (d <= this.hitRadius && d < bestD) {\n\t\t\t\tbest = w;\n\t\t\t\tbestD = d;\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t}\n\n\tprivate hitAnchor(screen: Vec2, refs: readonly VectorAnchorRef[]): VectorAnchorRef | null {\n\t\tlet best: VectorAnchorRef | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (const ref of refs) {\n\t\t\tconst a = getAnchorWorld(this.doc, ref);\n\t\t\tif (!a) continue;\n\t\t\tconst s = this.documentToScreen(a);\n\t\t\tconst d = Math.hypot(s.x - screen.x, s.y - screen.y);\n\t\t\tif (d <= this.hitRadius && d < bestD) {\n\t\t\t\tbest = ref;\n\t\t\t\tbestD = d;\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t}\n\n\t/** Deepest unlocked visible path under `p`. */\n\tprivate hitPath(p: Vec2): VectorPathNode | null {\n\t\tconst tol = this.tolerance();\n\t\tconst search = (list: readonly VectorNode[], parent: AffineMatrix): VectorPathNode | null => {\n\t\t\tfor (let i = list.length - 1; i >= 0; i--) {\n\t\t\t\tconst n = list[i];\n\t\t\t\tif (n.visible === false || n.locked) continue;\n\t\t\t\tif (n.type === 'group') {\n\t\t\t\t\tconst found = search(n.children, multiplyMatrices(nodeMatrix(n), parent));\n\t\t\t\t\tif (found) return found;\n\t\t\t\t} else if (hitTestVectorNode(n, p, tol, parent)) return n;\n\t\t\t}\n\t\t\treturn null;\n\t\t};\n\t\treturn search(this.doc.nodes, IDENTITY_MATRIX);\n\t}\n\n\t/** Endpoints of open subpaths of unlocked visible paths (pen tool resumes from them). */\n\tprivate openEndpoints(): VectorAnchorRef[] {\n\t\tconst out: VectorAnchorRef[] = [];\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (n.type !== 'path' || n.locked || n.visible === false) return;\n\t\t\tn.subpaths.forEach((sp, s) => {\n\t\t\t\tif (sp.closed || sp.anchors.length < 1) return;\n\t\t\t\tout.push({ nodeId: n.id, subpath: s, index: 0 });\n\t\t\t\tif (sp.anchors.length > 1) out.push({ nodeId: n.id, subpath: s, index: sp.anchors.length - 1 });\n\t\t\t});\n\t\t});\n\t\treturn out;\n\t}\n\n\tprivate computeHover(screen: Vec2): VectorHover | null {\n\t\tconst p = this.screenToDocument(screen);\n\t\tswitch (this.tool) {\n\t\t\tcase 'select': {\n\t\t\t\tconst handle = this.hitTransformHandle(screen);\n\t\t\t\tif (handle) return { nodeId: null, transformHandle: handle };\n\t\t\t\tconst node = hitTestVectorNodes(this.doc.nodes, p, this.tolerance());\n\t\t\t\treturn node ? { nodeId: node.id } : null;\n\t\t\t}\n\t\t\tcase 'direct': {\n\t\t\t\tconst handle = this.hitHandle(screen);\n\t\t\t\tif (handle) return { nodeId: handle.nodeId, handle };\n\t\t\t\tconst anchor = this.hitAnchor(screen, getVisibleAnchors(this.view()));\n\t\t\t\tif (anchor) return { nodeId: anchor.nodeId, anchor };\n\t\t\t\tconst widget = this.hitCornerWidget(screen);\n\t\t\t\tif (widget) return { nodeId: widget.ref.nodeId, corner: widget.ref };\n\t\t\t\tfor (const id of getEditablePathIds(this.view())) {\n\t\t\t\t\tconst node = this.getNode(id) as VectorPathNode;\n\t\t\t\t\tconst seg = nearestSegment(node, this.toLocal(id, p));\n\t\t\t\t\tif (seg && seg.distance <= this.tolerance()) {\n\t\t\t\t\t\tconst point = applyMatrix(this.worldOf(id), seg.point);\n\t\t\t\t\t\treturn { nodeId: id, segment: { nodeId: id, subpath: seg.subpath, segment: seg.segment, t: seg.t, point } };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst path = this.hitPath(p);\n\t\t\t\treturn path ? { nodeId: path.id } : null;\n\t\t\t}\n\t\t\tcase 'pen': {\n\t\t\t\tconst refs = this.pen ? [{ nodeId: this.pen.nodeId, subpath: this.pen.subpath, index: 0 }] : this.openEndpoints();\n\t\t\t\tconst anchor = this.hitAnchor(screen, refs);\n\t\t\t\treturn anchor ? { nodeId: anchor.nodeId, anchor } : null;\n\t\t\t}\n\t\t\tcase 'scissors': {\n\t\t\t\tconst seg = this.nearestOutline(p);\n\t\t\t\treturn seg ? { nodeId: seg.nodeId, segment: seg } : null;\n\t\t\t}\n\t\t\tcase 'width': {\n\t\t\t\tconst hit = this.hitWidthHandle(screen);\n\t\t\t\tif (hit) return { nodeId: hit.ref.nodeId, widthPoint: hit.ref };\n\t\t\t\tconst spot = this.strokeSpotAt(p);\n\t\t\t\treturn spot ? { nodeId: spot.nodeId, strokeSpot: spot } : null;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate widthView() {\n\t\treturn { document: this.doc, selection: this.selection, tool: this.tool, hover: this.hover, interaction: this.interaction, selectedWidthPoint: this.widthPoint };\n\t}\n\n\t/** The width point centre or side end under `screen` (width tool). */\n\tprivate hitWidthHandle(screen: Vec2): { ref: VectorWidthPointRef & { part: 'center' | 'left' | 'right' } } | null {\n\t\tlet best: { ref: VectorWidthPointRef & { part: 'center' | 'left' | 'right' } } | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (const h of getVectorWidthHandles(this.widthView())) {\n\t\t\tfor (const [part, q] of [['center', h], ['left', h.left], ['right', h.right]] as const) {\n\t\t\t\tconst s = this.documentToScreen(q);\n\t\t\t\tconst d = Math.hypot(s.x - screen.x, s.y - screen.y);\n\t\t\t\t// Ties go to the centre (listed first), so a zero-width point can still be moved.\n\t\t\t\tif (d <= this.hitRadius && d < bestD - 1e-9) {\n\t\t\t\t\tbest = { ref: { ...h.ref, part } };\n\t\t\t\t\tbestD = d;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t}\n\n\t/** The nearest stroked, unlocked visible path whose stroke is under document point `p` (width tool). */\n\tprivate strokeSpotAt(p: Vec2): VectorStrokeSpot | null {\n\t\tlet best: (VectorStrokeSpot & { distance: number }) | null = null;\n\t\tconst tol = this.tolerance();\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (n.type !== 'path' || n.visible === false || n.locked) return;\n\t\t\tif (hiddenOrLocked(this.doc.nodes, n.id)) return;\n\t\t\tconst g = vectorStrokeWidthGeometry(n);\n\t\t\tif (!g) return;\n\t\t\tconst m = this.worldOf(n.id);\n\t\t\tconst local = applyMatrix(invertMatrix(m), p);\n\t\t\tconst near = nearestStrokePosition(g.line, [local.x, local.y]);\n\t\t\tif (!near) return;\n\t\t\tconst profile = strokeWidthProfileOf(n);\n\t\t\tconst w = widthProfileAt(profile, near.t);\n\t\t\tconst reach = Math.max(near.side === 'left' ? w.left : w.right, 0) * g.unit + tol;\n\t\t\tif (near.distance > reach || near.distance > widthProfileMaxScale(profile) * g.unit + tol) return;\n\t\t\tif (best && near.distance >= best.distance) return;\n\t\t\tconst nx = near.tangent[1];\n\t\t\tconst ny = -near.tangent[0];\n\t\t\tconst [cx, cy] = near.point;\n\t\t\tbest = {\n\t\t\t\tnodeId: n.id,\n\t\t\t\tsubpath: near.contour,\n\t\t\t\tt: near.t,\n\t\t\t\tpoint: applyMatrix(m, { x: cx, y: cy }),\n\t\t\t\tleft: applyMatrix(m, { x: cx + nx * w.left * g.unit, y: cy + ny * w.left * g.unit }),\n\t\t\t\tright: applyMatrix(m, { x: cx - nx * w.right * g.unit, y: cy - ny * w.right * g.unit }),\n\t\t\t\tdistance: near.distance\n\t\t\t};\n\t\t});\n\t\tif (!best) return null;\n\t\tconst { distance: _d, ...spot } = best as VectorStrokeSpot & { distance: number };\n\t\treturn spot;\n\t}\n\n\tprivate downWidth(screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tconst hit = this.hitWidthHandle(screen);\n\t\tconst spot = hit ? null : this.strokeSpotAt(p);\n\t\tconst nodeId = hit?.ref.nodeId ?? spot?.nodeId;\n\t\tconst node = nodeId ? this.getNode(nodeId) : undefined;\n\t\tconst g = node?.type === 'path' ? vectorStrokeWidthGeometry(node) : null;\n\t\tif (!node || node.type !== 'path' || !g) {\n\t\t\tif (this.widthPoint) {\n\t\t\t\tthis.widthPoint = null;\n\t\t\t\tthis.notify();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tconst before = this.snapshot();\n\t\tconst local = this.toLocal(node.id, p);\n\t\tlet profile: VectorWidthPoint[];\n\t\tlet ref: VectorWidthPointRef;\n\t\tlet mode: 'width' | 'move' = 'width';\n\t\tlet side: 'both' | 'left' | 'right' = 'both';\n\t\tlet t: number;\n\t\tlet subpath: number;\n\t\tif (hit) {\n\t\t\tprofile = sanitizeWidthProfile(node.strokeWidthProfile);\n\t\t\tref = { nodeId: node.id, index: hit.ref.index, subpath: hit.ref.subpath };\n\t\t\tt = profile[ref.index]?.t ?? 0;\n\t\t\tsubpath = hit.ref.subpath;\n\t\t\tif (hit.ref.part === 'center') mode = 'move';\n\t\t\telse if (input.alt) side = hit.ref.part;\n\t\t} else {\n\t\t\tconst near = nearestStrokePosition(g.line, [local.x, local.y])!;\n\t\t\tconst inserted = insertWidthPoint(strokeWidthProfileOf(node), near.t);\n\t\t\tprofile = inserted.points;\n\t\t\tsubpath = near.contour;\n\t\t\tt = near.t;\n\t\t\tref = { nodeId: node.id, index: inserted.index, subpath };\n\t\t\tif (input.alt) side = near.side;\n\t\t}\n\t\tconst at = strokePositionPoint(g.line, subpath, t);\n\t\tif (!at) return;\n\t\tconst base = { ...this.doc, nodes: mapTree(this.doc.nodes, (n) => (n.id === node.id ? { ...(n as VectorPathNode), strokeWidthProfile: profile } : n)) };\n\t\tthis.doc = base;\n\t\tthis.widthPoint = { nodeId: node.id, index: ref.index, subpath };\n\t\tthis.drag = {\n\t\t\tkind: 'width',\n\t\t\tref,\n\t\t\tmode,\n\t\t\tside,\n\t\t\torigin: { x: at.point[0], y: at.point[1] },\n\t\t\tnormal: { x: at.tangent[1], y: -at.tangent[0] },\n\t\t\tunit: g.unit,\n\t\t\tprofile,\n\t\t\tbefore,\n\t\t\tbase,\n\t\t\tstart: p,\n\t\t\tmoved: false,\n\t\t\tcreated: !hit\n\t\t};\n\t\tconst w = profile[ref.index];\n\t\tthis.interaction = { type: 'width', ref, mode, width: (w.left + w.right) * g.unit };\n\t\tthis.notify(!hit);\n\t}\n\n\t/** The nearest outline point of any visible, unlocked path within the pick distance of document point `p`. */\n\tprivate nearestOutline(p: Vec2): NonNullable<VectorHover['segment']> | null {\n\t\tlet best: (NonNullable<VectorHover['segment']> & { distance: number }) | null = null;\n\t\tconst tol = this.tolerance();\n\t\tconst visit = (list: readonly VectorNode[], parent: AffineMatrix) => {\n\t\t\tfor (let i = list.length - 1; i >= 0; i--) {\n\t\t\t\tconst n = list[i];\n\t\t\t\tif (n.visible === false || n.locked) continue;\n\t\t\t\tconst m = multiplyMatrices(nodeMatrix(n), parent);\n\t\t\t\tif (n.type === 'group') {\n\t\t\t\t\tvisit(n.children, m);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst hit = nearestSegment(n, applyMatrix(invertMatrix(m), p));\n\t\t\t\t// Node matrices are rigid, so local distances are document distances.\n\t\t\t\tif (hit && hit.distance <= tol && (!best || hit.distance < best.distance - 1e-9)) {\n\t\t\t\t\tbest = { nodeId: n.id, subpath: hit.subpath, segment: hit.segment, t: hit.t, point: applyMatrix(m, hit.point), distance: hit.distance };\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tvisit(this.doc.nodes, IDENTITY_MATRIX);\n\t\tif (!best) return null;\n\t\tconst { distance: _d, ...seg } = best as NonNullable<VectorHover['segment']> & { distance: number };\n\t\treturn seg;\n\t}\n\n\tprivate sameHover(a: VectorHover | null, b: VectorHover | null): boolean {\n\t\treturn JSON.stringify(a) === JSON.stringify(b);\n\t}\n\n\t/** Primary button down on the canvas at `screen` (pixels relative to the canvas). */\n\tpointerDown(screen: Vec2, input: VectorPointerInput = {}): void {\n\t\tthis.cancelDrag();\n\t\tif (input.button === 1 || this.spaceHeld) {\n\t\t\tthis.drag = { kind: 'pan', start: screen, viewport: this.viewport };\n\t\t\tthis.interaction = { type: 'pan' };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (input.button !== undefined && input.button !== 0) return;\n\t\tconst p = this.screenToDocument(screen);\n\t\tthis.pointer = p;\n\t\tswitch (this.tool) {\n\t\t\tcase 'select':\n\t\t\t\treturn this.downSelect(screen, p, input);\n\t\t\tcase 'direct':\n\t\t\t\treturn this.downDirect(screen, p, input);\n\t\t\tcase 'pen':\n\t\t\t\treturn this.downPen(screen, p, input);\n\t\t\tcase 'pencil':\n\t\t\t\treturn this.downPencil(p, input);\n\t\t\tcase 'width':\n\t\t\t\treturn this.downWidth(screen, p, input);\n\t\t\tcase 'scissors': {\n\t\t\t\tconst seg = this.nearestOutline(p);\n\t\t\t\tif (seg) this.cutPathAt(seg.nodeId, seg.point);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'knife':\n\t\t\tcase 'eraser':\n\t\t\t\tthis.drag = { kind: 'stroke', tool: this.tool, points: [p], before: this.snapshot() };\n\t\t\t\tthis.interaction = { type: 'stroke', tool: this.tool, points: [p], width: this.tool === 'eraser' ? this.editing.eraserSize : 0 };\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\tdefault:\n\t\t\t\treturn this.downShape(p, input);\n\t\t}\n\t}\n\n\tprivate downSelect(screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tconst handle = this.hitTransformHandle(screen);\n\t\tif (handle) {\n\t\t\tconst frame = this.frameOf(this.selectedRoots())!;\n\t\t\tconst before = this.snapshot();\n\t\t\tconst center = applyMatrix(rotateMatrix(frame.angle), { x: frame.x + frame.width / 2, y: frame.y + frame.height / 2 });\n\t\t\tthis.drag =\n\t\t\t\thandle === 'rotate'\n\t\t\t\t\t? { kind: 'rotate', start: p, center, before, base: this.doc }\n\t\t\t\t\t: { kind: 'scale', handle, start: p, frame, before, base: this.doc };\n\t\t\tthis.interaction = handle === 'rotate' ? { type: 'rotate', angle: 0 } : { type: 'scale', handle, sx: 1, sy: 1 };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst node = hitTestVectorNodes(this.doc.nodes, p, this.tolerance());\n\t\tif (node) {\n\t\t\tconst selected = this.selection.includes(node.id);\n\t\t\tif (input.shift) {\n\t\t\t\tthis.selection = selected ? this.selection.filter((id) => id !== node.id) : [...this.selection, node.id];\n\t\t\t\tif (selected) {\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else if (!selected) this.selection = [node.id];\n\t\t\tthis.anchors = [];\n\t\t\tconst before = this.snapshot();\n\t\t\tthis.drag = {\n\t\t\t\tkind: 'move',\n\t\t\t\tstart: p,\n\t\t\t\torigin: this.boundsOf(this.selectedRoots()),\n\t\t\t\tbefore,\n\t\t\t\tbase: this.doc,\n\t\t\t\tmoved: false,\n\t\t\t\tduplicated: false,\n\t\t\t\tclickId: selected && !input.shift ? node.id : null\n\t\t\t};\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (!input.shift) this.selection = [];\n\t\tthis.drag = { kind: 'marquee', start: p, base: this.selection, baseAnchors: [], anchorsMode: false };\n\t\tthis.interaction = { type: 'marquee', bounds: { x: p.x, y: p.y, width: 0, height: 0 } };\n\t\tthis.notify();\n\t}\n\n\tprivate downDirect(screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tconst handle = this.hitHandle(screen);\n\t\tif (handle) {\n\t\t\tthis.drag = { kind: 'handle', ref: handle, before: this.snapshot(), base: this.doc };\n\t\t\tthis.interaction = { type: 'handle', ref: handle };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst anchor = this.hitAnchor(screen, getVisibleAnchors(this.view()));\n\t\tif (anchor) {\n\t\t\tconst selected = this.anchors.some((a) => sameRef(a, anchor));\n\t\t\tthis.editingId = anchor.nodeId;\n\t\t\tif (input.alt) {\n\t\t\t\t// Alt-drag an anchor pulls out fresh symmetric handles.\n\t\t\t\tthis.anchors = [anchor];\n\t\t\t\tthis.drag = { kind: 'pull', ref: anchor, before: this.snapshot(), base: this.doc, label: 'Make Smooth', outOnly: false, closing: false, altBreaks: false };\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (input.shift) {\n\t\t\t\tthis.anchors = selected ? this.anchors.filter((a) => !sameRef(a, anchor)) : [...this.anchors, anchor];\n\t\t\t\tif (selected) {\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else if (!selected) this.anchors = [anchor];\n\t\t\tthis.drag = { kind: 'anchors', start: p, before: this.snapshot(), base: this.doc, moved: false, clickRef: selected && !input.shift ? anchor : null, lead: anchor };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst widget = this.hitCornerWidget(screen);\n\t\tif (widget) {\n\t\t\tconst refs = getVectorCornerWidgets(this.cornerView()).map((w) => w.ref);\n\t\t\tthis.drag = { kind: 'corner', widget, refs, start: p, before: this.snapshot(), base: this.doc, moved: false, alt: !!input.alt, shift: !!input.shift };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tfor (const id of getEditablePathIds(this.view())) {\n\t\t\tconst node = this.getNode(id) as VectorPathNode;\n\t\t\tconst seg = nearestSegment(node, this.toLocal(id, p));\n\t\t\tif (!seg || seg.distance > this.tolerance()) continue;\n\t\t\tconst sp = node.subpaths[seg.subpath];\n\t\t\tif (input.alt) {\n\t\t\t\tconst before = this.snapshot();\n\t\t\t\tconst { subpath, index } = insertAnchor(sp, seg.segment, seg.t);\n\t\t\t\tthis.replaceNode(id, { ...node, subpaths: node.subpaths.map((s, i) => (i === seg.subpath ? subpath : s)) });\n\t\t\t\tconst ref = { nodeId: id, subpath: seg.subpath, index };\n\t\t\t\tthis.anchors = [ref];\n\t\t\t\tthis.editingId = id;\n\t\t\t\tthis.drag = { kind: 'anchors', start: p, before, base: this.doc, moved: true, clickRef: null, lead: ref };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// A click selects the segment's anchors; a drag bends it through the pointer.\n\t\t\tconst a = { nodeId: id, subpath: seg.subpath, index: seg.segment };\n\t\t\tconst b = { nodeId: id, subpath: seg.subpath, index: (seg.segment + 1) % sp.anchors.length };\n\t\t\tthis.anchors = input.shift ? [...this.anchors.filter((r) => !sameRef(r, a) && !sameRef(r, b)), a, b] : [a, b];\n\t\t\tthis.editingId = id;\n\t\t\tthis.drag = { kind: 'bend', ref: { nodeId: id, subpath: seg.subpath, segment: seg.segment }, t: seg.t, start: p, before: this.snapshot(), base: this.doc, moved: false };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst path = this.hitPath(p);\n\t\tif (path) {\n\t\t\tthis.editingId = path.id;\n\t\t\tif (!input.shift) this.selection = [path.id];\n\t\t\telse if (!this.selection.includes(path.id)) this.selection = [...this.selection, path.id];\n\t\t\tthis.anchors = path.subpaths.flatMap((sp, s) => sp.anchors.map((_, i) => ({ nodeId: path.id, subpath: s, index: i })));\n\t\t\tthis.drag = { kind: 'anchors', start: p, before: this.snapshot(), base: this.doc, moved: false, clickRef: null, lead: null };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (!input.shift) {\n\t\t\tthis.anchors = [];\n\t\t}\n\t\tthis.drag = { kind: 'marquee', start: p, base: this.selection, baseAnchors: this.anchors, anchorsMode: getEditablePathIds(this.view()).length > 0 };\n\t\tthis.interaction = { type: 'marquee', bounds: { x: p.x, y: p.y, width: 0, height: 0 } };\n\t\tthis.notify();\n\t}\n\n\tprivate downPen(screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tconst before = this.snapshot();\n\t\tconst sp = this.pen ? (this.getNode(this.pen.nodeId) as VectorPathNode | undefined)?.subpaths[this.pen.subpath] : undefined;\n\t\tif (this.pen && sp) {\n\t\t\tconst pen = this.pen;\n\t\t\tconst first = { nodeId: pen.nodeId, subpath: pen.subpath, index: 0 };\n\t\t\tif (sp.anchors.length >= 2 && this.hitAnchor(screen, [first])) {\n\t\t\t\tconst node = this.getNode(pen.nodeId) as VectorPathNode;\n\t\t\t\tthis.replaceNode(pen.nodeId, { ...node, subpaths: node.subpaths.map((s, i) => (i === pen.subpath ? { ...s, closed: true } : s)) });\n\t\t\t\tthis.drag = { kind: 'pull', ref: first, before, base: this.doc, label: 'Close Path', outOnly: false, closing: true, altBreaks: true };\n\t\t\t\tthis.interaction = { type: 'pen', nodeId: pen.nodeId };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst last = getAnchorWorld(this.doc, { nodeId: pen.nodeId, subpath: pen.subpath, index: sp.anchors.length - 1 })!;\n\t\t\tconst leave = { at: { x: last.x, y: last.y }, constrain: input.shift ? ('angle' as const) : null };\n\t\t\tlet pt = this.snapDrawn(p, leave, input, () => this.drawingTargets(pen.nodeId));\n\t\t\tpt = this.toLocal(pen.nodeId, pt);\n\t\t\tconst node = this.getNode(pen.nodeId) as VectorPathNode;\n\t\t\tconst anchors = [...sp.anchors, { x: pt.x, y: pt.y }];\n\t\t\tthis.replaceNode(pen.nodeId, { ...node, subpaths: node.subpaths.map((s, i) => (i === pen.subpath ? { ...s, anchors } : s)) });\n\t\t\tconst ref = { nodeId: pen.nodeId, subpath: pen.subpath, index: anchors.length - 1 };\n\t\t\tthis.anchors = [ref];\n\t\t\tthis.drag = { kind: 'pull', ref, before, base: this.doc, label: 'Add Point', outOnly: false, closing: false, altBreaks: true };\n\t\t\tthis.interaction = { type: 'pen', nodeId: pen.nodeId };\n\t\t\tthis.notify(true);\n\t\t\treturn;\n\t\t}\n\t\tconst endpoint = this.hitAnchor(screen, this.openEndpoints());\n\t\tif (endpoint) {\n\t\t\tlet node = this.getNode(endpoint.nodeId) as VectorPathNode;\n\t\t\tlet index = endpoint.index;\n\t\t\tif (index === 0 && node.subpaths[endpoint.subpath].anchors.length > 1) {\n\t\t\t\tnode = { ...node, subpaths: node.subpaths.map((s, i) => (i === endpoint.subpath ? reverseSubpath(s) : s)) };\n\t\t\t\tthis.replaceNode(node.id, node);\n\t\t\t\tindex = node.subpaths[endpoint.subpath].anchors.length - 1;\n\t\t\t}\n\t\t\tthis.pen = { nodeId: node.id, subpath: endpoint.subpath };\n\t\t\tthis.selection = [node.id];\n\t\t\tthis.editingId = node.id;\n\t\t\tconst ref = { nodeId: node.id, subpath: endpoint.subpath, index };\n\t\t\tthis.anchors = [ref];\n\t\t\tthis.drag = { kind: 'pull', ref, before, base: this.doc, label: 'Continue Path', outOnly: true, closing: false, altBreaks: true };\n\t\t\tthis.interaction = { type: 'pen', nodeId: node.id };\n\t\t\tthis.notify(this.doc !== before.doc);\n\t\t\treturn;\n\t\t}\n\t\tconst pt = this.snapDrawn(p, null, input, () => this.drawingTargets(null));\n\t\tconst node: VectorPathNode = { id: this.newId(), type: 'path', name: 'Path', ...this.styleFor(true), subpaths: [{ anchors: [{ x: pt.x, y: pt.y }], closed: false }] };\n\t\tthis.setDoc([...this.doc.nodes, node]);\n\t\tthis.pen = { nodeId: node.id, subpath: 0 };\n\t\tthis.selection = [node.id];\n\t\tthis.editingId = node.id;\n\t\tconst ref = { nodeId: node.id, subpath: 0, index: 0 };\n\t\tthis.anchors = [ref];\n\t\tthis.drag = { kind: 'pull', ref, before, base: this.doc, label: 'Start Path', outOnly: false, closing: false, altBreaks: true };\n\t\tthis.interaction = { type: 'pen', nodeId: node.id };\n\t\tthis.notify(true);\n\t}\n\n\tprivate downPencil(p: Vec2, input: VectorPointerInput = {}) {\n\t\tconst before = this.snapshot();\n\t\tconst node: VectorPathNode = {\n\t\t\tid: this.newId(),\n\t\t\ttype: 'path',\n\t\t\tname: 'Pencil',\n\t\t\t...this.styleFor(true),\n\t\t\tstrokeLinecap: this.defaults.strokeLinecap ?? 'round',\n\t\t\tstrokeLinejoin: this.defaults.strokeLinejoin ?? 'round',\n\t\t\tsubpaths: [{ anchors: [{ x: p.x, y: p.y }], closed: false }]\n\t\t};\n\t\tthis.setDoc([...this.doc.nodes, node]);\n\t\tconst lazy = new LazyMouse((this.editing.pencilSmoothing * VECTOR_PENCIL_STRING_PX) / this.viewport.zoom);\n\t\tlazy.push([p.x, p.y]);\n\t\tconst mode = this.editing.pencilPressure;\n\t\tconst hasPressure = typeof input.pressure === 'number' && Number.isFinite(input.pressure);\n\t\tconst record = hasPressure && (mode === 'all' || (mode === 'pen' && input.pointerType === 'pen'));\n\t\tconst pressure = hasPressure ? input.pressure! : 0.5;\n\t\tthis.drag = { kind: 'pencil', nodeId: node.id, points: [[p.x, p.y]], before, lazy, pressures: record ? [pressure] : null, pressure };\n\t\tthis.interaction = { type: 'draw', tool: 'pencil', nodeId: node.id, bounds: { x: p.x, y: p.y, width: 0, height: 0 } };\n\t\tthis.notify(true);\n\t}\n\n\tprivate downShape(p: Vec2, input: VectorPointerInput) {\n\t\tconst before = this.snapshot();\n\t\t// The targets are gathered before the new shape joins the document, and kept for the drag.\n\t\tconst targets = this.drawingTargets(null);\n\t\tconst start = this.snapDrawn(p, null, input, () => targets);\n\t\tconst kind = this.tool as VectorShapeInput['kind'];\n\t\tconst node = this.createShapeNode({ kind, x: start.x, y: start.y, width: 0, height: 0 });\n\t\tthis.setDoc([...this.doc.nodes, node]);\n\t\tthis.drag = { kind: 'shape', tool: this.tool, start, nodeId: node.id, before, targets };\n\t\tthis.interaction = { type: 'draw', tool: this.tool, nodeId: node.id, bounds: { x: start.x, y: start.y, width: 0, height: 0 } };\n\t\tthis.notify(true);\n\t}\n\n\t/** Pointer moved over the canvas (with or without a button down). */\n\tpointerMove(screen: Vec2, input: VectorPointerInput = {}): void {\n\t\tconst p = this.screenToDocument(screen);\n\t\tconst drag = this.drag;\n\t\tif (!drag) {\n\t\t\tconst hover = this.computeHover(screen);\n\t\t\tconst pointerMatters = this.tool === 'pen' && !!this.pen;\n\t\t\tconst guides = this.guides;\n\t\t\tthis.hover = hover;\n\t\t\tconst pointer = this.hoverSnap(p, input);\n\t\t\tif (this.sameHover(hover, this.state.hover) && !pointerMatters && JSON.stringify(guides) === JSON.stringify(this.guides)) return;\n\t\t\tthis.pointer = pointer;\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tthis.pointer = p;\n\t\tswitch (drag.kind) {\n\t\t\tcase 'pan':\n\t\t\t\tthis.viewport = { ...drag.viewport, x: drag.viewport.x + screen.x - drag.start.x, y: drag.viewport.y + screen.y - drag.start.y };\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\tcase 'move': {\n\t\t\t\tlet dx = p.x - drag.start.x;\n\t\t\t\tlet dy = p.y - drag.start.y;\n\t\t\t\tif (!drag.moved && Math.hypot(dx, dy) * this.viewport.zoom < 2) return;\n\t\t\t\tdrag.moved = true;\n\t\t\t\tif (input.shift) Math.abs(dx) > Math.abs(dy) ? (dy = 0) : (dx = 0);\n\t\t\t\tif (input.alt && !drag.duplicated) {\n\t\t\t\t\tdrag.duplicated = true;\n\t\t\t\t\tconst created: string[] = [];\n\t\t\t\t\tdrag.base = this.withDuplicates(drag.base, this.selectedRoots(), { x: 0, y: 0 }, created);\n\t\t\t\t\tthis.selection = created;\n\t\t\t\t\t// The originals stay behind as targets.\n\t\t\t\t\tdrag.targets = undefined;\n\t\t\t\t}\n\t\t\t\t({ dx, dy } = this.snapMove(drag, dx, dy, input));\n\t\t\t\tthis.doc = this.transformed(drag.base, new Set(this.selectedRoots()), translateMatrix(dx, dy));\n\t\t\t\tthis.interaction = { type: 'move', dx, dy };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'scale': {\n\t\t\t\t// Scale in the box's own (possibly rotated) frame.\n\t\t\t\tconst angle = drag.frame.angle;\n\t\t\t\tconst q = angle ? applyMatrix(rotateMatrix(-angle), p) : p;\n\t\t\t\tlet { sx, sy, origin } = scaleFor(drag.handle, drag.frame, q, input);\n\t\t\t\tif (this.snap.objects && !input.mod && drag.handle !== 'rotate') {\n\t\t\t\t\tdrag.targets ??= VectorSnapTargets.forResize(drag.base, this.selectedRoots());\n\t\t\t\t\tconst res = drag.targets.snapScale(drag.frame, drag.handle, sx, sy, input, this.snapTolerance());\n\t\t\t\t\t({ sx, sy } = res);\n\t\t\t\t\tthis.setGuides(res);\n\t\t\t\t} else this.setGuides(null);\n\t\t\t\tconst ids = new Set(this.selectedRoots());\n\t\t\t\tthis.doc = this.transformed(drag.base, ids, this.inFrame(angle, scaleMatrix(sx, sy, origin)));\n\t\t\t\tthis.interaction = { type: 'scale', handle: drag.handle, sx, sy };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'rotate': {\n\t\t\t\tconst a0 = Math.atan2(drag.start.y - drag.center.y, drag.start.x - drag.center.x);\n\t\t\t\tconst a1 = Math.atan2(p.y - drag.center.y, p.x - drag.center.x);\n\t\t\t\tlet angle = ((a1 - a0) * 180) / Math.PI;\n\t\t\t\tif (input.shift) angle = Math.round(angle / 15) * 15;\n\t\t\t\tthis.doc = this.transformed(drag.base, new Set(this.selectedRoots()), rotateMatrix(angle, drag.center));\n\t\t\t\tthis.interaction = { type: 'rotate', angle };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'marquee': {\n\t\t\t\tconst bounds = boundsFromPoints(drag.start, p);\n\t\t\t\tthis.interaction = { type: 'marquee', bounds };\n\t\t\t\tif (drag.anchorsMode) {\n\t\t\t\t\tconst inside = getVisibleAnchors(this.view()).filter((r) => {\n\t\t\t\t\t\tconst a = getAnchorWorld(this.doc, r)!;\n\t\t\t\t\t\treturn a.x >= bounds.x && a.x <= bounds.x + bounds.width && a.y >= bounds.y && a.y <= bounds.y + bounds.height;\n\t\t\t\t\t});\n\t\t\t\t\tthis.anchors = [...drag.baseAnchors, ...inside.filter((r) => !drag.baseAnchors.some((b) => sameRef(b, r)))];\n\t\t\t\t} else {\n\t\t\t\t\tconst hits = this.doc.nodes\n\t\t\t\t\t\t.filter((n) => !n.locked && n.visible !== false)\n\t\t\t\t\t\t.filter((n) => {\n\t\t\t\t\t\t\tconst b = vectorNodeBounds(n);\n\t\t\t\t\t\t\treturn b && boundsIntersect(b, bounds);\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.map((n) => n.id);\n\t\t\t\t\tthis.selection = [...new Set([...drag.base, ...hits])];\n\t\t\t\t}\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'anchors': {\n\t\t\t\tlet dx = p.x - drag.start.x;\n\t\t\t\tlet dy = p.y - drag.start.y;\n\t\t\t\tif (!drag.moved && Math.hypot(dx, dy) * this.viewport.zoom < 2) return;\n\t\t\t\tdrag.moved = true;\n\t\t\t\tconst lead = this.leadAnchor(drag);\n\t\t\t\tif (lead) {\n\t\t\t\t\t// The grabbed (or nearest) anchor snaps; the others move with it.\n\t\t\t\t\tconst leave = input.shift ? { at: lead, constrain: 'axis' as const, curves: false } : null;\n\t\t\t\t\tconst q = this.snapDrawn({ x: lead.x + dx, y: lead.y + dy }, leave, input, () => (drag.targets ??= VectorSnapTargets.forAnchorDrag(drag.base, this.anchors)));\n\t\t\t\t\tdx = q.x - lead.x;\n\t\t\t\t\tdy = q.y - lead.y;\n\t\t\t\t} else if (input.shift) Math.abs(dx) > Math.abs(dy) ? (dy = 0) : (dx = 0);\n\t\t\t\tconst single = this.anchors.length === 1 ? this.anchors[0] : null;\n\t\t\t\tconst from = single ? getAnchorWorld(drag.base, single) : undefined;\n\t\t\t\t// A lone point bends its segments with the Curvature setting (Alt held flips it).\n\t\t\t\tif (single && from && this.editing.curvatureMoves !== !!input.alt) this.doc = this.curvatureMoved(drag.base, single, { x: from.x + dx, y: from.y + dy });\n\t\t\t\telse this.doc = this.movedAnchors(drag.base, this.anchors, dx, dy);\n\t\t\t\tthis.interaction = { type: 'anchors', dx, dy };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'handle': {\n\t\t\t\tconst anchor = getAnchorWorld(drag.base, drag.ref);\n\t\t\t\tconst leave = anchor ? { at: { x: anchor.x, y: anchor.y }, constrain: input.shift ? ('angle' as const) : null } : null;\n\t\t\t\tconst pt = this.snapDrawn(p, leave, input, () => (drag.targets ??= VectorSnapTargets.forHandle(drag.base, drag.ref.nodeId)));\n\t\t\t\tconst local = this.toLocal(drag.ref.nodeId, pt, drag.base);\n\t\t\t\tthis.doc = this.updateAnchors(drag.base, [drag.ref], (a) => moveAnchorHandle(a, drag.ref.handle, local, input.alt));\n\t\t\t\tthis.interaction = { type: 'handle', ref: drag.ref };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'corner': {\n\t\t\t\tif (!drag.moved && Math.hypot(p.x - drag.start.x, p.y - drag.start.y) * this.viewport.zoom < 3) return;\n\t\t\t\tdrag.moved = true;\n\t\t\t\tconst c = drag.widget.corner;\n\t\t\t\tconst inv = invertMatrix(this.worldOf(drag.widget.ref.nodeId, drag.base));\n\t\t\t\tconst d = applyMatrixLinear(inv, { x: p.x - drag.start.x, y: p.y - drag.start.y });\n\t\t\t\tconst radius = Math.max(0, Math.min(c.maxRadius, drag.widget.drawnRadius + cornerRadiusChange(c, d)));\n\t\t\t\tthis.doc = this.updateAnchors(drag.base, drag.refs, (a) => setAnchorCorner(a, radius));\n\t\t\t\tthis.interaction = { type: 'corner', ref: drag.widget.ref, radius };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'bend': {\n\t\t\t\tif (!drag.moved && Math.hypot(p.x - drag.start.x, p.y - drag.start.y) * this.viewport.zoom < 2) return;\n\t\t\t\tdrag.moved = true;\n\t\t\t\tthis.doc = this.bent(drag.base, drag.ref, drag.t, p);\n\t\t\t\tthis.interaction = { type: 'bend', ref: drag.ref };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'stroke': {\n\t\t\t\tconst last = drag.points[drag.points.length - 1];\n\t\t\t\tif (Math.hypot(p.x - last.x, p.y - last.y) * this.viewport.zoom < 1.5) return;\n\t\t\t\tdrag.points.push(p);\n\t\t\t\tthis.interaction = { type: 'stroke', tool: drag.tool, points: drag.points.slice(), width: drag.tool === 'eraser' ? this.editing.eraserSize : 0 };\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'pull': {\n\t\t\t\tconst anchor = getAnchorWorld(drag.base, drag.ref);\n\t\t\t\tif (!anchor) return;\n\t\t\t\tif (Math.hypot(p.x - anchor.x, p.y - anchor.y) * this.viewport.zoom < 2) {\n\t\t\t\t\tthis.doc = drag.base;\n\t\t\t\t\tthis.notify(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.guides = null;\n\t\t\t\tlet pt = p;\n\t\t\t\tif (input.shift) pt = constrain45(anchor, pt);\n\t\t\t\tconst side = drag.closing ? 'in' : 'out';\n\t\t\t\t// Dragging out of the closing anchor pulls its incoming handle toward the pointer's mirror.\n\t\t\t\tconst pos = this.toLocal(drag.ref.nodeId, drag.closing ? { x: 2 * anchor.x - pt.x, y: 2 * anchor.y - pt.y } : pt, drag.base);\n\t\t\t\tthis.doc = this.updateAnchors(drag.base, [drag.ref], (a) => {\n\t\t\t\t\tif (drag.outOnly || (drag.altBreaks && input.alt)) return moveAnchorHandle(a, side, pos, true);\n\t\t\t\t\treturn moveAnchorHandle({ ...a, type: 'symmetric' }, side, pos);\n\t\t\t\t});\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'shape': {\n\t\t\t\tconst node = this.getNode(drag.nodeId);\n\t\t\t\tif (node?.type !== 'path') return;\n\t\t\t\tconst leave = { at: drag.start, constrain: input.shift ? (drag.tool === 'line' ? ('angle' as const) : ('square' as const)) : null, curves: false };\n\t\t\t\tlet end = this.snapDrawn(p, leave, input, () => (drag.targets ??= this.drawingTargets(null)));\n\t\t\t\tif (!this.snappedToObject && drag.tool !== 'line' && !input.shift && !input.mod && this.snap.objects && drag.targets) end = this.matchShapeSize(drag.targets, drag.start, end, input.alt);\n\t\t\t\tlet start = drag.start;\n\t\t\t\tlet bounds: VectorBounds;\n\t\t\t\tif (drag.tool === 'line') {\n\t\t\t\t\tif (input.shift) end = constrain45(start, end);\n\t\t\t\t\tif (input.alt) start = { x: 2 * start.x - end.x, y: 2 * start.y - end.y };\n\t\t\t\t\tbounds = { x: start.x, y: start.y, width: end.x - start.x, height: end.y - start.y };\n\t\t\t\t} else {\n\t\t\t\t\tlet w = end.x - start.x;\n\t\t\t\t\tlet h = end.y - start.y;\n\t\t\t\t\tif (input.shift) {\n\t\t\t\t\t\tconst s = Math.max(Math.abs(w), Math.abs(h));\n\t\t\t\t\t\tw = Math.sign(w || 1) * s;\n\t\t\t\t\t\th = Math.sign(h || 1) * s;\n\t\t\t\t\t}\n\t\t\t\t\tif (input.alt) start = { x: start.x - w, y: start.y - h };\n\t\t\t\t\tconst x2 = drag.start.x + w;\n\t\t\t\t\tconst y2 = drag.start.y + h;\n\t\t\t\t\tbounds = boundsFromPoints(start, { x: x2, y: y2 });\n\t\t\t\t}\n\t\t\t\tconst shaped = this.createShapeNode({ kind: drag.tool as VectorShapeInput['kind'], ...bounds });\n\t\t\t\tthis.replaceNode(drag.nodeId, { ...node, subpaths: shaped.subpaths });\n\t\t\t\tthis.interaction = { type: 'draw', tool: drag.tool, nodeId: drag.nodeId, bounds };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'width': {\n\t\t\t\tif (!drag.moved && Math.hypot(p.x - drag.start.x, p.y - drag.start.y) * this.viewport.zoom < 2) return;\n\t\t\t\tdrag.moved = true;\n\t\t\t\tconst node = findVectorNode(drag.base.nodes, drag.ref.nodeId) as VectorPathNode;\n\t\t\t\tconst local = this.toLocal(node.id, p, drag.base);\n\t\t\t\tlet profile: VectorWidthPoint[];\n\t\t\t\tif (drag.mode === 'move') {\n\t\t\t\t\tconst g = vectorStrokeWidthGeometry(node);\n\t\t\t\t\tconst near = g ? nearestStrokePosition(g.line, [local.x, local.y], drag.ref.subpath) : null;\n\t\t\t\t\tif (!near) return;\n\t\t\t\t\tprofile = setWidthPoint(drag.profile, drag.ref.index, { t: near.t });\n\t\t\t\t} else {\n\t\t\t\t\tconst off = ((local.x - drag.origin.x) * drag.normal.x + (local.y - drag.origin.y) * drag.normal.y) / drag.unit;\n\t\t\t\t\tconst patch =\n\t\t\t\t\t\tdrag.side === 'both' ? { left: Math.abs(off), right: Math.abs(off) } : drag.side === 'left' ? { left: Math.max(0, off) } : { right: Math.max(0, -off) };\n\t\t\t\t\tprofile = setWidthPoint(drag.profile, drag.ref.index, patch);\n\t\t\t\t}\n\t\t\t\tthis.doc = { ...drag.base, nodes: mapTree(drag.base.nodes, (n) => (n.id === node.id ? { ...(n as VectorPathNode), strokeWidthProfile: profile } : n)) };\n\t\t\t\tconst w = profile[drag.ref.index];\n\t\t\t\tthis.interaction = { type: 'width', ref: drag.ref, mode: drag.mode, width: (w.left + w.right) * drag.unit };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'pencil': {\n\t\t\t\tconst last = drag.points[drag.points.length - 1];\n\t\t\t\tlet moved = false;\n\t\t\t\tif (typeof input.pressure === 'number' && Number.isFinite(input.pressure)) drag.pressure = input.pressure;\n\t\t\t\tfor (const q of drag.lazy.push([p.x, p.y])) {\n\t\t\t\t\tif (Math.hypot(q[0] - last[0], q[1] - last[1]) * this.viewport.zoom < 1.5) continue;\n\t\t\t\t\tdrag.points.push(q);\n\t\t\t\t\tdrag.pressures?.push(drag.pressure);\n\t\t\t\t\tmoved = true;\n\t\t\t\t}\n\t\t\t\tconst string = drag.lazy.string();\n\t\t\t\tconst node = this.getNode(drag.nodeId);\n\t\t\t\tif (node?.type !== 'path') return;\n\t\t\t\tif (!moved) {\n\t\t\t\t\tif (string && this.interaction?.type === 'draw') {\n\t\t\t\t\t\tthis.interaction = { ...this.interaction, string: [{ x: string[0][0], y: string[0][1] }, { x: string[1][0], y: string[1][1] }] };\n\t\t\t\t\t\tthis.notify();\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.replaceNode(drag.nodeId, { ...node, subpaths: [{ anchors: drag.points.map(([x, y]) => ({ x, y })), closed: false }] });\n\t\t\t\tconst xs = drag.points.map((q) => q[0]);\n\t\t\t\tconst ys = drag.points.map((q) => q[1]);\n\t\t\t\tthis.interaction = {\n\t\t\t\t\ttype: 'draw',\n\t\t\t\t\ttool: 'pencil',\n\t\t\t\t\tnodeId: drag.nodeId,\n\t\t\t\t\tbounds: { x: Math.min(...xs), y: Math.min(...ys), width: Math.max(...xs) - Math.min(...xs), height: Math.max(...ys) - Math.min(...ys) },\n\t\t\t\t\t...(string ? { string: [{ x: string[0][0], y: string[0][1] }, { x: string[1][0], y: string[1][1] }] as [Vec2, Vec2] } : {})\n\t\t\t\t};\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Snaps a move of the selection by (dx, dy): its bounds line up with targets or space evenly, else go to the grid. */\n\tprivate snapMove(drag: Extract<Drag, { kind: 'move' }>, dx: number, dy: number, input: VectorModifiers): { dx: number; dy: number } {\n\t\tconst origin = drag.origin;\n\t\tif (input.mod || !origin) {\n\t\t\tthis.setGuides(null);\n\t\t\treturn { dx, dy };\n\t\t}\n\t\t// A Shift-locked axis stays put.\n\t\tconst axes = { x: !input.shift || dx !== 0, y: !input.shift || dy !== 0 };\n\t\tlet res = null;\n\t\tif (this.snap.objects) {\n\t\t\tdrag.targets ??= VectorSnapTargets.forMove(drag.base, this.selectedRoots());\n\t\t\tres = drag.targets.snapRect({ ...origin, x: origin.x + dx, y: origin.y + dy }, this.snapTolerance(), { spacing: true, axes });\n\t\t}\n\t\tthis.setGuides(res);\n\t\treturn {\n\t\t\tdx: res?.x ? dx + res.dx : axes.x ? this.gridValue(origin.x + dx) - origin.x : dx,\n\t\t\tdy: res?.y ? dy + res.dy : axes.y ? this.gridValue(origin.y + dy) - origin.y : dy\n\t\t};\n\t}\n\n\t/** The anchor a point drag snaps by, where it started: the grabbed one, else the moving one nearest the press. */\n\tprivate leadAnchor(drag: Extract<Drag, { kind: 'anchors' }>): Vec2 | null {\n\t\tconst ref = drag.lead && this.anchors.some((a) => sameRef(a, drag.lead!)) ? drag.lead : null;\n\t\tif (ref) {\n\t\t\tconst a = getAnchorWorld(drag.base, ref);\n\t\t\treturn a ? { x: a.x, y: a.y } : null;\n\t\t}\n\t\tlet best: Vec2 | null = null;\n\t\tfor (const r of this.anchors) {\n\t\t\tconst a = getAnchorWorld(drag.base, r);\n\t\t\tif (a && (!best || Math.hypot(a.x - drag.start.x, a.y - drag.start.y) < Math.hypot(best.x - drag.start.x, best.y - drag.start.y))) best = { x: a.x, y: a.y };\n\t\t}\n\t\treturn best;\n\t}\n\n\t/** A shape's dragged corner moved so its width or height matches another object's, when one is within reach. */\n\tprivate matchShapeSize(targets: VectorSnapTargets, start: Vec2, end: Vec2, fromCentre = false): Vec2 {\n\t\t// Dragged from the centre, the shape is twice as large as the drag.\n\t\tconst k = fromCentre ? 2 : 1;\n\t\tconst tol = this.snapTolerance() * k;\n\t\tconst out = { ...end };\n\t\tconst guides: VectorSnapGuides = { lines: [], labels: [] };\n\t\tfor (const axis of ['x', 'y'] as const) {\n\t\t\tconst d = end[axis] - start[axis];\n\t\t\tconst len = Math.abs(d) > 1e-9 ? targets.matchSize(Math.abs(d) * k, tol) : null;\n\t\t\tif (len === null || len <= 0) continue;\n\t\t\tout[axis] = start[axis] + (Math.sign(d) * len) / k;\n\t\t\tconst from = { ...out, [axis]: fromCentre ? 2 * start[axis] - out[axis] : start[axis] };\n\t\t\tguides.lines.push({ kind: 'size', x1: from.x, y1: from.y, x2: out.x, y2: out.y });\n\t\t\tguides.labels.push({ kind: 'size', x: (from.x + out.x) / 2, y: (from.y + out.y) / 2, text: `${axis === 'x' ? 'W' : 'H'} ${Math.round(len * 100) / 100}` });\n\t\t}\n\t\tthis.setGuides(guides);\n\t\treturn out;\n\t}\n\n\t/** Primary button released. */\n\tpointerUp(screen?: Vec2, input: VectorPointerInput = {}): void {\n\t\t// A pen reports no pressure as it lifts: keep the last pressure for the final move.\n\t\tif (screen && this.drag && this.drag.kind !== 'pan') this.pointerMove(screen, { ...input, pressure: undefined });\n\t\tconst drag = this.drag;\n\t\tthis.drag = null;\n\t\tthis.interaction = null;\n\t\tthis.guides = null;\n\t\tif (!drag) return;\n\t\tswitch (drag.kind) {\n\t\t\tcase 'pan':\n\t\t\tcase 'marquee':\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\tcase 'move':\n\t\t\t\tif (!drag.moved) {\n\t\t\t\t\tif (drag.clickId) this.selection = [drag.clickId];\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn this.commit(drag.duplicated ? 'Duplicate' : 'Move', drag.before);\n\t\t\tcase 'scale':\n\t\t\t\treturn this.commit('Scale', drag.before);\n\t\t\tcase 'rotate':\n\t\t\t\treturn this.commit('Rotate', drag.before);\n\t\t\tcase 'anchors':\n\t\t\t\tif (!drag.moved) {\n\t\t\t\t\tif (drag.clickRef) this.anchors = [drag.clickRef];\n\t\t\t\t\tif (drag.before.doc !== this.doc) return this.commit('Add Point', drag.before);\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn this.commit(drag.before.doc !== drag.base ? 'Add Point' : 'Move Points', drag.before);\n\t\t\tcase 'handle':\n\t\t\t\treturn this.commit('Move Handle', drag.before);\n\t\t\tcase 'bend':\n\t\t\t\tif (!drag.moved) {\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn this.commit('Bend Segment', drag.before);\n\t\t\tcase 'corner': {\n\t\t\t\tif (drag.moved) return this.commit('Corner Radius', drag.before);\n\t\t\t\tif (drag.alt) {\n\t\t\t\t\tconst kind = nextVectorCornerKind(drag.widget.kind);\n\t\t\t\t\tthis.doc = this.updateAnchors(drag.base, drag.refs, (a) => setAnchorCorner(a, a.corner?.radius ?? 0, kind));\n\t\t\t\t\treturn this.commit('Corner Kind', drag.before);\n\t\t\t\t}\n\t\t\t\t// A click selects the widget's corner, so the next drag rounds that corner alone.\n\t\t\t\tconst ref = drag.widget.ref;\n\t\t\t\tconst has = this.anchors.some((a) => sameRef(a, ref));\n\t\t\t\tthis.editingId = ref.nodeId;\n\t\t\t\tthis.anchors = drag.shift ? (has ? this.anchors.filter((a) => !sameRef(a, ref)) : [...this.anchors, ref]) : [ref];\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'width': {\n\t\t\t\tif (drag.moved) return this.commit(drag.mode === 'move' ? 'Move Width Point' : 'Width Point', drag.before);\n\t\t\t\t// A click adds nothing; on a width point it selects it.\n\t\t\t\tif (drag.created) {\n\t\t\t\t\tthis.doc = drag.before.doc;\n\t\t\t\t\tthis.widthPoint = null;\n\t\t\t\t\tthis.notify(true);\n\t\t\t\t} else this.notify();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'stroke': {\n\t\t\t\tthis.notify();\n\t\t\t\tif (drag.tool === 'knife') this.knife(drag.points);\n\t\t\t\telse this.erase(drag.points);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'pull':\n\t\t\t\tif (drag.closing) this.pen = null;\n\t\t\t\treturn this.commit(drag.label, drag.before);\n\t\t\tcase 'shape': {\n\t\t\t\tconst node = this.getNode(drag.nodeId);\n\t\t\t\tconst b = node ? vectorNodeBounds(node) : null;\n\t\t\t\tconst min = 2 / this.viewport.zoom;\n\t\t\t\tif (!b || (b.width < min && b.height < min)) {\n\t\t\t\t\tthis.doc = drag.before.doc;\n\t\t\t\t\tthis.notify(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.selection = [drag.nodeId];\n\t\t\t\tthis.anchors = [];\n\t\t\t\tthis.tool = 'select';\n\t\t\t\treturn this.commit(`Draw ${TOOL_LABELS[drag.tool]}`, drag.before);\n\t\t\t}\n\t\t\tcase 'pencil': {\n\t\t\t\tconst node = this.getNode(drag.nodeId);\n\t\t\t\tif (node?.type !== 'path' || drag.points.length < 2) {\n\t\t\t\t\tthis.doc = drag.before.doc;\n\t\t\t\t\tthis.notify(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tfor (const q of drag.lazy.finish()) {\n\t\t\t\t\tdrag.points.push(q);\n\t\t\t\t\tdrag.pressures?.push(drag.pressure);\n\t\t\t\t}\n\t\t\t\tconst shape = this.editing.recognizeShapes ? recognizeInkShape(drag.points, { minSize: 6 / this.viewport.zoom }) : null;\n\t\t\t\tif (shape) {\n\t\t\t\t\tthis.replaceNode(drag.nodeId, { ...node, name: inkShapeLabel(shape), subpaths: [inkShapeSubpath(shape)] });\n\t\t\t\t\tthis.selection = [drag.nodeId];\n\t\t\t\t\treturn this.commit(`Draw ${inkShapeLabel(shape)}`, drag.before);\n\t\t\t\t}\n\t\t\t\tconst fitted = fitCubics(drag.points, 1.5 / this.viewport.zoom, { cornerAngleDeg: 60 });\n\t\t\t\tconst anchors: VectorAnchor[] = [];\n\t\t\t\tfor (const c of fitted) {\n\t\t\t\t\tif (!anchors.length) anchors.push({ x: c.p0[0], y: c.p0[1] });\n\t\t\t\t\tanchors[anchors.length - 1].out = { x: c.p1[0], y: c.p1[1] };\n\t\t\t\t\tanchors.push({ x: c.p3[0], y: c.p3[1], in: { x: c.p2[0], y: c.p2[1] } });\n\t\t\t\t}\n\t\t\t\tconst subpaths = anchors.length > 1 ? bezierToSubpaths(subpathsToBezier([{ anchors, closed: false }])) : node.subpaths;\n\t\t\t\tconst profile = drag.pressures ? pencilPressureProfile(drag.points, drag.pressures) : [];\n\t\t\t\tthis.replaceNode(drag.nodeId, { ...node, subpaths, ...(profile.length ? { strokeWidthProfile: profile } : {}) });\n\t\t\t\tthis.selection = [drag.nodeId];\n\t\t\t\treturn this.commit('Draw', drag.before);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** The pointer left the canvas. */\n\tpointerLeave(): void {\n\t\tif (this.drag) return;\n\t\tif (!this.hover && !this.pointer && !this.guides) return;\n\t\tthis.hover = null;\n\t\tthis.pointer = null;\n\t\tthis.guides = null;\n\t\tthis.notify();\n\t}\n\n\t/** Abandons the drag in progress (Escape, lost capture). */\n\tcancelDrag(): void {\n\t\tconst drag = this.drag;\n\t\tif (!drag) return;\n\t\tthis.drag = null;\n\t\tthis.interaction = null;\n\t\tthis.guides = null;\n\t\tif (drag.kind === 'pan') {\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (drag.kind === 'marquee') {\n\t\t\tthis.selection = drag.base;\n\t\t\tthis.anchors = drag.baseAnchors;\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tthis.restore(drag.before);\n\t}\n\n\t/** Double click: select tool enters path editing, direct tool toggles an anchor or adds one. */\n\tdoubleClick(screen: Vec2): void {\n\t\tconst p = this.screenToDocument(screen);\n\t\tif (this.tool === 'select') {\n\t\t\tconst path = this.hitPath(p);\n\t\t\tif (!path) return;\n\t\t\tthis.tool = 'direct';\n\t\t\tthis.selection = [path.id];\n\t\t\tthis.editingId = path.id;\n\t\t\tthis.anchors = [];\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (this.tool === 'direct') {\n\t\t\tconst anchor = this.hitAnchor(screen, getVisibleAnchors(this.view()));\n\t\t\tif (anchor) {\n\t\t\t\tconst a = getAnchor(this.doc, anchor)!;\n\t\t\t\tthis.convertAnchors(a.in || a.out ? 'corner' : 'smooth', [anchor]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst id = this.hover?.segment?.nodeId ?? this.editingId;\n\t\t\tif (id) {\n\t\t\t\tconst node = this.getNode(id) as VectorPathNode | undefined;\n\t\t\t\tconst seg = node ? nearestSegment(node, this.toLocal(id, p)) : null;\n\t\t\t\tif (seg && seg.distance <= this.tolerance()) this.insertAnchorAt(id, p);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (this.tool === 'pen') this.finishPath();\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Keyboard input\n\t// -------------------------------------------------------------------------\n\n\t/**\n\t * Handles editor shortcuts. Returns true when the key was used (call `preventDefault`).\n\t * Do not forward keys typed into text inputs.\n\t */\n\tkeyDown(input: VectorKeyInput): boolean {\n\t\tconst key = input.key;\n\t\tconst lower = key.length === 1 ? key.toLowerCase() : key;\n\t\tif (key === ' ') {\n\t\t\tif (!this.spaceHeld) {\n\t\t\t\tthis.spaceHeld = true;\n\t\t\t\tthis.notify();\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tif (input.mod) {\n\t\t\tswitch (lower) {\n\t\t\t\tcase 'z':\n\t\t\t\t\tinput.shift ? this.redo() : this.undo();\n\t\t\t\t\treturn true;\n\t\t\t\tcase 'y':\n\t\t\t\t\tthis.redo();\n\t\t\t\t\treturn true;\n\t\t\t\tcase 'a':\n\t\t\t\t\tthis.selectAll();\n\t\t\t\t\treturn true;\n\t\t\t\tcase 'd':\n\t\t\t\t\tthis.duplicate();\n\t\t\t\t\treturn true;\n\t\t\t\tcase 'g':\n\t\t\t\t\tinput.shift ? this.ungroup() : this.group();\n\t\t\t\t\treturn true;\n\t\t\t\tcase 'j':\n\t\t\t\t\treturn input.alt ? this.averageAnchors('both').ok : this.joinPaths().ok;\n\t\t\t\tcase ']':\n\t\t\t\t\tthis.arrange(input.alt ? 'front' : 'forward');\n\t\t\t\t\treturn true;\n\t\t\t\tcase '[':\n\t\t\t\t\tthis.arrange(input.alt ? 'back' : 'backward');\n\t\t\t\t\treturn true;\n\t\t\t\tcase '=':\n\t\t\t\tcase '+':\n\t\t\t\t\tthis.setViewport({ zoom: this.viewport.zoom * 1.25 });\n\t\t\t\t\treturn true;\n\t\t\t\tcase '-':\n\t\t\t\t\tthis.setViewport({ zoom: this.viewport.zoom / 1.25 });\n\t\t\t\t\treturn true;\n\t\t\t\tcase '0':\n\t\t\t\t\tthis.setViewport({ zoom: 1 });\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\tswitch (key) {\n\t\t\tcase 'Escape':\n\t\t\t\tif (this.drag) this.cancelDrag();\n\t\t\t\telse if (this.tool === 'width' && this.widthPoint) {\n\t\t\t\t\tthis.widthPoint = null;\n\t\t\t\t\tthis.notify();\n\t\t\t\t}\n\t\t\t\telse if (this.pen) this.finishPath();\n\t\t\t\telse if (this.tool === 'direct' && this.anchors.length) {\n\t\t\t\t\tthis.anchors = [];\n\t\t\t\t\tthis.notify();\n\t\t\t\t} else if (this.tool !== 'select') this.setTool('select');\n\t\t\t\telse this.clearSelection();\n\t\t\t\treturn true;\n\t\t\tcase 'Enter':\n\t\t\t\tif (this.pen) {\n\t\t\t\t\tthis.finishPath();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (this.tool === 'select' && this.selection.length === 1 && this.getNode(this.selection[0])?.type === 'path') {\n\t\t\t\t\tthis.tool = 'direct';\n\t\t\t\t\tthis.editingId = this.selection[0];\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\tcase 'Delete':\n\t\t\tcase 'Backspace':\n\t\t\t\tif (this.tool === 'width' && this.widthPoint) return this.removeWidthPoint(this.widthPoint).ok;\n\t\t\t\tif (this.pen) {\n\t\t\t\t\tconst node = this.getNode(this.pen.nodeId) as VectorPathNode;\n\t\t\t\t\tconst sp = node.subpaths[this.pen.subpath];\n\t\t\t\t\tif (sp.anchors.length > 2) this.deleteAnchors([{ nodeId: node.id, subpath: this.pen.subpath, index: sp.anchors.length - 1 }]);\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis.removeNodes([node.id], { label: 'Delete Path' });\n\t\t\t\t\t\tthis.pen = null;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn this.deleteSelection().ok;\n\t\t\tcase 'ArrowLeft':\n\t\t\tcase 'ArrowRight':\n\t\t\tcase 'ArrowUp':\n\t\t\tcase 'ArrowDown': {\n\t\t\t\tconst step = input.shift ? 10 : 1;\n\t\t\t\tconst dx = key === 'ArrowLeft' ? -step : key === 'ArrowRight' ? step : 0;\n\t\t\t\tconst dy = key === 'ArrowUp' ? -step : key === 'ArrowDown' ? step : 0;\n\t\t\t\treturn this.translate(dx, dy).ok;\n\t\t\t}\n\t\t}\n\t\tif (key.length === 1 && !input.alt) {\n\t\t\tconst tool = TOOL_KEYS[lower];\n\t\t\tif (tool) {\n\t\t\t\tthis.setTool(tool);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tkeyUp(input: VectorKeyInput): void {\n\t\tif (input.key === ' ' && this.spaceHeld) {\n\t\t\tthis.spaceHeld = false;\n\t\t\tthis.notify();\n\t\t}\n\t}\n}\n\n/** \"Rectangle\", \"Square\", \"Ellipse\", \"Circle\", \"Line\", \"Triangle\" or \"Polygon\". */\nfunction inkShapeLabel(shape: VectorInkShape): string {\n\tconst name = vectorInkShapeName(shape);\n\treturn name[0].toUpperCase() + name.slice(1);\n}\n\n/** The subpath of a recognised pencil shape. */\nfunction inkShapeSubpath(shape: VectorInkShape): VectorSubpath {\n\tswitch (shape.kind) {\n\t\tcase 'line':\n\t\t\treturn lineSubpath({ x: shape.a[0], y: shape.a[1] }, { x: shape.b[0], y: shape.b[1] });\n\t\tcase 'rect':\n\t\t\treturn rectSubpath(shape);\n\t\tcase 'ellipse':\n\t\t\treturn ellipseSubpath(shape);\n\t\tcase 'polygon':\n\t\t\treturn { anchors: shape.points.map(([x, y]) => ({ x, y })), closed: true };\n\t}\n}\n\n/** Snaps `p` to the nearest 45° direction from `origin`, keeping its distance. */\nfunction constrain45(origin: Vec2, p: Vec2): Vec2 {\n\tconst dx = p.x - origin.x;\n\tconst dy = p.y - origin.y;\n\tconst len = Math.hypot(dx, dy);\n\tconst a = Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * (Math.PI / 4);\n\treturn { x: origin.x + Math.cos(a) * len, y: origin.y + Math.sin(a) * len };\n}\n\n/** Scale factors and origin for dragging a selection-box handle to `p`. */\nexport function scaleFor(handle: VectorTransformHandle, b: VectorBounds, p: Vec2, mods: VectorModifiers = {}): { sx: number; sy: number; origin: Vec2 } {\n\tconst west = handle.includes('w');\n\tconst east = handle.includes('e');\n\tconst north = handle.startsWith('n');\n\tconst south = handle.startsWith('s');\n\tconst center = { x: b.x + b.width / 2, y: b.y + b.height / 2 };\n\tconst origin = mods.alt ? center : { x: west ? b.x + b.width : east ? b.x : center.x, y: north ? b.y + b.height : south ? b.y : center.y };\n\tconst reachX = mods.alt ? b.width / 2 : b.width;\n\tconst reachY = mods.alt ? b.height / 2 : b.height;\n\tlet sx = west || east ? (reachX > 1e-9 ? ((p.x - origin.x) * (west ? -1 : 1)) / reachX : 1) : 1;\n\tlet sy = north || south ? (reachY > 1e-9 ? ((p.y - origin.y) * (north ? -1 : 1)) / reachY : 1) : 1;\n\tif (mods.shift) {\n\t\tif ((west || east) && (north || south)) {\n\t\t\tconst s = Math.max(Math.abs(sx), Math.abs(sy));\n\t\t\tsx = Math.sign(sx || 1) * s;\n\t\t\tsy = Math.sign(sy || 1) * s;\n\t\t} else if (west || east) sy = Math.abs(sx);\n\t\telse sx = Math.abs(sy);\n\t}\n\treturn { sx, sy, origin };\n}\n\n/** A style applied to a path; a `null` (or empty) width profile removes it. */\nfunction withStyle(node: VectorPathNode, style: VectorStyle & { opacity?: number }): VectorNode {\n\tconst next = { ...node, ...style } as VectorPathNode;\n\tif ('strokeWidthProfile' in style) {\n\t\tconst p = style.strokeWidthProfile ? sanitizeWidthProfile(style.strokeWidthProfile) : [];\n\t\tif (p.length) next.strokeWidthProfile = p;\n\t\telse delete next.strokeWidthProfile;\n\t}\n\treturn next;\n}\n\n/** True when node `id` or one of its ancestors is locked or hidden. */\nfunction hiddenOrLocked(nodes: readonly VectorNode[], id: string): boolean {\n\tconst loc = locateVectorNode(nodes as VectorNode[], id);\n\tif (!loc) return false;\n\tconst n = loc.list[loc.index];\n\tif (n.locked || n.visible === false) return true;\n\treturn loc.parent ? hiddenOrLocked(nodes, loc.parent.id) : false;\n}\n\n/** The width profile of pencil samples and their pressures (positions by length along the samples). */\nfunction pencilPressureProfile(points: readonly Point[], pressures: readonly number[]): VectorWidthPoint[] {\n\tconst n = Math.min(points.length, pressures.length);\n\tif (n < 2) return [];\n\tconst s = [0];\n\tfor (let i = 1; i < n; i++) s.push(s[i - 1] + Math.hypot(points[i][0] - points[i - 1][0], points[i][1] - points[i - 1][1]));\n\tconst total = s[n - 1];\n\tif (!(total > 0)) return [];\n\treturn pressureWidthProfile(s.map((d, i) => ({ t: d / total, pressure: pressures[i] })));\n}\n","/**\n * Framework-neutral render data for a vector editor: the scene (document-space SVG paths and\n * gradient defs) and the overlay (screen-space selection box, anchors, handles, marquee and\n * pen preview). React, Svelte or plain DOM code turns these into `<svg>` elements.\n */\nimport { bezierPathToSvg, transformBezierPath } from '../canvas/pathops/bezier.js';\nimport type { SvgGradientDef } from '../canvas/gradient.js';\n\nexport type { SvgGradientDef };\nimport {\n\tgetAnchorWorld,\n\tgetVectorCornerWidgets,\n\tgetVectorSelectionBoxGeometry,\n\tgetVectorWidthHandles,\n\tgetVisibleAnchors,\n\tgetVisibleHandles,\n\ttype VectorEditorController,\n\ttype VectorEditorState,\n\ttype VectorSelectionBoxGeometry,\n\ttype VectorWidthPointRef\n} from './controller.js';\nimport { sanitizeWidthProfile, widthProfilePresetId, type VectorWidthPreset } from './width.js';\nimport {\n\tfindVectorNode,\n\tIDENTITY_MATRIX,\n\tinferAnchorType,\n\tmultiplyMatrices,\n\tnodeMatrix,\n\tvectorNodeBounds,\n\tvectorParentMatrix,\n\tvectorPathData,\n\tvectorPathWorldBezier,\n\ttype AffineMatrix\n} from './geometry.js';\nimport { vectorPaintToSvg, vectorStrokeSvgParts, type VectorRenderStrokeParts } from './svg.js';\nimport { vectorCorners } from './corners.js';\nimport type { VectorGuideKind, VectorSnapKind } from './snap.js';\nimport type {\n\tVectorAnchorRef,\n\tVectorAnchorType,\n\tVectorArrowAlign,\n\tVectorArrowhead,\n\tVectorBounds,\n\tVectorCornerKind,\n\tVectorHandleRef,\n\tVectorNode,\n\tVectorPaint,\n\tVectorPathNode,\n\tVectorStrokeAlign,\n\tVectorTransformHandle,\n\tVectorWidthPoint,\n\tVec2\n} from './types.js';\n\nexport interface VectorRenderPath {\n\tkind: 'path';\n\tid: string;\n\t/** SVG `transform` (`matrix(…)`) for a rotated node. */\n\ttransform?: string;\n\td: string;\n\t/** `none`, a colour, or `url(#id)` of a gradient in `defs`. */\n\tfill: string;\n\tstroke: string;\n\tstrokeWidth: number;\n\tstrokeLinecap?: string;\n\tstrokeLinejoin?: string;\n\tstrokeDasharray?: string;\n\tfillRule: 'nonzero' | 'evenodd';\n\topacity: number;\n\t/**\n\t * Set when the stroke takes more than one element: an inside / outside alignment or\n\t * arrowheads. Draw `d` with the fill only, then `stroke.d` with the stroke (at\n\t * `stroke.width`, clipped or masked as `stroke.clip` says), then each head filled with\n\t * `stroke`; group them under `id`, `transform` and `opacity`.\n\t */\n\tstrokeParts?: VectorRenderStrokeParts;\n}\n\nexport interface VectorRenderGroup {\n\tkind: 'group';\n\tid: string;\n\t/** SVG `transform` (`matrix(…)`) for a rotated group. */\n\ttransform?: string;\n\topacity: number;\n\tchildren: VectorRenderNode[];\n}\n\nexport type VectorRenderNode = VectorRenderPath | VectorRenderGroup;\n\nexport interface VectorSceneRenderData {\n\t/** SVG `transform` for the document layer: `translate(x y) scale(zoom)`. */\n\ttransform: string;\n\twidth: number;\n\theight: number;\n\tbackground?: string;\n\t/** Gradients referenced by `fill` / `stroke` values. */\n\tdefs: SvgGradientDef[];\n\t/** Visible nodes, bottom to top. */\n\tnodes: VectorRenderNode[];\n}\n\nexport interface VectorRenderAnchor {\n\tref: VectorAnchorRef;\n\t/** Screen position. */\n\tx: number;\n\ty: number;\n\ttype: VectorAnchorType;\n\tselected: boolean;\n\thovered: boolean;\n\t/** The pen tool closes the path when this anchor is clicked. */\n\tcloses: boolean;\n}\n\nexport interface VectorRenderHandle {\n\tref: VectorHandleRef;\n\tx: number;\n\ty: number;\n\t/** Screen position of the handle's anchor (draw a line to it). */\n\tanchorX: number;\n\tanchorY: number;\n\thovered: boolean;\n}\n\n/** A live corner widget in screen pixels. */\nexport interface VectorRenderCornerWidget {\n\tref: VectorAnchorRef;\n\tx: number;\n\ty: number;\n\tradius: number;\n\tkind: VectorCornerKind;\n\thovered: boolean;\n\t/** Its corners are being dragged. */\n\tactive: boolean;\n}\n\n/**\n * A width point of the width tool in screen pixels: a diamond at (`x`, `y`) on the path and a\n * line across the stroke from `left` to `right`, with a handle at each end.\n */\nexport interface VectorRenderWidthPoint {\n\tref: VectorWidthPointRef;\n\tx: number;\n\ty: number;\n\tleft: Vec2;\n\tright: Vec2;\n\tselected: boolean;\n\t/** The part under the pointer, if any. */\n\thovered: 'center' | 'left' | 'right' | null;\n\t/** Being dragged. */\n\tactive: boolean;\n}\n\n/** A smart guide line in screen pixels. */\nexport interface VectorRenderGuideLine {\n\tkind: VectorGuideKind;\n\tx1: number;\n\ty1: number;\n\tx2: number;\n\ty2: number;\n}\n\n/** A smart guide label (\"anchor\", \"intersect\", \"align\", \"centre\", a gap or a size) at a screen position. */\nexport interface VectorRenderGuideLabel {\n\tkind: VectorSnapKind;\n\tx: number;\n\ty: number;\n\ttext: string;\n}\n\nexport interface VectorOverlayRenderData {\n\t/** Outlines (screen-space path data) of hovered and selected nodes. */\n\toutlines: { id: string; d: string; selected: boolean }[];\n\t/**\n\t * Selection box with resize and rotate handles (select tool). `x / y / width / height` and\n\t * each handle's `x / y` are the unrotated box in screen pixels: draw them inside\n\t * `<g transform={transform}>`. `corners` and each handle's `screen` are true positions.\n\t */\n\tselectionBox:\n\t\t| (VectorBounds & { angle: number; transform: string; corners: Vec2[]; handles: VectorSelectionBoxGeometry['handles'] })\n\t\t| null;\n\tanchors: VectorRenderAnchor[];\n\thandles: VectorRenderHandle[];\n\t/** Marquee rectangle, screen space. */\n\tmarquee: VectorBounds | null;\n\t/** Rubber-band segment from the pen path's last anchor to the pointer, screen space. */\n\tpenPreview: string | null;\n\t/** Artboard rectangle, screen space. */\n\tartboard: VectorBounds;\n\t/** Smart guides of the snap in progress, screen space (empty when nothing snapped). */\n\tguides: { lines: VectorRenderGuideLine[]; labels: VectorRenderGuideLabel[] };\n\t/**\n\t * The knife or eraser stroke being drawn, screen space: `d` is an open polyline; draw the\n\t * eraser's with a round-capped stroke `width` pixels wide (0 for the knife: a thin line).\n\t */\n\ttoolStroke: { tool: 'knife' | 'eraser'; d: string; width: number } | null;\n\t/** The pencil's lazy-mouse string from the pen to the pointer, screen space. */\n\tpencilString: { x1: number; y1: number; x2: number; y2: number } | null;\n\t/** Where the scissors would cut (screen space). */\n\tcutPoint: Vec2 | null;\n\t/**\n\t * Live corner widgets of the direct tool (screen space): drag one to round its corners,\n\t * Alt-click to cycle round / inverted / chamfer, click to pick its corner alone.\n\t */\n\tcornerWidgets: VectorRenderCornerWidget[];\n\t/** Width points of the width tool (screen space). */\n\twidthPoints: VectorRenderWidthPoint[];\n\t/**\n\t * Where a width-tool drag would add a width point (screen space): draw a dashed line from\n\t * `left` to `right` and a hollow diamond at (`x`, `y`).\n\t */\n\twidthSpot: { x: number; y: number; left: Vec2; right: Vec2 } | null;\n\t/** A short status, e.g. \"W 120 × H 80\" or \"45°\". */\n\tstatus: string | null;\n}\n\nconst fmt = (n: number) => Math.round(n * 100) / 100;\nconst fmtMatrix = (m: AffineMatrix) => `matrix(${m.map((n) => Math.round(n * 1e6) / 1e6).join(' ')})`;\n\nfunction renderNode(node: VectorNode, defs: SvgGradientDef[], idPrefix: string): VectorRenderNode | null {\n\tif (node.visible === false) return null;\n\tif (node.type === 'group') {\n\t\tconst children = node.children.map((c) => renderNode(c, defs, idPrefix)).filter((c): c is VectorRenderNode => !!c);\n\t\treturn { kind: 'group', id: node.id, ...(node.transform ? { transform: fmtMatrix(node.transform) } : {}), opacity: node.opacity ?? 1, children };\n\t}\n\tconst fill = vectorPaintToSvg(node.fill, `${idPrefix}fill-${node.id}`);\n\tconst stroke = vectorPaintToSvg(node.stroke, `${idPrefix}stroke-${node.id}`);\n\tif (fill.gradient) defs.push(fill.gradient);\n\tif (stroke.gradient) defs.push(stroke.gradient);\n\tconst strokeParts = stroke.value !== 'none' ? vectorStrokeSvgParts(node, `${idPrefix}clip-${node.id}`) : undefined;\n\treturn {\n\t\tkind: 'path',\n\t\tid: node.id,\n\t\t...(node.transform ? { transform: fmtMatrix(node.transform) } : {}),\n\t\t...(strokeParts ? { strokeParts } : {}),\n\t\td: vectorPathData(node),\n\t\tfill: fill.value,\n\t\tstroke: stroke.value,\n\t\tstrokeWidth: node.strokeWidth ?? 1,\n\t\t...(node.strokeLinecap ? { strokeLinecap: node.strokeLinecap } : {}),\n\t\t...(node.strokeLinejoin ? { strokeLinejoin: node.strokeLinejoin } : {}),\n\t\t...(node.strokeDasharray?.length ? { strokeDasharray: node.strokeDasharray.join(' ') } : {}),\n\t\tfillRule: node.fillRule ?? 'nonzero',\n\t\topacity: node.opacity ?? 1\n\t};\n}\n\n/**\n * The document layer. Render the nodes inside `<g transform={transform}>` and `defs` in a\n * `<defs>` block. Pass a unique `idPrefix` when several editors share a page.\n */\nexport function getVectorSceneRenderData(state: Pick<VectorEditorState, 'document' | 'viewport'>, options: { idPrefix?: string } = {}): VectorSceneRenderData {\n\tconst defs: SvgGradientDef[] = [];\n\tconst prefix = options.idPrefix ?? 've-';\n\tconst nodes = state.document.nodes.map((n) => renderNode(n, defs, prefix)).filter((n): n is VectorRenderNode => !!n);\n\tconst v = state.viewport;\n\treturn {\n\t\ttransform: `translate(${fmt(v.x)} ${fmt(v.y)}) scale(${v.zoom})`,\n\t\twidth: state.document.width,\n\t\theight: state.document.height,\n\t\t...(state.document.background ? { background: state.document.background } : {}),\n\t\tdefs,\n\t\tnodes\n\t};\n}\n\nconst toScreen = (state: Pick<VectorEditorState, 'viewport'>, p: Vec2) => ({ x: p.x * state.viewport.zoom + state.viewport.x, y: p.y * state.viewport.zoom + state.viewport.y });\n\nfunction screenOutline(state: VectorEditorState, node: VectorNode): string {\n\tconst v = state.viewport;\n\tconst view: AffineMatrix = [v.zoom, 0, 0, v.zoom, v.x, v.y];\n\tconst parent = vectorParentMatrix(state.document.nodes, node.id) ?? IDENTITY_MATRIX;\n\treturn collectWithMatrix(node, parent)\n\t\t.map(({ path, parent: m }) => bezierPathToSvg(transformBezierPath(vectorPathWorldBezier(path, m), view), { precision: 2 }))\n\t\t.join(' ');\n}\n\n/** Path nodes in a subtree with the matrix of their parent space → document. */\nfunction collectWithMatrix(node: VectorNode, parent: AffineMatrix): { path: VectorPathNode; parent: AffineMatrix }[] {\n\tif (node.type === 'path') return [{ path: node, parent }];\n\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\treturn node.children.flatMap((c) => collectWithMatrix(c, m));\n}\n\nfunction collect(node: VectorNode): VectorPathNode[] {\n\tif (node.type === 'path') return [node];\n\treturn node.children.flatMap(collect);\n}\n\n/** The editing overlay in screen pixels. Render it on top of the scene, untransformed. */\nexport function getVectorOverlayRenderData(state: VectorEditorState): VectorOverlayRenderData {\n\tconst doc = state.document;\n\tconst z = state.viewport.zoom;\n\tconst outlines: VectorOverlayRenderData['outlines'] = [];\n\tconst seen = new Set<string>();\n\tconst outline = (id: string, selected: boolean) => {\n\t\tif (seen.has(id)) return;\n\t\tconst node = findVectorNode(doc.nodes, id);\n\t\tif (!node || node.visible === false) return;\n\t\tseen.add(id);\n\t\toutlines.push({ id, d: screenOutline(state, node), selected });\n\t};\n\tfor (const id of state.selection) outline(id, true);\n\tif (state.editingId) outline(state.editingId, true);\n\tif (state.hover?.nodeId && !state.interaction) outline(state.hover.nodeId, false);\n\n\tlet selectionBox: VectorOverlayRenderData['selectionBox'] = null;\n\tif (state.tool === 'select' && state.selectionFrame && state.interaction?.type !== 'marquee') {\n\t\tconst g = getVectorSelectionBoxGeometry(state.selectionFrame, state.viewport);\n\t\tselectionBox = { ...g.box, angle: g.angle, transform: g.transform, corners: g.corners, handles: g.handles };\n\t}\n\n\tconst selected = (r: VectorAnchorRef) => state.selectedAnchors.some((a) => a.nodeId === r.nodeId && a.subpath === r.subpath && a.index === r.index);\n\tconst sameAnchor = (a: VectorAnchorRef | undefined, b: VectorAnchorRef) => !!a && a.nodeId === b.nodeId && a.subpath === b.subpath && a.index === b.index;\n\tconst anchors: VectorRenderAnchor[] = getVisibleAnchors(state).map((ref) => {\n\t\tconst a = getAnchorWorld(doc, ref)!;\n\t\tconst s = toScreen(state, a);\n\t\tconst closes = !!state.pen && state.pen.nodeId === ref.nodeId && state.pen.subpath === ref.subpath && ref.index === 0;\n\t\treturn { ref, x: s.x, y: s.y, type: a.type ?? inferAnchorType(a), selected: selected(ref), hovered: sameAnchor(state.hover?.anchor, ref), closes };\n\t});\n\tif (state.tool === 'pen' && !state.pen && state.hover?.anchor) {\n\t\tconst a = getAnchorWorld(doc, state.hover.anchor);\n\t\tif (a) {\n\t\t\tconst s = toScreen(state, a);\n\t\t\tanchors.push({ ref: state.hover.anchor, x: s.x, y: s.y, type: a.type ?? 'corner', selected: false, hovered: true, closes: false });\n\t\t}\n\t}\n\n\tconst handles: VectorRenderHandle[] = getVisibleHandles(state).flatMap((ref) => {\n\t\tconst a = getAnchorWorld(doc, ref);\n\t\tconst h = a?.[ref.handle];\n\t\tif (!a || !h) return [];\n\t\tconst s = toScreen(state, h);\n\t\tconst sa = toScreen(state, a);\n\t\tconst hovered = !!state.hover?.handle && sameAnchor(state.hover.handle, ref) && state.hover.handle.handle === ref.handle;\n\t\treturn [{ ref, x: s.x, y: s.y, anchorX: sa.x, anchorY: sa.y, hovered }];\n\t});\n\n\tlet marquee: VectorBounds | null = null;\n\tif (state.interaction?.type === 'marquee') {\n\t\tconst b = state.interaction.bounds;\n\t\tconst tl = toScreen(state, b);\n\t\tmarquee = { x: tl.x, y: tl.y, width: b.width * z, height: b.height * z };\n\t}\n\n\tlet penPreview: string | null = null;\n\tif (state.tool === 'pen' && state.pen && state.pointer && !state.interaction) {\n\t\tconst node = findVectorNode(doc.nodes, state.pen.nodeId);\n\t\tconst sp = node?.type === 'path' ? node.subpaths[state.pen.subpath] : undefined;\n\t\tconst last = sp ? getAnchorWorld(doc, { nodeId: state.pen.nodeId, subpath: state.pen.subpath, index: sp.anchors.length - 1 }) : undefined;\n\t\tif (last) {\n\t\t\tconst a = toScreen(state, last);\n\t\t\tconst p = toScreen(state, state.pointer);\n\t\t\tconst c = last.out ? toScreen(state, last.out) : null;\n\t\t\tpenPreview = c ? `M${fmt(a.x)} ${fmt(a.y)}Q${fmt(c.x)} ${fmt(c.y)} ${fmt(p.x)} ${fmt(p.y)}` : `M${fmt(a.x)} ${fmt(a.y)}L${fmt(p.x)} ${fmt(p.y)}`;\n\t\t}\n\t}\n\n\tconst origin = toScreen(state, { x: 0, y: 0 });\n\tconst artboard = { x: origin.x, y: origin.y, width: doc.width * z, height: doc.height * z };\n\n\tlet status: string | null = null;\n\tconst it = state.interaction;\n\tif (it?.type === 'rotate') status = `${Math.round(it.angle)}°`;\n\telse if (it?.type === 'move' || it?.type === 'anchors') status = `Δ ${fmt(it.dx)}, ${fmt(it.dy)}`;\n\telse if (it?.type === 'scale' || it?.type === 'draw') {\n\t\tconst b = it.type === 'draw' ? (findVectorNode(doc.nodes, it.nodeId) ? vectorNodeBounds(findVectorNode(doc.nodes, it.nodeId)!) : null) : state.selectionFrame;\n\t\tif (b) status = `W ${fmt(b.width)} × H ${fmt(b.height)}`;\n\t}\n\n\tconst guides: VectorOverlayRenderData['guides'] = { lines: [], labels: [] };\n\tif (state.guides) {\n\t\tfor (const l of state.guides.lines) {\n\t\t\tconst a = toScreen(state, { x: l.x1, y: l.y1 });\n\t\t\tconst b = toScreen(state, { x: l.x2, y: l.y2 });\n\t\t\tguides.lines.push({ kind: l.kind, x1: fmt(a.x), y1: fmt(a.y), x2: fmt(b.x), y2: fmt(b.y) });\n\t\t}\n\t\tfor (const l of state.guides.labels) {\n\t\t\tconst p = toScreen(state, l);\n\t\t\tguides.labels.push({ kind: l.kind, x: fmt(p.x), y: fmt(p.y), text: l.text });\n\t\t}\n\t}\n\n\tlet toolStroke: VectorOverlayRenderData['toolStroke'] = null;\n\tif (it?.type === 'stroke') {\n\t\tconst pts = it.points.map((q) => toScreen(state, q));\n\t\tconst d = pts.map((q, i) => `${i ? 'L' : 'M'}${fmt(q.x)} ${fmt(q.y)}`).join('') + (pts.length === 1 ? `L${fmt(pts[0].x)} ${fmt(pts[0].y)}` : '');\n\t\ttoolStroke = { tool: it.tool, d, width: fmt(it.width * z) };\n\t}\n\tlet pencilString: VectorOverlayRenderData['pencilString'] = null;\n\tif (it?.type === 'draw' && it.string) {\n\t\tconst a = toScreen(state, it.string[0]);\n\t\tconst b = toScreen(state, it.string[1]);\n\t\tpencilString = { x1: fmt(a.x), y1: fmt(a.y), x2: fmt(b.x), y2: fmt(b.y) };\n\t}\n\tconst dragged = it?.type === 'corner' ? it.ref : null;\n\tconst cornerWidgets: VectorRenderCornerWidget[] = getVectorCornerWidgets(state).map((w) => {\n\t\tconst s = toScreen(state, w);\n\t\treturn { ref: w.ref, x: fmt(s.x), y: fmt(s.y), radius: w.radius, kind: w.kind, hovered: sameAnchor(state.hover?.corner, w.ref), active: !!dragged };\n\t});\n\tif (it?.type === 'corner') status = `R ${fmt(it.radius)}`;\n\tconst cutPoint = state.tool === 'scissors' && state.hover?.segment && !it ? (({ x, y }) => ({ x: fmt(x), y: fmt(y) }))(toScreen(state, state.hover.segment.point)) : null;\n\n\tconst sc = (p: Vec2) => {\n\t\tconst q = toScreen(state, p);\n\t\treturn { x: fmt(q.x), y: fmt(q.y) };\n\t};\n\tconst sameWidth = (a: VectorWidthPointRef | null | undefined, b: VectorWidthPointRef) => !!a && a.nodeId === b.nodeId && a.index === b.index;\n\tconst widthPoints: VectorRenderWidthPoint[] = getVectorWidthHandles(state).map((h) => {\n\t\tconst c = sc(h);\n\t\tconst hw = state.hover?.widthPoint;\n\t\tconst hovered = hw && sameWidth(hw, h.ref) && hw.subpath === h.ref.subpath ? hw.part : null;\n\t\treturn { ref: h.ref, x: c.x, y: c.y, left: sc(h.left), right: sc(h.right), selected: h.selected, hovered, active: it?.type === 'width' && sameWidth(it.ref, h.ref) };\n\t});\n\tconst spot = state.tool === 'width' && !it ? state.hover?.strokeSpot : null;\n\tconst widthSpot = spot ? { ...sc(spot.point), left: sc(spot.left), right: sc(spot.right) } : null;\n\tif (it?.type === 'width') status = it.mode === 'move' ? 'Move width point' : `W ${fmt(it.width)}`;\n\n\treturn { outlines, selectionBox, anchors, handles, marquee, penPreview, artboard, guides, status, toolStroke, pencilString, cutPoint, cornerWidgets, widthPoints, widthSpot };\n}\n\n// ---------------------------------------------------------------------------\n// Event adapters (duck-typed, so they work with DOM, React and Svelte events)\n// ---------------------------------------------------------------------------\n\n/** Colours and sizes (screen pixels) the bundled canvases draw the overlay with. */\nexport const VECTOR_OVERLAY_THEME = {\n\taccent: '#0ea5e9',\n\t/** Smart guide lines and labels. */\n\tguide: '#ff3dfc',\n\thandleFill: '#ffffff',\n\tmarqueeFill: 'rgba(14, 165, 233, 0.08)',\n\t/** The eraser's swath while it is dragged. */\n\teraserFill: 'rgba(239, 68, 68, 0.25)',\n\ttransformHandleSize: 8,\n\tanchorSize: 7,\n\thandleRadius: 3.5,\n\t/** Radius of a live corner widget (a ring with a dot). */\n\tcornerWidgetRadius: 4,\n\t/** Half the diagonal of a width point's diamond. */\n\twidthPointSize: 5\n} as const;\n\n/** SVG path data of the diamond a width point is drawn with (screen pixels). */\nexport function vectorDiamondPath(x: number, y: number, r: number = VECTOR_OVERLAY_THEME.widthPointSize): string {\n\treturn `M${fmt(x)} ${fmt(y - r)}L${fmt(x + r)} ${fmt(y)}L${fmt(x)} ${fmt(y + r)}L${fmt(x - r)} ${fmt(y)}Z`;\n}\n\ninterface ModifierEventLike {\n\tshiftKey?: boolean;\n\taltKey?: boolean;\n\tmetaKey?: boolean;\n\tctrlKey?: boolean;\n}\n\n/** Modifiers of a mouse / pointer / key event (`mod` is Cmd or Ctrl). */\nexport function toVectorModifiers(event: ModifierEventLike): { shift: boolean; alt: boolean; mod: boolean } {\n\treturn { shift: !!event.shiftKey, alt: !!event.altKey, mod: !!(event.metaKey || event.ctrlKey) };\n}\n\n/**\n * A pointer event as `VectorEditorController.pointerDown/Move/Up` input: modifiers, button,\n * and the pressure and pointer type the pencil records as a width profile.\n */\nexport function toVectorPointerInput(event: ModifierEventLike & { button?: number; pressure?: number; pointerType?: string }) {\n\treturn {\n\t\t...toVectorModifiers(event),\n\t\tbutton: event.button,\n\t\t...(typeof event.pressure === 'number' ? { pressure: event.pressure } : {}),\n\t\t...(event.pointerType ? { pointerType: event.pointerType } : {})\n\t};\n}\n\n/** A key event as `VectorEditorController.keyDown/keyUp` input. */\nexport function toVectorKeyInput(event: ModifierEventLike & { key: string }) {\n\treturn { key: event.key, ...toVectorModifiers(event) };\n}\n\n/** True for targets that should keep their own keys (inputs, textareas, contenteditable). */\nexport function isVectorTextTarget(target: unknown): boolean {\n\tconst el = target as { tagName?: string; isContentEditable?: boolean; getAttribute?: (name: string) => string | null } | null;\n\tif (!el || typeof el !== 'object') return false;\n\tconst tag = (el.tagName ?? '').toUpperCase();\n\tif (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true;\n\treturn !!el.isContentEditable || el.getAttribute?.('contenteditable') === 'true';\n}\n\n// ---------------------------------------------------------------------------\n// Style panel helpers\n// ---------------------------------------------------------------------------\n\n/** Style shown in a style panel: the first selected path's, with `mixed` flags when paths differ. */\nexport interface VectorSelectionStyle {\n\tfill: VectorPaint;\n\tstroke: VectorPaint;\n\tstrokeWidth: number;\n\topacity: number;\n\tstrokeAlign: VectorStrokeAlign;\n\tstartArrow: VectorArrowhead | null;\n\tendArrow: VectorArrowhead | null;\n\tarrowAlign: VectorArrowAlign;\n\tstartArrowScale: number;\n\tendArrowScale: number;\n\t/** The first path's width profile (null when uniform) and the preset it matches. */\n\tstrokeWidthProfile: VectorWidthPoint[] | null;\n\twidthProfile: VectorWidthPreset | 'custom';\n\t/**\n\t * Live corners of the selected anchors (direct tool) or of every corner of the selected\n\t * paths: the first one's radius and kind, and how many corners there are (0: none to round).\n\t */\n\tcornerRadius: number;\n\tcornerKind: VectorCornerKind;\n\tcorners: number;\n\t/** Some selected path is open, so arrowheads apply. */\n\thasOpenPath: boolean;\n\tmixed: {\n\t\tfill: boolean;\n\t\tstroke: boolean;\n\t\tstrokeWidth: boolean;\n\t\topacity: boolean;\n\t\tstrokeAlign: boolean;\n\t\tstartArrow: boolean;\n\t\tendArrow: boolean;\n\t\tarrowAlign: boolean;\n\t\tstartArrowScale: boolean;\n\t\tendArrowScale: boolean;\n\t\twidthProfile: boolean;\n\t\tcornerRadius: boolean;\n\t\tcornerKind: boolean;\n\t};\n\t/** Ids of the paths the style applies to. */\n\tpathIds: string[];\n}\n\nexport function getVectorSelectionStyle(\n\tstate: Pick<VectorEditorState, 'document' | 'selection'> & Partial<Pick<VectorEditorState, 'selectedAnchors' | 'tool'>>\n): VectorSelectionStyle | null {\n\tconst paths: VectorPathNode[] = [];\n\tfor (const id of state.selection) {\n\t\tconst node = findVectorNode(state.document.nodes, id);\n\t\tif (node) paths.push(...collect(node));\n\t}\n\tconst anchorMode = state.tool === 'direct' && !!state.selectedAnchors?.length;\n\tif (anchorMode) {\n\t\tfor (const r of state.selectedAnchors!) {\n\t\t\tif (paths.some((p) => p.id === r.nodeId)) continue;\n\t\t\tconst node = findVectorNode(state.document.nodes, r.nodeId);\n\t\t\tif (node?.type === 'path') paths.push(node);\n\t\t}\n\t}\n\tif (!paths.length) return null;\n\tconst first = paths[0];\n\tconst same = (get: (p: VectorPathNode) => unknown) => paths.every((p) => JSON.stringify(get(p) ?? null) === JSON.stringify(get(first) ?? null));\n\t// Corners: those of the selected anchors in the direct tool, else every corner of the paths.\n\tconst corners: { radius: number; kind: VectorCornerKind }[] = [];\n\tfor (const p of paths) {\n\t\tfor (const c of vectorCorners(p.subpaths)) {\n\t\t\tif (anchorMode && !state.selectedAnchors!.some((r) => r.nodeId === p.id && r.subpath === c.subpath && r.index === c.index)) continue;\n\t\t\tconst corner = p.subpaths[c.subpath].anchors[c.index].corner;\n\t\t\tcorners.push({ radius: corner?.radius ?? 0, kind: corner?.kind ?? 'round' });\n\t\t}\n\t}\n\tconst c0 = corners[0] ?? { radius: 0, kind: 'round' as const };\n\treturn {\n\t\tfill: first.fill ?? null,\n\t\tstroke: first.stroke ?? null,\n\t\tstrokeWidth: first.strokeWidth ?? 1,\n\t\topacity: first.opacity ?? 1,\n\t\tstrokeAlign: first.strokeAlign ?? 'center',\n\t\tstartArrow: first.startArrow ?? null,\n\t\tendArrow: first.endArrow ?? null,\n\t\tarrowAlign: first.arrowAlign ?? 'extend',\n\t\tstartArrowScale: first.startArrowScale ?? 1,\n\t\tendArrowScale: first.endArrowScale ?? 1,\n\t\tstrokeWidthProfile: profileOf(first),\n\t\twidthProfile: widthProfilePresetId(profileOf(first)),\n\t\tcornerRadius: c0.radius,\n\t\tcornerKind: c0.kind,\n\t\tcorners: corners.length,\n\t\thasOpenPath: paths.some((p) => p.subpaths.some((sp) => !sp.closed && sp.anchors.length > 1)),\n\t\tmixed: {\n\t\t\tfill: !same((p) => p.fill),\n\t\t\tstroke: !same((p) => p.stroke),\n\t\t\tstrokeWidth: !same((p) => p.strokeWidth ?? 1),\n\t\t\topacity: !same((p) => p.opacity ?? 1),\n\t\t\tstrokeAlign: !same((p) => p.strokeAlign ?? 'center'),\n\t\t\tstartArrow: !same((p) => p.startArrow ?? null),\n\t\t\tendArrow: !same((p) => p.endArrow ?? null),\n\t\t\tarrowAlign: !same((p) => p.arrowAlign ?? 'extend'),\n\t\t\tstartArrowScale: !same((p) => p.startArrowScale ?? 1),\n\t\t\tendArrowScale: !same((p) => p.endArrowScale ?? 1),\n\t\t\twidthProfile: !same(profileOf),\n\t\t\tcornerRadius: corners.some((c) => c.radius !== c0.radius),\n\t\t\tcornerKind: corners.some((c) => c.kind !== c0.kind)\n\t\t},\n\t\tpathIds: paths.map((p) => p.id)\n\t};\n}\n\nfunction profileOf(p: VectorPathNode): VectorWidthPoint[] | null {\n\tconst points = sanitizeWidthProfile(p.strokeWidthProfile);\n\treturn points.length && widthProfilePresetId(points) !== 'uniform' ? points : null;\n}\n\n/** Labels of the stroke alignments, corner kinds and arrowheads, for style panels. */\nexport const VECTOR_STROKE_ALIGN_LABELS: Readonly<Record<VectorStrokeAlign, string>> = { center: 'Center', inside: 'Inside', outside: 'Outside' };\nexport const VECTOR_CORNER_KIND_LABELS: Readonly<Record<VectorCornerKind, string>> = { round: 'Round', inverted: 'Inverted', chamfer: 'Chamfer' };\nexport const VECTOR_ARROWHEAD_LABELS: Readonly<Record<VectorArrowhead, string>> = {\n\ttriangle: 'Triangle',\n\tarrow: 'Arrow',\n\topen: 'Open arrow',\n\tcircle: 'Circle',\n\tsquare: 'Square',\n\tbar: 'Bar'\n};\n\n/** A paint as `#rrggbb` for `<input type=\"color\">`, or null for none, gradients and other CSS colours. */\nexport function vectorPaintToHex(paint: VectorPaint | undefined): string | null {\n\tif (typeof paint !== 'string') return null;\n\tconst m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(paint.trim());\n\tif (!m) return null;\n\tconst hex = m[1].length === 3 ? m[1].replace(/./g, (c) => c + c) : m[1];\n\treturn `#${hex.toLowerCase()}`;\n}\n\n// ---------------------------------------------------------------------------\n// Toolbar helpers\n// ---------------------------------------------------------------------------\n\n/** A path-editing button of the bundled toolbars. */\nexport interface VectorPathAction {\n\tid: 'join' | 'average' | 'cut' | 'clean' | 'smooth' | 'outline';\n\tlabel: string;\n\ttitle: string;\n\t/** Shortcut after Cmd / Ctrl, if any. */\n\tshortcut?: string;\n\t/** Whether it can run with `selected` nodes and `points` selected anchors (direct tool). */\n\tenabled: (selected: number, points: number) => boolean;\n\trun: (controller: VectorEditorController) => unknown;\n}\n\n/** Join, Average, Cut at Points, Remove Redundant Points, Smooth and Outline Stroke, as the toolbars show them. */\nexport const VECTOR_PATH_ACTIONS: readonly VectorPathAction[] = [\n\t{ id: 'join', label: '⋈', title: 'Join', shortcut: 'J', enabled: (s, p) => s + p > 0, run: (c) => c.joinPaths() },\n\t{ id: 'average', label: '⊹', title: 'Average Points', shortcut: 'Alt+J', enabled: (_s, p) => p > 1, run: (c) => c.averageAnchors('both') },\n\t{ id: 'cut', label: '✂·', title: 'Cut at Points', enabled: (_s, p) => p > 0, run: (c) => c.cutAtAnchors() },\n\t{ id: 'clean', label: '⌁', title: 'Remove Redundant Points', enabled: (s, p) => s + p > 0, run: (c) => c.removeRedundantPoints() },\n\t{ id: 'smooth', label: '∿', title: 'Smooth', enabled: (s, p) => s + p > 0, run: (c) => c.smoothPaths() },\n\t{ id: 'outline', label: '⊡', title: 'Outline Stroke', enabled: (s) => s > 0, run: (c) => c.outlineStroke() }\n];\n\n/** The on / off path-editing settings the toolbars toggle. */\nexport const VECTOR_EDIT_TOGGLES: readonly { key: 'keepShapeOnDelete' | 'curvatureMoves' | 'recognizeShapes'; label: string; title: string }[] = [\n\t{ key: 'keepShapeOnDelete', label: 'Keep', title: 'Keep shape when deleting points' },\n\t{ key: 'curvatureMoves', label: 'Curv', title: 'Curvature point moves (Alt flips while dragging)' },\n\t{ key: 'recognizeShapes', label: 'Shapes', title: 'Turn pencil scribbles into shapes' }\n];\n\n","import type { CommandSpec } from '../commands/registry.js';\nimport type { VectorEditorController, VectorShapeInput } from './controller.js';\nimport { vectorNodeBounds, vectorNodeRotation, vectorParentMatrix, vectorPathData, IDENTITY_MATRIX } from './geometry.js';\nimport type { VectorAlign, VectorAnchorRef, VectorArrange, VectorAverageAxis, VectorBooleanOperation, VectorCornerKind, VectorNode, VectorStyle, VectorTool } from './types.js';\nimport { VECTOR_ARROWHEADS, VECTOR_CORNER_KINDS, VECTOR_TOOLS, type VectorWidthPoint } from './types.js';\nimport { VECTOR_WIDTH_PRESET_IDS, type VectorTaperOptions, type VectorWaveOptions, type VectorWidthPreset } from './width.js';\n\nexport interface VectorCommandOptions {\n\t/** Id prefix (default `vector.`); use one per editor when several are registered. */\n\tprefix?: string;\n\t/** Palette group (default `Vector`). */\n\tgroup?: string;\n\t/** Command scope. Omit for global commands. */\n\tscope?: string;\n}\n\n/** A node as listed for agents. */\nexport interface VectorNodeListing {\n\tid: string;\n\ttype: 'path' | 'group';\n\tname?: string;\n\tdepth: number;\n\t/** Axis-aligned bounds in document units. */\n\tbounds: { x: number; y: number; width: number; height: number } | null;\n\t/** Rotation in degrees, clockwise (ancestors' rotations included). */\n\trotation: number;\n\tvisible: boolean;\n\tlocked: boolean;\n\tselected: boolean;\n\tfill?: unknown;\n\tstroke?: unknown;\n\tstrokeWidth?: number;\n\t/** SVG path data (paths only). */\n\td?: string;\n\tchildren?: number;\n}\n\nconst fail = (message: string): never => {\n\tthrow new Error(message);\n};\n\nconst IDS = { type: 'array', items: { type: 'string' }, description: 'Node ids (default: the selection).' } as const;\n\nconst ANCHORS = {\n\ttype: 'array',\n\titems: {\n\t\ttype: 'object',\n\t\tproperties: { nodeId: { type: 'string' }, subpath: { type: 'integer', minimum: 0 }, index: { type: 'integer', minimum: 0 } },\n\t\trequired: ['nodeId', 'subpath', 'index']\n\t},\n\tdescription: 'Anchors as { nodeId, subpath, index } (default: the selected points).'\n} as const;\n\nconst POINTS = {\n\ttype: 'array',\n\titems: { type: 'array', items: { type: 'number' }, minItems: 2, maxItems: 2 },\n\tminItems: 1,\n\tdescription: 'Polyline [[x, y], …] in document units.'\n} as const;\n\nconst WIDTH_POINTS = {\n\ttype: ['array', 'null'],\n\titems: {\n\t\ttype: 'object',\n\t\tproperties: {\n\t\t\tt: { type: 'number', minimum: 0, maximum: 1, description: 'Position along each subpath by length (0 start, 1 end).' },\n\t\t\tleft: { type: 'number', minimum: 0, description: 'Left side as a multiple of half the stroke width (1 = uniform).' },\n\t\t\tright: { type: 'number', minimum: 0, description: 'Right side (looking along the path, y down).' }\n\t\t},\n\t\trequired: ['t', 'left', 'right']\n\t},\n\tdescription: 'Variable-width profile points, interpolated smoothly (monotone cubic); two points at one `t` make a step. `null` or `[]` strokes at a uniform width.'\n} as const;\n\nconst PAINT = {\n\tdescription: 'A CSS colour, `null` for none, or a gradient `{ type: \"linear\", angle, stops: [{ offset, color }] }`.'\n} as const;\n\nconst STYLE_PROPS = {\n\tfill: PAINT,\n\tstroke: PAINT,\n\tstrokeWidth: { type: 'number', minimum: 0 },\n\tstrokeLinecap: { type: 'string', enum: ['butt', 'round', 'square'] },\n\tstrokeLinejoin: { type: 'string', enum: ['miter', 'round', 'bevel'] },\n\tstrokeDasharray: { type: 'array', items: { type: 'number' } },\n\tfillRule: { type: 'string', enum: ['nonzero', 'evenodd'] },\n\tstrokeAlign: { type: 'string', enum: ['center', 'inside', 'outside'], description: 'Where the stroke sits on the outline (closed shapes only; open paths stroke centred).' },\n\tstartArrow: { type: ['string', 'null'], enum: [...VECTOR_ARROWHEADS, null], description: 'Head at the start of an open path, or null for none.' },\n\tendArrow: { type: ['string', 'null'], enum: [...VECTOR_ARROWHEADS, null], description: 'Head at the end of an open path, or null for none.' },\n\tarrowAlign: { type: 'string', enum: ['extend', 'tip'], description: '`extend`: the tip sits past the end point; `tip`: on it, the stroke shortened under the head.' },\n\tstartArrowScale: { type: 'number', exclusiveMinimum: 0, description: 'Start head size as a multiple of the stroke width (default 1).' },\n\tendArrowScale: { type: 'number', exclusiveMinimum: 0, description: 'End head size as a multiple of the stroke width (default 1).' },\n\tstrokeWidthProfile: WIDTH_POINTS\n} as const;\n\nconst pickStyle = (params: Record<string, unknown>): VectorStyle => {\n\tconst out: Record<string, unknown> = {};\n\tfor (const key of Object.keys(STYLE_PROPS)) if (params[key] !== undefined) out[key] = params[key];\n\treturn out as VectorStyle;\n};\n\nconst check = (result: { ok: boolean; message?: string }) => {\n\tif (!result.ok) fail(result.message ?? 'The command failed.');\n};\n\n/**\n * Palette and agent commands for a vector editor: list, select, add shapes and paths, style,\n * transform, align, arrange, group, boolean operations and SVG import / export. Register them\n * in a `CommandRegistry` and agents get them through `createCommandToolProvider`. Failures\n * throw sentences, which the registry returns as `{ ok: false, code: 'failed', message }`.\n */\nexport function createVectorCommands(controller: VectorEditorController, options: VectorCommandOptions = {}): CommandSpec[] {\n\tconst prefix = options.prefix ?? 'vector.';\n\tconst group = options.group ?? 'Vector';\n\tconst base = { group, ...(options.scope ? { scope: options.scope } : {}) };\n\tconst hasSelection = () => (controller.getState().selection.length ? true : 'Nothing is selected.');\n\tconst ids = (params: { ids?: string[] } | undefined) => {\n\t\tconst list = params?.ids ?? controller.getState().selection;\n\t\tfor (const id of list) if (!controller.getNode(id)) fail(`There is no node \"${id}\".`);\n\t\tif (!list.length) fail('Nothing is selected; pass ids.');\n\t\treturn list;\n\t};\n\tconst enabledFor = (_: unknown, params: { ids?: string[] } | undefined) => (params?.ids?.length ? true : hasSelection());\n\tconst anchorsOf = (refs: VectorAnchorRef[] | undefined): VectorAnchorRef[] => {\n\t\tif (!refs) return [...controller.getState().selectedAnchors];\n\t\tfor (const r of refs) {\n\t\t\tconst node = controller.getNode(r.nodeId);\n\t\t\tif (node?.type !== 'path' || !node.subpaths[r.subpath]?.anchors[r.index]) fail(`There is no anchor ${r.index} on subpath ${r.subpath} of \"${r.nodeId}\".`);\n\t\t}\n\t\treturn refs;\n\t};\n\n\tconst list = (): { width: number; height: number; nodes: VectorNodeListing[]; selection: readonly string[]; tool: VectorTool } => {\n\t\tconst state = controller.getState();\n\t\tconst out: VectorNodeListing[] = [];\n\t\tconst visit = (nodes: readonly VectorNode[], depth: number) => {\n\t\t\tfor (const n of nodes) {\n\t\t\t\tconst parent = vectorParentMatrix(state.document.nodes, n.id) ?? IDENTITY_MATRIX;\n\t\t\t\tconst b = vectorNodeBounds(n, parent);\n\t\t\t\tout.push({\n\t\t\t\t\tid: n.id,\n\t\t\t\t\ttype: n.type,\n\t\t\t\t\t...(n.name ? { name: n.name } : {}),\n\t\t\t\t\tdepth,\n\t\t\t\t\trotation: Math.round(vectorNodeRotation(n, parent) * 100) / 100,\n\t\t\t\t\tbounds: b && { x: Math.round(b.x * 100) / 100, y: Math.round(b.y * 100) / 100, width: Math.round(b.width * 100) / 100, height: Math.round(b.height * 100) / 100 },\n\t\t\t\t\tvisible: n.visible !== false,\n\t\t\t\t\tlocked: !!n.locked,\n\t\t\t\t\tselected: state.selection.includes(n.id),\n\t\t\t\t\t...(n.type === 'path'\n\t\t\t\t\t\t? { fill: n.fill ?? null, stroke: n.stroke ?? null, strokeWidth: n.strokeWidth ?? 1, d: vectorPathData(n, 2) }\n\t\t\t\t\t\t: { children: n.children.length })\n\t\t\t\t});\n\t\t\t\tif (n.type === 'group') visit(n.children, depth + 1);\n\t\t\t}\n\t\t};\n\t\tvisit(state.document.nodes, 0);\n\t\treturn { width: state.document.width, height: state.document.height, nodes: out, selection: state.selection, tool: state.tool };\n\t};\n\n\treturn [\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}list`,\n\t\t\tlabel: 'List Vector Nodes',\n\t\t\treadOnly: true,\n\t\t\tkeywords: ['layers', 'shapes', 'document', 'outline'],\n\t\t\tdescription: 'Lists every node (paths and groups, depth first) with bounds, style, path data and selection.',\n\t\t\trun: list\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}select`,\n\t\t\tlabel: 'Select Nodes',\n\t\t\tkeywords: ['pick', 'choose'],\n\t\t\tdescription: 'Selects nodes by id (empty list clears the selection).',\n\t\t\tparams: { type: 'object', properties: { ids: { type: 'array', items: { type: 'string' } }, add: { type: 'boolean' } }, required: ['ids'] },\n\t\t\trun: (_ctx: unknown, params: { ids: string[]; add?: boolean }) => {\n\t\t\t\tfor (const id of params.ids) if (!controller.getNode(id)) fail(`There is no node \"${id}\".`);\n\t\t\t\tif (!params.ids.length && !params.add) controller.clearSelection();\n\t\t\t\telse controller.select(params.ids, { add: params.add });\n\t\t\t\treturn { selection: controller.getState().selection };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}addShape`,\n\t\t\tlabel: 'Add Shape…',\n\t\t\tkeywords: ['rectangle', 'ellipse', 'circle', 'polygon', 'star', 'line', 'draw'],\n\t\t\tdescription: 'Adds a rectangle, ellipse, polygon, star or line in document units, using the current default style unless overridden.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tkind: { type: 'string', enum: ['rect', 'ellipse', 'polygon', 'star', 'line'] },\n\t\t\t\t\tx: { type: 'number' },\n\t\t\t\t\ty: { type: 'number' },\n\t\t\t\t\twidth: { type: 'number', description: 'For a line: the x offset of its end.' },\n\t\t\t\t\theight: { type: 'number', description: 'For a line: the y offset of its end.' },\n\t\t\t\t\tcornerRadius: { type: 'number', minimum: 0, description: 'Live corner radius of a rect, polygon or star.' },\n\t\t\t\t\tcornerKind: { type: 'string', enum: VECTOR_CORNER_KINDS },\n\t\t\t\t\tsides: { type: 'integer', minimum: 3 },\n\t\t\t\t\tpoints: { type: 'integer', minimum: 3 },\n\t\t\t\t\tinnerRatio: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\tname: { type: 'string' },\n\t\t\t\t\t...STYLE_PROPS\n\t\t\t\t},\n\t\t\t\trequired: ['kind', 'x', 'y', 'width', 'height']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: VectorShapeInput) => ({ id: controller.addShape(params) })\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}addPath`,\n\t\t\tlabel: 'Add Path…',\n\t\t\tkeywords: ['svg', 'path data', 'bezier', 'curve'],\n\t\t\tdescription: 'Adds a path from SVG path data (`d`), in document units.',\n\t\t\tparams: { type: 'object', properties: { d: { type: 'string' }, name: { type: 'string' }, ...STYLE_PROPS }, required: ['d'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { d: string; name?: string } & Record<string, unknown>) => {\n\t\t\t\tconst id = controller.addPath(params.d, { ...pickStyle(params), ...(params.name ? { name: params.name } : {}) });\n\t\t\t\tconst node = controller.getNode(id);\n\t\t\t\tif (node?.type === 'path' && !node.subpaths.length) {\n\t\t\t\t\tcontroller.undo();\n\t\t\t\t\tfail('The path data has no points.');\n\t\t\t\t}\n\t\t\t\treturn { id };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setStyle`,\n\t\t\tlabel: 'Set Style…',\n\t\t\tkeywords: ['fill', 'stroke', 'colour', 'color', 'gradient', 'width'],\n\t\t\tdescription: 'Sets fill, stroke and stroke settings of nodes (groups apply to every path inside).',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, ...STYLE_PROPS } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } & Record<string, unknown>) => {\n\t\t\t\tconst style = pickStyle(params);\n\t\t\t\tif (!Object.keys(style).length) fail('Pass at least one style property.');\n\t\t\t\tcheck(controller.setStyle(style, ids(params)));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setCorners`,\n\t\t\tlabel: 'Corner Radius…',\n\t\t\tkeywords: ['round', 'rounded', 'corners', 'radius', 'fillet', 'chamfer', 'live corners'],\n\t\t\tdescription:\n\t\t\t\t'Sets the live corner radius (and optionally `kind`: round, inverted or chamfer) of `anchors`, else the selected points (direct tool), else every corner of `ids` / the selection. Radius 0 makes corners sharp; radii shrink to fit short sides. The anchors stay editable.',\n\t\t\tparams: { type: 'object', properties: { radius: { type: 'number', minimum: 0 }, kind: { type: 'string', enum: VECTOR_CORNER_KINDS }, ids: IDS, anchors: ANCHORS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { radius?: number; kind?: VectorCornerKind; ids?: string[]; anchors?: VectorAnchorRef[] } | undefined) => {\n\t\t\t\tconst refs = params?.anchors ? anchorsOf(params.anchors) : undefined;\n\t\t\t\tconst target = { refs, ids: params?.ids ? ids(params) : undefined };\n\t\t\t\tif (params?.radius !== undefined) check(controller.setCornerRadius(params.radius, { ...target, kind: params.kind }));\n\t\t\t\telse if (params?.kind) check(controller.setCornerKind(params.kind, target));\n\t\t\t\telse fail('Pass `radius` and / or `kind`.');\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setWidthProfile`,\n\t\t\tlabel: 'Width Profile…',\n\t\t\tkeywords: ['variable width', 'taper', 'tapered', 'pressure', 'profile', 'brush', 'calligraphy', 'bulge', 'thick', 'thin'],\n\t\t\tdescription:\n\t\t\t\t'Gives the stroke of paths a variable width: a `preset` (`uniform` removes the profile), explicit `points` ({ t, left, right }: side scales along each subpath), or a parametric `taper` (startLength / endLength as fractions of the path, startWidth / endWidth 0–1, startEase / endEase 0–1) and / or `wave` (amount 0–1, cycles, phase in degrees). Profiled strokes draw as filled outlines; Outline Stroke bakes them.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tids: IDS,\n\t\t\t\t\tpreset: { type: 'string', enum: VECTOR_WIDTH_PRESET_IDS },\n\t\t\t\t\tpoints: WIDTH_POINTS,\n\t\t\t\t\ttaper: {\n\t\t\t\t\t\ttype: 'object',\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tstartLength: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\t\t\tendLength: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\t\t\tstartWidth: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\t\t\tendWidth: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\t\t\tstartEase: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\t\t\tendEase: { type: 'number', minimum: 0, maximum: 1 }\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\twave: { type: 'object', properties: { amount: { type: 'number', minimum: 0, maximum: 1 }, cycles: { type: 'number', exclusiveMinimum: 0 }, phase: { type: 'number' } } }\n\t\t\t\t}\n\t\t\t},\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (\n\t\t\t\t_ctx: unknown,\n\t\t\t\tparams: { ids?: string[]; preset?: VectorWidthPreset; points?: VectorWidthPoint[] | null; taper?: VectorTaperOptions; wave?: VectorWaveOptions } | undefined\n\t\t\t) => {\n\t\t\t\tconst target = { ids: ids(params) };\n\t\t\t\tif (params?.preset) check(controller.setWidthProfile(params.preset, target));\n\t\t\t\telse if (params?.points !== undefined) check(controller.setWidthProfile(params.points ?? null, target));\n\t\t\t\telse if (params?.taper || params?.wave) check(controller.setWidthProfile({ taper: params.taper, wave: params.wave }, target));\n\t\t\t\telse fail('Pass `preset`, `points`, `taper` or `wave`.');\n\t\t\t\tconst node = controller.getNode(target.ids[0]);\n\t\t\t\treturn { ok: true, points: node?.type === 'path' ? (node.strokeWidthProfile ?? []) : [] };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}outlineStroke`,\n\t\t\tlabel: 'Outline Stroke',\n\t\t\tkeywords: ['expand', 'stroke to path', 'outline', 'convert stroke'],\n\t\t\tdescription: 'Turns the stroke of paths into filled shapes of the area it paints (alignment, caps, joins, dashes and arrowheads included). Returns the new ids.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => {\n\t\t\t\tconst created = controller.outlineStroke({ ids: params?.ids ? ids(params) : undefined });\n\t\t\t\tif (!created.length) fail('No selected path has a stroke.');\n\t\t\t\treturn { ids: created };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}transform`,\n\t\t\tlabel: 'Transform…',\n\t\t\tkeywords: ['move', 'translate', 'scale', 'resize', 'rotate', 'flip'],\n\t\t\tdescription:\n\t\t\t\t'Moves (dx, dy), scales (sx, sy, along the selection box axes) and/or rotates (`rotate`: by degrees clockwise around the combined centre; `angle`: to an absolute rotation, each node around its own centre), in that order.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tids: IDS,\n\t\t\t\t\tdx: { type: 'number' },\n\t\t\t\t\tdy: { type: 'number' },\n\t\t\t\t\tsx: { type: 'number' },\n\t\t\t\t\tsy: { type: 'number' },\n\t\t\t\t\trotate: { type: 'number' },\n\t\t\t\t\tangle: { type: 'number' }\n\t\t\t\t}\n\t\t\t},\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; dx?: number; dy?: number; sx?: number; sy?: number; rotate?: number; angle?: number }) => {\n\t\t\t\tconst target = ids(params);\n\t\t\t\tif (params.dx || params.dy) check(controller.translate(params.dx ?? 0, params.dy ?? 0, { ids: target }));\n\t\t\t\tif (params.sx !== undefined || params.sy !== undefined) check(controller.scale(params.sx ?? 1, params.sy ?? params.sx ?? 1, { ids: target }));\n\t\t\t\tif (params.rotate) check(controller.rotate(params.rotate, { ids: target }));\n\t\t\t\tif (params.angle !== undefined) check(controller.setRotation(params.angle, { ids: target }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}delete`,\n\t\t\tlabel: 'Delete',\n\t\t\tkeywords: ['remove'],\n\t\t\tdescription: 'Deletes nodes.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => {\n\t\t\t\tcheck(controller.removeNodes(ids(params)));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}boolean`,\n\t\t\tlabel: 'Boolean Operation…',\n\t\t\tkeywords: ['union', 'unite', 'subtract', 'intersect', 'exclude', 'combine', 'pathfinder'],\n\t\t\tdescription: 'Combines two or more paths with union, subtract (upper shapes from the lowest), intersect or exclude.',\n\t\t\tparams: { type: 'object', properties: { operation: { type: 'string', enum: ['union', 'subtract', 'intersect', 'exclude'] }, ids: IDS }, required: ['operation'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { operation: VectorBooleanOperation; ids?: string[] }) => {\n\t\t\t\tconst id = controller.booleanOp(params.operation, { ids: ids(params) });\n\t\t\t\tif (!id) fail('Select at least two overlapping paths (the result was empty).');\n\t\t\t\treturn { id };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}align`,\n\t\t\tlabel: 'Align…',\n\t\t\tkeywords: ['left', 'right', 'center', 'top', 'bottom', 'middle'],\n\t\t\tdescription: 'Aligns nodes to their combined bounds, or to the artboard (`to: \"artboard\"`, or when only one node is given).',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: { edge: { type: 'string', enum: ['left', 'center', 'right', 'top', 'middle', 'bottom'] }, to: { type: 'string', enum: ['selection', 'artboard'] }, ids: IDS },\n\t\t\t\trequired: ['edge']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { edge: VectorAlign; to?: 'selection' | 'artboard'; ids?: string[] }) => {\n\t\t\t\tcheck(controller.align(params.edge, { ids: ids(params), to: params.to }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}distribute`,\n\t\t\tlabel: 'Distribute…',\n\t\t\tkeywords: ['space', 'evenly', 'gaps'],\n\t\t\tdescription: 'Spaces three or more nodes with equal gaps.',\n\t\t\tparams: { type: 'object', properties: { direction: { type: 'string', enum: ['horizontal', 'vertical'] }, ids: IDS }, required: ['direction'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { direction: 'horizontal' | 'vertical'; ids?: string[] }) => {\n\t\t\t\tcheck(controller.distribute(params.direction, { ids: ids(params) }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}arrange`,\n\t\t\tlabel: 'Arrange…',\n\t\t\tkeywords: ['order', 'front', 'back', 'forward', 'backward', 'z-index', 'stack'],\n\t\t\tdescription: 'Changes stacking order within each node’s parent.',\n\t\t\tparams: { type: 'object', properties: { order: { type: 'string', enum: ['front', 'forward', 'backward', 'back'] }, ids: IDS }, required: ['order'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { order: VectorArrange; ids?: string[] }) => {\n\t\t\t\tcheck(controller.arrange(params.order, { ids: ids(params) }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}group`,\n\t\t\tlabel: 'Group',\n\t\t\tshortcut: 'Mod+G',\n\t\t\tdescription: 'Groups nodes that share a parent.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, name: { type: 'string' } } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; name?: string } | undefined) => {\n\t\t\t\tconst id = controller.group({ ids: ids(params), name: params?.name });\n\t\t\t\tif (!id) fail('Only nodes that share a parent can be grouped.');\n\t\t\t\treturn { id };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}ungroup`,\n\t\t\tlabel: 'Ungroup',\n\t\t\tshortcut: 'Mod+Shift+G',\n\t\t\tdescription: 'Replaces groups with their children.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => {\n\t\t\t\tcheck(controller.ungroup({ ids: ids(params) }));\n\t\t\t\treturn { selection: controller.getState().selection };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}deleteAnchors`,\n\t\t\tlabel: 'Delete Points',\n\t\t\tkeywords: ['remove', 'anchor', 'point', 'node'],\n\t\t\tdescription:\n\t\t\t\t'Deletes anchors. With `keepShape` (default: the editor setting, on) the neighbouring handles are refitted so the outline keeps its shape; off, the neighbours are joined as they are.',\n\t\t\tparams: { type: 'object', properties: { anchors: ANCHORS, keepShape: { type: 'boolean' } } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { anchors?: VectorAnchorRef[]; keepShape?: boolean } | undefined) => {\n\t\t\t\tcheck(controller.deleteAnchors(anchorsOf(params?.anchors), { keepShape: params?.keepShape }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}moveAnchor`,\n\t\t\tlabel: 'Move Point…',\n\t\t\tkeywords: ['anchor', 'drag', 'curvature'],\n\t\t\tdescription: 'Moves one anchor to (x, y) in document units. `curvature: true` bends its two segments like the Curvature tool instead of carrying its handles along.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: { nodeId: { type: 'string' }, subpath: { type: 'integer', minimum: 0 }, index: { type: 'integer', minimum: 0 }, x: { type: 'number' }, y: { type: 'number' }, curvature: { type: 'boolean' } },\n\t\t\t\trequired: ['nodeId', 'subpath', 'index', 'x', 'y']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: VectorAnchorRef & { x: number; y: number; curvature?: boolean }) => {\n\t\t\t\tcheck(controller.moveAnchor({ nodeId: params.nodeId, subpath: params.subpath, index: params.index }, { x: params.x, y: params.y }, { curvature: params.curvature }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}bendSegment`,\n\t\t\tlabel: 'Bend Segment…',\n\t\t\tkeywords: ['curve', 'segment', 'drag'],\n\t\t\tdescription: 'Bends segment `segment` (from anchor `segment` to the next) so the curve passes through (x, y) at parameter `t` (default 0.5).',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tnodeId: { type: 'string' },\n\t\t\t\t\tsubpath: { type: 'integer', minimum: 0 },\n\t\t\t\t\tsegment: { type: 'integer', minimum: 0 },\n\t\t\t\t\tx: { type: 'number' },\n\t\t\t\t\ty: { type: 'number' },\n\t\t\t\t\tt: { type: 'number', minimum: 0, maximum: 1 }\n\t\t\t\t},\n\t\t\t\trequired: ['nodeId', 'subpath', 'segment', 'x', 'y']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { nodeId: string; subpath: number; segment: number; x: number; y: number; t?: number }) => {\n\t\t\t\tcheck(controller.bendSegment({ nodeId: params.nodeId, subpath: params.subpath, segment: params.segment }, { x: params.x, y: params.y }, params.t));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}join`,\n\t\t\tlabel: 'Join',\n\t\t\tshortcut: 'Mod+J',\n\t\t\tkeywords: ['connect', 'close', 'merge', 'endpoints'],\n\t\t\tdescription: 'Joins the open subpaths of paths nearest endpoints first (ends within `tolerance` merge); a single open path is closed.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, tolerance: { type: 'number', minimum: 0 } } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; tolerance?: number } | undefined) => {\n\t\t\t\tcheck(controller.joinPaths({ ids: params?.ids ? ids(params) : undefined, tolerance: params?.tolerance }));\n\t\t\t\treturn { selection: controller.getState().selection };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}average`,\n\t\t\tlabel: 'Average Points…',\n\t\t\tshortcut: 'Mod+Alt+J',\n\t\t\tkeywords: ['align', 'points', 'anchors', 'collapse'],\n\t\t\tdescription: 'Moves anchors onto their average position: the same y (`horizontal`), the same x (`vertical`) or the same point (`both`, default).',\n\t\t\tparams: { type: 'object', properties: { axis: { type: 'string', enum: ['horizontal', 'vertical', 'both'] }, anchors: ANCHORS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { axis?: VectorAverageAxis; anchors?: VectorAnchorRef[] } | undefined) => {\n\t\t\t\tcheck(controller.averageAnchors(params?.axis ?? 'both', anchorsOf(params?.anchors)));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}removeRedundantPoints`,\n\t\t\tlabel: 'Remove Redundant Points',\n\t\t\tkeywords: ['simplify', 'clean up', 'anchors', 'collinear'],\n\t\t\tdescription: 'Drops anchors that can go without moving the outline more than `tolerance` document units (default 0.5).',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, tolerance: { type: 'number', minimum: 0 } } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; tolerance?: number } | undefined) => {\n\t\t\t\tcheck(controller.removeRedundantPoints({ ids: params?.ids ? ids(params) : undefined, tolerance: params?.tolerance }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}smooth`,\n\t\t\tlabel: 'Smooth Path',\n\t\t\tkeywords: ['round', 'soften', 'handles', 'curves'],\n\t\t\tdescription: 'Pulls the handles of paths (or of the selected points) towards smooth tangents by `amount` (0–1, default 1).',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, amount: { type: 'number', minimum: 0, maximum: 1 }, anchors: ANCHORS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; amount?: number; anchors?: VectorAnchorRef[] } | undefined) => {\n\t\t\t\tcheck(controller.smoothPaths({ ids: params?.ids ? ids(params) : undefined, amount: params?.amount, refs: params?.anchors }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}cut`,\n\t\t\tlabel: 'Cut Path (Scissors)…',\n\t\t\tkeywords: ['scissors', 'split', 'open', 'break'],\n\t\t\tdescription: 'Scissors: cuts path `nodeId` at the outline point nearest (x, y), or cuts at `anchors`. A closed path opens; an open one splits in two.',\n\t\t\tparams: { type: 'object', properties: { nodeId: { type: 'string' }, x: { type: 'number' }, y: { type: 'number' }, anchors: ANCHORS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { nodeId?: string; x?: number; y?: number; anchors?: VectorAnchorRef[] } | undefined) => {\n\t\t\t\tif (params?.nodeId !== undefined) {\n\t\t\t\t\tif (!controller.getNode(params.nodeId)) fail(`There is no node \"${params.nodeId}\".`);\n\t\t\t\t\tif (params.x === undefined || params.y === undefined) fail('Pass x and y with nodeId.');\n\t\t\t\t\tconst created = controller.cutPathAt(params.nodeId, { x: params.x!, y: params.y! });\n\t\t\t\t\tif (!created) fail('Nothing to cut there (the end of an open path, or a locked path).');\n\t\t\t\t\treturn { ids: created };\n\t\t\t\t}\n\t\t\t\tcheck(controller.cutAtAnchors(anchorsOf(params?.anchors)));\n\t\t\t\treturn { ids: controller.getState().selection };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}knife`,\n\t\t\tlabel: 'Knife…',\n\t\t\tkeywords: ['slice', 'cut', 'split', 'divide'],\n\t\t\tdescription: 'Cuts closed paths along a polyline wherever it crosses them edge to edge (no gap between pieces). Cuts `ids`, else the selection, else every path the line crosses.',\n\t\t\tparams: { type: 'object', properties: { points: { ...POINTS, minItems: 2 }, ids: IDS }, required: ['points'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { points: [number, number][]; ids?: string[] }) => {\n\t\t\t\tconst created = controller.knife(params.points.map(([x, y]) => ({ x, y })), { ids: params.ids ? ids(params) : undefined });\n\t\t\t\tif (!created.length) fail('The knife did not cross any closed path from edge to edge.');\n\t\t\t\treturn { ids: created };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}erase`,\n\t\t\tlabel: 'Erase…',\n\t\t\tkeywords: ['eraser', 'rub out', 'remove'],\n\t\t\tdescription:\n\t\t\t\t'Erases a round stroke of diameter `size` (default: the eraser size setting) along a polyline: filled shapes lose the area, outlines are cut under it. Erases from `ids`, else the selection, else every path it reaches.',\n\t\t\tparams: { type: 'object', properties: { points: POINTS, size: { type: 'number', exclusiveMinimum: 0 }, ids: IDS }, required: ['points'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { points: [number, number][]; size?: number; ids?: string[] }) => {\n\t\t\t\tconst changed = controller.erase(params.points.map(([x, y]) => ({ x, y })), { size: params.size, ids: params.ids ? ids(params) : undefined });\n\t\t\t\tif (!changed.length) fail('The eraser did not touch any path.');\n\t\t\t\treturn { ids: changed.filter((id) => controller.getNode(id)) };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setEditing`,\n\t\t\tlabel: 'Path Editing Options…',\n\t\t\tkeywords: ['settings', 'curvature', 'pencil', 'smoothing', 'lazy mouse', 'shapes', 'eraser'],\n\t\t\tdescription:\n\t\t\t\t'Sets how editing behaves: `keepShapeOnDelete`, `curvatureMoves` (anchor drags bend like the Curvature tool), `pencilSmoothing` (lazy mouse, 0–1), `recognizeShapes` (pencil scribbles become lines, rectangles, ellipses, polygons), `eraserSize` and `pencilPressure` (`pen`: record pen pressure on pencil strokes as a width profile, `all`: any pointer reporting pressure, `off`).',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tkeepShapeOnDelete: { type: 'boolean' },\n\t\t\t\t\tcurvatureMoves: { type: 'boolean' },\n\t\t\t\t\tpencilSmoothing: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\trecognizeShapes: { type: 'boolean' },\n\t\t\t\t\teraserSize: { type: 'number', exclusiveMinimum: 0 },\n\t\t\t\t\tpencilPressure: { type: 'string', enum: ['pen', 'all', 'off'] }\n\t\t\t\t}\n\t\t\t},\n\t\t\trun: (_ctx: unknown, params: Record<string, unknown> | undefined) => {\n\t\t\t\tconst patch: Record<string, unknown> = {};\n\t\t\t\tfor (const key of ['keepShapeOnDelete', 'curvatureMoves', 'pencilSmoothing', 'recognizeShapes', 'eraserSize', 'pencilPressure']) if (params?.[key] !== undefined) patch[key] = params[key];\n\t\t\t\tcontroller.setEditing(patch);\n\t\t\t\treturn { editing: controller.getState().editing };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setTool`,\n\t\t\tlabel: 'Choose Tool…',\n\t\t\tkeywords: ['pen', 'pencil', 'select', 'rectangle', 'ellipse'],\n\t\t\tdescription: 'Switches the canvas tool.',\n\t\t\tparams: { type: 'object', properties: { tool: { type: 'string', enum: [...VECTOR_TOOLS] } }, required: ['tool'] },\n\t\t\trun: (_ctx: unknown, params: { tool: VectorTool }) => {\n\t\t\t\tcontroller.setTool(params.tool);\n\t\t\t\treturn { tool: params.tool };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}exportSvg`,\n\t\t\tlabel: 'Export SVG',\n\t\t\treadOnly: true,\n\t\t\tkeywords: ['download', 'save', 'markup'],\n\t\t\tdescription: 'Returns the document as SVG markup.',\n\t\t\tparams: { type: 'object', properties: { precision: { type: 'integer', minimum: 0, maximum: 8 } } },\n\t\t\trun: (_ctx: unknown, params: { precision?: number } | undefined) => ({ svg: controller.toSvg({ precision: params?.precision }) })\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}importSvg`,\n\t\t\tlabel: 'Import SVG…',\n\t\t\tkeywords: ['open', 'load', 'paste', 'markup'],\n\t\t\tdescription: 'Adds the shapes of SVG markup on top of the document (or replaces it with `replace: true`).',\n\t\t\tparams: { type: 'object', properties: { svg: { type: 'string' }, replace: { type: 'boolean' } }, required: ['svg'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { svg: string; replace?: boolean }) => {\n\t\t\t\tcheck(params.replace ? controller.loadSvg(params.svg) : controller.importSvg(params.svg));\n\t\t\t\treturn { nodes: controller.getState().document.nodes.length, selection: controller.getState().selection };\n\t\t\t}\n\t\t}\n\t];\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/editor/editor/packages/core/dist/vector/index.cjs","../../src/vector/types.ts","../../src/vector/corners.ts","../../src/vector/width.ts","../../src/vector/varstroke.ts","../../src/vector/stroke.ts","../../src/vector/geometry.ts","../../src/vector/svg.ts","../../src/vector/snap.ts","../../src/vector/pathEdit.ts","../../src/vector/pathCut.ts","../../src/vector/ink.ts","../../src/vector/builder.ts","../../src/vector/controller.ts","../../src/vector/render.ts","../../src/vector/commands.ts"],"names":["t","v","sides","p","sub","len","w","cross","dot","polygon","near","pt","s","dist","EPS","KAPPA","out","corners","width","node","lines","crossing","length","movesX","unit","onAnchor","at","along","usable","from","to","line","last","editable","toScreen","flatten","key","ref","list"],"mappings":"AAAA;AACE;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACA;ACjBO,IAAM,oBAAA,EAAmD,CAAC,OAAA,EAAS,UAAA,EAAY,SAAS,CAAA;AAkDxF,IAAM,kBAAA,EAAgD,CAAC,UAAA,EAAY,OAAA,EAAS,MAAA,EAAQ,QAAA,EAAU,QAAA,EAAU,KAAK,CAAA;AAuI7G,IAAM,aAAA,EAAsC;AAAA,EAClD,QAAA;AAAA,EACA,Q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AAA;AACH,MAAA;AACR,IAAA;AACO,IAAA;AACR,EAAA;AACY,EAAA;AACb;AAES;AAEN,EAAA;AAOH;AAEM;AAQU;AACL,EAAA;AACA,EAAA;AACI,EAAA;AACf;AAGgB;AACO,EAAA;AACV,EAAA;AACD,EAAA;AACP,EAAA;AACW,EAAA;AACJ,IAAA;AACe,IAAA;AACd,IAAA;AACL,MAAA;AACE,QAAA;AACN,QAAA;AACI,MAAA;AACG,QAAA;AACP,QAAA;AACI,MAAA;AACG,QAAA;AACP,QAAA;AACI,MAAA;AACG,QAAA;AACP,QAAA;AACI,MAAA;AACI,QAAA;AACR,QAAA;AACI,MAAA;AACI,QAAA;AACR,QAAA;AACF,IAAA;AAEI,IAAA;AACL,EAAA;AACO,EAAA;AACR;AAYM;AACC,EAAA;AACE,EAAA;AACR,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACa,EAAA;AACd;AAES;AACM,EAAA;AACF,EAAA;AACD,EAAA;AACA,IAAA;AACC,IAAA;AACC,IAAA;AACH,IAAA;AACV,EAAA;AACO,EAAA;AACR;AAES;AACE,EAAA;AAGF,IAAA;AACI,MAAA;AAIV,IAAA;AACY,IAAA;AACN,IAAA;AACA,IAAA;AACC,IAAA;AACE,MAAA;AACD,MAAA;AACH,MAAA;AACL,IAAA;AACA,EAAA;AACH;AAEkB;AACP,EAAA;AACA,EAAA;AACE,EAAA;AACE,EAAA;AACf;AAES;AACA,EAAA;AACG,EAAA;AACZ;AAES;AACG,EAAA;AACA,EAAA;AACA,EAAA;AACC,EAAA;AACC,EAAA;AACF,EAAA;AACA,EAAA;AACJ,EAAA;AACG,IAAA;AACV,EAAA;AACW,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AAEG,EAAA;AACL,EAAA;AACV;AAGgB;AACF,EAAA;AACF,EAAA;AACG,EAAA;AACR,EAAA;AACA,EAAA;AACQ,EAAA;AACF,IAAA;AACA,IAAA;AACF,MAAA;AACD,MAAA;AACR,IAAA;AACW,IAAA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AAA;AACY,EAAA;AACb;AAGgB;AACF,EAAA;AACd;AAEiB;AAGH;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACC,EAAA;AACD,EAAA;AACA,EAAA;AACH,EAAA;AACH,EAAA;AACR;AAGS;AACK,EAAA;AACA,EAAA;AACD,EAAA;AACb;AAUS;AACE,EAAA;AACG,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACL,IAAA;AACF,MAAA;AACC,MAAA;AACA,MAAA;AACI,MAAA;AACA,MAAA;AACH,IAAA;AACF,MAAA;AACC,MAAA;AACA,MAAA;AACI,MAAA;AACA,MAAA;AACV,IAAA;AACD,EAAA;AACU,EAAA;AACX;AAOS;AACK,EAAA;AACS,IAAA;AACZ,IAAA;AACA,IAAA;AACF,IAAA;AACR,EAAA;AACO,EAAA;AACR;AASgB;AACT,EAAA;AACI,EAAA;AACE,EAAA;AACJ,EAAA;AACK,IAAA;AACA,IAAA;AACN,IAAA;AACC,MAAA;AACA,MAAA;AACI,MAAA;AACJ,MAAA;AACC,MAAA;AACA,MAAA;AACD,MAAA;AACA,MAAA;AACE,MAAA;AACH,MAAA;AACI,QAAA;AACA,QAAA;AACT,MAAA;AACD,IAAA;AACD,EAAA;AACQ,EAAA;AACK,EAAA;AACR,EAAA;AAEK,IAAA;AACH,IAAA;AACM,IAAA;AACb,EAAA;AACY,EAAA;AACH,EAAA;AACV;AAGgB;AACD,EAAA;AACD,EAAA;AACd;AAYgB;AACT,EAAA;AACI,EAAA;AACI,EAAA;AACH,EAAA;AACA,EAAA;AACC,EAAA;AACF,EAAA;AACA,EAAA;AACI,EAAA;AACA,EAAA;AACA,EAAA;AACD,EAAA;AACA,EAAA;AACC,EAAA;AACA,EAAA;AACL,EAAA;AACV;AAGgB;AACJ,EAAA;AACG,EAAA;AACf;AAagB;AACT,EAAA;AACO,EAAA;AACL,EAAA;AACgC,EAAA;AAC9BC,IAAAA;AACCA,IAAAA;AACX,EAAA;AAC0C,EAAA;AAC/B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;AAGgB;AACT,EAAA;AACa,EAAA;AACA,EAAA;AACX,EAAA;AACP,IAAA;AACD,IAAA;AACM,MAAA;AACJ,MAAA;AACP,IAAA;AACD,EAAA;AACc,EAAA;AACD,IAAA;AACH,IAAA;AACV,EAAA;AACc,EAAA;AACA,EAAA;AACF,EAAA;AACH,EAAA;AACV;AAGS;AACgB,EAAA;AACX,EAAA;AACN,EAAA;AACR;AAOgB;AACH,EAAA;AACJ,EAAA;AACI,EAAA;AACD,EAAA;AACD,EAAA;AACG,EAAA;AACD,EAAA;AACC,EAAA;AACF,EAAA;AACF,EAAA;AACgD,IAAA;AAClD,IAAA;AACC,MAAA;AACG,MAAA;AACA,QAAA;AACF,QAAA;AACD,QAAA;AAAkB,UAAA;AAErB,YAAA;AACI,YAAA;AACJ,YAAA;AACC,cAAA;AACA,cAAA;AACD,YAAA;AACA,UAAA;AACF,QAAA;AACD,MAAA;AACU,MAAA;AACJ,MAAA;AACA,MAAA;AACC,QAAA;AACA,QAAA;AACA,QAAA;AACC,QAAA;AACR,MAAA;AACS,MAAA;AACFkB,QAAAA;AACAC,QAAAA;AACF,QAAA;AACC,QAAA;AACL,QAAA;AACD,MAAA;AACA,IAAA;AACU,IAAA;AACH,IAAA;AACF,IAAA;AAEAb,IAAAA;AACG,IAAA;AACD,IAAA;AACF,IAAA;AACA,IAAA;AACK,IAAA;AACL,IAAA;AACG,IAAA;AACF,MAAA;AACA,MAAA;AACA,MAAA;AACG,QAAA;AACA,QAAA;AACT,MAAA;AACM,IAAA;AAEA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACE,QAAA;AACC,QAAA;AACR,MAAA;AACF,IAAA;AACY,IAAA;AACA,IAAA;AACZ,IAAA;AACD,EAAA;AACc,EAAA;AACf;AAOgB;AACH,EAAA;AACF,EAAA;AACD,EAAA;AACK,EAAA;AACF,EAAA;AACA,IAAA;AACD,IAAA;AACH,IAAA;AACE,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,M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,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACF,QAAA;AACE,UAAA;AACA,UAAA;AACA,UAAA;AACC,UAAA;AACN,UAAA;AACK,UAAA;AACL,UAAA;AACA,UAAA;AACA,UAAA;AACA,QAAA;AACD,MAAA;AACF,IAAA;AACD,EAAA;AACO,EAAA;AACR;AAGgB;AACF,EAAA;AACA,EAAA;AACd;AAGgB;AACL,EAAA;AACF,EAAA;AACE,EAAA;AACA,EAAA;AACI,EAAA;AACf;AAgBgB;AACD,EAAA;AACH,EAAA;AACL,EAAA;AACO,EAAA;AACC,EAAA;AACR,EAAA;AACI,EAAA;AACG,EAAA;AACd;AAEM;AAGU;AACD,EAAA;AACP,EAAA;AACI,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACX,EAAA;AACD;AAgBgB;AACL,EAAA;AACI,EAAA;AACF,EAAA;AACNQ,EAAAA;AACA,EAAA;AACAjB,EAAAA;AACO,IAAA;AACH,IAAA;AACA,IAAA;AACG,IAAA;AACPiB,EAAAA;AACK,EAAA;AACG,EAAA;AACf;AAEM;AACA;AAGU;AACX,EAAA;AACS,EAAA;AACN,EAAA;AACR;AAGM;AACG,EAAA;AACA,EAAA;AACH,EAAA;AACG,EAAA;AACF,EAAA;AACG,EAAA;AACA,EAAA;AACH,EAAA;AACA,EAAA;AACI,EAAA;AACH,EAAA;AACC,EAAA;AACD,EAAA;AACO,EAAA;AACD,EAAA;AACd;AAE8C;AAC1C,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACJ;AAEgB;AACR,EAAA;AACR;AAGa;AACJ,EAAA;AACA,EAAA;AACH,EAAA;AACG,EAAA;AACF,EAAA;AACG,EAAA;AAC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,MAAA;AACD,MAAA;AACA,MAAA;AACL,MAAA;AACD,IAAA;AACW,IAAA;AACJ,MAAA;AACA,MAAA;AACD,MAAA;AACC,MAAA;AACI,MAAA;AACH,QAAA;AACE,QAAA;AACH,QAAA;AACC,QAAA;AACD,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACL,QAAA;AACD,MAAA;AAEU,MAAA;AACA,MAAA;AACL,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACL,MAAA;AACD,IAAA;AACM,IAAA;AACI,IAAA;AACJ,MAAA;AACA,MAAA;AACK,MAAA;AACL,MAAA;AACA,MAAA;AACA,MAAA;AACL,MAAA;AACD,IAAA;AACW,IAAA;AACL,MAAA;AACN,IAAA;AACY,IAAA;AACP,IAAA;AACO,IAAA;AACb,EAAA;AAEgB,EAAA;AACT,IAAA;AACK,IAAA;AACF,IAAA;AACF,MAAA;AACA,MAAA;AACC,MAAA;AACAS,QAAAA;AACD,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACL,QAAA;AACD,MAAA;AACM,MAAA;AACA,MAAA;AACG,MAAA;AACJ,MAAA;AACCA,MAAAA;AACA,MAAA;AACD,MAAA;AACCkB,MAAAA;AACD,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACL,MAAA;AACD,IAAA;AACM,IAAA;AACF,IAAA;AACClB,MAAAA;AACA,MAAA;AACA,MAAA;AACI,QAAA;AACF,QAAA;AACGA,QAAAA;AACT,MAAA;AACK,MAAA;AACA,MAAA;AACA,MAAA;AACCkB,MAAAA;AACD,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACL,MAAA;AACD,IAAA;AACW,IAAA;AACL,IAAA;AACM,IAAA;AACD,IAAA;AACN,IAAA;AACA,IAAA;AACO,IAAA;AACP,IAAA;AACO,IAAA;AACP,IAAA;AACO,IAAA;AACb,EAAA;AAE4B,EAAA;AACrB,IAAA;AACA,IAAA;AACI,MAAA;AACH,MAAA;AACA,MAAA;AACE,M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,QAAA;AACK,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACA,QAAA;AACA,QAAA;AACC,QAAA;AACA,QAAA;AACC,QAAA;AACF,QAAA;AAEG,UAAA;AACA,UAAA;AACD,UAAA;AACA,UAAA;AACN,QAAA;AACM,QAAA;AACA,QAAA;AAEF,QAAA;AACC,QAAA;AACA,QAAA;AACA,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACE,QAAA;AACA,QAAA;AACA1B,QAAAA;AACA,QAAA;AACD,QAAA;AACA,QAAA;AACA,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACC,QAAA;AACA,QAAA;AACC,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACD,QAAA;AACA,QAAA;AACA,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACC,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACG,QAAA;AACH,MAAA;AACE,QAAA;AACF,QAAA;AACC,QAAA;AACA,QAAA;AACA,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACE,QAAA;AACD,QAAA;AACD,QAAA;AACE,UAAA;AACA,UAAA;AACL,UAAA;AACD,QAAA;AACK,QAAA;AACDA,QAAAA;AACA,QAAA;AACE,QAAA;AAEA,QAAA;AACD,QAAA;AACA,UAAA;AACJ,UAAA;AACA,QAAA;AACI,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACE,QAAA;AACF,QAAA;AACE,QAAA;AACF,QAAA;AACC,QAAA;AACD,QAAA;AACA,QAAA;AACA,QAAA;AACC,UAAA;AACA,UAAA;AACJ,UAAA;AACM,QAAA;AACF,UAAA;AACA,UAAA;AACA,UAAA;AACH,YAAA;AACI,YAAA;AACA,YAAA;AACL,UAAA;AACI,UAAA;AACE,UAAA;AACA,UAAA;AACN,UAAA;AACD,QAAA;AACM,QAAA;AACD,QAAA;AACA,QAAA;AACA,QAAA;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AACE,IAAA;AACM,IAAA;AACP,IAAA;AACA,IAAA;AACM,IAAA;AACH,IAAA;AACF,MAAA;AACA,MAAA;AACC,QAAA;AACL,QAAA;AACI,MAAA;AACC,QAAA;AACA,UAAA;AACC,UAAA;AACL,UAAA;AACD,QAAA;AACO,QAAA;AACH,MAAA;AACG,QAAA;AACH,MAAA;AACG,QAAA;AACH,MAAA;AACC,QAAA;AACA,UAAA;AACA,UAAA;AACC,UAAA;AACL,UAAA;AACD,QAAA;AACO,QAAA;AACH,MAAA;AACG,QAAA;AACH,MAAA;AACC,QAAA;AACC,UAAA;AACL,UAAA;AACD,QAAA;AACO,QAAA;AACH,MAAA;AACA,QAAA;AACA,QAAA;AACG,UAAA;AACD,UAAA;AACL,UAAA;AACD,QAAA;AAEM,QAAA;AACA,QAAA;AACD,QAAA;AACA,QAAA;AACA,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACA,QAAA;AAEA,QAAA;AACE,UAAA;AACA,UAAA;AACA,UAAA;AACC,QAAA;AACP,QAAA;AACD,MAAA;AACK,MAAA;AACG,QAAA;AACH,MAAA;AACC,QAAA;AACD,QAAA;AACC,QAAA;AACL,QAAA;AACD,MAAA;AACK,MAAA;AACA,QAAA;AACG,QAAA;AACH,MAAA;AACE,QAAA;AACA,QAAA;AACA,QAAA;AACD,QAAA;AACC,UAAA;AACA,UAAA;AACL,UAAA;AACD,QAAA;AACK,QAAA;AACA,QAAA;AACA,QAAA;AACE,QAAA;AACR,MAAA;AACK,MAAA;AACE,QAAA;AACF,QAAA;AACE,UAAA;AACA,UAAA;AACL,UAAA;AACD,QAAA;AACA,QAAA;AACM,UAAA;AACA,0BAAA;AACN,QAAA;AACM,QAAA;AACF,QAAA;AACE,UAAA;AACA,UAAA;AACL,UAAA;AACD,QAAA;AACM,QAAA;AACA,QAAA;AACN,QAAA;AACM,UAAA;AACL,UAAA;AACA,UAAA;AACD,QAAA;AACM,QAAA;AACA,QAAA;AACD,QAAA;AACA,QAAA;AACE,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AAA;AACG,MAAA;AACV,MAAA;AAEU,MAAA;AACA,MAAA;AACJ,MAAA;AACC,QAAA;AACC,QAAA;AACR,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACV,MAAA;AACQ,MAAA;AACD,QAAA;AACN,QAAA;AACA,QAAA;AACD,MAAA;AACU,MAAA;AACJ,MAAA;AACC,QAAA;AACC,QAAA;AACR,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACV,MAAA;AACQ,MAAA;AACD,QAAA;AACN,QAAA;AACC,UAAA;AACA,UAAA;AACA,UAAA;AACK,UAAA;AACA,UAAA;AACA,UAAA;AACN,QAAA;AACA,QAAA;AACD,MAAA;AACU,MAAA;AACJ,MAAA;AACC,QAAA;AACC,QAAA;AACR,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACA,MAAA;AACV,MAAA;AACU,MAAA;AACA,MAAA;AACJ,MAAA;AACC,QAAA;AACC,QAAA;AACR,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACA,MAAA;AACV,MAAA;AACU,MAAA;AACA,MAAA;AACJ,MAAA;AACC,QAAA;AACC,QAAA;AACR,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACV,MAAA;AACU,MAAA;AACD,MAAA;AACC,MAAA;AACJ,MAAA;AACC,QAAA;AACC,QAAA;AACR,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACV,MAAA;AACU,MAAA;AACA,MAAA;AACJ,MAAA;AACC,QAAA;AACC,QAAA;AACR,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACV,MAAA;AACU,MAAA;AACA,MAAA;AACJ,MAAA;AACD,QAAA;AACE,UAAA;AACD,UAAA;AACE,UAAA;AACD,UAAA;AACL,UAAA;AACD,QAAA;AACM,QAAA;AACC,QAAA;AACR,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACV,MAAA;AACU,MAAA;AACA,MAAA;AACJ,MAAA;AACC,QAAA;AACD,QAAA;AACE,QAAA;AACR,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACV,MAAA;AAEU,MAAA;AACA,MAAA;AACJ,MAAA;AACC,QAAA;AACD,QAAA;AACE,QAAA;AACR,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACV,MAAA;AAEQ,MAAA;AACD,QAAA;AACN,QAAA;AACC,UAAA;AACA,UAAA;AACA,UAAA;AACA,UAAA;AACA,UAAA;AACA,UAAA;AACD,QAAA;AACD,MAAA;AACM,MAAA;AACC,QAAA;AACN,QAAA;AACA,QAAA;AACO,QAAA;AACR,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACV,MAAA;AACU,MAAA;AACJ,MAAA;AACL,QAAA;AACO,QAAA;AACR,MAAA;AACD,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACA,MAAA;AACV,MAAA;AACU,MAAA;AACJ,MAAA;AACP,IAAA;AACA,IAAA;AACI,MAAA;AACI,MAAA;AACA,MAAA;AACG,MAAA;AACV,MAAA;AACU,MAAA;AACA,MAAA;AACJ,MAAA;AACC,QAAA;AACC,QAAA;AACR,MAAA;AACD,IAAA;AACD,EAAA;AACD;Afu+OgB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/editor/editor/packages/core/dist/vector/index.cjs","sourcesContent":[null,"import type { CanvasGradientDef } from '../canvas/gradient.js';\n\n/** An affine matrix `[a, b, c, d, e, f]`: `x' = a·x + c·y + e`, `y' = b·x + d·y + f` (SVG order). */\nexport type VectorMatrix = readonly [number, number, number, number, number, number];\n\n/** A point in document coordinates. */\nexport interface Vec2 {\n\tx: number;\n\ty: number;\n}\n\n/**\n * How an anchor's handles relate:\n * - `corner`: handles move independently (or are absent).\n * - `smooth`: handles stay on one line through the anchor, lengths independent.\n * - `symmetric`: handles stay on one line with equal lengths.\n */\nexport type VectorAnchorType = 'corner' | 'smooth' | 'symmetric';\n\n/**\n * Live corner shapes: `round` (an arc tangent to both sides), `inverted` (an arc centred on\n * the corner, cut into the shape) and `chamfer` (a straight bevel).\n */\nexport type VectorCornerKind = 'round' | 'inverted' | 'chamfer';\n\nexport const VECTOR_CORNER_KINDS: readonly VectorCornerKind[] = ['round', 'inverted', 'chamfer'];\n\n/**\n * A live corner: drawn rounded (or cut) at render, hit-test, bounds, boolean, outline and export\n * time while the stored anchor stays sharp. The radius shrinks to fit when the sides are short:\n * the cut reaches at most halfway along each side.\n */\nexport interface VectorCorner {\n\tradius: number;\n\t/** Default `round`. */\n\tkind?: VectorCornerKind;\n}\n\n/**\n * One anchor of a subpath. Handles are absolute document positions; a missing (or `null`)\n * handle sits on the anchor, so a segment with no handles at either end is a straight line.\n */\nexport interface VectorAnchor {\n\tx: number;\n\ty: number;\n\t/** Control point of the segment arriving at this anchor. */\n\tin?: Vec2 | null;\n\t/** Control point of the segment leaving this anchor. */\n\tout?: Vec2 | null;\n\t/** Default `corner`. */\n\ttype?: VectorAnchorType;\n\t/** Live corner radius. Ignored on smooth / symmetric anchors and the ends of open subpaths. */\n\tcorner?: VectorCorner | null;\n}\n\n/** A chain of anchors joined by line or cubic Bézier segments. */\nexport interface VectorSubpath {\n\tanchors: VectorAnchor[];\n\t/** Joins the last anchor back to the first. */\n\tclosed: boolean;\n}\n\n/** A fill or stroke: any CSS colour, a gradient, or `null` / `'none'` for no paint. */\nexport type VectorPaint = string | CanvasGradientDef | null;\n\nexport type VectorFillRule = 'nonzero' | 'evenodd';\nexport type VectorLineCap = 'butt' | 'round' | 'square';\nexport type VectorLineJoin = 'miter' | 'round' | 'bevel';\n/**\n * Where the stroke sits on the outline: centred on it, inside the shape or outside it. Only\n * shapes whose subpaths are all closed have an inside; open paths always stroke centred.\n */\nexport type VectorStrokeAlign = 'center' | 'inside' | 'outside';\n/** Arrowheads and end markers for the ends of open paths. */\nexport type VectorArrowhead = 'triangle' | 'arrow' | 'open' | 'circle' | 'square' | 'bar';\nexport const VECTOR_ARROWHEADS: readonly VectorArrowhead[] = ['triangle', 'arrow', 'open', 'circle', 'square', 'bar'];\n/**\n * `extend`: the head's tip sits past the end point and the path keeps its length; `tip`: the\n * tip sits on the end point and the stroke is shortened under the head.\n */\nexport type VectorArrowAlign = 'extend' | 'tip';\n\n/**\n * One point of a variable-width stroke profile. `t` is the position along the subpath by\n * length (0 at its start, 1 at its end); `left` and `right` are how far the stroke reaches on\n * each side, as multiples of half the stroke width (looking along the path on screen, y down).\n * A uniform stroke has 1 on both sides. Two points at the same `t` make a step.\n */\nexport interface VectorWidthPoint {\n\tt: number;\n\tleft: number;\n\tright: number;\n}\n\n/** Paint and stroke settings of a path. */\nexport interface VectorStyle {\n\tfill?: VectorPaint;\n\tstroke?: VectorPaint;\n\t/** Default 1. */\n\tstrokeWidth?: number;\n\tstrokeLinecap?: VectorLineCap;\n\tstrokeLinejoin?: VectorLineJoin;\n\tstrokeDasharray?: number[];\n\t/** Default `nonzero`. */\n\tfillRule?: VectorFillRule;\n\t/** Default `center`. */\n\tstrokeAlign?: VectorStrokeAlign;\n\t/** Head at the start of the first subpath when it is open, or none. */\n\tstartArrow?: VectorArrowhead | null;\n\t/** Head at the end of the last subpath when it is open, or none. */\n\tendArrow?: VectorArrowhead | null;\n\t/** Default `extend`. */\n\tarrowAlign?: VectorArrowAlign;\n\t/** Size of the start head as a multiple of the stroke width (default 1: a head 4 widths long). */\n\tstartArrowScale?: number;\n\t/** Size of the end head (default 1). */\n\tendArrowScale?: number;\n\t/**\n\t * Variable width: side scales along each subpath, interpolated with a monotone cubic (see\n\t * `widthProfileAt`). Absent, empty or `null` strokes at a uniform width. A profiled stroke is\n\t * drawn as its filled outline.\n\t */\n\tstrokeWidthProfile?: VectorWidthPoint[] | null;\n}\n\ninterface VectorNodeBase {\n\tid: string;\n\tname?: string;\n\t/** Default true. */\n\tvisible?: boolean;\n\t/** Locked nodes are drawn but cannot be picked or edited on the canvas. */\n\tlocked?: boolean;\n\t/** 0–1, default 1. */\n\topacity?: number;\n\t/**\n\t * Placement in the parent's space: a rigid matrix (rotation + translation). Anchors and\n\t * children are in the node's own space. Omitted for unrotated nodes, whose positions are\n\t * stored directly. Scale and skew are never stored here — `transformVectorNode` bakes\n\t * them into the geometry, so stroke widths and the rotated selection box stay exact.\n\t */\n\ttransform?: VectorMatrix;\n}\n\n/** A shape made of one or more subpaths (holes and compound shapes included). */\nexport interface VectorPathNode extends VectorNodeBase, VectorStyle {\n\ttype: 'path';\n\tsubpaths: VectorSubpath[];\n}\n\n/** A group of nodes that select and transform together. */\nexport interface VectorGroupNode extends VectorNodeBase {\n\ttype: 'group';\n\tchildren: VectorNode[];\n}\n\nexport type VectorNode = VectorPathNode | VectorGroupNode;\n\n/** A vector drawing: an artboard and its nodes, bottom to top. */\nexport interface VectorDocument {\n\twidth: number;\n\theight: number;\n\t/** Artboard colour (default: transparent). */\n\tbackground?: string;\n\tnodes: VectorNode[];\n}\n\n/** An axis-aligned rectangle. */\nexport interface VectorBounds {\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n}\n\n/** Identifies one anchor of a path node. */\nexport interface VectorAnchorRef {\n\tnodeId: string;\n\tsubpath: number;\n\tindex: number;\n}\n\n/** Identifies one handle of an anchor. */\nexport interface VectorHandleRef extends VectorAnchorRef {\n\thandle: 'in' | 'out';\n}\n\n/**\n * Canvas tools. `direct` edits anchors, handles and segments; the shape tools drag out a new\n * shape; `scissors` cuts a path at a point, `knife` cuts filled shapes along a freehand stroke,\n * `eraser` rubs out the area under one and `width` drags a stroke's width at a point.\n * `shapeBuilder` merges (Alt: deletes) the faces the selected shapes make, and `paintBucket`\n * fills the region the visible outlines enclose around a click with a new shape.\n */\nexport type VectorTool =\n\t| 'select'\n\t| 'direct'\n\t| 'pen'\n\t| 'pencil'\n\t| 'rect'\n\t| 'ellipse'\n\t| 'polygon'\n\t| 'star'\n\t| 'line'\n\t| 'scissors'\n\t| 'knife'\n\t| 'eraser'\n\t| 'width'\n\t| 'shapeBuilder'\n\t| 'paintBucket';\n\nexport const VECTOR_TOOLS: readonly VectorTool[] = [\n\t'select',\n\t'direct',\n\t'pen',\n\t'pencil',\n\t'rect',\n\t'ellipse',\n\t'polygon',\n\t'star',\n\t'line',\n\t'scissors',\n\t'knife',\n\t'eraser',\n\t'width',\n\t'shapeBuilder',\n\t'paintBucket'\n];\n\n/** Keyboard modifiers held during a pointer event. */\nexport interface VectorModifiers {\n\tshift?: boolean;\n\talt?: boolean;\n\t/** Cmd on macOS, Ctrl elsewhere. */\n\tmod?: boolean;\n}\n\n/** The eight resize handles of a selection box and the rotation handle. */\nexport type VectorTransformHandle = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'rotate';\n\nexport const VECTOR_TRANSFORM_HANDLES: readonly VectorTransformHandle[] = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'rotate'];\n\n/** Pan and zoom of the canvas: `screen = document × zoom + (x, y)`. */\nexport interface VectorViewport {\n\t/** Screen position of the document origin, in screen pixels. */\n\tx: number;\n\ty: number;\n\tzoom: number;\n}\n\n/** What the next shape and pen path are drawn with. */\nexport interface VectorDefaults extends VectorStyle {\n\t/** Sides of the polygon tool (default 6). */\n\tpolygonSides?: number;\n\t/** Points of the star tool (default 5). */\n\tstarPoints?: number;\n\t/** Inner radius of the star tool as a fraction of the outer one (default 0.5). */\n\tstarInnerRatio?: number;\n\t/** Live corner radius the rectangle, polygon and star tools give their corners (default 0). */\n\tcornerRadius?: number;\n\t/** Corner kind of those tools (default `round`). */\n\tcornerKind?: VectorCornerKind;\n}\n\nexport type VectorAlign = 'left' | 'center' | 'right' | 'top' | 'middle' | 'bottom';\nexport type VectorDistribute = 'horizontal' | 'vertical';\nexport type VectorBooleanOperation = 'union' | 'subtract' | 'intersect' | 'exclude';\n/**\n * Pathfinder operations: `divide` (every face its own shape), `trim` (hidden parts removed),\n * `merge` (Trim, then touching parts of one fill joined), `crop` (the top shape crops the others),\n * `outline` (outlines cut into open strokes where they meet) and `minusBack` (the top shape minus\n * everything below it).\n */\nexport type VectorPathfinderOperation = 'divide' | 'trim' | 'merge' | 'crop' | 'outline' | 'minusBack';\nexport const VECTOR_PATHFINDER_OPERATIONS: readonly VectorPathfinderOperation[] = ['divide', 'trim', 'merge', 'crop', 'outline', 'minusBack'];\nexport type VectorArrange = 'front' | 'forward' | 'backward' | 'back';\n/** Average: line anchors up on a horizontal line (same y), a vertical one (same x), or both. */\nexport type VectorAverageAxis = 'horizontal' | 'vertical' | 'both';\n\n/** Identifies one segment of a path node: from anchor `segment` to the next. */\nexport interface VectorSegmentRef {\n\tnodeId: string;\n\tsubpath: number;\n\tsegment: number;\n}\n","/**\n * Live corners: a radius stored on an anchor, drawn as a round, inverted or chamfered cut when\n * the path is turned into curves. The stored anchors never change; `expandVectorCorners` is the\n * one place the cut geometry is made, and `subpathsToBezier` calls it, so rendering,\n * hit-testing, bounds, booleans, stroke outlines and SVG export all see the same shape.\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, see THIRD_PARTY_NOTICES.md):\n * - figcraft `crates/doc/src/vector.rs` — `VectorNetwork::rounded` / `corner` and `trim`: each\n * side is trimmed by arc length (the radius clamped so a cut takes at most half of each\n * side) and the round cut is a cubic with handles `4/3 · tan(φ/4) · ρ` along the sides'\n * directions at the cut, φ the turn between them and ρ the radius of the circle through\n * both ends. That is exact at any angle and works where a curve meets a corner.\n * - vectorcraft `crates/geom/src/corners.rs` — `path_corners`, `Corner` (setback, max radius,\n * bisector and radius change for the drag widget) and `cut_corners` (inverted round and\n * chamfer kinds, trimming curved sides between cuts, a closed subpath whose first corner is\n * cut starting where that cut ends).\n */\nimport type { Point } from '../canvas/types.js';\nimport { segmentDerivative, segmentLength, segmentParamAtLength, segmentPoint, subSegment } from '../canvas/pathops/bezier.js';\nimport type { VectorAnchor, VectorCornerKind, VectorSubpath, Vec2 } from './types.js';\n\nconst EPS = 1e-9;\n/** Sides closer than this to straight on (or folded back), as the sine of their angle, make no corner. */\nconst MIN_SINE = 1e-6;\n\nconst sub = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x - b.x, y: a.y - b.y });\nconst add = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x + b.x, y: a.y + b.y });\nconst mul = (a: Vec2, k: number): Vec2 => ({ x: a.x * k, y: a.y * k });\nconst dot = (a: Vec2, b: Vec2) => a.x * b.x + a.y * b.y;\nconst cross = (a: Vec2, b: Vec2) => a.x * b.y - a.y * b.x;\nconst len = (a: Vec2) => Math.hypot(a.x, a.y);\nconst pt = (p: Vec2): Point => [p.x, p.y];\nconst vec = (p: Point): Vec2 => ({ x: p[0], y: p[1] });\nconst onAnchor = (a: VectorAnchor, h: Vec2 | null | undefined) => !h || (Math.abs(h.x - a.x) < EPS && Math.abs(h.y - a.y) < EPS);\n\n/** A side of a corner: the segment from the corner's anchor to a neighbour, as a cubic leaving the corner. */\nclass Side {\n\treadonly curve: Point[];\n\treadonly straight: boolean;\n\treadonly length: number;\n\tconstructor(a: VectorAnchor, h1: Vec2 | null | undefined, h2: Vec2 | null | undefined, b: VectorAnchor) {\n\t\tthis.straight = onAnchor(a, h1) && onAnchor(b, h2);\n\t\tthis.curve = this.straight ? [pt(a), pt(b)] : [pt(a), pt(h1 ?? a), pt(h2 ?? b), pt(b)];\n\t\tthis.length = this.straight ? Math.hypot(b.x - a.x, b.y - a.y) : segmentLength(this.curve);\n\t}\n\n\t/** Unit direction the side leaves the corner in (towards its first control point off the corner). */\n\tdirection(): Vec2 | null {\n\t\tconst p0 = vec(this.curve[0]);\n\t\tfor (const q of this.curve.slice(1)) {\n\t\t\tconst d = sub(vec(q), p0);\n\t\t\tconst l = len(d);\n\t\t\tif (l > EPS) return mul(d, 1 / l);\n\t\t}\n\t\treturn null;\n\t}\n\n\t/** The point `s` along the side from the corner: its parameter, position and the direction the side runs on in there. */\n\tat(s: number, u: Vec2): { t: number; p: Vec2; dir: Vec2 } {\n\t\tif (this.straight) {\n\t\t\tconst t = this.length > EPS ? Math.min(1, Math.max(0, s / this.length)) : 0;\n\t\t\treturn { t, p: add(vec(this.curve[0]), mul(u, s)), dir: u };\n\t\t}\n\t\tconst t = segmentParamAtLength(this.curve, s, this.length);\n\t\tconst d = vec(segmentDerivative(this.curve, t));\n\t\tconst l = len(d);\n\t\treturn { t, p: vec(segmentPoint(this.curve, t)), dir: l > EPS ? mul(d, 1 / l) : u };\n\t}\n}\n\n/**\n * A corner a live radius can cut: an anchor that is not smooth, where two sides (straight or\n * curved) meet at an angle. Positions are in the path node's own space.\n */\nexport interface VectorCornerInfo {\n\tsubpath: number;\n\tindex: number;\n\t/** Where the sides meet. */\n\tat: Vec2;\n\t/** Unit directions the sides leave the corner in: towards the previous anchor, then the next one. */\n\tu: Vec2;\n\tv: Vec2;\n\t/** The sides' lengths (along curves), in the same order. */\n\tlu: number;\n\tlv: number;\n\t/** Cosine and sine of the angle between the sides. */\n\tcos: number;\n\tsin: number;\n\t/** The angle between the sides in degrees (90 at a rectangle's corners). */\n\tangle: number;\n\t/** The largest radius that fits: its cut then reaches halfway along the shorter side. */\n\tmaxRadius: number;\n}\n\ninterface CornerData extends VectorCornerInfo {\n\tsideU: Side;\n\tsideV: Side;\n}\n\nfunction cornerOf(sp: VectorSubpath, s: number, i: number): CornerData | null {\n\tconst n = sp.anchors.length;\n\tif (n < 2 || (!sp.closed && (i === 0 || i === n - 1))) return null;\n\tif (n === 2 && sp.closed) return null;\n\tconst a = sp.anchors[i];\n\tif (a.type === 'smooth' || a.type === 'symmetric') return null;\n\tconst prev = sp.anchors[(i - 1 + n) % n];\n\tconst next = sp.anchors[(i + 1) % n];\n\tconst sideU = new Side(a, a.in, prev.out, prev);\n\tconst sideV = new Side(a, a.out, next.in, next);\n\tconst u = sideU.direction();\n\tconst v = sideV.direction();\n\tif (!u || !v) return null;\n\tconst lu = sideU.length;\n\tconst lv = sideV.length;\n\tif (!(lu > EPS && lv > EPS) || !Number.isFinite(lu) || !Number.isFinite(lv)) return null;\n\tconst cos = Math.max(-1, Math.min(1, dot(u, v)));\n\tconst sin = Math.abs(cross(u, v));\n\tif (sin <= MIN_SINE) return null;\n\treturn { subpath: s, index: i, at: { x: a.x, y: a.y }, u, v, lu, lv, cos, sin, angle: (Math.atan2(sin, cos) * 180) / Math.PI, maxRadius: ((Math.min(lu, lv) / 2) * sin) / (1 + cos), sideU, sideV };\n}\n\nconst strip = ({ sideU: _u, sideV: _v, ...info }: CornerData): VectorCornerInfo => info;\n\n/** The corner at anchor `index` of a subpath, or null when the anchor makes none (an open end, smooth, or straight on). */\nexport function vectorCornerAt(sp: VectorSubpath, index: number, subpath = 0): VectorCornerInfo | null {\n\tconst c = cornerOf(sp, subpath, index);\n\treturn c ? strip(c) : null;\n}\n\n/** Every corner of the subpaths that a live radius can cut, in anchor order. */\nexport function vectorCorners(subpaths: readonly VectorSubpath[]): VectorCornerInfo[] {\n\tconst out: VectorCornerInfo[] = [];\n\tsubpaths.forEach((sp, s) => {\n\t\tfor (let i = 0; i < sp.anchors.length; i++) {\n\t\t\tconst c = cornerOf(sp, s, i);\n\t\t\tif (c) out.push(strip(c));\n\t\t}\n\t});\n\treturn out;\n}\n\n/** How far from the corner a round cut of radius `r` meets each side: r / tan(angle / 2). */\nexport const cornerSetback = (c: Pick<VectorCornerInfo, 'cos' | 'sin'>, r: number) => (r * (1 + c.cos)) / c.sin;\n\n/** `radius` clamped to what the corner can draw (0 for negative or non-finite radii). */\nexport const fitCornerRadius = (c: Pick<VectorCornerInfo, 'maxRadius'>, radius: number) => (Number.isFinite(radius) ? Math.min(Math.max(0, radius), c.maxRadius) : 0);\n\n/** The point `k` along the corner's bisector, measured in (u + v): a round cut of radius r is centred at k = r / sin. */\nexport const cornerBisectorPoint = (c: VectorCornerInfo, k: number): Vec2 => add(c.at, mul(add(c.u, c.v), k));\n\n/** How much the radius grows when the round cut's centre moves by `d` (its part along the bisector, in radius units). */\nexport const cornerRadiusChange = (c: VectorCornerInfo, d: Vec2) => (dot(d, add(c.u, c.v)) * c.sin) / (2 + 2 * c.cos);\n\n/** Handle length per unit radius of a cubic arc spanning the angle whose cosine is `cos`: 4/3 · tan(angle / 4). */\nfunction arcHandle(cos: number): number {\n\tconst c = Math.max(-1, Math.min(1, cos));\n\tconst sinHalf = Math.sqrt(Math.max(0, (1 - c) / 2));\n\tconst cosHalf = Math.sqrt(Math.max(0, (1 + c) / 2));\n\treturn ((4 / 3) * sinHalf) / (1 + cosHalf);\n}\n\n/** The unit direction square to unit `a`, on `b`'s side. */\nfunction squareTo(a: Vec2, b: Vec2): Vec2 {\n\tconst w = sub(b, mul(a, dot(a, b)));\n\tconst l = len(w);\n\treturn l > EPS ? mul(w, 1 / l) : { x: 0, y: 0 };\n}\n\ninterface Cut {\n\t/** Parameters along each side (from the corner) where the cut meets it. */\n\ttu: number;\n\ttv: number;\n\tstart: Vec2;\n\t/** Handles of the cut's own segment (absent for a chamfer). */\n\tout: Vec2 | null;\n\tin: Vec2 | null;\n\tend: Vec2;\n}\n\nfunction cutCorner(c: CornerData, radius: number, kind: VectorCornerKind): Cut | null {\n\t// figcraft `corner`: trim each side by arc length, at most half of it.\n\tconst s = Math.min(cornerSetback(c, radius), Math.min(c.lu, c.lv) / 2);\n\tif (!(s > EPS)) return null;\n\tconst a = c.sideU.at(s, c.u);\n\tconst b = c.sideV.at(s, c.v);\n\tif (kind === 'chamfer') return { tu: a.t, tv: b.t, start: a.p, out: null, in: null, end: b.p };\n\tif (kind === 'inverted') {\n\t\t// vectorcraft `cut`: an arc centred on the corner through both ends, spanning the corner's angle.\n\t\tconst h = s * arcHandle(dot(a.dir, b.dir));\n\t\treturn { tu: a.t, tv: b.t, start: a.p, out: add(a.p, mul(squareTo(a.dir, b.dir), h)), in: add(b.p, mul(squareTo(b.dir, a.dir), h)), end: b.p };\n\t}\n\t// Round: d1, d2 point back towards the corner at the cut's ends; φ is the turn between them\n\t// and ρ the radius of the circle through both ends.\n\tconst d1 = mul(a.dir, -1);\n\tconst d2 = mul(b.dir, -1);\n\tconst turn = Math.acos(Math.max(-1, Math.min(1, -dot(d1, d2))));\n\tconst chord = len(sub(b.p, a.p));\n\tconst k = turn < 1e-9 ? chord / 3 : (((4 / 3) * Math.tan(turn / 4) * chord) / (2 * Math.sin(turn / 2)));\n\tif (!Number.isFinite(k)) return null;\n\treturn { tu: a.t, tv: b.t, start: a.p, out: add(a.p, mul(d1, k)), in: add(b.p, mul(d2, k)), end: b.p };\n}\n\nconst radiusOf = (a: VectorAnchor) => {\n\tconst r = a.corner?.radius;\n\treturn typeof r === 'number' && r > 0 && Number.isFinite(r) ? r : 0;\n};\n\n/** True when any anchor of the subpaths has a live corner radius. */\nexport function hasVectorCorners(subpaths: readonly VectorSubpath[]): boolean {\n\treturn subpaths.some((sp) => sp.anchors.some((a) => radiusOf(a) > 0));\n}\n\n/** One subpath with its corners cut; `sources[i]` is the stored anchor each output anchor comes from. */\nexport function expandVectorCornersOf(sp: VectorSubpath, subpath = 0): { subpath: VectorSubpath; sources: number[] } {\n\tconst n = sp.anchors.length;\n\tconst cuts: (Cut | null)[] = sp.anchors.map((a, i) => {\n\t\tconst r = radiusOf(a);\n\t\tif (!r) return null;\n\t\tconst c = cornerOf(sp, subpath, i);\n\t\tif (!c) return null;\n\t\tconst fitted = fitCornerRadius(c, r);\n\t\treturn fitted > EPS ? cutCorner(c, fitted, a.corner?.kind ?? 'round') : null;\n\t});\n\tif (!cuts.some(Boolean)) return { subpath: { closed: sp.closed, anchors: sp.anchors.map(plain) }, sources: sp.anchors.map((_, i) => i) };\n\t// Each segment from anchor j trimmed to what the cuts at its ends leave: its handles, or\n\t// undefined when it is untouched (null handles: a straight segment).\n\tconst trimmed: ({ out: Vec2 | null; in: Vec2 | null } | undefined)[] = sp.anchors.map((a, j) => {\n\t\tconst k = (j + 1) % n;\n\t\tif (k === 0 && !sp.closed) return undefined;\n\t\tconst b = sp.anchors[k];\n\t\tconst from = cuts[j];\n\t\tconst to = cuts[k];\n\t\tif (!from && !to) return undefined;\n\t\tif (onAnchor(a, a.out) && onAnchor(b, b.in)) return { out: null, in: null };\n\t\tconst s0 = from ? from.tv : 0;\n\t\tconst s1 = to ? 1 - to.tu : 1;\n\t\tconst seg: Point[] = [pt(a), pt(a.out ?? a), pt(b.in ?? b), pt(b)];\n\t\tconst part = subSegment(seg, s0, Math.max(s0, s1));\n\t\treturn { out: vec(part[1]), in: vec(part[2]) };\n\t});\n\tconst anchors: VectorAnchor[] = [];\n\tconst sources: number[] = [];\n\tlet closing: VectorAnchor | null = null;\n\tconst handleIn = (i: number, a: VectorAnchor) => {\n\t\tconst t = trimmed[(i - 1 + n) % n];\n\t\treturn t ? t.in : (a.in ?? null);\n\t};\n\tconst handleOut = (i: number, a: VectorAnchor) => {\n\t\tconst t = trimmed[i];\n\t\treturn t ? t.out : (a.out ?? null);\n\t};\n\tsp.anchors.forEach((a, i) => {\n\t\tconst c = cuts[i];\n\t\tif (!c) {\n\t\t\tanchors.push(withHandles({ x: a.x, y: a.y, ...(a.type ? { type: a.type } : {}) }, handleIn(i, a), handleOut(i, a)));\n\t\t\tsources.push(i);\n\t\t\treturn;\n\t\t}\n\t\tconst start = withHandles({ x: c.start.x, y: c.start.y }, handleIn(i, a), c.out);\n\t\tconst end = withHandles({ x: c.end.x, y: c.end.y }, c.in, handleOut(i, a));\n\t\tif (i === 0 && sp.closed) closing = start;\n\t\telse {\n\t\t\tanchors.push(start);\n\t\t\tsources.push(i);\n\t\t}\n\t\tanchors.push(end);\n\t\tsources.push(i);\n\t});\n\tif (closing) {\n\t\tanchors.push(closing);\n\t\tsources.push(0);\n\t}\n\treturn { subpath: { closed: sp.closed, anchors }, sources };\n}\n\nfunction withHandles(a: VectorAnchor, hin: Vec2 | null, hout: Vec2 | null): VectorAnchor {\n\tif (hin && !onAnchor(a, hin)) a.in = { x: hin.x, y: hin.y };\n\tif (hout && !onAnchor(a, hout)) a.out = { x: hout.x, y: hout.y };\n\treturn a;\n}\n\nfunction plain(a: VectorAnchor): VectorAnchor {\n\tif (!('corner' in a)) return a;\n\tconst { corner: _c, ...rest } = a;\n\treturn rest;\n}\n\n/**\n * The subpaths with every live corner cut (round, inverted or chamfer), each radius no larger\n * than fits. A cut corner becomes two anchors and curved sides are trimmed to what the cuts\n * leave of them. Subpaths without corners come back unchanged.\n */\nexport function expandVectorCorners(subpaths: readonly VectorSubpath[]): VectorSubpath[] {\n\tif (!hasVectorCorners(subpaths)) return subpaths as VectorSubpath[];\n\treturn subpaths.map((sp, s) => (sp.anchors.some((a) => radiusOf(a) > 0) ? expandVectorCornersOf(sp, s).subpath : sp));\n}\n\n/**\n * Sets (or clears, with radius 0) the live corner of anchors. `kind` keeps each anchor's own\n * kind when omitted. Anchors that make no corner keep the radius too, so it applies once they do.\n */\nexport function setAnchorCorner(a: VectorAnchor, radius: number, kind?: VectorCornerKind): VectorAnchor {\n\tconst { corner, ...rest } = a;\n\tconst r = Number.isFinite(radius) ? Math.max(0, radius) : 0;\n\tconst k = kind ?? corner?.kind;\n\tif (r <= 0 && !kind) return rest;\n\treturn { ...rest, corner: { radius: r, ...(k && k !== 'round' ? { kind: k } : {}) } };\n}\n\n/** The next corner kind (Alt-clicking a corner widget cycles round → inverted → chamfer). */\nexport function nextVectorCornerKind(kind: VectorCornerKind | undefined): VectorCornerKind {\n\treturn kind === 'inverted' ? 'chamfer' : kind === 'chamfer' ? 'round' : 'inverted';\n}\n\n/** Every anchor of a subpath given the same live corner (radius 0 clears them). */\nexport function setSubpathCorners(sp: VectorSubpath, radius: number, kind?: VectorCornerKind): VectorSubpath {\n\treturn { closed: sp.closed, anchors: sp.anchors.map((a) => setAnchorCorner(a, radius, kind)) };\n}\n","/**\n * Variable-width stroke profiles: stroke widths at positions along a path (each subpath on its\n * own), interpolated smoothly and held flat before the first and after the last point. Each\n * point has a left and a right side scale (looking along the path on screen, y down), so a\n * stroke can grow on one side only.\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, see THIRD_PARTY_NOTICES.md):\n * - figcraft `crates/doc/src/props.rs` — `WidthProfile` / `WidthPoint`: sanitising, side\n * scales, inserting and moving points, and the monotone cubic (Fritsch–Carlson) interpolation\n * that never overshoots its neighbouring points.\n * - vectorcraft `crates/doc/src/appearance.rs` — `WidthProfile` as `(t, left, right)` points,\n * discontinuous points (two points at one `t` make a step) and the profile presets.\n * - effectcraft `crates/path/src/varstroke.rs` — `width_factor`: the parametric Taper (lengths,\n * end widths, ease) and Wave (amount, cycles, phase) shapes, used here as profile generators.\n */\nimport type { VectorWidthPoint } from './types.js';\n\n/** The most points a profile keeps. */\nexport const VECTOR_WIDTH_PROFILE_MAX_POINTS = 64;\n/** The widest a side can be, as a multiple of the stroke width. */\nexport const VECTOR_WIDTH_PROFILE_MAX_SCALE = 1000;\n/** Positions closer than this are the same place (the two sides of a discontinuous point). */\nexport const VECTOR_WIDTH_SAME_T = 1e-6;\n\n/** Built-in profiles. `uniform` is the plain stroke (no profile). */\nexport type VectorWidthPreset = 'uniform' | 'taperStart' | 'taperEnd' | 'taperBoth' | 'bulge' | 'pinch' | 'teardrop' | 'wave' | 'pressure';\n\n/** One preset as a menu shows it. */\nexport interface VectorWidthPresetInfo {\n\tid: VectorWidthPreset;\n\tlabel: string;\n\tpoints: readonly VectorWidthPoint[];\n}\n\nconst sym = (t: number, s: number): VectorWidthPoint => ({ t, left: s, right: s });\n\n/** The built-in profiles, in menu order. */\nexport const VECTOR_WIDTH_PRESETS: readonly VectorWidthPresetInfo[] = [\n\t{ id: 'uniform', label: 'Uniform', points: [] },\n\t{ id: 'taperStart', label: 'Taper start', points: [sym(0, 0), sym(1, 1)] },\n\t{ id: 'taperEnd', label: 'Taper end', points: [sym(0, 1), sym(1, 0)] },\n\t{ id: 'taperBoth', label: 'Taper both', points: [sym(0, 0), sym(0.5, 1), sym(1, 0)] },\n\t// Full width at the ends, swelling to twice the width in the middle.\n\t{ id: 'bulge', label: 'Bulge', points: [sym(0, 1), sym(0.5, 2), sym(1, 1)] },\n\t// Full width at the ends, pinched to a quarter in the middle.\n\t{ id: 'pinch', label: 'Pinch', points: [sym(0, 1), sym(0.5, 0.25), sym(1, 1)] },\n\t// A round head a fifth of the way along, then a long taper to the end.\n\t{ id: 'teardrop', label: 'Teardrop', points: [sym(0, 0), sym(0.2, 1), sym(1, 0)] },\n\t// Two swells between narrow necks.\n\t{ id: 'wave', label: 'Wave', points: [sym(0, 0.3), sym(0.25, 1), sym(0.5, 0.3), sym(0.75, 1), sym(1, 0.3)] },\n\t// A pen stroke: a quick press, a slow lift.\n\t{ id: 'pressure', label: 'Pressure', points: [sym(0, 0.15), sym(0.12, 0.85), sym(0.45, 1), sym(0.8, 0.7), sym(1, 0.05)] }\n];\n\nexport const VECTOR_WIDTH_PRESET_IDS: readonly VectorWidthPreset[] = VECTOR_WIDTH_PRESETS.map((p) => p.id);\n\nconst clean = (v: unknown, max: number) => (typeof v === 'number' && Number.isFinite(v) ? Math.min(Math.max(v, 0), max) : null);\n\n/**\n * A profile as the outline uses it: finite points only, `t` in 0–1, side scales in 0–1000,\n * sorted by `t` (stable, so a step keeps its order), at most 64 points. Points missing a side\n * take the other side's scale.\n */\nexport function sanitizeWidthProfile(points: readonly Partial<VectorWidthPoint>[] | null | undefined): VectorWidthPoint[] {\n\tif (!Array.isArray(points)) return [];\n\tconst out: VectorWidthPoint[] = [];\n\tfor (const p of points) {\n\t\tif (!p || typeof p !== 'object') continue;\n\t\tconst t = clean(p.t, 1);\n\t\tconst l = clean(p.left, VECTOR_WIDTH_PROFILE_MAX_SCALE);\n\t\tconst r = clean(p.right, VECTOR_WIDTH_PROFILE_MAX_SCALE);\n\t\tif (t === null || (l === null && r === null)) continue;\n\t\tout.push({ t, left: l ?? r!, right: r ?? l! });\n\t\tif (out.length >= VECTOR_WIDTH_PROFILE_MAX_POINTS) break;\n\t}\n\treturn out.map((p, i) => [p, i] as const).sort((a, b) => a[0].t - b[0].t || a[1] - b[1]).map(([p]) => p);\n}\n\n/** True when the profile draws a plain stroke: no points, or every side at scale 1. */\nexport function isUniformWidthProfile(points: readonly VectorWidthPoint[] | null | undefined): boolean {\n\treturn !points?.length || points.every((p) => p.left === 1 && p.right === 1);\n}\n\n/** Slope of side `k` from point `i` to `i + 1` (0 when they share a position). */\nfunction secant(pts: readonly VectorWidthPoint[], i: number, k: 'left' | 'right'): number {\n\tconst a = pts[i];\n\tconst b = pts[i + 1];\n\treturn a && b && b.t - a.t > 1e-12 ? (b[k] - a[k]) / (b.t - a.t) : 0;\n}\n\n/** Fritsch–Carlson tangent: one-sided at the ends, the harmonic mean of the slopes inside, flat at local extremes. */\nfunction tangent(pts: readonly VectorWidthPoint[], i: number, k: 'left' | 'right'): number {\n\tconst last = pts.length - 1;\n\tif (i <= 0) return secant(pts, 0, k);\n\tif (i >= last) return secant(pts, last - 1, k);\n\tconst d0 = secant(pts, i - 1, k);\n\tconst d1 = secant(pts, i, k);\n\treturn d0 * d1 <= 0 ? 0 : (2 * d0 * d1) / (d0 + d1);\n}\n\nfunction interp(pts: readonly VectorWidthPoint[], t: number, k: 'left' | 'right'): number {\n\tconst first = pts[0];\n\tconst last = pts[pts.length - 1];\n\tif (!(t > first.t)) return first[k];\n\tif (t >= last.t) return last[k];\n\t// The last point at or before t (the second of a step at exactly t).\n\tlet i = 0;\n\twhile (i + 1 < pts.length && pts[i + 1].t <= t) i++;\n\tconst a = pts[i];\n\tconst b = pts[i + 1];\n\tconst h = b.t - a.t;\n\tif (h <= 1e-12) return b[k];\n\tconst u = (t - a.t) / h;\n\tconst u2 = u * u;\n\tconst u3 = u2 * u;\n\tconst w = (2 * u3 - 3 * u2 + 1) * a[k] + (u3 - 2 * u2 + u) * h * tangent(pts, i, k) + (3 * u2 - 2 * u3) * b[k] + (u3 - u2) * h * tangent(pts, i + 1, k);\n\treturn Math.max(0, w);\n}\n\n/**\n * The left and right side scales at `t` (0–1 along the subpath by length). Each side is\n * interpolated on its own with a monotone cubic, so the width never overshoots its points;\n * a profile without points is uniform (1, 1).\n */\nexport function widthProfileAt(points: readonly VectorWidthPoint[] | null | undefined, t: number): { left: number; right: number } {\n\tif (!points?.length) return { left: 1, right: 1 };\n\treturn { left: interp(points, t, 'left'), right: interp(points, t, 'right') };\n}\n\n/** The largest side scale (the interpolation never exceeds its points); 1 without a profile. */\nexport function widthProfileMaxScale(points: readonly VectorWidthPoint[] | null | undefined): number {\n\tif (!points?.length) return 1;\n\treturn points.reduce((m, p) => Math.max(m, p.left, p.right), 0);\n}\n\n/** The points of a preset (empty for `uniform`), or null for an unknown id. */\nexport function widthProfilePreset(id: string): VectorWidthPoint[] | null {\n\tconst p = VECTOR_WIDTH_PRESETS.find((q) => q.id === id);\n\treturn p ? p.points.map((q) => ({ ...q })) : null;\n}\n\n/** The preset a profile matches: `uniform` without one (or all at scale 1), `custom` when none matches. */\nexport function widthProfilePresetId(points: readonly VectorWidthPoint[] | null | undefined): VectorWidthPreset | 'custom' {\n\tif (isUniformWidthProfile(points)) return 'uniform';\n\tconst same = (a: readonly VectorWidthPoint[], b: readonly VectorWidthPoint[]) =>\n\t\ta.length === b.length && a.every((p, i) => Math.abs(p.t - b[i].t) < 1e-9 && Math.abs(p.left - b[i].left) < 1e-9 && Math.abs(p.right - b[i].right) < 1e-9);\n\treturn VECTOR_WIDTH_PRESETS.find((p) => p.points.length && same(points!, p.points))?.id ?? 'custom';\n}\n\n/** The profile of the reversed path: positions mirrored and the sides swapped. */\nexport function reverseWidthProfile(points: readonly VectorWidthPoint[]): VectorWidthPoint[] {\n\treturn points.map((p) => ({ t: 1 - p.t, left: p.right, right: p.left })).reverse();\n}\n\n/** The profile of a mirrored path (it runs the same way, but its sides swap). */\nexport function mirrorWidthProfile(points: readonly VectorWidthPoint[]): VectorWidthPoint[] {\n\treturn points.map((p) => ({ t: p.t, left: p.right, right: p.left }));\n}\n\n/** The points a profile edit starts from: the profile, or a uniform one with a point at each end. */\nfunction editable(points: readonly VectorWidthPoint[] | null | undefined): VectorWidthPoint[] {\n\treturn points?.length ? points.map((p) => ({ ...p })) : [sym(0, 1), sym(1, 1)];\n}\n\n/**\n * Adds a width point at `t` (side scales `left` / `right`, default: as wide as the stroke is\n * there) and returns the new profile and the point's index. Inserting at the position of an\n * existing point replaces it, unless `step` is set (which makes a discontinuous point).\n */\nexport function insertWidthPoint(\n\tpoints: readonly VectorWidthPoint[] | null | undefined,\n\tt: number,\n\tsides: { left?: number; right?: number } = {},\n\toptions: { step?: boolean } = {}\n): { points: VectorWidthPoint[]; index: number } {\n\tconst pts = editable(points);\n\tconst tt = Math.min(Math.max(Number.isFinite(t) ? t : 0, 0), 1);\n\tconst here = widthProfileAt(points?.length ? points : null, tt);\n\tconst p: VectorWidthPoint = {\n\t\tt: tt,\n\t\tleft: clean(sides.left, VECTOR_WIDTH_PROFILE_MAX_SCALE) ?? here.left,\n\t\tright: clean(sides.right, VECTOR_WIDTH_PROFILE_MAX_SCALE) ?? here.right\n\t};\n\tconst same = pts.findIndex((q) => Math.abs(q.t - tt) <= VECTOR_WIDTH_SAME_T);\n\tif (same >= 0 && !options.step) {\n\t\tpts[same] = { ...p, t: pts[same].t };\n\t\treturn { points: pts, index: same };\n\t}\n\tlet i = 0;\n\twhile (i < pts.length && pts[i].t <= tt) i++;\n\tif (pts.length >= VECTOR_WIDTH_PROFILE_MAX_POINTS) return { points: pts, index: Math.max(0, i - 1) };\n\tpts.splice(i, 0, p);\n\treturn { points: pts, index: i };\n}\n\n/**\n * Changes point `index`: moves it to `t` (kept between its neighbours, so indices stay put)\n * and / or sets its side scales. Out-of-range indices leave the profile as it is.\n */\nexport function setWidthPoint(points: readonly VectorWidthPoint[], index: number, patch: Partial<VectorWidthPoint>): VectorWidthPoint[] {\n\tconst pts = points.map((p) => ({ ...p }));\n\tconst p = pts[index];\n\tif (!p) return pts;\n\tif (typeof patch.t === 'number' && Number.isFinite(patch.t)) {\n\t\tconst lo = index > 0 ? pts[index - 1].t : 0;\n\t\tconst hi = index < pts.length - 1 ? pts[index + 1].t : 1;\n\t\tp.t = Math.min(Math.max(patch.t, lo), Math.max(hi, lo));\n\t}\n\tconst l = clean(patch.left, VECTOR_WIDTH_PROFILE_MAX_SCALE);\n\tconst r = clean(patch.right, VECTOR_WIDTH_PROFILE_MAX_SCALE);\n\tif (l !== null) p.left = l;\n\tif (r !== null) p.right = r;\n\treturn pts;\n}\n\n/** Removes the points at `indices`. */\nexport function removeWidthPoints(points: readonly VectorWidthPoint[], indices: readonly number[]): VectorWidthPoint[] {\n\tconst drop = new Set(indices);\n\treturn points.filter((_, i) => !drop.has(i)).map((p) => ({ ...p }));\n}\n\n// ---------------------------------------------------------------------------\n// Generators\n// ---------------------------------------------------------------------------\n\n/** effectcraft's ease from the tip (`u = 0`) to full width (`u = 1`): linear at 0, a quarter circle at 1. */\nfunction ease(u: number, e: number): number {\n\tconst x = Math.min(Math.max(u, 0), 1);\n\tconst round = Math.sqrt(Math.max(0, 1 - (1 - x) * (1 - x)));\n\treturn x + (round - x) * Math.min(Math.max(e, 0), 1);\n}\n\n/** A parametric taper (effectcraft's Stroke Taper), lengths as fractions of the path. */\nexport interface VectorTaperOptions {\n\t/** Fraction of the path the start taper covers (default 0). */\n\tstartLength?: number;\n\t/** Fraction the end taper covers (default 0). */\n\tendLength?: number;\n\t/** Width at the start as a fraction of the stroke width (default 0: a point). */\n\tstartWidth?: number;\n\tendWidth?: number;\n\t/** 0 linear, 1 a quarter circle bulging outwards (default 0). */\n\tstartEase?: number;\n\tendEase?: number;\n}\n\n/** A width wave (effectcraft's Stroke Wave): the width swings between `1 − amount` and 1. */\nexport interface VectorWaveOptions {\n\t/** 0–1 (default 0.5). */\n\tamount?: number;\n\t/** Whole cycles along the path (default 4). */\n\tcycles?: number;\n\t/** Degrees (default 0). */\n\tphase?: number;\n}\n\n/** The width factor at fraction `t` of a taper and / or a wave (effectcraft `width_factor`). */\nexport function taperWaveFactor(t: number, taper?: VectorTaperOptions | null, wave?: VectorWaveOptions | null): number {\n\tlet k = 1;\n\tif (taper) {\n\t\tlet ls = Math.max(0, taper.startLength ?? 0);\n\t\tlet le = Math.max(0, taper.endLength ?? 0);\n\t\t// Overlapping tapers share the path in proportion.\n\t\tif (ls + le > 1) {\n\t\t\tconst f = 1 / (ls + le);\n\t\t\tls *= f;\n\t\t\tle *= f;\n\t\t}\n\t\tconst sw = Math.min(Math.max(taper.startWidth ?? 0, 0), 1);\n\t\tconst ew = Math.min(Math.max(taper.endWidth ?? 0, 0), 1);\n\t\tif (ls > 0 && t < ls) k = Math.min(k, sw + (1 - sw) * ease(t / ls, taper.startEase ?? 0));\n\t\tif (le > 0 && t > 1 - le) k = Math.min(k, ew + (1 - ew) * ease((1 - t) / le, taper.endEase ?? 0));\n\t}\n\tif (wave) {\n\t\tconst cycles = wave.cycles ?? 4;\n\t\tconst amount = Math.min(Math.max(wave.amount ?? 0.5, 0), 1);\n\t\tif (cycles > 0 && amount > 0) {\n\t\t\tconst ph = 2 * Math.PI * t * cycles + ((wave.phase ?? 0) * Math.PI) / 180;\n\t\t\tk *= 1 - amount * (0.5 - 0.5 * Math.cos(ph));\n\t\t}\n\t}\n\treturn k;\n}\n\n/**\n * Samples a taper and / or wave into profile points (symmetric), simplified to within\n * `tolerance` of the factor (default 0.01). The monotone interpolation draws them back smoothly.\n */\nexport function generateWidthProfile(options: { taper?: VectorTaperOptions | null; wave?: VectorWaveOptions | null; samples?: number; tolerance?: number }): VectorWidthPoint[] {\n\tconst cycles = options.wave ? Math.max(0, options.wave.cycles ?? 4) : 0;\n\tconst n = Math.max(8, Math.min(VECTOR_WIDTH_PROFILE_MAX_POINTS * 4, options.samples ?? Math.ceil(32 + cycles * 16)));\n\tconst raw: [number, number][] = [];\n\tfor (let i = 0; i <= n; i++) raw.push([i / n, taperWaveFactor(i / n, options.taper, options.wave)]);\n\t// Keep the taper ends exactly.\n\tconst ts = [options.taper?.startLength, options.taper?.endLength !== undefined ? 1 - options.taper.endLength : undefined];\n\tfor (const t of ts) if (typeof t === 'number' && t > 0 && t < 1) raw.push([t, taperWaveFactor(t, options.taper, options.wave)]);\n\traw.sort((a, b) => a[0] - b[0]);\n\tconst kept = simplifySamples(raw, options.tolerance ?? 0.01, VECTOR_WIDTH_PROFILE_MAX_POINTS);\n\treturn kept.map(([t, k]) => sym(t, k));\n}\n\n/** Douglas–Peucker on (t, value) samples (vertical distance), then thinned to at most `max`. */\nfunction simplifySamples(samples: readonly [number, number][], tolerance: number, max: number): [number, number][] {\n\tif (samples.length <= 2) return samples.slice();\n\tconst keep = new Array(samples.length).fill(false);\n\tkeep[0] = keep[samples.length - 1] = true;\n\tconst stack: [number, number][] = [[0, samples.length - 1]];\n\twhile (stack.length) {\n\t\tconst [a, b] = stack.pop()!;\n\t\tconst [ta, va] = samples[a];\n\t\tconst [tb, vb] = samples[b];\n\t\tlet worst = -1;\n\t\tlet err = tolerance;\n\t\tfor (let i = a + 1; i < b; i++) {\n\t\t\tconst [t, v] = samples[i];\n\t\t\tconst lin = tb - ta > 1e-12 ? va + ((vb - va) * (t - ta)) / (tb - ta) : va;\n\t\t\tconst e = Math.abs(v - lin);\n\t\t\tif (e > err) {\n\t\t\t\terr = e;\n\t\t\t\tworst = i;\n\t\t\t}\n\t\t}\n\t\tif (worst >= 0) {\n\t\t\tkeep[worst] = true;\n\t\t\tstack.push([a, worst], [worst, b]);\n\t\t}\n\t}\n\tlet out = samples.filter((_, i) => keep[i]);\n\twhile (out.length > max) out = out.filter((_, i) => i === 0 || i === out.length - 1 || i % 2 === 0);\n\treturn out;\n}\n\n/** Pen pressure that draws the stroke's own width (a mouse reports 0.5 while a button is down). */\nexport const VECTOR_PRESSURE_NOMINAL = 0.5;\n\n/**\n * A profile from pen pressure recorded along a stroke: `(t, pressure 0–1)` samples in order.\n * The width scale is pressure ÷ 0.5 (so half pressure draws the stroke's width, full pressure\n * twice it), at least 0.05; the samples are simplified to within `tolerance` (default 0.02).\n * Returns an empty (uniform) profile when every sample is the same.\n */\nexport function pressureWidthProfile(samples: readonly { t: number; pressure: number }[], options: { tolerance?: number } = {}): VectorWidthPoint[] {\n\tconst raw: [number, number][] = samples\n\t\t.filter((s) => Number.isFinite(s.t) && Number.isFinite(s.pressure))\n\t\t.map((s) => [Math.min(Math.max(s.t, 0), 1), Math.max(0.05, Math.min(1, Math.max(0, s.pressure)) / VECTOR_PRESSURE_NOMINAL)] as [number, number]);\n\tif (raw.length < 2) return [];\n\tif (raw.every((s) => Math.abs(s[1] - raw[0][1]) < 1e-6)) return [];\n\treturn simplifySamples(raw, options.tolerance ?? 0.02, VECTOR_WIDTH_PROFILE_MAX_POINTS).map(([t, k]) => sym(t, Math.round(k * 1000) / 1000));\n}\n","/**\n * The outline of a variable-width stroke, as a clean filled Bézier path.\n *\n * Each subpath is flattened (finely enough for the width to vary smoothly) and the stroke is\n * the union of positively wound pieces: one trapezoid per flattened segment (its ends at the\n * local side widths), a wedge on the outer side of every bend (the style's join at the path's\n * own corners, round inside curves) and the caps. Filled with the non-zero rule the union is\n * exact whatever the profile does; it is built as the boundary those pieces add up to (see\n * `variableStrokeRings`), normalised with the polygon boolean engine, and every ring is refitted\n * with cubics (`fitCubics`) to within the tolerance — a real Bézier outline, not a polyline.\n *\n * Ported from ArtCraft effectcraft `crates/path/src/varstroke.rs` (`outline`, `dash_intervals`)\n * (MIT OR Apache-2.0, see THIRD_PARTY_NOTICES.md), with one-sided widths after figcraft\n * `crates/pathops/src/width.rs` (`variable_outline`).\n */\nimport type { Point } from '../canvas/types.js';\nimport { fitCubics, isStraightCubic } from '../canvas/curveFit.js';\nimport { polygonBoolean } from '../canvas/polygonBoolean.js';\nimport {\n\tflattenChain,\n\tpathToContours,\n\tsegmentLength,\n\tsegmentNearest,\n\tsegmentTangent,\n\ttype BezierPath,\n\ttype BezierSegment\n} from '../canvas/pathops/bezier.js';\nimport type { StrokeCap, StrokeJoin } from '../canvas/pathops/stroke.js';\nimport type { VectorWidthPoint } from './types.js';\nimport { widthProfileAt } from './width.js';\n\nexport interface VariableStrokeOptions {\n\t/** Stroke width: a side scale of 1 reaches half of it from the centre line. */\n\twidth: number;\n\tprofile: readonly VectorWidthPoint[];\n\t/** Joins at the path's own corners (default `miter`); bends inside curves are always round. */\n\tjoin?: StrokeJoin;\n\t/** Default `butt`. */\n\tcap?: StrokeCap;\n\t/** Default 4 (as SVG). */\n\tmiterLimit?: number;\n\t/** Dash pattern (as SVG); the profile still runs along the whole subpath. */\n\tdash?: readonly number[];\n\tdashOffset?: number;\n\t/** Largest distance of the result from the exact outline (default 0.05). */\n\ttolerance?: number;\n}\n\n/** Width samples per subpath at least (so the width varies smoothly along long straight runs). */\nconst SAMPLES_PER_SUBPATH = 128;\n/** The most dashes one subpath makes. */\nconst MAX_DASHES = 5000;\n\ntype Vec = [number, number];\nconst sub = (a: Point, b: Point): Vec => [a[0] - b[0], a[1] - b[1]];\nconst along = (p: Point, v: Vec, k: number): Point => [p[0] + v[0] * k, p[1] + v[1] * k];\nconst lerp = (a: Point, b: Point, u: number): Point => [a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u];\nconst dist = (a: Point, b: Point) => Math.hypot(a[0] - b[0], a[1] - b[1]);\nconst unitOf = (v: Vec): Vec => {\n\tconst l = Math.hypot(v[0], v[1]);\n\treturn l > 0 ? [v[0] / l, v[1] / l] : [1, 0];\n};\n/** The left normal of a direction on screen (y down): `(dy, −dx)`. */\nconst leftNormal = (d: Vec): Vec => [d[1], -d[0]];\n\n/** A flattened subpath: points, their arc lengths, and which are the path's own vertices. */\ninterface Poly {\n\tpts: Point[];\n\ts: number[];\n\tcorner: boolean[];\n\tclosed: boolean;\n}\n\nfunction flatten(segments: readonly BezierSegment[], closed: boolean, tol: number): Poly | null {\n\tconst pts: Point[] = [];\n\tconst corner: boolean[] = [];\n\tconst push = (p: Point, isCorner: boolean) => {\n\t\tconst last = pts[pts.length - 1];\n\t\tif (last && dist(last, p) <= 1e-9) {\n\t\t\tcorner[corner.length - 1] ||= isCorner;\n\t\t\treturn;\n\t\t}\n\t\tpts.push(p);\n\t\tcorner.push(isCorner);\n\t};\n\tfor (const seg of segments) {\n\t\tconst flat = flattenChain([seg], tol);\n\t\t// flattenChain drops a closing duplicate; segments that end where they start keep it.\n\t\tif (dist(seg[0], seg[seg.length - 1]) <= 1e-12 && flat.length > 1) flat.push(seg[seg.length - 1]);\n\t\tflat.forEach((p, i) => push(p, i === 0 || i === flat.length - 1));\n\t}\n\tif (closed && pts.length > 2 && dist(pts[0], pts[pts.length - 1]) > 1e-9) push(pts[0], true);\n\tif (pts.length < 2) return null;\n\t// Subdivide so no piece is longer than the width sampling step.\n\tlet total = 0;\n\tfor (let i = 1; i < pts.length; i++) total += dist(pts[i - 1], pts[i]);\n\tif (!(total > 0)) return null;\n\tconst step = Math.max(total / SAMPLES_PER_SUBPATH, tol);\n\tconst fine: Point[] = [pts[0]];\n\tconst fineCorner: boolean[] = [corner[0]];\n\tfor (let i = 1; i < pts.length; i++) {\n\t\tconst n = Math.max(1, Math.ceil(dist(pts[i - 1], pts[i]) / step));\n\t\tfor (let k = 1; k <= n; k++) {\n\t\t\tfine.push(k === n ? pts[i] : lerp(pts[i - 1], pts[i], k / n));\n\t\t\tfineCorner.push(k === n ? corner[i] : false);\n\t\t}\n\t}\n\tconst s = [0];\n\tfor (let i = 1; i < fine.length; i++) s.push(s[i - 1] + dist(fine[i - 1], fine[i]));\n\treturn { pts: fine, s, corner: fineCorner, closed };\n}\n\n/** Arc-length intervals that are \"on\" for a dash pattern on a path `len` long (effectcraft `dash_intervals`). */\nexport function dashIntervals(pattern: readonly number[], offset: number, len: number): [number, number][] {\n\tlet pat = pattern.map((v) => (Number.isFinite(v) ? Math.max(0, v) : 0));\n\tif (pat.length % 2 === 1) pat = [...pat, ...pat];\n\tconst period = pat.reduce((a, b) => a + b, 0);\n\tif (pat.length < 2 || !(period > 1e-9) || !(len > 0)) return [[0, len]];\n\tlet pos = (((Number.isFinite(offset) ? offset : 0) % period) + period) % period;\n\tlet idx = 0;\n\twhile (pos >= pat[idx]) {\n\t\tpos -= pat[idx];\n\t\tidx = (idx + 1) % pat.length;\n\t}\n\tconst out: [number, number][] = [];\n\tlet s = 0;\n\tlet guard = 0;\n\twhile (s < len && guard++ < MAX_DASHES * pat.length) {\n\t\tconst e = Math.min(s + pat[idx] - pos, len);\n\t\tif (idx % 2 === 0 && e >= s) out.push([s, e]);\n\t\ts += pat[idx] - pos;\n\t\tpos = 0;\n\t\tidx = (idx + 1) % pat.length;\n\t}\n\treturn out;\n}\n\n/** The point at arc length `t` of a polyline and the index of the segment it lies on. */\nfunction at(poly: Poly, t: number): [Point, number] {\n\tlet i = 1;\n\twhile (i < poly.pts.length - 1 && poly.s[i] <= t) i++;\n\tconst a = poly.s[i - 1];\n\tconst b = poly.s[i];\n\tconst u = b > a ? Math.min(Math.max((t - a) / (b - a), 0), 1) : 0;\n\treturn [lerp(poly.pts[i - 1], poly.pts[i], u), i];\n}\n\n/** Points of an arc around `c` from angle `a0` turning by `sweep`, radius going from `r0` to `r1` (ends excluded). */\nfunction arcPoints(c: Point, a0: number, sweep: number, r0: number, r1: number, tol: number): Point[] {\n\tconst r = Math.max(r0, r1);\n\tif (!(r > tol * 0.5) || !Number.isFinite(sweep)) return [];\n\tconst stepAngle = 2 * Math.acos(Math.min(Math.max(1 - tol / r, -1), 1));\n\tconst n = Math.min(128, Math.max(2, Math.ceil(Math.abs(sweep) / Math.max(stepAngle, 1e-3))));\n\tconst out: Point[] = [];\n\tfor (let k = 1; k < n; k++) {\n\t\tconst f = k / n;\n\t\tconst a = a0 + sweep * f;\n\t\tconst rr = r0 + (r1 - r0) * f;\n\t\tout.push([c[0] + Math.cos(a) * rr, c[1] + Math.sin(a) * rr]);\n\t}\n\treturn out;\n}\n\n/** Where segments `a0 → a1` and `b0 → b1` cross, if they do (strictly inside `b`, anywhere past the start of `a`). */\nfunction crossing(a0: Point, a1: Point, b0: Point, b1: Point): Point | null {\n\tconst r = sub(a1, a0);\n\tconst q = sub(b1, b0);\n\tconst den = r[0] * q[1] - r[1] * q[0];\n\tif (Math.abs(den) < 1e-12) return null;\n\tconst w = sub(b0, a0);\n\tconst t = (w[0] * q[1] - w[1] * q[0]) / den;\n\tconst u = (w[0] * r[1] - w[1] * r[0]) / den;\n\treturn t > 1e-9 && t <= 1 && u >= 0 && u < 1 - 1e-9 ? [a0[0] + r[0] * t, a0[1] + r[1] * t] : null;\n}\n\n/**\n * The rings of a variable-width stroke in the path's own space; filled with the non-zero rule\n * they are the stroke.\n *\n * effectcraft builds the stroke as a union of positively wound pieces: a trapezoid per flattened\n * segment (its ends at the local side widths), a wedge on the outer side of every bend and the\n * caps. Unioning thousands of overlapping pieces is slow, so each run is emitted as the boundary\n * those pieces add up to instead (winding numbers add, so the non-zero fill is the same): the\n * offset sides with the outer join between them, and on the inner side of a bend either the point\n * where the two offsets cross (the region cut off is covered by both trapezoids) or, when they do\n * not cross, a detour through the centre point (which keeps the winding right when segments are\n * shorter than the width). A closed subpath gives two rings, an open run one.\n */\nexport function variableStrokeRings(path: BezierPath, options: VariableStrokeOptions): Point[][] {\n\tconst half = options.width / 2;\n\tif (!(half > 0) || !Number.isFinite(half)) return [];\n\tconst tol = options.tolerance && options.tolerance > 0 ? options.tolerance : 0.05;\n\tconst join = options.join ?? 'miter';\n\tconst cap = options.cap ?? 'butt';\n\tconst miterLimit = options.miterLimit && options.miterLimit >= 1 ? options.miterLimit : 4;\n\tconst rings: Point[][] = [];\n\tconst push = (out: Point[], p: Point) => {\n\t\tconst last = out[out.length - 1];\n\t\tif (!last || dist(last, p) > 1e-12) out.push(p);\n\t};\n\tfor (const contour of pathToContours(path)) {\n\t\tif (!contour.segments.length) continue;\n\t\t// Chords of the offsets lose area on the outer side of a curve; a quarter of the tolerance keeps that well inside it.\n\t\tconst poly = flatten(contour.segments, contour.closed, Math.min(tol, half) / 4);\n\t\tif (!poly) continue;\n\t\tconst len = poly.s[poly.s.length - 1];\n\t\tconst sides = (s: number): [number, number] => {\n\t\t\tconst w = widthProfileAt(options.profile, s / len);\n\t\t\treturn [w.left * half, w.right * half];\n\t\t};\n\t\tconst intervals = options.dash?.some((v) => v > 0) ? dashIntervals(options.dash, options.dashOffset ?? 0, len) : [[0, len] as [number, number]];\n\t\tconst whole = intervals.length === 1 && intervals[0][0] <= 0 && intervals[0][1] >= len;\n\t\tfor (const [a, b] of intervals) {\n\t\t\tconst [pa, ia] = at(poly, a);\n\t\t\tconst [pb, ib] = at(poly, b);\n\t\t\tconst pts: { p: Point; s: number; corner: boolean }[] = [{ p: pa, s: a, corner: poly.corner[0] && a <= 0 }];\n\t\t\tfor (let i = ia; i < ib; i++) pts.push({ p: poly.pts[i], s: poly.s[i], corner: poly.corner[i] });\n\t\t\tpts.push({ p: pb, s: b, corner: false });\n\t\t\tconst run = pts.filter((q, i) => i === 0 || dist(q.p, pts[i - 1].p) > 1e-9);\n\t\t\tif (run.length < 2) {\n\t\t\t\t// A zero-length dash: only its caps show.\n\t\t\t\tconst [l, r] = sides(a);\n\t\t\t\tconst w = (l + r) / 2;\n\t\t\t\tif (cap === 'round' && w > 0) rings.push([[pa[0] + w, pa[1]], ...arcPoints(pa, 0, 2 * Math.PI, w, w, tol)]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst closed = whole && poly.closed;\n\t\t\tconst m = run.length - 1;\n\t\t\tconst dirs: Vec[] = [];\n\t\t\tfor (let i = 0; i < m; i++) dirs.push(unitOf(sub(run[i + 1].p, run[i].p)));\n\t\t\tconst normals = dirs.map(leftNormal);\n\t\t\tconst w = run.map((q) => sides(q.s));\n\n\t\t\t/** One side (`sigma` +1 left, −1 right) along the run, joins included. */\n\t\t\tconst side = (sigma: 1 | -1): Point[] => {\n\t\t\t\tconst k = sigma > 0 ? 0 : 1;\n\t\t\t\tconst S = (i: number) => along(run[i].p, normals[i], sigma * w[i][k]);\n\t\t\t\tconst E = (i: number) => along(run[i + 1].p, normals[i], sigma * w[i + 1][k]);\n\t\t\t\tconst out: Point[] = [S(0)];\n\t\t\t\tfor (let i = 0; i < m; i++) {\n\t\t\t\t\tconst seam = i === m - 1;\n\t\t\t\t\tif (seam && !closed) {\n\t\t\t\t\t\tpush(out, E(i));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst j = seam ? 0 : i + 1;\n\t\t\t\t\tconst p = run[i + 1].p;\n\t\t\t\t\tconst d0 = dirs[i];\n\t\t\t\t\tconst d1 = dirs[j];\n\t\t\t\t\tconst cross = d0[0] * d1[1] - d0[1] * d1[0];\n\t\t\t\t\tconst dot = d0[0] * d1[0] + d0[1] * d1[1];\n\t\t\t\t\tconst r0 = w[i + 1][k];\n\t\t\t\t\tconst r1 = w[j][k];\n\t\t\t\t\tconst e = E(i);\n\t\t\t\t\tconst st = S(j);\n\t\t\t\t\tif (Math.abs(cross) < 1e-12 && dot > 0) {\n\t\t\t\t\t\tpush(out, e);\n\t\t\t\t\t\tif (!seam) push(out, st);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst uturn = Math.abs(cross) < 1e-12;\n\t\t\t\t\t// Turning right on screen puts the left side outside the bend (a U-turn: the left side).\n\t\t\t\t\tconst outer = uturn ? sigma > 0 : cross * sigma > 0;\n\t\t\t\t\tif (!outer) {\n\t\t\t\t\t\tconst x = seam ? null : crossing(out[out.length - 1], e, st, E(j));\n\t\t\t\t\t\tif (x) push(out, x);\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tpush(out, e);\n\t\t\t\t\t\t\tpush(out, p);\n\t\t\t\t\t\t\tif (!seam) push(out, st);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tpush(out, e);\n\t\t\t\t\tconst theta = uturn ? Math.PI : Math.atan2(cross, dot);\n\t\t\t\t\tconst r = (r0 + r1) / 2;\n\t\t\t\t\tconst kind: StrokeJoin = run[i + 1].corner || (seam && poly.corner[0]) ? join : 'round';\n\t\t\t\t\tif (r > 1e-9) {\n\t\t\t\t\t\tif (kind === 'round') {\n\t\t\t\t\t\t\tif (r * (1 - Math.cos(Math.abs(theta) / 2)) > tol * 0.25) {\n\t\t\t\t\t\t\t\tfor (const q of arcPoints(p, Math.atan2(e[1] - p[1], e[0] - p[0]), theta, r0, r1, tol)) push(out, q);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (kind === 'miter') {\n\t\t\t\t\t\t\tconst halfCos = Math.cos(theta / 2);\n\t\t\t\t\t\t\tconst bis: Vec = [normals[i][0] + normals[j][0], normals[i][1] + normals[j][1]];\n\t\t\t\t\t\t\tconst bl = Math.hypot(bis[0], bis[1]);\n\t\t\t\t\t\t\tif (halfCos > 1e-6 && 1 / halfCos <= miterLimit && bl > 1e-9) push(out, along(p, bis, (sigma * r) / halfCos / bl));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!seam) push(out, st);\n\t\t\t\t}\n\t\t\t\tif (closed && out.length > 1 && dist(out[0], out[out.length - 1]) <= 1e-12) out.pop();\n\t\t\t\treturn out;\n\t\t\t};\n\t\t\tconst left = side(1);\n\t\t\tconst right = side(-1);\n\t\t\tif (closed) {\n\t\t\t\trings.push(left, right.reverse());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Caps: round or square around each end, from one side to the other.\n\t\t\tconst capPoints = (atStart: boolean): Point[] => {\n\t\t\t\tif (cap === 'butt') return [];\n\t\t\t\tconst i = atStart ? 0 : m;\n\t\t\t\tconst d = atStart ? dirs[0] : dirs[m - 1];\n\t\t\t\tconst [l, r] = w[i];\n\t\t\t\tif (!(l + r > 1e-9)) return [];\n\t\t\t\tconst p = run[i].p;\n\t\t\t\tconst n = leftNormal(d);\n\t\t\t\tconst L = along(p, n, l);\n\t\t\t\tconst R = along(p, n, -r);\n\t\t\t\tif (cap === 'round') {\n\t\t\t\t\t// Half a turn around the outside: right side to left at the start, left to right at the end.\n\t\t\t\t\tconst a0 = Math.atan2(d[1], d[0]) + (atStart ? Math.PI / 2 : -Math.PI / 2);\n\t\t\t\t\treturn arcPoints(p, a0, Math.PI, atStart ? r : l, atStart ? l : r, tol);\n\t\t\t\t}\n\t\t\t\tconst ext = (l + r) / 2;\n\t\t\t\tconst o: Vec = atStart ? [-d[0], -d[1]] : d;\n\t\t\t\treturn atStart ? [along(R, o, ext), along(L, o, ext)] : [along(L, o, ext), along(R, o, ext)];\n\t\t\t};\n\t\t\tconst ring: Point[] = [];\n\t\t\tfor (const q of [...left, ...capPoints(false), ...right.reverse(), ...capPoints(true)]) push(ring, q);\n\t\t\tif (ring.length > 2) rings.push(ring);\n\t\t}\n\t}\n\treturn rings;\n}\n\n/**\n * The outline of a variable-width stroke of `path` (side widths from `profile`), as a clean\n * Bézier path: overlaps removed, outer rings and holes, each refitted with cubics to within\n * `tolerance` of the exact outline. Fill it with the non-zero rule (either rule works).\n */\nexport function variableStrokeOutline(path: BezierPath, options: VariableStrokeOptions): BezierPath {\n\tconst pieces = variableStrokeRings(path, options);\n\tif (!pieces.length) return [];\n\tconst tol = options.tolerance && options.tolerance > 0 ? options.tolerance : 0.05;\n\tlet polygons;\n\ttry {\n\t\tpolygons = polygonBoolean('union', [{ rings: pieces, fillRule: 'nonzero' }]);\n\t} catch {\n\t\treturn [];\n\t}\n\tconst out: BezierPath = [];\n\tfor (const polygon of polygons) {\n\t\tfor (const ring of polygon) {\n\t\t\tif (ring.length < 3) continue;\n\t\t\tconst cubics = fitCubics(ring, tol, { closed: true, cornerAngleDeg: 25 });\n\t\t\tif (!cubics.length) continue;\n\t\t\tout.push({ type: 'M', x: cubics[0].p0[0], y: cubics[0].p0[1] });\n\t\t\tcubics.forEach((c, i) => {\n\t\t\t\tif (isStraightCubic(c, tol * 0.02)) {\n\t\t\t\t\tif (i < cubics.length - 1) out.push({ type: 'L', x: c.p3[0], y: c.p3[1] });\n\t\t\t\t} else out.push({ type: 'C', x1: c.p1[0], y1: c.p1[1], x2: c.p2[0], y2: c.p2[1], x: c.p3[0], y: c.p3[1] });\n\t\t\t});\n\t\t\tout.push({ type: 'Z' });\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * Where point `p` lies relative to the stroke's centre line: the nearest point's contour,\n * its position `t` by length (0–1), the distance, and the side (`left` looking along the\n * path on screen) — what hit-testing and the width tool need.\n */\nexport function nearestStrokePosition(\n\tpath: BezierPath,\n\tp: Point,\n\t/** Only this contour (subpath) of the path. */\n\tonly?: number\n): { contour: number; t: number; distance: number; side: 'left' | 'right'; point: Point; tangent: Vec; length: number } | null {\n\tlet best: ReturnType<typeof nearestStrokePosition> = null;\n\tpathToContours(path).forEach((c, ci) => {\n\t\tif (!c.segments.length || (only !== undefined && ci !== only)) return;\n\t\tconst lengths = c.segments.map((s) => segmentLength(s));\n\t\tconst total = lengths.reduce((a, b) => a + b, 0);\n\t\tif (!(total > 0)) return;\n\t\tlet acc = 0;\n\t\tc.segments.forEach((seg, si) => {\n\t\t\tconst near = segmentNearest(seg, p);\n\t\t\tif (!best || near.distance < best.distance) {\n\t\t\t\tconst s = acc + segmentLength(seg, 0, near.t);\n\t\t\t\tconst tan = segmentTangent(seg, near.t);\n\t\t\t\tconst pt = seg.length === 2 ? lerp(seg[0], seg[1], near.t) : evalSeg(seg, near.t);\n\t\t\t\tconst n = leftNormal([tan[0], tan[1]]);\n\t\t\t\tconst side = (p[0] - pt[0]) * n[0] + (p[1] - pt[1]) * n[1] >= 0 ? 'left' : 'right';\n\t\t\t\tbest = { contour: ci, t: Math.min(Math.max(s / total, 0), 1), distance: near.distance, side, point: pt, tangent: [tan[0], tan[1]], length: total };\n\t\t\t}\n\t\t\tacc += lengths[si];\n\t\t});\n\t});\n\treturn best;\n}\n\nfunction evalSeg(seg: BezierSegment, t: number): Point {\n\t// de Casteljau\n\tlet pts = seg.map((q) => [q[0], q[1]] as Point);\n\twhile (pts.length > 1) pts = pts.slice(1).map((q, i) => lerp(pts[i], q, t));\n\treturn pts[0];\n}\n\n/** The point and unit tangent at position `t` (0–1 by length) of contour `index` of `path`. */\nexport function strokePositionPoint(path: BezierPath, index: number, t: number): { point: Point; tangent: Vec } | null {\n\tconst c = pathToContours(path)[index];\n\tif (!c?.segments.length) return null;\n\tconst lengths = c.segments.map((s) => segmentLength(s));\n\tconst total = lengths.reduce((a, b) => a + b, 0);\n\tlet want = Math.min(Math.max(t, 0), 1) * total;\n\tfor (let i = 0; i < c.segments.length; i++) {\n\t\tconst seg = c.segments[i];\n\t\tif (want <= lengths[i] + 1e-12 || i === c.segments.length - 1) {\n\t\t\t// Bisect the parameter for the remaining length.\n\t\t\tlet lo = 0;\n\t\t\tlet hi = 1;\n\t\t\tconst target = Math.min(want, lengths[i]);\n\t\t\tfor (let k = 0; k < 40; k++) {\n\t\t\t\tconst mid = (lo + hi) / 2;\n\t\t\t\tif (segmentLength(seg, 0, mid) < target) lo = mid;\n\t\t\t\telse hi = mid;\n\t\t\t}\n\t\t\tconst u = (lo + hi) / 2;\n\t\t\tconst tan = segmentTangent(seg, u);\n\t\t\treturn { point: evalSeg(seg, u), tangent: [tan[0], tan[1]] };\n\t\t}\n\t\twant -= lengths[i];\n\t}\n\treturn null;\n}\n","/**\n * Stroke options of vector paths: alignment (centre, inside, outside) and arrowheads at the\n * ends of open paths. Everything here works on a path's Bézier outline in one space (the\n * node's own, or the document's), so the canvases, hit-testing, SVG export and Outline Stroke\n * share it.\n *\n * Ported from ArtCraft (MIT OR Apache-2.0, see THIRD_PARTY_NOTICES.md):\n * - figcraft `crates/pathops/src/lib.rs` — `stroke_outline_of`: an inside stroke is a stroke of\n * twice the width intersected with the fill, an outside one twice the width minus the fill,\n * and only closed shapes have an inside (open paths stroke centred).\n * - vectorcraft `crates/effects/src/stroke/arrow.rs` — arrowhead shapes, sizes and insets (where\n * the stroke stops under each head), `tip` vs `extend` alignment and trimming the stroke by\n * arc length under the head.\n */\nimport type { Point } from '../canvas/types.js';\nimport {\n\tcontoursToPath,\n\tdistanceToBezierPath,\n\tpathToContours,\n\tpointInBezierPath,\n\tsegmentLength,\n\tsegmentTangent,\n\ttrimSegments,\n\ttype BezierContour,\n\ttype BezierPath,\n\ttype BezierSegment\n} from '../canvas/pathops/bezier.js';\nimport { pathBoolean, type PathOperandInput } from '../canvas/pathops/boolean.js';\nimport { outlineStroke } from '../canvas/pathops/stroke.js';\nimport type { VectorArrowhead, VectorStrokeAlign, VectorStyle, VectorWidthPoint, Vec2 } from './types.js';\nimport { nearestStrokePosition, variableStrokeOutline } from './varstroke.js';\nimport { isUniformWidthProfile, sanitizeWidthProfile, widthProfileAt, widthProfileMaxScale } from './width.js';\n\n/** Handle length that makes a cubic approximate a quarter circle. */\nconst KAPPA = 0.5522847498307936;\n/** Where the notch of the (notched) arrow sits, as a fraction of the head's length. */\nconst NOTCH = 0.7;\n\n/** One arrowhead: a filled outline (nonzero) painted with the stroke's paint. */\nexport interface VectorArrowheadShape {\n\tend: 'start' | 'end';\n\tkind: VectorArrowhead;\n\ttip: Vec2;\n\t/** Unit direction the head points in. */\n\tdir: Vec2;\n\t/** Distance from the tip back to where the stroke ends under the head. */\n\tinset: number;\n\tpath: BezierPath;\n}\n\n/** What the stroke of a path draws. */\nexport interface VectorStrokeParts {\n\t/** Where the stroke sits (`center` for open shapes, whatever the style says). */\n\talign: VectorStrokeAlign;\n\t/** The line the stroke follows: the outline, shortened under `tip`-aligned heads. */\n\tline: BezierPath;\n\t/** The stroke width to draw `line` with: twice the style's width for inside / outside (half is clipped away). */\n\tdrawWidth: number;\n\theads: VectorArrowheadShape[];\n}\n\n/** True when the path has subpaths and all of them are closed (only such shapes have an inside). */\nexport function isClosedBezierShape(path: BezierPath): boolean {\n\tconst contours = pathToContours(path).filter((c) => c.segments.length > 0);\n\treturn contours.length > 0 && contours.every((c) => c.closed);\n}\n\n/** The alignment a stroke is drawn with: the style's, or `center` for open shapes. */\nexport function effectiveStrokeAlign(style: Pick<VectorStyle, 'strokeAlign'>, closedShape: boolean): VectorStrokeAlign {\n\tconst a = style.strokeAlign ?? 'center';\n\treturn closedShape ? a : 'center';\n}\n\n/** The style's width profile, sanitised, or null when the stroke is uniform. */\nexport function strokeWidthProfileOf(style: Pick<VectorStyle, 'strokeWidthProfile'>): VectorWidthPoint[] | null {\n\tif (!style.strokeWidthProfile?.length) return null;\n\tconst p = sanitizeWidthProfile(style.strokeWidthProfile);\n\treturn isUniformWidthProfile(p) ? null : p;\n}\n\n/** True when the style asks for more than a plain centred stroke (an alignment, arrowheads or a width profile). */\nexport function hasStrokeExtras(style: VectorStyle): boolean {\n\treturn (style.strokeAlign ?? 'center') !== 'center' || !!style.startArrow || !!style.endArrow || !!strokeWidthProfileOf(style);\n}\n\n/**\n * The area of the stroke along `parts.line` before alignment clipping: SVG's stroke for a\n * uniform width, the variable-width outline (`variableStrokeOutline`) for a profiled one.\n */\nexport function vectorStrokeLineArea(parts: Pick<VectorStrokeParts, 'line' | 'drawWidth'>, style: VectorStyle, tolerance?: number): BezierPath {\n\tconst profile = strokeWidthProfileOf(style);\n\tconst dash = style.strokeDasharray?.length ? { dash: style.strokeDasharray } : {};\n\tconst join = style.strokeLinejoin ?? 'miter';\n\tconst cap = style.strokeLinecap ?? 'butt';\n\tif (profile) return variableStrokeOutline(parts.line, { width: parts.drawWidth, profile, join, cap, ...dash, ...(tolerance ? { tolerance } : {}) });\n\treturn outlineStroke(parts.line, { width: parts.drawWidth, join, cap, ...dash, ...(tolerance ? { tolerance } : {}) });\n}\n\nconst capExtent = (style: VectorStyle, width: number) => (style.strokeLinecap === 'round' || style.strokeLinecap === 'square' ? width / 2 : 0);\n\n/** The weight of a head: the stroke width times its scale (at least 0.25). A head is 4 weights long and wide. */\nexport function arrowheadWeight(style: VectorStyle, end: 'start' | 'end'): number {\n\tconst scale = end === 'start' ? style.startArrowScale : style.endArrowScale;\n\tconst s = typeof scale === 'number' && scale > 0 && Number.isFinite(scale) ? scale : 1;\n\treturn Math.max(0.25, (style.strokeWidth ?? 1) * s);\n}\n\n/** Distance from the tip where the stroke ends, for a stroke whose cap reaches `cap` past its end. */\nexport function arrowheadInset(kind: VectorArrowhead, hw: number, cap: number): number {\n\tconst l = 4 * hw;\n\tconst solid = (back: number) => Math.max(back / 2, cap);\n\tswitch (kind) {\n\t\tcase 'triangle':\n\t\tcase 'circle':\n\t\tcase 'square':\n\t\t\treturn solid(l);\n\t\tcase 'arrow':\n\t\t\treturn solid(NOTCH * l);\n\t\tcase 'bar':\n\t\t\treturn solid(0.75 * hw);\n\t\tcase 'open':\n\t\t\t// The inner corner of the chevron: arm / sin(half angle).\n\t\t\treturn Math.max((hw * Math.sqrt(l * l + (l * l) / 4)) / (l / 2), cap);\n\t}\n}\n\nconst v = (x: number, y: number): Vec2 => ({ x, y });\nconst plus = (a: Vec2, b: Vec2, k = 1): Vec2 => ({ x: a.x + b.x * k, y: a.y + b.y * k });\nconst unit = (a: Vec2): Vec2 => {\n\tconst l = Math.hypot(a.x, a.y);\n\treturn l > 0 ? { x: a.x / l, y: a.y / l } : { x: 1, y: 0 };\n};\n\nfunction polygon(pts: Vec2[]): BezierPath {\n\treturn [{ type: 'M', x: pts[0].x, y: pts[0].y }, ...pts.slice(1).map((p) => ({ type: 'L' as const, x: p.x, y: p.y })), { type: 'Z' }];\n}\n\nfunction circle(c: Vec2, r: number): BezierPath {\n\tconst k = r * KAPPA;\n\tconst { x, y } = c;\n\treturn [\n\t\t{ type: 'M', x: x + r, y },\n\t\t{ type: 'C', x1: x + r, y1: y + k, x2: x + k, y2: y + r, x, y: y + r },\n\t\t{ type: 'C', x1: x - k, y1: y + r, x2: x - r, y2: y + k, x: x - r, y },\n\t\t{ type: 'C', x1: x - r, y1: y - k, x2: x - k, y2: y - r, x, y: y - r },\n\t\t{ type: 'C', x1: x + k, y1: y - r, x2: x + r, y2: y - k, x: x + r, y },\n\t\t{ type: 'Z' }\n\t];\n}\n\n/** The outline of a `kind` head of weight `hw` with its tip at `tip`, pointing along unit `dir`. */\nexport function arrowheadPath(kind: VectorArrowhead, tip: Vec2, dir: Vec2, hw: number): BezierPath {\n\tconst n = v(-dir.y, dir.x);\n\tconst l = 4 * hw;\n\tconst half = l / 2;\n\tconst base = plus(tip, dir, -l);\n\tswitch (kind) {\n\t\tcase 'triangle':\n\t\t\treturn polygon([tip, plus(base, n, half), plus(base, n, -half)]);\n\t\tcase 'arrow':\n\t\t\treturn polygon([tip, plus(base, n, half), plus(tip, dir, -NOTCH * l), plus(base, n, -half)]);\n\t\tcase 'open': {\n\t\t\t// Arms `hw` thick from the tip to the base corners, cut square at their ends.\n\t\t\tconst t = hw;\n\t\t\tconst a = plus(base, n, half);\n\t\t\tconst b = plus(base, n, -half);\n\t\t\tconst ua = unit(plus(a, tip, -1));\n\t\t\tconst ub = unit(plus(b, tip, -1));\n\t\t\tconst na = v(-ua.y, ua.x);\n\t\t\tconst nb = v(ub.y, -ub.x);\n\t\t\tconst inner = plus(tip, dir, -(t * Math.hypot(a.x - tip.x, a.y - tip.y)) / half);\n\t\t\treturn polygon([tip, a, plus(a, na, t), inner, plus(b, nb, t), b]);\n\t\t}\n\t\tcase 'circle':\n\t\t\treturn circle(plus(tip, dir, -half), half);\n\t\tcase 'square':\n\t\t\treturn polygon([plus(tip, n, half), plus(base, n, half), plus(base, n, -half), plus(tip, n, -half)]);\n\t\tcase 'bar': {\n\t\t\tconst t = 0.75 * hw;\n\t\t\treturn polygon([plus(tip, n, half), plus(plus(tip, n, half), dir, -t), plus(plus(tip, n, -half), dir, -t), plus(tip, n, -half)]);\n\t\t}\n\t}\n}\n\nconst toVec = (p: Point): Vec2 => ({ x: p[0], y: p[1] });\nconst segLen = (s: BezierSegment) => segmentLength(s);\n\n/** The end point of a contour and the unit direction pointing out of it there. */\nfunction endOf(segs: readonly BezierSegment[], atStart: boolean): { p: Vec2; out: Vec2 } {\n\tconst long = (s: BezierSegment) => segLen(s) > 1e-9;\n\tif (atStart) {\n\t\tconst s = segs.find(long) ?? segs[0];\n\t\tconst t = segmentTangent(s, 0);\n\t\treturn { p: toVec(segs[0][0]), out: v(-t[0], -t[1]) };\n\t}\n\tconst s = [...segs].reverse().find(long) ?? segs[segs.length - 1];\n\tconst t = segmentTangent(s, 1);\n\tconst last = segs[segs.length - 1];\n\treturn { p: toVec(last[last.length - 1]), out: v(t[0], t[1]) };\n}\n\n/** The point `dist` along the contour from its start (or back from its end), if it is that long. */\nfunction pointAlong(segs: readonly BezierSegment[], fromStart: boolean, dist: number): Vec2 | null {\n\tconst order = fromStart ? segs : [...segs].reverse();\n\tlet acc = 0;\n\tfor (const s of order) {\n\t\tconst l = segLen(s);\n\t\tif (acc + l >= dist) {\n\t\t\tconst want = fromStart ? dist - acc : l - (dist - acc);\n\t\t\tconst pts = trimSegments([s], 0, want);\n\t\t\tconst p = pts.length ? pts[0][pts[0].length - 1] : s[0];\n\t\t\treturn toVec(p);\n\t\t}\n\t\tacc += l;\n\t}\n\treturn null;\n}\n\n/**\n * The stroke of `path` as `style` draws it: its alignment, the line it follows (shortened under\n * `tip`-aligned heads) and its arrowheads. Heads go on the start of the first subpath and the\n * end of the last one, when those are open.\n */\nexport function vectorStrokeParts(path: BezierPath, style: VectorStyle): VectorStrokeParts {\n\tconst width = style.strokeWidth ?? 1;\n\tconst contours = pathToContours(path).filter((c) => c.segments.length > 0);\n\tconst closedShape = contours.length > 0 && contours.every((c) => c.closed);\n\tconst align = effectiveStrokeAlign(style, closedShape);\n\tconst drawWidth = align === 'center' ? width : width * 2;\n\tconst heads: VectorArrowheadShape[] = [];\n\tif (!contours.length || (!style.startArrow && !style.endArrow)) return { align, line: path, drawWidth, heads };\n\tconst first = contours[0];\n\tconst last = contours[contours.length - 1];\n\tconst cap = capExtent(style, width);\n\tconst tipMode = style.arrowAlign === 'tip';\n\tconst trims = contours.map(() => [0, 0]);\n\tconst place = (end: 'start' | 'end', contour: BezierContour, ci: number) => {\n\t\tconst kind = end === 'start' ? style.startArrow : style.endArrow;\n\t\tif (!kind || contour.closed) return;\n\t\tconst hw = arrowheadWeight(style, end);\n\t\tconst inset = arrowheadInset(kind, hw, cap);\n\t\tconst atStart = end === 'start';\n\t\tconst { p, out } = endOf(contour.segments, atStart);\n\t\tlet tip: Vec2;\n\t\tlet dir: Vec2;\n\t\tif (tipMode) {\n\t\t\t// Point along the chord from where the stroke now ends to the end point.\n\t\t\tconst q = pointAlong(contour.segments, atStart, inset);\n\t\t\tconst d = q ? v(p.x - q.x, p.y - q.y) : null;\n\t\t\tdir = d && Math.hypot(d.x, d.y) > 1e-9 ? unit(d) : out;\n\t\t\ttip = p;\n\t\t\ttrims[ci][atStart ? 0 : 1] = inset;\n\t\t} else {\n\t\t\ttip = plus(p, out, inset);\n\t\t\tdir = out;\n\t\t}\n\t\theads.push({ end, kind, tip, dir, inset, path: arrowheadPath(kind, tip, dir, hw) });\n\t};\n\tplace('start', first, 0);\n\tplace('end', last, contours.length - 1);\n\tif (!tipMode || !heads.length) return { align, line: path, drawWidth, heads };\n\tconst trimmed: BezierContour[] = contours.map((c, i) => {\n\t\tconst [s0, s1] = trims[i];\n\t\tif (!s0 && !s1) return c;\n\t\tconst lengths = c.segments.map(segLen);\n\t\tconst total = lengths.reduce((a, b) => a + b, 0);\n\t\treturn { closed: false, segments: total - s1 > s0 ? trimSegments(c.segments, s0, total - s1, lengths) : [] };\n\t});\n\treturn { align, line: contoursToPath(trimmed), drawWidth, heads };\n}\n\n/**\n * The area the stroke paints, as one filled path: the outlined stroke (joins, caps and dashes\n * as SVG) clipped by the alignment (against the fill, read with the style's `fillRule`), plus\n * the arrowheads.\n */\nexport function vectorStrokeOutlinePath(path: BezierPath, style: VectorStyle): BezierPath {\n\tconst parts = vectorStrokeParts(path, style);\n\tconst stroke = vectorStrokeLineArea(parts, style);\n\tconst fill: PathOperandInput = { path, fillRule: style.fillRule ?? 'nonzero' };\n\tlet area = stroke;\n\tif (parts.align === 'inside') area = pathBoolean('intersection', [stroke, fill]).path;\n\telse if (parts.align === 'outside') area = pathBoolean('difference', [stroke, fill]).path;\n\tif (!parts.heads.length) return area;\n\treturn pathBoolean('union', [area, ...parts.heads.map((h) => h.path)]).path;\n}\n\n/**\n * Whether point `p` hits the stroke of `path` (`tolerance` added on every side): within half\n * the width of the outline for a centred stroke, within the whole width on the inside or the\n * outside of the fill for an aligned one, or on an arrowhead.\n */\nexport function hitTestVectorStroke(path: BezierPath, p: Vec2, style: VectorStyle, tolerance = 0): boolean {\n\tconst parts = vectorStrokeParts(path, style);\n\tconst point: Point = [p.x, p.y];\n\tconst width = style.strokeWidth ?? 1;\n\tfor (const h of parts.heads) {\n\t\tif (pointInBezierPath(h.path, point) || (tolerance > 0 && distanceToBezierPath(h.path, point) <= tolerance)) return true;\n\t}\n\tif (!parts.line.length) return false;\n\tconst profile = strokeWidthProfileOf(style);\n\tlet d: number;\n\tlet reach = width / 2;\n\tif (profile) {\n\t\t// The side width at the nearest point of the centre line (twice it when aligned).\n\t\tconst near = nearestStrokePosition(parts.line, point);\n\t\tif (!near) return false;\n\t\td = near.distance;\n\t\tconst w = widthProfileAt(profile, near.t);\n\t\treach = (width / 2) * (near.side === 'left' ? w.left : w.right);\n\t\tif (parts.align !== 'center') reach *= 2;\n\t\tconst atEnd = near.t <= 1e-9 || near.t >= 1 - 1e-9;\n\t\tif (atEnd && (style.strokeLinecap === 'round' || style.strokeLinecap === 'square') && d > reach) {\n\t\t\t// Past an open end the cap reaches as far as the width there.\n\t\t\treach = Math.max(reach, ((width / 2) * (w.left + w.right)) / 2);\n\t\t}\n\t} else {\n\t\td = distanceToBezierPath(parts.line, point);\n\t\tif (parts.align !== 'center') reach = width;\n\t}\n\tif (parts.align === 'center') return d <= reach + tolerance;\n\tif (d > reach + tolerance) return false;\n\tif (d <= tolerance) return true;\n\tconst inside = pointInBezierPath(path, point, style.fillRule ?? 'nonzero');\n\treturn parts.align === 'inside' ? inside : !inside;\n}\n\n/** How far the stroke can reach past the outline (for padding bounds and masks). */\nexport function vectorStrokeReach(style: VectorStyle): number {\n\tconst width = (style.strokeWidth ?? 1) * widthProfileMaxScale(strokeWidthProfileOf(style));\n\tconst align = style.strokeAlign ?? 'center';\n\tlet reach = align === 'center' ? width / 2 : align === 'outside' ? width : 0;\n\tif (style.strokeLinejoin !== 'round' && style.strokeLinejoin !== 'bevel') reach *= 4;\n\tfor (const end of ['start', 'end'] as const) {\n\t\tif (end === 'start' ? style.startArrow : style.endArrow) reach = Math.max(reach, 8 * arrowheadWeight(style, end) + width);\n\t}\n\treturn reach;\n}\n","/**\n * Vector path geometry: anchors and handles to Bézier paths and back, bounds, hit-testing,\n * affine transforms, segment splitting, anchor-type conversion and shape factories.\n */\nimport type { Point } from '../canvas/types.js';\nimport {\n\tbezierPathBounds,\n\tbezierPathToSvg,\n\ttransformBezierPath,\n\tdistanceToBezierPath,\n\tpointInBezierPath,\n\tsegmentNearest,\n\tsegmentPoint,\n\tsplitSegment,\n\ttoBezierPath,\n\ttype AffineMatrix,\n\ttype BezierPath,\n\ttype BezierPathInput\n} from '../canvas/pathops/bezier.js';\nimport { expandVectorCorners, setSubpathCorners } from './corners.js';\nimport { hitTestVectorStroke, vectorStrokeOutlinePath } from './stroke.js';\nimport { mirrorWidthProfile } from './width.js';\nimport type {\n\tVectorAnchor,\n\tVectorAnchorType,\n\tVectorCornerKind,\n\tVectorBounds,\n\tVectorDocument,\n\tVectorGroupNode,\n\tVectorNode,\n\tVectorPaint,\n\tVectorPathNode,\n\tVectorSubpath,\n\tVec2\n} from './types.js';\n\nexport type { AffineMatrix };\n\nconst EPS = 1e-9;\n\n// ---------------------------------------------------------------------------\n// Small helpers\n// ---------------------------------------------------------------------------\n\nexport const cloneAnchor = (a: VectorAnchor): VectorAnchor => ({\n\tx: a.x,\n\ty: a.y,\n\t...(a.in ? { in: { x: a.in.x, y: a.in.y } } : {}),\n\t...(a.out ? { out: { x: a.out.x, y: a.out.y } } : {}),\n\t...(a.type && a.type !== 'corner' ? { type: a.type } : {}),\n\t...(a.corner ? { corner: { ...a.corner } } : {})\n});\n\nexport const cloneSubpath = (s: VectorSubpath): VectorSubpath => ({ anchors: s.anchors.map(cloneAnchor), closed: s.closed });\n\n/** A deep copy of a node (ids kept). */\nexport function cloneVectorNode<T extends VectorNode>(node: T): T {\n\treturn JSON.parse(JSON.stringify(node)) as T;\n}\n\nexport function cloneVectorDocument(doc: VectorDocument): VectorDocument {\n\treturn JSON.parse(JSON.stringify(doc)) as VectorDocument;\n}\n\n/** True when the paint draws something (not `null`, `'none'`, `'transparent'` or empty). */\nexport function hasPaint(paint: VectorPaint | undefined): boolean {\n\tif (paint === undefined || paint === null) return false;\n\tif (typeof paint === 'string') {\n\t\tconst p = paint.trim().toLowerCase();\n\t\treturn p !== '' && p !== 'none' && p !== 'transparent';\n\t}\n\treturn true;\n}\n\nconst handleOf = (a: VectorAnchor, side: 'in' | 'out'): Vec2 => a[side] ?? { x: a.x, y: a.y };\nconst isOnAnchor = (a: VectorAnchor, h: Vec2 | null | undefined) => !h || (Math.abs(h.x - a.x) < EPS && Math.abs(h.y - a.y) < EPS);\n\n// ---------------------------------------------------------------------------\n// Anchors ↔ Bézier\n// ---------------------------------------------------------------------------\n\n/** Number of segments of a subpath (a closed one has a segment from the last anchor back to the first). */\nexport function subpathSegmentCount(sp: VectorSubpath): number {\n\tconst n = sp.anchors.length;\n\tif (n < 2) return 0;\n\treturn sp.closed ? n : n - 1;\n}\n\n/** Control points of segment `i` of a subpath: 2 for a line, 4 for a cubic. */\nexport function subpathSegment(sp: VectorSubpath, i: number): Point[] {\n\tconst a = sp.anchors[i];\n\tconst b = sp.anchors[(i + 1) % sp.anchors.length];\n\tif (isOnAnchor(a, a.out) && isOnAnchor(b, b.in)) return [[a.x, a.y], [b.x, b.y]];\n\tconst c1 = handleOf(a, 'out');\n\tconst c2 = handleOf(b, 'in');\n\treturn [[a.x, a.y], [c1.x, c1.y], [c2.x, c2.y], [b.x, b.y]];\n}\n\n/**\n * Absolute `M` / `L` / `C` / `Z` commands of subpaths, with live corners cut\n * (`expandVectorCorners`). Pass `{ corners: false }` for the stored anchors as they are.\n */\nexport function subpathsToBezier(subpaths: readonly VectorSubpath[], options: { corners?: boolean } = {}): BezierPath {\n\tconst out: BezierPath = [];\n\tfor (const sp of options.corners === false ? subpaths : expandVectorCorners(subpaths)) {\n\t\tif (sp.anchors.length === 0) continue;\n\t\tconst first = sp.anchors[0];\n\t\tout.push({ type: 'M', x: first.x, y: first.y });\n\t\tconst count = subpathSegmentCount(sp);\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst seg = subpathSegment(sp, i);\n\t\t\tif (sp.closed && i === count - 1 && seg.length === 2) break; // `Z` draws the closing line.\n\t\t\tif (seg.length === 2) out.push({ type: 'L', x: seg[1][0], y: seg[1][1] });\n\t\t\telse out.push({ type: 'C', x1: seg[1][0], y1: seg[1][1], x2: seg[2][0], y2: seg[2][1], x: seg[3][0], y: seg[3][1] });\n\t\t}\n\t\tif (sp.closed) out.push({ type: 'Z' });\n\t}\n\treturn out;\n}\n\n/** The node's outline as Bézier commands. Groups have none. */\nexport function vectorNodeToBezier(node: VectorNode): BezierPath {\n\treturn node.type === 'path' ? subpathsToBezier(node.subpaths) : [];\n}\n\n/** SVG path data (`d`) of a path node or subpaths. */\nexport function vectorPathData(input: VectorPathNode | readonly VectorSubpath[], precision = 3): string {\n\tconst subpaths = Array.isArray(input) ? (input as readonly VectorSubpath[]) : (input as VectorPathNode).subpaths;\n\treturn bezierPathToSvg(subpathsToBezier(subpaths), { precision });\n}\n\n/** Infers the anchor type from its handles. */\nexport function inferAnchorType(a: VectorAnchor): VectorAnchorType {\n\tif (isOnAnchor(a, a.in) || isOnAnchor(a, a.out)) return 'corner';\n\tconst ix = a.in!.x - a.x;\n\tconst iy = a.in!.y - a.y;\n\tconst ox = a.out!.x - a.x;\n\tconst oy = a.out!.y - a.y;\n\tconst li = Math.hypot(ix, iy);\n\tconst lo = Math.hypot(ox, oy);\n\tconst cross = (ix * oy - iy * ox) / (li * lo);\n\tconst dot = (ix * ox + iy * oy) / (li * lo);\n\tif (Math.abs(cross) > 1e-3 || dot > 0) return 'corner';\n\treturn Math.abs(li - lo) <= 1e-3 * Math.max(li, lo) ? 'symmetric' : 'smooth';\n}\n\n/**\n * Converts SVG path data or Bézier commands to editable subpaths. Quadratics become cubics,\n * arcs become cubics, a closing anchor that repeats the first one is merged into it, and\n * each anchor's type is inferred from its handles.\n */\nexport function bezierToSubpaths(input: BezierPathInput): VectorSubpath[] {\n\tconst path = toBezierPath(input);\n\tconst out: VectorSubpath[] = [];\n\tlet current: VectorSubpath | null = null;\n\tconst last = () => current!.anchors[current!.anchors.length - 1];\n\tfor (const cmd of path) {\n\t\tswitch (cmd.type) {\n\t\t\tcase 'M':\n\t\t\t\tcurrent = { anchors: [{ x: cmd.x, y: cmd.y }], closed: false };\n\t\t\t\tout.push(current);\n\t\t\t\tbreak;\n\t\t\tcase 'L':\n\t\t\t\tcurrent!.anchors.push({ x: cmd.x, y: cmd.y });\n\t\t\t\tbreak;\n\t\t\tcase 'Q': {\n\t\t\t\tconst p0 = last();\n\t\t\t\tp0.out = { x: p0.x + (2 / 3) * (cmd.x1 - p0.x), y: p0.y + (2 / 3) * (cmd.y1 - p0.y) };\n\t\t\t\tcurrent!.anchors.push({ x: cmd.x, y: cmd.y, in: { x: cmd.x + (2 / 3) * (cmd.x1 - cmd.x), y: cmd.y + (2 / 3) * (cmd.y1 - cmd.y) } });\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 'C':\n\t\t\t\tlast().out = { x: cmd.x1, y: cmd.y1 };\n\t\t\t\tcurrent!.anchors.push({ x: cmd.x, y: cmd.y, in: { x: cmd.x2, y: cmd.y2 } });\n\t\t\t\tbreak;\n\t\t\tcase 'Z': {\n\t\t\t\tif (!current) break;\n\t\t\t\tcurrent.closed = true;\n\t\t\t\tconst anchors = current.anchors;\n\t\t\t\tif (anchors.length > 1) {\n\t\t\t\t\tconst first = anchors[0];\n\t\t\t\t\tconst end = anchors[anchors.length - 1];\n\t\t\t\t\tif (Math.abs(end.x - first.x) < 1e-7 && Math.abs(end.y - first.y) < 1e-7) {\n\t\t\t\t\t\tif (end.in) first.in = end.in;\n\t\t\t\t\t\tanchors.pop();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrent = null;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tfor (const sp of out) {\n\t\tfor (const a of sp.anchors) {\n\t\t\tif (isOnAnchor(a, a.in)) delete a.in;\n\t\t\tif (isOnAnchor(a, a.out)) delete a.out;\n\t\t\tconst type = inferAnchorType(a);\n\t\t\tif (type !== 'corner') a.type = type;\n\t\t}\n\t}\n\treturn out.filter((sp) => sp.anchors.length > 0);\n}\n\n// ---------------------------------------------------------------------------\n// Tree helpers\n// ---------------------------------------------------------------------------\n\n/** Calls `fn` for every node, depth first, parents before children. */\nexport function walkVectorNodes(nodes: readonly VectorNode[], fn: (node: VectorNode, parent: VectorGroupNode | null, depth: number) => void): void {\n\tconst visit = (list: readonly VectorNode[], parent: VectorGroupNode | null, depth: number) => {\n\t\tfor (const node of list) {\n\t\t\tfn(node, parent, depth);\n\t\t\tif (node.type === 'group') visit(node.children, node, depth + 1);\n\t\t}\n\t};\n\tvisit(nodes, null, 0);\n}\n\n/** Finds a node by id anywhere in the tree. */\nexport function findVectorNode(nodes: readonly VectorNode[], id: string): VectorNode | undefined {\n\tfor (const node of nodes) {\n\t\tif (node.id === id) return node;\n\t\tif (node.type === 'group') {\n\t\t\tconst found = findVectorNode(node.children, id);\n\t\t\tif (found) return found;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** The list that contains node `id` (the root list or a group's children) and its index there. */\nexport function locateVectorNode(nodes: VectorNode[], id: string): { list: VectorNode[]; index: number; parent: VectorGroupNode | null } | null {\n\tconst search = (list: VectorNode[], parent: VectorGroupNode | null): ReturnType<typeof locateVectorNode> => {\n\t\tfor (let i = 0; i < list.length; i++) {\n\t\t\tconst node = list[i];\n\t\t\tif (node.id === id) return { list, index: i, parent };\n\t\t\tif (node.type === 'group') {\n\t\t\t\tconst found = search(node.children, node);\n\t\t\t\tif (found) return found;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t};\n\treturn search(nodes, null);\n}\n\n/** Every path node in the subtree (a path node itself, or a group's descendants). */\nexport function collectPathNodes(node: VectorNode): VectorPathNode[] {\n\tif (node.type === 'path') return [node];\n\tconst out: VectorPathNode[] = [];\n\twalkVectorNodes(node.children, (n) => {\n\t\tif (n.type === 'path') out.push(n);\n\t});\n\treturn out;\n}\n\n// ---------------------------------------------------------------------------\n// Bounds\n// ---------------------------------------------------------------------------\n\n/** The node's local → parent matrix (identity when it has no `transform`). */\nexport function nodeMatrix(node: VectorNode): AffineMatrix {\n\treturn node.transform ?? IDENTITY_MATRIX;\n}\n\n/** A path node's outline in the space `parent` maps to (default: its parent's space). */\nexport function vectorPathWorldBezier(node: VectorPathNode, parent: AffineMatrix = IDENTITY_MATRIX): BezierPath {\n\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\tconst path = subpathsToBezier(node.subpaths);\n\treturn isIdentityMatrix(m) ? path : transformBezierPath(path, m);\n}\n\n/**\n * Geometric bounds of a node (stroke width not included) in the space `parent` maps to —\n * by default the node's parent space, which for top-level nodes is the document. Null when\n * the node has no points.\n */\nexport function vectorNodeBounds(node: VectorNode, parent: AffineMatrix = IDENTITY_MATRIX): VectorBounds | null {\n\tif (node.type === 'group') {\n\t\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\t\treturn unionBounds(node.children.map((c) => vectorNodeBounds(c, m)));\n\t}\n\tconst b = bezierPathBounds(vectorPathWorldBezier(node, parent));\n\tif (!b) return null;\n\treturn { x: b.minX, y: b.minY, width: b.maxX - b.minX, height: b.maxY - b.minY };\n}\n\n/** The smallest box around all non-null boxes, or null. */\nexport function unionBounds(list: readonly (VectorBounds | null | undefined)[]): VectorBounds | null {\n\tlet minX = Infinity;\n\tlet minY = Infinity;\n\tlet maxX = -Infinity;\n\tlet maxY = -Infinity;\n\tfor (const b of list) {\n\t\tif (!b) continue;\n\t\tminX = Math.min(minX, b.x);\n\t\tminY = Math.min(minY, b.y);\n\t\tmaxX = Math.max(maxX, b.x + b.width);\n\t\tmaxY = Math.max(maxY, b.y + b.height);\n\t}\n\tif (minX === Infinity) return null;\n\treturn { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n}\n\n/** True when two boxes overlap (touching counts). */\nexport function boundsIntersect(a: VectorBounds, b: VectorBounds): boolean {\n\treturn a.x <= b.x + b.width && b.x <= a.x + a.width && a.y <= b.y + b.height && b.y <= a.y + a.height;\n}\n\n/** A box from two corners in any order. */\nexport function boundsFromPoints(a: Vec2, b: Vec2): VectorBounds {\n\treturn { x: Math.min(a.x, b.x), y: Math.min(a.y, b.y), width: Math.abs(b.x - a.x), height: Math.abs(b.y - a.y) };\n}\n\n// ---------------------------------------------------------------------------\n// Hit-testing\n// ---------------------------------------------------------------------------\n\n/**\n * Whether `p` hits a node: inside its fill (when it has one), on its stroke as drawn (its\n * alignment and arrowheads respected) or within `tolerance` of either. A group is hit when\n * any visible child is.\n */\nexport function hitTestVectorNode(node: VectorNode, p: Vec2, tolerance = 0, parent: AffineMatrix = IDENTITY_MATRIX): boolean {\n\tif (node.visible === false) return false;\n\tif (node.type === 'group') {\n\t\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\t\treturn node.children.some((c) => hitTestVectorNode(c, p, tolerance, m));\n\t}\n\tconst path = vectorPathWorldBezier(node, parent);\n\tif (path.length === 0) return false;\n\tconst point: Point = [p.x, p.y];\n\tif (hasPaint(node.fill) && pointInBezierPath(path, point, node.fillRule ?? 'nonzero')) return true;\n\tif (hasPaint(node.stroke)) return hitTestVectorStroke(path, p, node, tolerance);\n\treturn distanceToBezierPath(path, point) <= tolerance;\n}\n\n/**\n * The area a path node's stroke paints (alignment, caps, joins, dashes and arrowheads\n * included), as a filled path in the space `parent` maps to. Empty without a stroke.\n */\nexport function vectorStrokeOutline(node: VectorPathNode, parent: AffineMatrix = IDENTITY_MATRIX): BezierPath {\n\tif (!hasPaint(node.stroke) || !((node.strokeWidth ?? 1) > 0)) return [];\n\treturn vectorStrokeOutlinePath(vectorPathWorldBezier(node, parent), node);\n}\n\n/** The topmost node hit by `p` (skipping hidden and locked ones), or null. */\nexport function hitTestVectorNodes(nodes: readonly VectorNode[], p: Vec2, tolerance = 0): VectorNode | null {\n\tfor (let i = nodes.length - 1; i >= 0; i--) {\n\t\tconst node = nodes[i];\n\t\tif (node.visible === false || node.locked) continue;\n\t\tif (hitTestVectorNode(node, p, tolerance)) return node;\n\t}\n\treturn null;\n}\n\nexport interface NearestSegment {\n\tsubpath: number;\n\tsegment: number;\n\t/** Curve parameter 0–1 on the segment. */\n\tt: number;\n\tpoint: Vec2;\n\tdistance: number;\n}\n\n/** The closest point on any segment of a path node (`p` and the result are in the node's own space). */\nexport function nearestSegment(node: VectorPathNode, p: Vec2): NearestSegment | null {\n\tlet best: NearestSegment | null = null;\n\tnode.subpaths.forEach((sp, s) => {\n\t\tconst count = subpathSegmentCount(sp);\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst seg = subpathSegment(sp, i);\n\t\t\tconst hit = segmentNearest(seg, [p.x, p.y]);\n\t\t\tif (!best || hit.distance < best.distance) {\n\t\t\t\tconst pt = segmentPoint(seg, hit.t);\n\t\t\t\tbest = { subpath: s, segment: i, t: hit.t, point: { x: pt[0], y: pt[1] }, distance: hit.distance };\n\t\t\t}\n\t\t}\n\t});\n\treturn best;\n}\n\n// ---------------------------------------------------------------------------\n// Affine transforms\n// ---------------------------------------------------------------------------\n\nexport const IDENTITY_MATRIX: AffineMatrix = [1, 0, 0, 1, 0, 0];\n\n/** `a` then `b` (apply `a` first). */\nexport function multiplyMatrices(a: AffineMatrix, b: AffineMatrix): AffineMatrix {\n\tconst [a0, a1, a2, a3, a4, a5] = a;\n\tconst [b0, b1, b2, b3, b4, b5] = b;\n\treturn [b0 * a0 + b2 * a1, b1 * a0 + b3 * a1, b0 * a2 + b2 * a3, b1 * a2 + b3 * a3, b0 * a4 + b2 * a5 + b4, b1 * a4 + b3 * a5 + b5];\n}\n\nexport const translateMatrix = (dx: number, dy: number): AffineMatrix => [1, 0, 0, 1, dx, dy];\n\nexport function scaleMatrix(sx: number, sy: number, origin: Vec2 = { x: 0, y: 0 }): AffineMatrix {\n\treturn [sx, 0, 0, sy, origin.x - sx * origin.x, origin.y - sy * origin.y];\n}\n\n/** Rotation by `degrees` clockwise (y points down) around `origin`. */\nexport function rotateMatrix(degrees: number, origin: Vec2 = { x: 0, y: 0 }): AffineMatrix {\n\tconst r = (degrees * Math.PI) / 180;\n\tconst cos = Math.cos(r);\n\tconst sin = Math.sin(r);\n\treturn [cos, sin, -sin, cos, origin.x - cos * origin.x + sin * origin.y, origin.y - sin * origin.x - cos * origin.y];\n}\n\nexport function applyMatrix(m: AffineMatrix, p: Vec2): Vec2 {\n\treturn { x: m[0] * p.x + m[2] * p.y + m[4], y: m[1] * p.x + m[3] * p.y + m[5] };\n}\n\nexport function isIdentityMatrix(m: AffineMatrix, eps = 1e-12): boolean {\n\treturn Math.abs(m[0] - 1) < eps && Math.abs(m[1]) < eps && Math.abs(m[2]) < eps && Math.abs(m[3] - 1) < eps && Math.abs(m[4]) < eps && Math.abs(m[5]) < eps;\n}\n\n/** The inverse matrix (the identity for a singular one). */\nexport function invertMatrix(m: AffineMatrix): AffineMatrix {\n\tconst [a, b, c, d, e, f] = m;\n\tconst det = a * d - b * c;\n\tif (!det || !Number.isFinite(det)) return IDENTITY_MATRIX;\n\treturn [d / det, -b / det, -c / det, a / det, (c * f - d * e) / det, (b * e - a * f) / det];\n}\n\n/** Applies only the linear part (for directions and offsets). */\nexport function applyMatrixLinear(m: AffineMatrix, v: Vec2): Vec2 {\n\treturn { x: m[0] * v.x + m[2] * v.y, y: m[1] * v.x + m[3] * v.y };\n}\n\n/**\n * The rotation of a matrix in degrees, clockwise (y down), in (−180, 180]. For a mirrored\n * matrix it is the rotation left after undoing a horizontal flip, so a flipped rotated shape\n * keeps its angle.\n */\nexport function matrixRotation(m: AffineMatrix): number {\n\tconst [a, b, c, d] = m;\n\tconst mirrored = a * d - b * c < 0;\n\tconst deg = ((mirrored ? Math.atan2(-b - c, d - a) : Math.atan2(b - c, a + d)) * 180) / Math.PI;\n\treturn Math.abs(deg) < 1e-9 ? 0 : deg;\n}\n\n/**\n * Splits `m` into `residual` then `rigid` (`m = residual × rigid` in apply order): `rigid` is\n * the nearest rotation plus the translation, `residual` the linear rest (scale, skew,\n * reflection). An unrotated `m` gives an identity `rigid` and everything in `residual`.\n */\nexport function decomposeRigid(m: AffineMatrix): { rigid: AffineMatrix; residual: AffineMatrix } {\n\tconst [a, b, c, d, e, f] = m;\n\tconst deg = matrixRotation(m);\n\tif (deg === 0) return { rigid: IDENTITY_MATRIX, residual: m };\n\tconst r = (deg * Math.PI) / 180;\n\tconst cos = Math.cos(r);\n\tconst sin = Math.sin(r);\n\treturn {\n\t\trigid: [cos, sin, -sin, cos, e, f],\n\t\tresidual: [cos * a + sin * b, -sin * a + cos * b, cos * c + sin * d, -sin * c + cos * d, 0, 0]\n\t};\n}\n\n/** Every anchor and handle mapped through `m` (the node's own `transform` is untouched). */\nfunction bakeIntoGeometry<T extends VectorNode>(node: T, m: AffineMatrix): T {\n\tif (isIdentityMatrix(m)) return node;\n\tif (node.type === 'group') return { ...node, children: node.children.map((c) => transformVectorNode(c, m)) };\n\tconst path = node as VectorPathNode;\n\t// A mirror swaps the sides of a variable-width stroke (the path still runs the same way).\n\tconst mirrored = m[0] * m[3] - m[1] * m[2] < 0 && path.strokeWidthProfile?.length;\n\treturn {\n\t\t...path,\n\t\t...(mirrored ? { strokeWidthProfile: mirrorWidthProfile(path.strokeWidthProfile!) } : {}),\n\t\tsubpaths: path.subpaths.map((sp) => ({\n\t\t\tclosed: sp.closed,\n\t\t\tanchors: sp.anchors.map((a) => {\n\t\t\t\tconst p = applyMatrix(m, a);\n\t\t\t\tconst next: VectorAnchor = { x: p.x, y: p.y };\n\t\t\t\tif (a.in) next.in = applyMatrix(m, a.in);\n\t\t\t\tif (a.out) next.out = applyMatrix(m, a.out);\n\t\t\t\tif (a.type) next.type = a.type;\n\t\t\t\tif (a.corner) next.corner = { ...a.corner };\n\t\t\t\treturn next;\n\t\t\t})\n\t\t}))\n\t} as T;\n}\n\n/**\n * A copy of the node moved by `m`, given in its parent's space. The node's rotation and\n * translation go to its rigid `transform`; scale and skew are baked into its anchors (or its\n * children), so the result draws exactly as `m` says. Stroke widths are kept.\n */\nexport function transformVectorNode<T extends VectorNode>(node: T, m: AffineMatrix): T {\n\tconst total = multiplyMatrices(nodeMatrix(node), m);\n\tconst { rigid, residual } = decomposeRigid(total);\n\tconst { transform: _old, ...rest } = node as VectorNode;\n\tconst baked = bakeIntoGeometry(rest as T, residual);\n\treturn isIdentityMatrix(rigid) ? baked : ({ ...baked, transform: rigid } as T);\n}\n\n/** The node's rotation in degrees (from its `transform` and its ancestors' when `parent` is given). */\nexport function vectorNodeRotation(node: VectorNode, parent: AffineMatrix = IDENTITY_MATRIX): number {\n\treturn matrixRotation(multiplyMatrices(nodeMatrix(node), parent));\n}\n\n/** The local → document matrix of node `id` (ancestors' transforms included), or null. */\nexport function vectorWorldMatrix(nodes: readonly VectorNode[], id: string): AffineMatrix | null {\n\tconst search = (list: readonly VectorNode[], parent: AffineMatrix): AffineMatrix | null => {\n\t\tfor (const n of list) {\n\t\t\tconst m = multiplyMatrices(nodeMatrix(n), parent);\n\t\t\tif (n.id === id) return m;\n\t\t\tif (n.type === 'group') {\n\t\t\t\tconst found = search(n.children, m);\n\t\t\t\tif (found) return found;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t};\n\treturn search(nodes, IDENTITY_MATRIX);\n}\n\n/** The parent space → document matrix of node `id` (identity for top-level nodes), or null. */\nexport function vectorParentMatrix(nodes: readonly VectorNode[], id: string): AffineMatrix | null {\n\tconst node = findVectorNode(nodes, id);\n\tconst world = vectorWorldMatrix(nodes, id);\n\tif (!node || !world) return null;\n\treturn multiplyMatrices(invertMatrix(nodeMatrix(node)), world);\n}\n\n// ---------------------------------------------------------------------------\n// Anchor editing\n// ---------------------------------------------------------------------------\n\n/** Moves an anchor and its handles by (dx, dy). */\nexport function translateAnchor(a: VectorAnchor, dx: number, dy: number): VectorAnchor {\n\tconst next = cloneAnchor(a);\n\tnext.x += dx;\n\tnext.y += dy;\n\tif (next.in) next.in = { x: next.in.x + dx, y: next.in.y + dy };\n\tif (next.out) next.out = { x: next.out.x + dx, y: next.out.y + dy };\n\treturn next;\n}\n\n/**\n * Moves one handle to `pos`, keeping the other in line for `smooth` anchors and mirrored for\n * `symmetric` ones. With `breakHandles` the anchor becomes a `corner` and only this handle moves.\n */\nexport function moveAnchorHandle(a: VectorAnchor, side: 'in' | 'out', pos: Vec2, breakHandles = false): VectorAnchor {\n\tconst next = cloneAnchor(a);\n\tnext[side] = { x: pos.x, y: pos.y };\n\tconst other = side === 'in' ? 'out' : 'in';\n\tconst type = breakHandles ? 'corner' : (a.type ?? 'corner');\n\tif (breakHandles) delete next.type;\n\tconst dx = pos.x - a.x;\n\tconst dy = pos.y - a.y;\n\tconst len = Math.hypot(dx, dy);\n\tif (type === 'symmetric') next[other] = { x: a.x - dx, y: a.y - dy };\n\telse if (type === 'smooth' && len > EPS) {\n\t\tconst o = a[other];\n\t\tconst olen = o ? Math.hypot(o.x - a.x, o.y - a.y) : len;\n\t\tnext[other] = { x: a.x - (dx / len) * olen, y: a.y - (dy / len) * olen };\n\t}\n\tif (isOnAnchor(next, next.in)) delete next.in;\n\tif (isOnAnchor(next, next.out)) delete next.out;\n\treturn next;\n}\n\n/**\n * Converts anchor `index` of a subpath. `corner` removes both handles; `smooth` and\n * `symmetric` keep existing handles in line, or add handles a third of the way to the\n * neighbours along the line between them.\n */\nexport function convertAnchor(sp: VectorSubpath, index: number, type: VectorAnchorType): VectorSubpath {\n\tconst anchors = sp.anchors.map(cloneAnchor);\n\tconst a = anchors[index];\n\tif (!a) return { anchors, closed: sp.closed };\n\tif (type === 'corner') {\n\t\tdelete a.in;\n\t\tdelete a.out;\n\t\tdelete a.type;\n\t\treturn { anchors, closed: sp.closed };\n\t}\n\tconst n = anchors.length;\n\tconst prev = index > 0 ? anchors[index - 1] : sp.closed ? anchors[n - 1] : null;\n\tconst next = index < n - 1 ? anchors[index + 1] : sp.closed ? anchors[0] : null;\n\tlet dir: Vec2 | null = null;\n\tlet lenIn = 0;\n\tlet lenOut = 0;\n\tif (!isOnAnchor(a, a.out)) dir = { x: a.out!.x - a.x, y: a.out!.y - a.y };\n\telse if (!isOnAnchor(a, a.in)) dir = { x: a.x - a.in!.x, y: a.y - a.in!.y };\n\telse if (prev && next) dir = { x: next.x - prev.x, y: next.y - prev.y };\n\telse if (next) dir = { x: next.x - a.x, y: next.y - a.y };\n\telse if (prev) dir = { x: a.x - prev.x, y: a.y - prev.y };\n\tif (!dir || Math.hypot(dir.x, dir.y) < EPS) return { anchors, closed: sp.closed };\n\tconst dl = Math.hypot(dir.x, dir.y);\n\tconst ux = dir.x / dl;\n\tconst uy = dir.y / dl;\n\tlenIn = a.in && !isOnAnchor(a, a.in) ? Math.hypot(a.in.x - a.x, a.in.y - a.y) : prev ? Math.hypot(prev.x - a.x, prev.y - a.y) / 3 : 0;\n\tlenOut = a.out && !isOnAnchor(a, a.out) ? Math.hypot(a.out.x - a.x, a.out.y - a.y) : next ? Math.hypot(next.x - a.x, next.y - a.y) / 3 : 0;\n\tif (type === 'symmetric') lenIn = lenOut = (lenIn + lenOut) / 2 || Math.max(lenIn, lenOut);\n\tif (lenIn > EPS) a.in = { x: a.x - ux * lenIn, y: a.y - uy * lenIn };\n\tif (lenOut > EPS) a.out = { x: a.x + ux * lenOut, y: a.y + uy * lenOut };\n\ta.type = type;\n\treturn { anchors, closed: sp.closed };\n}\n\n/**\n * Inserts an anchor on segment `segment` at parameter `t` without changing the curve's\n * shape (de Casteljau split). Returns the new subpath and the new anchor's index.\n */\nexport function insertAnchor(sp: VectorSubpath, segment: number, t: number): { subpath: VectorSubpath; index: number } {\n\tconst anchors = sp.anchors.map(cloneAnchor);\n\tconst n = anchors.length;\n\tconst ia = segment;\n\tconst ib = (segment + 1) % n;\n\tconst seg = subpathSegment(sp, segment);\n\tconst [left, right] = splitSegment(seg, t);\n\tconst mid = left[left.length - 1];\n\tconst anchor: VectorAnchor = { x: mid[0], y: mid[1] };\n\tif (seg.length === 4) {\n\t\tanchors[ia].out = { x: left[1][0], y: left[1][1] };\n\t\tanchor.in = { x: left[2][0], y: left[2][1] };\n\t\tanchor.out = { x: right[1][0], y: right[1][1] };\n\t\tanchor.type = 'smooth';\n\t\tanchors[ib].in = { x: right[2][0], y: right[2][1] };\n\t\tfor (const k of [ia, ib]) if (isOnAnchor(anchors[k], anchors[k].in)) delete anchors[k].in;\n\t\tfor (const k of [ia, ib]) if (isOnAnchor(anchors[k], anchors[k].out)) delete anchors[k].out;\n\t}\n\tconst index = segment + 1;\n\tanchors.splice(index, 0, anchor);\n\treturn { subpath: { anchors, closed: sp.closed }, index };\n}\n\n/**\n * Removes anchors from a subpath. An open subpath with fewer than 2 anchors left, or a\n * closed one with fewer than 2, is returned with whatever remains (callers drop empty ones).\n */\nexport function removeAnchors(sp: VectorSubpath, indices: readonly number[]): VectorSubpath {\n\tconst drop = new Set(indices);\n\treturn { anchors: sp.anchors.filter((_, i) => !drop.has(i)).map(cloneAnchor), closed: sp.closed };\n}\n\n/** Reverses a subpath's direction (handles swap sides). */\nexport function reverseSubpath(sp: VectorSubpath): VectorSubpath {\n\tconst anchors = sp.anchors\n\t\t.slice()\n\t\t.reverse()\n\t\t.map((a) => {\n\t\t\tconst next: VectorAnchor = { x: a.x, y: a.y };\n\t\t\tif (a.out) next.in = { ...a.out };\n\t\t\tif (a.in) next.out = { ...a.in };\n\t\t\tif (a.type) next.type = a.type;\n\t\t\tif (a.corner) next.corner = { ...a.corner };\n\t\t\treturn next;\n\t\t});\n\treturn { anchors, closed: sp.closed };\n}\n\n// ---------------------------------------------------------------------------\n// Shape factories\n// ---------------------------------------------------------------------------\n\n/** Handle length that makes a cubic approximate a quarter circle. */\nexport const KAPPA = 0.5522847498307936;\n\n/**\n * A rectangle. A `radius` becomes a live corner on each of its four anchors (drawn round, and\n * clamped to half the shorter side, when the path is turned into curves).\n */\nexport function rectSubpath(b: VectorBounds, radius = 0, kind?: VectorCornerKind): VectorSubpath {\n\tconst { x, y, width: w, height: h } = b;\n\tconst sp: VectorSubpath = { anchors: [{ x, y }, { x: x + w, y }, { x: x + w, y: y + h }, { x, y: y + h }], closed: true };\n\treturn radius > 0 ? setSubpathCorners(sp, radius, kind) : sp;\n}\n\n/** An ellipse inscribed in a box (four smooth anchors). */\nexport function ellipseSubpath(b: VectorBounds): VectorSubpath {\n\tconst rx = b.width / 2;\n\tconst ry = b.height / 2;\n\tconst cx = b.x + rx;\n\tconst cy = b.y + ry;\n\tconst kx = rx * KAPPA;\n\tconst ky = ry * KAPPA;\n\treturn {\n\t\tclosed: true,\n\t\tanchors: [\n\t\t\t{ x: cx, y: cy - ry, in: { x: cx - kx, y: cy - ry }, out: { x: cx + kx, y: cy - ry }, type: 'symmetric' },\n\t\t\t{ x: cx + rx, y: cy, in: { x: cx + rx, y: cy - ky }, out: { x: cx + rx, y: cy + ky }, type: 'symmetric' },\n\t\t\t{ x: cx, y: cy + ry, in: { x: cx + kx, y: cy + ry }, out: { x: cx - kx, y: cy + ry }, type: 'symmetric' },\n\t\t\t{ x: cx - rx, y: cy, in: { x: cx - rx, y: cy + ky }, out: { x: cx - rx, y: cy - ky }, type: 'symmetric' }\n\t\t]\n\t};\n}\n\n/** A regular polygon inscribed in a box, first vertex at the top. */\nexport function polygonSubpath(b: VectorBounds, sides = 6): VectorSubpath {\n\tconst n = Math.max(3, Math.round(sides));\n\tconst cx = b.x + b.width / 2;\n\tconst cy = b.y + b.height / 2;\n\tconst anchors: VectorAnchor[] = [];\n\tfor (let i = 0; i < n; i++) {\n\t\tconst t = -Math.PI / 2 + (i * 2 * Math.PI) / n;\n\t\tanchors.push({ x: cx + (Math.cos(t) * b.width) / 2, y: cy + (Math.sin(t) * b.height) / 2 });\n\t}\n\treturn { anchors, closed: true };\n}\n\n/** A star inscribed in a box, first point at the top. `innerRatio` is inner / outer radius. */\nexport function starSubpath(b: VectorBounds, points = 5, innerRatio = 0.5): VectorSubpath {\n\tconst n = Math.max(3, Math.round(points));\n\tconst cx = b.x + b.width / 2;\n\tconst cy = b.y + b.height / 2;\n\tconst anchors: VectorAnchor[] = [];\n\tfor (let i = 0; i < n * 2; i++) {\n\t\tconst t = -Math.PI / 2 + (i * Math.PI) / n;\n\t\tconst r = i % 2 === 0 ? 1 : innerRatio;\n\t\tanchors.push({ x: cx + (Math.cos(t) * r * b.width) / 2, y: cy + (Math.sin(t) * r * b.height) / 2 });\n\t}\n\treturn { anchors, closed: true };\n}\n\n/** A straight open line. */\nexport function lineSubpath(a: Vec2, b: Vec2): VectorSubpath {\n\treturn { anchors: [{ x: a.x, y: a.y }, { x: b.x, y: b.y }], closed: false };\n}\n\n/** Rounds every coordinate to `precision` decimals (stable JSON and SVG output). */\nexport function roundSubpaths(subpaths: readonly VectorSubpath[], precision = 3): VectorSubpath[] {\n\tconst f = 10 ** precision;\n\tconst r = (n: number) => Math.round(n * f) / f;\n\tconst rp = (p: Vec2) => ({ x: r(p.x), y: r(p.y) });\n\treturn subpaths.map((sp) => ({\n\t\tclosed: sp.closed,\n\t\tanchors: sp.anchors.map((a) => ({ ...cloneAnchor(a), x: r(a.x), y: r(a.y), ...(a.in ? { in: rp(a.in) } : {}), ...(a.out ? { out: rp(a.out) } : {}) }))\n\t}));\n}\n","/**\n * SVG export and import for vector documents. Import is DOM-free (works in Node and\n * workers): it reads `<svg>`, `<g>`, `<path>`, `<rect>`, `<circle>`, `<ellipse>`, `<line>`,\n * `<polyline>`, `<polygon>`, linear / radial gradients, presentation attributes, `style`\n * declarations and `transform`s. Text, images, clip paths, masks, filters and `<use>` are\n * skipped.\n *\n * Live corners export as their cut outline plus `data-vector-d` (the sharp path) and\n * `data-vector-corners` (the radii), so the editor's own SVG imports with editable corners.\n * Inside / outside strokes, which SVG cannot express, export (after vectorcraft\n * `crates/svg/src/lib.rs`, MIT OR Apache-2.0) as a `<g data-vector-path>` holding the fill, a\n * stroke of twice the width clipped to the shape (inside) or masked by it (outside), and the\n * arrowheads as filled outlines; import merges such a group back into one path. A variable-width\n * stroke exports as its filled outline (`data-vector-part=\"stroke-outline\"`) with the profile\n * and line style kept in `data-vector-width-profile` / `data-vector-stroke-*` attributes.\n */\nimport { bezierPathToSvg } from '../canvas/pathops/bezier.js';\nimport { bezierPathBounds } from '../canvas/pathops/bezier.js';\nimport { hasStrokeExtras, strokeWidthProfileOf, vectorStrokeLineArea, vectorStrokeOutlinePath, vectorStrokeParts, vectorStrokeReach } from './stroke.js';\nimport { sanitizeWidthProfile } from './width.js';\nimport { gradientToSvgDef, type CanvasGradientDef, type GradientStop, type SvgGradientDef } from '../canvas/gradient.js';\nimport { formatNumber } from '../canvas/shapeGeometry.js';\nimport {\n\tbezierToSubpaths,\n\tellipseSubpath,\n\thasPaint,\n\tIDENTITY_MATRIX,\n\tlineSubpath,\n\tmultiplyMatrices,\n\trectSubpath,\n\trotateMatrix,\n\tscaleMatrix,\n\tsubpathsToBezier,\n\ttransformVectorNode,\n\ttranslateMatrix,\n\tvectorPathData,\n\ttype AffineMatrix\n} from './geometry.js';\nimport {\n\tVECTOR_ARROWHEADS,\n\tVECTOR_CORNER_KINDS,\n\ttype VectorArrowhead,\n\ttype VectorCornerKind,\n\ttype VectorDocument,\n\ttype VectorFillRule,\n\ttype VectorGroupNode,\n\ttype VectorLineCap,\n\ttype VectorLineJoin,\n\ttype VectorWidthPoint,\n\ttype VectorNode,\n\ttype VectorPaint,\n\ttype VectorBounds,\n\ttype VectorPathNode,\n\ttype VectorStrokeAlign,\n\ttype VectorSubpath\n} from './types.js';\n\n// ---------------------------------------------------------------------------\n// Export\n// ---------------------------------------------------------------------------\n\nexport interface VectorSvgExportOptions {\n\t/** Decimal places for coordinates (default 3). */\n\tprecision?: number;\n\t/** Draw `document.background` as a full-size rect (default true). */\n\tbackground?: boolean;\n\t/** Include hidden nodes with `display=\"none\"` instead of leaving them out (default false). */\n\tincludeHidden?: boolean;\n\t/** Prefix for gradient ids (default `vg-`), to keep ids unique when several SVGs share a page. */\n\tidPrefix?: string;\n\t/** Indent nested elements (default true). */\n\tpretty?: boolean;\n\t/**\n\t * How strokes with an inside / outside alignment or arrowheads are written: `clip` (default)\n\t * as a double-width stroke clipped or masked by the shape plus filled heads, `outline` as\n\t * one filled path of the area the stroke paints.\n\t */\n\tstrokes?: 'clip' | 'outline';\n}\n\n/** `data-vector-corners`: the live corners of subpaths as `subpath.index:radius[:kind]`, space separated. */\nexport function vectorCornersAttribute(subpaths: readonly VectorSubpath[], precision = 3): string {\n\tconst out: string[] = [];\n\tsubpaths.forEach((sp, s) =>\n\t\tsp.anchors.forEach((a, i) => {\n\t\t\tif (!a.corner || !(a.corner.radius > 0)) return;\n\t\t\tout.push(`${s}.${i}:${formatNumber(a.corner.radius, precision)}${a.corner.kind && a.corner.kind !== 'round' ? `:${a.corner.kind}` : ''}`);\n\t\t})\n\t);\n\treturn out.join(' ');\n}\n\n/** Puts `data-vector-corners` back on subpaths (malformed entries are ignored). */\nexport function applyVectorCornersAttribute(subpaths: VectorSubpath[], value: string): VectorSubpath[] {\n\tfor (const item of value.trim().split(/\\s+/)) {\n\t\tconst m = /^(\\d+)\\.(\\d+):([\\d.eE+-]+)(?::([a-z]+))?$/.exec(item);\n\t\tif (!m) continue;\n\t\tconst a = subpaths[+m[1]]?.anchors[+m[2]];\n\t\tconst radius = parseFloat(m[3]);\n\t\tif (!a || !(radius > 0)) continue;\n\t\tconst kind = VECTOR_CORNER_KINDS.includes(m[4] as VectorCornerKind) ? (m[4] as VectorCornerKind) : undefined;\n\t\ta.corner = { radius, ...(kind && kind !== 'round' ? { kind } : {}) };\n\t}\n\treturn subpaths;\n}\n\nconst escapeAttr = (value: string) => value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n\n/** A paint as an SVG attribute value plus the gradient def it needs (if any). */\nexport function vectorPaintToSvg(paint: VectorPaint | undefined, gradientId: string): { value: string; gradient: SvgGradientDef | null } {\n\tif (!hasPaint(paint)) return { value: 'none', gradient: null };\n\tif (typeof paint === 'string') return { value: paint, gradient: null };\n\treturn { value: `url(#${gradientId})`, gradient: gradientToSvgDef(paint as CanvasGradientDef, gradientId) };\n}\n\n/** The parts of an aligned or arrowed stroke (see `VectorRenderPath.strokeParts`). */\nexport interface VectorRenderStrokeParts {\n\talign: VectorStrokeAlign;\n\t/** The line the stroke follows (shortened under `tip`-aligned heads). */\n\td: string;\n\t/** Width to draw it with: twice the stroke width when aligned, half of it being clipped away. */\n\twidth: number;\n\t/**\n\t * A variable-width stroke: the area to fill with `stroke` (nonzero) instead of stroking `d`,\n\t * clipped or masked like the stroke would be.\n\t */\n\toutline?: string;\n\t/**\n\t * Inside: a `<clipPath id>` holding the shape (`d`, `clip-rule` = `fillRule`). Outside: a\n\t * `<mask id>` in user space over `bounds`, white with the shape (`d`) in black.\n\t */\n\tclip: { kind: 'clip' | 'mask'; id: string; bounds: VectorBounds } | null;\n\t/** Arrowhead outlines (fill with `stroke`, nonzero). */\n\theads: string[];\n}\n\n/** Stroke parts are recomputed only when the node (or the id / precision asked for) changes. */\nconst partsCache = new WeakMap<VectorPathNode, { clipId: string; precision: number; parts: VectorRenderStrokeParts | undefined }>();\n\n/** The stroke parts of a path whose stroke needs more than one element, in its own space (undefined otherwise). */\nexport function vectorStrokeSvgParts(node: VectorPathNode, clipId: string, precision = 3): VectorRenderStrokeParts | undefined {\n\tif (!hasPaint(node.stroke) || !hasStrokeExtras(node)) return undefined;\n\tconst hit = partsCache.get(node);\n\tif (hit && hit.clipId === clipId && hit.precision === precision) return hit.parts;\n\tconst parts = computeStrokeSvgParts(node, clipId, precision);\n\tpartsCache.set(node, { clipId, precision, parts });\n\treturn parts;\n}\n\nfunction computeStrokeSvgParts(node: VectorPathNode, clipId: string, precision: number): VectorRenderStrokeParts | undefined {\n\tconst path = subpathsToBezier(node.subpaths);\n\tconst parts = vectorStrokeParts(path, node);\n\tconst profiled = !!strokeWidthProfileOf(node);\n\tif (parts.align === 'center' && !parts.heads.length && !profiled) return undefined;\n\tlet clip: VectorRenderStrokeParts['clip'] = null;\n\tif (parts.align !== 'center') {\n\t\tconst b = bezierPathBounds(path);\n\t\tconst pad = vectorStrokeReach(node) + 1;\n\t\tconst bounds = b ? { x: round2(b.minX - pad), y: round2(b.minY - pad), width: round2(b.maxX - b.minX + 2 * pad), height: round2(b.maxY - b.minY + 2 * pad) } : { x: 0, y: 0, width: 0, height: 0 };\n\t\tclip = { kind: parts.align === 'inside' ? 'clip' : 'mask', id: clipId, bounds };\n\t}\n\treturn {\n\t\talign: parts.align,\n\t\td: bezierPathToSvg(parts.line, { precision }),\n\t\twidth: parts.drawWidth,\n\t\t...(profiled && (node.strokeWidth ?? 1) > 0 ? { outline: bezierPathToSvg(vectorStrokeLineArea(parts, node), { precision }) } : {}),\n\t\tclip,\n\t\theads: parts.heads.map((h) => bezierPathToSvg(h.path, { precision }))\n\t};\n}\n\n/** A width profile as a data attribute: `t,left,right` points separated by `;`. */\nexport function widthProfileToAttribute(points: readonly VectorWidthPoint[], precision = 4): string {\n\treturn points.map((p) => [p.t, p.left, p.right].map((n) => formatNumber(n, precision)).join(',')).join(';');\n}\n\n/** Reads `widthProfileToAttribute` output (invalid points are dropped). */\nexport function widthProfileFromAttribute(value: string | undefined): VectorWidthPoint[] {\n\tif (!value) return [];\n\treturn sanitizeWidthProfile(\n\t\tvalue.split(';').map((part) => {\n\t\t\tconst [t, left, right] = part.split(',').map((n) => parseFloat(n));\n\t\t\treturn { t, left, right: Number.isFinite(right) ? right : left };\n\t\t})\n\t);\n}\n\nconst round2 = (n: number) => Math.round(n * 100) / 100;\n\nfunction gradientMarkup(def: SvgGradientDef): string {\n\tconst tag = def.type === 'radial' ? 'radialGradient' : 'linearGradient';\n\tconst attrs = Object.entries(def.attrs)\n\t\t.map(([k, v]) => ` ${k}=\"${escapeAttr(String(v))}\"`)\n\t\t.join('');\n\tconst stops = def.stops\n\t\t.map((s) => `<stop offset=\"${s.offset}\" stop-color=\"${escapeAttr(s.stopColor)}\"${s.stopOpacity !== undefined ? ` stop-opacity=\"${s.stopOpacity}\"` : ''}/>`)\n\t\t.join('');\n\treturn `<${tag} id=\"${escapeAttr(def.id)}\"${attrs}>${stops}</${tag}>`;\n}\n\n/** Serializes a vector document as a standalone SVG string. */\nexport function vectorDocumentToSvg(doc: VectorDocument, options: VectorSvgExportOptions = {}): string {\n\tconst precision = options.precision ?? 3;\n\tconst prefix = options.idPrefix ?? 'vg-';\n\tconst pretty = options.pretty !== false;\n\tconst defs: string[] = [];\n\tconst lines: string[] = [];\n\tconst num = (n: number) => formatNumber(n, precision);\n\tconst indent = (depth: number) => (pretty ? ' '.repeat(depth) : '');\n\n\tconst common = (node: VectorNode) => {\n\t\tlet out = ` id=\"${escapeAttr(node.id)}\"`;\n\t\tif (node.transform) out += ` transform=\"matrix(${node.transform.map((n) => formatNumber(n, 6)).join(' ')})\"`;\n\t\tif (node.opacity !== undefined && node.opacity < 1) out += ` opacity=\"${num(node.opacity)}\"`;\n\t\tif (node.visible === false) out += ` display=\"none\"`;\n\t\treturn out;\n\t};\n\n\tconst emit = (node: VectorNode, depth: number) => {\n\t\tif (node.visible === false && !options.includeHidden) return;\n\t\tif (node.type === 'group') {\n\t\t\tlines.push(`${indent(depth)}<g${common(node)}>`);\n\t\t\tfor (const child of node.children) emit(child, depth + 1);\n\t\t\tlines.push(`${indent(depth)}</g>`);\n\t\t\treturn;\n\t\t}\n\t\tconst fill = vectorPaintToSvg(node.fill, `${prefix}fill-${node.id}`);\n\t\tconst stroke = vectorPaintToSvg(node.stroke, `${prefix}stroke-${node.id}`);\n\t\tif (fill.gradient) defs.push(gradientMarkup(fill.gradient));\n\t\tif (stroke.gradient) defs.push(gradientMarkup(stroke.gradient));\n\t\tconst d = vectorPathData(node, precision);\n\t\tconst corners = vectorCornersAttribute(node.subpaths, precision);\n\t\tconst live = corners ? ` data-vector-d=\"${bezierPathToSvg(subpathsToBezier(node.subpaths, { corners: false }), { precision })}\" data-vector-corners=\"${corners}\"` : '';\n\t\tconst fillAttrs = ` fill=\"${escapeAttr(fill.value)}\"${node.fillRule === 'evenodd' ? ` fill-rule=\"evenodd\"` : ''}`;\n\t\tconst lineAttrs = (width: number) => {\n\t\t\tlet out = ` stroke=\"${escapeAttr(stroke.value)}\" stroke-width=\"${num(width)}\"`;\n\t\t\tif (node.strokeLinecap && node.strokeLinecap !== 'butt') out += ` stroke-linecap=\"${node.strokeLinecap}\"`;\n\t\t\tif (node.strokeLinejoin && node.strokeLinejoin !== 'miter') out += ` stroke-linejoin=\"${node.strokeLinejoin}\"`;\n\t\t\tif (node.strokeDasharray?.length) out += ` stroke-dasharray=\"${node.strokeDasharray.map(num).join(' ')}\"`;\n\t\t\treturn out;\n\t\t};\n\t\tconst parts = stroke.value !== 'none' ? vectorStrokeSvgParts(node, `${prefix}clip-${node.id}`, precision) : undefined;\n\t\tif (!parts) {\n\t\t\tlines.push(`${indent(depth)}<path${common(node)} d=\"${d}\"${fillAttrs}${stroke.value !== 'none' ? lineAttrs(node.strokeWidth ?? 1) : ''}${live}/>`);\n\t\t\treturn;\n\t\t}\n\t\t// The stroke options SVG has no attribute for, kept for import.\n\t\tlet data = ` data-vector-path=\"\" data-vector-stroke-width=\"${num(node.strokeWidth ?? 1)}\"`;\n\t\tif (parts.align !== 'center') data += ` data-vector-stroke-align=\"${parts.align}\"`;\n\t\tif (node.startArrow) data += ` data-vector-start-arrow=\"${node.startArrow}\"`;\n\t\tif (node.endArrow) data += ` data-vector-end-arrow=\"${node.endArrow}\"`;\n\t\tif (node.arrowAlign && node.arrowAlign !== 'extend') data += ` data-vector-arrow-align=\"${node.arrowAlign}\"`;\n\t\tif (node.startArrowScale !== undefined && node.startArrowScale !== 1) data += ` data-vector-start-arrow-scale=\"${num(node.startArrowScale)}\"`;\n\t\tif (node.endArrowScale !== undefined && node.endArrowScale !== 1) data += ` data-vector-end-arrow-scale=\"${num(node.endArrowScale)}\"`;\n\t\tconst profile = strokeWidthProfileOf(node);\n\t\tif (profile) {\n\t\t\t// Drawn as a filled outline: keep the line style the outline was built with.\n\t\t\tdata += ` data-vector-width-profile=\"${widthProfileToAttribute(profile)}\"`;\n\t\t\tif (node.strokeLinecap && node.strokeLinecap !== 'butt') data += ` data-vector-stroke-linecap=\"${node.strokeLinecap}\"`;\n\t\t\tif (node.strokeLinejoin && node.strokeLinejoin !== 'miter') data += ` data-vector-stroke-linejoin=\"${node.strokeLinejoin}\"`;\n\t\t\tif (node.strokeDasharray?.length) data += ` data-vector-stroke-dasharray=\"${node.strokeDasharray.map(num).join(' ')}\"`;\n\t\t}\n\t\tlines.push(`${indent(depth)}<g${common(node)}${data}>`);\n\t\tlines.push(`${indent(depth + 1)}<path data-vector-part=\"fill\" d=\"${d}\"${fillAttrs}${live}/>`);\n\t\tif (options.strokes === 'outline') {\n\t\t\tconst area = bezierPathToSvg(vectorStrokeOutlinePath(subpathsToBezier(node.subpaths), node), { precision });\n\t\t\tlines.push(`${indent(depth + 1)}<path data-vector-part=\"stroke-outline\" d=\"${area}\" fill=\"${escapeAttr(stroke.value)}\"/>`);\n\t\t} else {\n\t\t\tlet clip = '';\n\t\t\tif (parts.clip) {\n\t\t\t\tconst rule = node.fillRule === 'evenodd' ? 'evenodd' : 'nonzero';\n\t\t\t\tconst id = escapeAttr(parts.clip.id);\n\t\t\t\tif (parts.clip.kind === 'clip') {\n\t\t\t\t\tdefs.push(`<clipPath id=\"${id}\"><path d=\"${d}\" clip-rule=\"${rule}\"/></clipPath>`);\n\t\t\t\t\tclip = ` clip-path=\"url(#${id})\"`;\n\t\t\t\t} else {\n\t\t\t\t\tconst b = parts.clip.bounds;\n\t\t\t\t\tconst box = `x=\"${num(b.x)}\" y=\"${num(b.y)}\" width=\"${num(b.width)}\" height=\"${num(b.height)}\"`;\n\t\t\t\t\tdefs.push(`<mask id=\"${id}\" maskUnits=\"userSpaceOnUse\" ${box}><rect ${box} fill=\"#fff\"/><path d=\"${d}\" fill=\"#000\" fill-rule=\"${rule}\"/></mask>`);\n\t\t\t\t\tclip = ` mask=\"url(#${id})\"`;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (parts.outline !== undefined) lines.push(`${indent(depth + 1)}<path data-vector-part=\"stroke-outline\" d=\"${parts.outline}\" fill=\"${escapeAttr(stroke.value)}\"${clip}/>`);\n\t\t\telse lines.push(`${indent(depth + 1)}<path data-vector-part=\"stroke\" d=\"${parts.d}\" fill=\"none\"${lineAttrs(parts.width)}${clip}/>`);\n\t\t\tfor (const h of parts.heads) lines.push(`${indent(depth + 1)}<path data-vector-part=\"head\" d=\"${h}\" fill=\"${escapeAttr(stroke.value)}\"/>`);\n\t\t}\n\t\tlines.push(`${indent(depth)}</g>`);\n\t};\n\n\tfor (const node of doc.nodes) emit(node, 1);\n\tconst w = num(doc.width);\n\tconst h = num(doc.height);\n\tconst nl = pretty ? '\\n' : '';\n\tconst out = [`<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${w}\" height=\"${h}\" viewBox=\"0 0 ${w} ${h}\">`];\n\tif (defs.length) out.push(`${indent(1)}<defs>${defs.join('')}</defs>`);\n\tif (doc.background && options.background !== false && hasPaint(doc.background)) {\n\t\tout.push(`${indent(1)}<rect width=\"${w}\" height=\"${h}\" fill=\"${escapeAttr(doc.background)}\"/>`);\n\t}\n\tout.push(...lines, '</svg>');\n\treturn out.join(nl);\n}\n\n// ---------------------------------------------------------------------------\n// Import\n// ---------------------------------------------------------------------------\n\nexport interface VectorSvgImportOptions {\n\t/** Makes ids for elements without a usable `id` (default `node-1`, `node-2`, …). */\n\tcreateId?: () => string;\n}\n\ninterface Element {\n\tname: string;\n\tattrs: Record<string, string>;\n\tchildren: Element[];\n}\n\n/** A tiny non-validating XML reader: elements and attributes only. */\nfunction parseXml(source: string): Element | null {\n\tconst text = source\n\t\t.replace(/<!--[\\s\\S]*?-->/g, '')\n\t\t.replace(/<\\?[\\s\\S]*?\\?>/g, '')\n\t\t.replace(/<!\\[CDATA\\[[\\s\\S]*?\\]\\]>/g, '')\n\t\t.replace(/<!DOCTYPE[^>[]*(\\[[\\s\\S]*?\\])?\\s*>/gi, '');\n\tconst root: Element = { name: '#root', attrs: {}, children: [] };\n\tconst stack: Element[] = [root];\n\tconst tag = /<(\\/?)([A-Za-z_][\\w:.-]*)((?:\\s+[^\\s=/>]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s>]+))?)*)\\s*(\\/?)>/g;\n\tconst attr = /([^\\s=/>]+)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s>]+)))?/g;\n\tlet m: RegExpExecArray | null;\n\twhile ((m = tag.exec(text))) {\n\t\tconst [, closing, rawName, rawAttrs, selfClosing] = m;\n\t\tconst name = rawName.replace(/^svg:/, '');\n\t\tif (closing) {\n\t\t\tfor (let i = stack.length - 1; i > 0; i--) {\n\t\t\t\tif (stack[i].name === name) {\n\t\t\t\t\tstack.length = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst attrs: Record<string, string> = {};\n\t\tlet a: RegExpExecArray | null;\n\t\tattr.lastIndex = 0;\n\t\twhile ((a = attr.exec(rawAttrs))) attrs[a[1]] = decodeEntities(a[2] ?? a[3] ?? a[4] ?? '');\n\t\tconst el: Element = { name, attrs, children: [] };\n\t\tstack[stack.length - 1].children.push(el);\n\t\tif (!selfClosing) stack.push(el);\n\t}\n\tconst find = (el: Element): Element | null => {\n\t\tif (el.name === 'svg') return el;\n\t\tfor (const c of el.children) {\n\t\t\tconst f = find(c);\n\t\t\tif (f) return f;\n\t\t}\n\t\treturn null;\n\t};\n\treturn find(root);\n}\n\nfunction decodeEntities(s: string): string {\n\treturn s\n\t\t.replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCodePoint(parseInt(h, 16)))\n\t\t.replace(/&#(\\d+);/g, (_, d) => String.fromCodePoint(parseInt(d, 10)))\n\t\t.replace(/&quot;/g, '\"')\n\t\t.replace(/&apos;/g, \"'\")\n\t\t.replace(/&lt;/g, '<')\n\t\t.replace(/&gt;/g, '>')\n\t\t.replace(/&amp;/g, '&');\n}\n\nconst numberList = (s: string | undefined): number[] =>\n\t(s ?? '')\n\t\t.trim()\n\t\t.split(/[\\s,]+|(?=-)(?<![eE])/)\n\t\t.filter(Boolean)\n\t\t.map(Number)\n\t\t.filter((n) => Number.isFinite(n));\n\nconst length = (s: string | undefined, fallback = 0): number => {\n\tif (s === undefined) return fallback;\n\tconst n = parseFloat(s);\n\treturn Number.isFinite(n) ? n : fallback;\n};\n\n/** Parses an SVG `transform` attribute into one matrix. */\nexport function parseSvgTransform(value: string | undefined): AffineMatrix {\n\tlet m: AffineMatrix = IDENTITY_MATRIX;\n\tif (!value) return m;\n\tconst re = /(matrix|translate|scale|rotate|skewX|skewY)\\s*\\(([^)]*)\\)/g;\n\tlet t: RegExpExecArray | null;\n\twhile ((t = re.exec(value))) {\n\t\tconst n = numberList(t[2]);\n\t\tlet step: AffineMatrix = IDENTITY_MATRIX;\n\t\tswitch (t[1]) {\n\t\t\tcase 'matrix':\n\t\t\t\tif (n.length >= 6) step = [n[0], n[1], n[2], n[3], n[4], n[5]];\n\t\t\t\tbreak;\n\t\t\tcase 'translate':\n\t\t\t\tstep = translateMatrix(n[0] ?? 0, n[1] ?? 0);\n\t\t\t\tbreak;\n\t\t\tcase 'scale':\n\t\t\t\tstep = scaleMatrix(n[0] ?? 1, n[1] ?? n[0] ?? 1);\n\t\t\t\tbreak;\n\t\t\tcase 'rotate':\n\t\t\t\tstep = rotateMatrix(n[0] ?? 0, { x: n[1] ?? 0, y: n[2] ?? 0 });\n\t\t\t\tbreak;\n\t\t\tcase 'skewX':\n\t\t\t\tstep = [1, 0, Math.tan(((n[0] ?? 0) * Math.PI) / 180), 1, 0, 0];\n\t\t\t\tbreak;\n\t\t\tcase 'skewY':\n\t\t\t\tstep = [1, Math.tan(((n[0] ?? 0) * Math.PI) / 180), 0, 1, 0, 0];\n\t\t\t\tbreak;\n\t\t}\n\t\t// SVG lists apply right to left: `translate(…) rotate(…)` rotates first.\n\t\tm = multiplyMatrices(step, m);\n\t}\n\treturn m;\n}\n\ninterface InheritedStyle {\n\tfill: string;\n\tstroke: string;\n\tstrokeWidth: string;\n\tstrokeLinecap?: string;\n\tstrokeLinejoin?: string;\n\tstrokeDasharray?: string;\n\tfillRule?: string;\n}\n\nconst STYLE_KEYS: Record<string, keyof InheritedStyle> = {\n\tfill: 'fill',\n\tstroke: 'stroke',\n\t'stroke-width': 'strokeWidth',\n\t'stroke-linecap': 'strokeLinecap',\n\t'stroke-linejoin': 'strokeLinejoin',\n\t'stroke-dasharray': 'strokeDasharray',\n\t'fill-rule': 'fillRule'\n};\n\nfunction readStyle(el: Element, parent: InheritedStyle): InheritedStyle {\n\tconst out = { ...parent };\n\tfor (const [attr, key] of Object.entries(STYLE_KEYS)) if (el.attrs[attr] !== undefined) out[key] = el.attrs[attr].trim();\n\tfor (const decl of (el.attrs.style ?? '').split(';')) {\n\t\tconst i = decl.indexOf(':');\n\t\tif (i < 0) continue;\n\t\tconst key = STYLE_KEYS[decl.slice(0, i).trim()];\n\t\tif (key) out[key] = decl.slice(i + 1).replace(/!important/, '').trim();\n\t}\n\treturn out;\n}\n\nfunction readStops(el: Element): GradientStop[] {\n\treturn el.children\n\t\t.filter((c) => c.name === 'stop')\n\t\t.map((c) => {\n\t\t\tconst style = Object.fromEntries(\n\t\t\t\t(c.attrs.style ?? '')\n\t\t\t\t\t.split(';')\n\t\t\t\t\t.map((d) => d.split(':').map((s) => s.trim()))\n\t\t\t\t\t.filter((d) => d.length === 2)\n\t\t\t);\n\t\t\tconst raw = c.attrs.offset ?? '0';\n\t\t\tconst offset = raw.endsWith('%') ? parseFloat(raw) / 100 : parseFloat(raw);\n\t\t\tconst opacity = style['stop-opacity'] ?? c.attrs['stop-opacity'];\n\t\t\treturn {\n\t\t\t\toffset: Number.isFinite(offset) ? Math.max(0, Math.min(1, offset)) : 0,\n\t\t\t\tcolor: style['stop-color'] ?? c.attrs['stop-color'] ?? '#000',\n\t\t\t\t...(opacity !== undefined ? { opacity: parseFloat(opacity) } : {})\n\t\t\t};\n\t\t});\n}\n\nconst fraction = (s: string | undefined, fallback: number) => {\n\tif (s === undefined) return fallback;\n\tconst n = parseFloat(s);\n\tif (!Number.isFinite(n)) return fallback;\n\treturn s.trim().endsWith('%') ? n / 100 : n;\n};\n\nfunction collectGradients(el: Element, raw: Map<string, Element>) {\n\tif ((el.name === 'linearGradient' || el.name === 'radialGradient') && el.attrs.id) raw.set(el.attrs.id, el);\n\tfor (const c of el.children) collectGradients(c, raw);\n}\n\nfunction resolveGradient(id: string, raw: Map<string, Element>, seen = new Set<string>()): CanvasGradientDef | null {\n\tconst el = raw.get(id);\n\tif (!el || seen.has(id)) return null;\n\tseen.add(id);\n\tlet stops = readStops(el);\n\tconst href = el.attrs.href ?? el.attrs['xlink:href'];\n\tif (!stops.length && href?.startsWith('#')) stops = resolveGradient(href.slice(1), raw, seen)?.stops ?? [];\n\tif (!stops.length) return null;\n\tif (el.name === 'radialGradient') {\n\t\treturn { type: 'radial', cx: fraction(el.attrs.cx, 0.5), cy: fraction(el.attrs.cy, 0.5), r: fraction(el.attrs.r, 0.5), stops };\n\t}\n\tconst x1 = fraction(el.attrs.x1, 0);\n\tconst y1 = fraction(el.attrs.y1, 0);\n\tconst x2 = fraction(el.attrs.x2, 1);\n\tconst y2 = fraction(el.attrs.y2, 0);\n\t// CSS angle: 0° points up, clockwise.\n\tconst angle = Math.round(((Math.atan2(x2 - x1, -(y2 - y1)) * 180) / Math.PI + 360) % 360);\n\treturn { type: 'linear', angle, stops };\n}\n\n/** Parses SVG markup into a vector document. Throws when there is no `<svg>` element. */\nexport function parseVectorSvg(svg: string, options: VectorSvgImportOptions = {}): VectorDocument {\n\tconst root = parseXml(svg);\n\tif (!root) throw new Error('The markup has no <svg> element.');\n\tlet counter = 0;\n\tconst usedIds = new Set<string>();\n\tconst createId = options.createId ?? (() => `node-${++counter}`);\n\tconst idFor = (el: Element) => {\n\t\tconst id = el.attrs.id;\n\t\tif (id && !usedIds.has(id)) {\n\t\t\tusedIds.add(id);\n\t\t\treturn id;\n\t\t}\n\t\tlet next = createId();\n\t\twhile (usedIds.has(next)) next = createId();\n\t\tusedIds.add(next);\n\t\treturn next;\n\t};\n\n\tconst rawGradients = new Map<string, Element>();\n\tcollectGradients(root, rawGradients);\n\tconst paint = (value: string): VectorPaint => {\n\t\tconst v = value.trim();\n\t\tconst url = /^url\\(\\s*['\"]?#([^'\")\\s]+)['\"]?\\s*\\)/.exec(v);\n\t\tif (url) return resolveGradient(url[1], rawGradients) ?? null;\n\t\tif (v === 'none' || v === '') return null;\n\t\treturn v;\n\t};\n\n\tconst viewBox = numberList(root.attrs.viewBox);\n\tconst width = viewBox.length === 4 ? viewBox[2] : length(root.attrs.width, 300);\n\tconst height = viewBox.length === 4 ? viewBox[3] : length(root.attrs.height, 150);\n\tconst rootMatrix: AffineMatrix = viewBox.length === 4 ? translateMatrix(-viewBox[0], -viewBox[1]) : IDENTITY_MATRIX;\n\n\tconst SKIP = new Set(['defs', 'clipPath', 'mask', 'symbol', 'style', 'title', 'desc', 'metadata', 'pattern', 'marker', 'filter', 'text', 'image', 'use', 'linearGradient', 'radialGradient', 'script', 'foreignObject']);\n\n\tconst shapeOf = (el: Element): VectorSubpath[] | null => {\n\t\tconst a = el.attrs;\n\t\tswitch (el.name) {\n\t\t\tcase 'path': {\n\t\t\t\t// Our own export: the sharp path and its live corners.\n\t\t\t\tif (a['data-vector-d'] && a['data-vector-corners']) {\n\t\t\t\t\tconst sharp = bezierToSubpaths(a['data-vector-d']);\n\t\t\t\t\tif (sharp.length) return applyVectorCornersAttribute(sharp, a['data-vector-corners']);\n\t\t\t\t}\n\t\t\t\treturn a.d ? bezierToSubpaths(a.d) : null;\n\t\t\t}\n\t\t\tcase 'rect': {\n\t\t\t\tconst w = length(a.width);\n\t\t\t\tconst h = length(a.height);\n\t\t\t\tif (w <= 0 || h <= 0) return null;\n\t\t\t\tconst r = length(a.rx ?? a.ry, 0);\n\t\t\t\treturn [rectSubpath({ x: length(a.x), y: length(a.y), width: w, height: h }, r)];\n\t\t\t}\n\t\t\tcase 'circle': {\n\t\t\t\tconst r = length(a.r);\n\t\t\t\tif (r <= 0) return null;\n\t\t\t\tconst cx = length(a.cx);\n\t\t\t\tconst cy = length(a.cy);\n\t\t\t\treturn [ellipseSubpath({ x: cx - r, y: cy - r, width: 2 * r, height: 2 * r })];\n\t\t\t}\n\t\t\tcase 'ellipse': {\n\t\t\t\tconst rx = length(a.rx);\n\t\t\t\tconst ry = length(a.ry);\n\t\t\t\tif (rx <= 0 || ry <= 0) return null;\n\t\t\t\treturn [ellipseSubpath({ x: length(a.cx) - rx, y: length(a.cy) - ry, width: 2 * rx, height: 2 * ry })];\n\t\t\t}\n\t\t\tcase 'line':\n\t\t\t\treturn [lineSubpath({ x: length(a.x1), y: length(a.y1) }, { x: length(a.x2), y: length(a.y2) })];\n\t\t\tcase 'polyline':\n\t\t\tcase 'polygon': {\n\t\t\t\tconst n = numberList(a.points);\n\t\t\t\tif (n.length < 4) return null;\n\t\t\t\tconst anchors = [];\n\t\t\t\tfor (let i = 0; i + 1 < n.length; i += 2) anchors.push({ x: n[i], y: n[i + 1] });\n\t\t\t\treturn [{ anchors, closed: el.name === 'polygon' }];\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t};\n\n\tconst strokeStyle = (s: InheritedStyle): Partial<VectorPathNode> => ({\n\t\t...(s.strokeWidth ? { strokeWidth: length(s.strokeWidth, 1) } : {}),\n\t\t...(s.strokeLinecap ? { strokeLinecap: s.strokeLinecap as VectorLineCap } : {}),\n\t\t...(s.strokeLinejoin ? { strokeLinejoin: s.strokeLinejoin as VectorLineJoin } : {}),\n\t\t...(s.strokeDasharray && s.strokeDasharray !== 'none' ? { strokeDasharray: numberList(s.strokeDasharray) } : {}),\n\t\t...(s.fillRule === 'evenodd' ? { fillRule: 'evenodd' as VectorFillRule } : {})\n\t});\n\n\t/** A node mapped by `m` (scale and skew baked in, stroke width scaled). */\n\tconst placed = (node: VectorPathNode, m: AffineMatrix): VectorPathNode => {\n\t\tif (m === IDENTITY_MATRIX) return node;\n\t\tconst next = transformVectorNode(node, m);\n\t\tconst strokeScale = Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]));\n\t\tif (hasPaint(next.stroke) && strokeScale > 0 && Math.abs(strokeScale - 1) > 1e-9) next.strokeWidth = (next.strokeWidth ?? 1) * strokeScale;\n\t\treturn next;\n\t};\n\n\t/**\n\t * A `<g data-vector-path>` from our own export (an aligned or arrowed stroke drawn in parts)\n\t * as the one path it came from: the fill part's outline and fill, the stroke part's paint and\n\t * line style, and the options the group's data attributes keep.\n\t */\n\tconst mergedPath = (g: Element, style: InheritedStyle, m: AffineMatrix, meta: Partial<VectorPathNode>): VectorPathNode | null => {\n\t\tconst part = (name: string) => g.children.find((c) => c.name === 'path' && c.attrs['data-vector-part'] === name);\n\t\tconst fillEl = part('fill');\n\t\tconst subpaths = fillEl ? shapeOf(fillEl) : null;\n\t\tif (!fillEl || !subpaths?.length) return null;\n\t\tconst a = g.attrs;\n\t\tconst fs = readStyle(fillEl, style);\n\t\tconst strokeEl = part('stroke');\n\t\tconst outlineEl = part('stroke-outline');\n\t\tconst ss = strokeEl ? readStyle(strokeEl, style) : null;\n\t\tconst width = length(a['data-vector-stroke-width'], ss ? length(ss.strokeWidth, 1) : 1);\n\t\tconst arrow = (v: string | undefined) => (VECTOR_ARROWHEADS.includes(v as VectorArrowhead) ? (v as VectorArrowhead) : undefined);\n\t\tconst scale = (v: string | undefined) => {\n\t\t\tconst n = v === undefined ? NaN : parseFloat(v);\n\t\t\treturn n > 0 ? n : undefined;\n\t\t};\n\t\tconst align = a['data-vector-stroke-align'];\n\t\tconst profile = widthProfileFromAttribute(a['data-vector-width-profile']);\n\t\tconst kept = (key: string, values: readonly string[]) => (values.includes(a[key]) ? a[key] : undefined);\n\t\tconst keptCap = kept('data-vector-stroke-linecap', ['round', 'square']) as VectorLineCap | undefined;\n\t\tconst keptJoin = kept('data-vector-stroke-linejoin', ['round', 'bevel']) as VectorLineJoin | undefined;\n\t\tconst keptDash = a['data-vector-stroke-dasharray'] ? numberList(a['data-vector-stroke-dasharray']) : undefined;\n\t\tconst node: VectorPathNode = {\n\t\t\tid: idFor(g),\n\t\t\ttype: 'path',\n\t\t\t...meta,\n\t\t\tsubpaths,\n\t\t\tfill: paint(fs.fill),\n\t\t\tstroke: ss ? paint(ss.stroke) : outlineEl ? paint(readStyle(outlineEl, style).fill) : null,\n\t\t\t...(ss ? strokeStyle(ss) : {}),\n\t\t\t...(fs.fillRule === 'evenodd' ? { fillRule: 'evenodd' as VectorFillRule } : {}),\n\t\t\tstrokeWidth: width,\n\t\t\t...(align === 'inside' || align === 'outside' ? { strokeAlign: align } : {}),\n\t\t\t...(arrow(a['data-vector-start-arrow']) ? { startArrow: arrow(a['data-vector-start-arrow']) } : {}),\n\t\t\t...(arrow(a['data-vector-end-arrow']) ? { endArrow: arrow(a['data-vector-end-arrow']) } : {}),\n\t\t\t...(a['data-vector-arrow-align'] === 'tip' ? { arrowAlign: 'tip' as const } : {}),\n\t\t\t...(scale(a['data-vector-start-arrow-scale']) ? { startArrowScale: scale(a['data-vector-start-arrow-scale']) } : {}),\n\t\t\t...(scale(a['data-vector-end-arrow-scale']) ? { endArrowScale: scale(a['data-vector-end-arrow-scale']) } : {}),\n\t\t\t...(profile.length ? { strokeWidthProfile: profile } : {}),\n\t\t\t...(keptCap ? { strokeLinecap: keptCap } : {}),\n\t\t\t...(keptJoin ? { strokeLinejoin: keptJoin } : {}),\n\t\t\t...(keptDash?.length ? { strokeDasharray: keptDash } : {})\n\t\t};\n\t\treturn placed(node, m);\n\t};\n\n\tconst visit = (el: Element, style: InheritedStyle, matrix: AffineMatrix): VectorNode[] => {\n\t\tconst out: VectorNode[] = [];\n\t\tfor (const child of el.children) {\n\t\t\tif (SKIP.has(child.name)) continue;\n\t\t\tconst m = multiplyMatrices(parseSvgTransform(child.attrs.transform), matrix);\n\t\t\tconst s = readStyle(child, style);\n\t\t\tconst opacity = child.attrs.opacity !== undefined ? parseFloat(child.attrs.opacity) : undefined;\n\t\t\tconst hidden = child.attrs.display === 'none' || child.attrs.visibility === 'hidden';\n\t\t\tconst meta = {\n\t\t\t\t...(child.attrs['inkscape:label'] || child.attrs['data-name'] ? { name: child.attrs['inkscape:label'] ?? child.attrs['data-name'] } : {}),\n\t\t\t\t...(opacity !== undefined && Number.isFinite(opacity) && opacity < 1 ? { opacity } : {}),\n\t\t\t\t...(hidden ? { visible: false } : {})\n\t\t\t};\n\t\t\tif (child.name === 'g' && child.attrs['data-vector-path'] !== undefined) {\n\t\t\t\tconst node = mergedPath(child, s, m, meta);\n\t\t\t\tif (node) out.push(node);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (child.name === 'g' || child.name === 'svg' || child.name === 'a' || child.name === 'switch') {\n\t\t\t\tconst children = visit(child, s, m);\n\t\t\t\tif (!children.length) continue;\n\t\t\t\tconst group: VectorGroupNode = { id: idFor(child), type: 'group', ...meta, children };\n\t\t\t\tout.push(group);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst subpaths = shapeOf(child);\n\t\t\tif (!subpaths || !subpaths.length) continue;\n\t\t\tconst node = placed(\n\t\t\t\t{\n\t\t\t\t\tid: idFor(child),\n\t\t\t\t\ttype: 'path',\n\t\t\t\t\t...meta,\n\t\t\t\t\tsubpaths,\n\t\t\t\t\tfill: child.name === 'line' ? null : paint(s.fill),\n\t\t\t\t\tstroke: paint(s.stroke),\n\t\t\t\t\t...strokeStyle(s)\n\t\t\t\t},\n\t\t\t\tm\n\t\t\t);\n\t\t\tout.push(node);\n\t\t}\n\t\treturn out;\n\t};\n\n\tconst nodes = visit(root, readStyle(root, { fill: '#000', stroke: 'none', strokeWidth: '' }), rootMatrix);\n\treturn { width, height, nodes };\n}\n","/**\n * Smart guides and object snapping for the vector editor. Targets — anchors, bounding-box\n * edges and centres, path segments and the artboard — are gathered once per gesture in\n * document space (rotated nodes included) and kept sorted by x and y, so each pointer move\n * finds the few near the pointer by bisection. A point snaps, in this order of priority: kept\n * to its Shift angle and slid into line with a target, onto an anchor or centre, onto an\n * intersection of two paths, onto the perpendicular foot or tangent point from where it\n * leaves, onto a path, onto a construction angle, then into line with targets on x and y. A\n * moved box lines its edges and centre up with targets, or spaces itself evenly in its row\n * and column; a resized box lands its moving edges on targets, or matches another object's\n * width or height. Every snap reports labelled guide lines in document units.\n *\n * Portions ported from vectorcraft-main/crates/tools/src/guides.rs (`Targets`, `within`,\n * `for_move`, `for_drawing`, `for_handle`, `for_anchor_drag`, `push_segments`, `snap_from`,\n * `slide`, `lined_up`, `on_segment`, `crossing`, `align_rects`, `snap_rects`, `even_spacing`,\n * `gap_marks`, `snap_scale`, `Leave`), figcraft-main/crates/engine/src/snap.rs (`spacings`,\n * `equal_spacing`, `spacing_guides`: equal-spacing cases and gap labels),\n * designcraft-main/crates/tools/src/snap.rs (`pass_dimensions`: matching other objects'\n * sizes) and cadcraft-main/crates/engine/src/snap/curves.rs (`Param::solve`: perpendicular and\n * tangent points by sign-change sampling and bisection) (MIT OR Apache-2.0, © ArtCraft Team\n * and contributors). See THIRD_PARTY_NOTICES.md.\n */\nimport type { Point } from '../canvas/types.js';\nimport { segmentDerivative, segmentNearest, segmentPoint, type BezierSegment } from '../canvas/pathops/bezier.js';\nimport { segmentIntersections } from '../canvas/pathops/boolean.js';\nimport {\n\tapplyMatrix,\n\tIDENTITY_MATRIX,\n\tmatrixRotation,\n\tmultiplyMatrices,\n\tnodeMatrix,\n\trotateMatrix,\n\tsubpathSegment,\n\tsubpathSegmentCount,\n\tvectorNodeBounds,\n\ttype AffineMatrix\n} from './geometry.js';\nimport type { VectorAnchorRef, VectorBounds, VectorDocument, VectorNode, VectorSubpath, VectorTransformHandle, Vec2 } from './types.js';\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * What a guide line shows: `align` lines run from a target through the snapped point or box,\n * `construction` lines from where a drawn point leaves, `spacing` marks equal gaps and `size`\n * the side whose length matches another object's.\n */\nexport type VectorGuideKind = 'align' | 'construction' | 'spacing' | 'size';\n\n/** A guide line in document units. */\nexport interface VectorGuideLine {\n\tkind: VectorGuideKind;\n\tx1: number;\n\ty1: number;\n\tx2: number;\n\ty2: number;\n}\n\n/** What a point or box snapped to. */\nexport type VectorSnapKind = 'anchor' | 'centre' | 'intersect' | 'perpendicular' | 'tangent' | 'path' | 'construction' | 'align' | 'spacing' | 'size';\n\n/** A guide label in document units: the snap kind's name, or a distance for gaps and sizes. */\nexport interface VectorGuideLabel {\n\tkind: VectorSnapKind;\n\tx: number;\n\ty: number;\n\ttext: string;\n}\n\nexport interface VectorSnapGuides {\n\tlines: VectorGuideLine[];\n\tlabels: VectorGuideLabel[];\n}\n\nexport interface VectorPointSnap extends VectorSnapGuides {\n\tpoint: Vec2;\n\t/** The rule that placed the point, or null when nothing was in reach. */\n\tkind: VectorSnapKind | null;\n\t/** Whether x / y were set by a target (for falling back to the grid on the other axis). */\n\tx: boolean;\n\ty: boolean;\n}\n\nexport interface VectorRectSnap extends VectorSnapGuides {\n\t/** Correction to add to the move. */\n\tdx: number;\n\tdy: number;\n\tx: boolean;\n\ty: boolean;\n}\n\nexport interface VectorScaleSnap extends VectorSnapGuides {\n\tsx: number;\n\tsy: number;\n\tsnapped: boolean;\n}\n\n/**\n * The point a drawn point leaves from (the anchor before it, a shape's start, a handle's\n * anchor) and how it keeps to it.\n */\nexport interface VectorSnapLeave {\n\tat: Vec2;\n\t/**\n\t * Shift held: keep to 45° steps round `at` (`angle`), to a diagonal (`square`, a box's\n\t * corner) or to the nearer axis (`axis`, a dragged point).\n\t */\n\tconstrain?: 'angle' | 'square' | 'axis' | null;\n\t/** Construction guide angles through `at`, degrees counter-clockwise on screen. */\n\tangles?: readonly number[];\n\t/** Snap to the perpendicular foot and tangent points from `at` on paths (default true). */\n\tcurves?: boolean;\n}\n\n/** The construction guide angles new editors start with. */\nexport const VECTOR_CONSTRUCTION_ANGLES: readonly number[] = [0, 45, 90, 135];\n\n/** Where `constrain` puts `p` (unchanged without one). */\nexport function constrainToLeave(leave: VectorSnapLeave | null | undefined, p: Vec2): Vec2 {\n\tif (!leave?.constrain) return p;\n\tconst dx = p.x - leave.at.x;\n\tconst dy = p.y - leave.at.y;\n\tswitch (leave.constrain) {\n\t\tcase 'axis':\n\t\t\treturn Math.abs(dx) > Math.abs(dy) ? { x: p.x, y: leave.at.y } : { x: leave.at.x, y: p.y };\n\t\tcase 'square': {\n\t\t\tconst s = Math.max(Math.abs(dx), Math.abs(dy));\n\t\t\treturn { x: leave.at.x + Math.sign(dx || 1) * s, y: leave.at.y + Math.sign(dy || 1) * s };\n\t\t}\n\t\tdefault: {\n\t\t\tconst len = Math.hypot(dx, dy);\n\t\t\tconst a = Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * (Math.PI / 4);\n\t\t\treturn { x: leave.at.x + Math.cos(a) * len, y: leave.at.y + Math.sin(a) * len };\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Targets\n// ---------------------------------------------------------------------------\n\ntype TargetKind = 'anchor' | 'centre' | 'edge' | 'artboard';\n\ninterface PointTarget {\n\tp: Vec2;\n\tkind: 'anchor' | 'centre';\n}\n\n/** A line to line up with: where it runs on its axis and the target point it comes from. */\ninterface LineTarget {\n\tv: number;\n\tfrom: Vec2;\n\tkind: TargetKind;\n}\n\ninterface SegmentTarget {\n\tseg: Point[];\n\tminX: number;\n\tminY: number;\n\tmaxX: number;\n\tmaxY: number;\n}\n\n/** How many anchors, and how many segments, the targets gather at most. */\nconst BUDGET = 20_000;\n/** The first near segments paired up when looking for intersections. */\nconst CROSSING_PAIRS = 32;\n/** Parameter samples per segment for perpendicular / tangent roots, and bisection steps. */\nconst CURVE_SAMPLES = 48;\nconst BISECT = 50;\nconst EQUAL = 1e-6;\n\n/** First index of `sorted` whose key is not below `v` (`strict`: above `v`). */\nfunction bound<T>(sorted: readonly T[], key: (e: T) => number, v: number, strict: boolean): number {\n\tlet lo = 0;\n\tlet hi = sorted.length;\n\twhile (lo < hi) {\n\t\tconst mid = (lo + hi) >>> 1;\n\t\tconst k = key(sorted[mid]);\n\t\tif (strict ? k <= v : k < v) lo = mid + 1;\n\t\telse hi = mid;\n\t}\n\treturn lo;\n}\n\n/** The entries of `sorted` (ascending by `key`) whose key is within `tol` of `v`, by bisection. */\nfunction within<T>(sorted: readonly T[], key: (e: T) => number, v: number, tol: number): readonly T[] {\n\treturn sorted.slice(bound(sorted, key, v - tol, false), bound(sorted, key, v + tol, true));\n}\n\nconst linesNear = (lines: readonly LineTarget[], v: number, tol: number) => within(lines, (l) => l.v, v, tol);\n\nconst distance = (a: Vec2, b: Vec2) => Math.hypot(a.x - b.x, a.y - b.y);\nconst toPoint = (p: Vec2): Point => [p.x, p.y];\nconst toVec = (p: Point): Vec2 => ({ x: p[0], y: p[1] });\n\n/** What `collect` gathers from each path besides its anchors and bounds. */\ntype Gather = 'bounds' | 'segments' | 'drawing';\n\nconst LABELS: Record<VectorSnapKind, string> = {\n\tanchor: 'anchor',\n\tcentre: 'centre',\n\tintersect: 'intersect',\n\tperpendicular: 'perpendicular',\n\ttangent: 'tangent',\n\tpath: 'path',\n\tconstruction: 'angle',\n\talign: 'align',\n\tspacing: 'spacing',\n\tsize: 'size'\n};\n\nconst fmtLength = (n: number) => String(Math.round(n * 100) / 100);\n\n/** A node's own (possibly rotated) frame: its size there and its centre in document space. */\nfunction nodeFrame(node: VectorNode, parent: AffineMatrix, aabb?: VectorBounds | null): { width: number; height: number; centre: Vec2 } | null {\n\tconst angle = matrixRotation(multiplyMatrices(nodeMatrix(node), parent));\n\tconst b = angle ? vectorNodeBounds(node, multiplyMatrices(parent, rotateMatrix(-angle))) : aabb !== undefined ? aabb : vectorNodeBounds(node, parent);\n\tif (!b) return null;\n\tconst c = { x: b.x + b.width / 2, y: b.y + b.height / 2 };\n\treturn { width: b.width, height: b.height, centre: angle ? applyMatrix(rotateMatrix(angle), c) : c };\n}\n\n/** True when `id` is `node` or inside it. */\nfunction contains(node: VectorNode, ids: ReadonlySet<string>): boolean {\n\tif (ids.has(node.id)) return true;\n\treturn node.type === 'group' && node.children.some((c) => contains(c, ids));\n}\n\n/**\n * Snap targets in document space, gathered once per gesture. Build them with `forMove`,\n * `forResize`, `forDrawing`, `forAnchorDrag` or `forHandle`, then call `snapFrom`,\n * `snapRect` or `snapScale` on every pointer move. Tolerances are in document units (screen\n * pixels divided by the zoom).\n */\nexport class VectorSnapTargets {\n\tprivate readonly points: PointTarget[] = [];\n\tprivate readonly xs: LineTarget[] = [];\n\tprivate readonly ys: LineTarget[] = [];\n\tprivate readonly segments: SegmentTarget[] = [];\n\t/** Bounds of the objects a moved box spaces itself evenly with. */\n\tprivate readonly boxes: VectorBounds[] = [];\n\t/** Side lengths of the other objects (in their own frames), which a resize may match. */\n\tprivate readonly sizes: number[] = [];\n\n\tprivate constructor() {}\n\n\t/** How many targets of each sort were gathered. */\n\tget counts(): { points: number; lines: number; segments: number; boxes: number } {\n\t\treturn { points: this.points.length, lines: this.xs.length + this.ys.length, segments: this.segments.length, boxes: this.boxes.length };\n\t}\n\n\t/** Targets for moving nodes `ids`: the other art's anchors, bounds and centres, the artboard, and boxes to space evenly with. */\n\tstatic forMove(doc: VectorDocument, ids: readonly string[]): VectorSnapTargets {\n\t\treturn VectorSnapTargets.collect(doc, new Set(ids), 'bounds');\n\t}\n\n\t/** Targets for resizing nodes `ids`: as for a move, plus the other objects' sizes. */\n\tstatic forResize(doc: VectorDocument, ids: readonly string[]): VectorSnapTargets {\n\t\treturn VectorSnapTargets.collect(doc, new Set(ids), 'bounds');\n\t}\n\n\t/**\n\t * Targets for a drawn point (pen, shape tools): the art but `exclude`, its anchors (as\n\t * points and in line), centres, edges and segments. The anchors and segments of `exclude`\n\t * (the path being drawn, whose bounds grow with it) stay targets.\n\t */\n\tstatic forDrawing(doc: VectorDocument, exclude: readonly string[] = []): VectorSnapTargets {\n\t\tconst skip = new Set(exclude);\n\t\tconst t = VectorSnapTargets.collect(doc, skip, 'drawing', false);\n\t\tt.pushPaths(doc, skip, () => false, true);\n\t\treturn t.index();\n\t}\n\n\t/**\n\t * Targets for dragging anchors: the other art with its segments, and the anchors and\n\t * segments that stay put on the paths being reshaped (their bounds move along, so they are\n\t * no targets). The moving anchors are left out.\n\t */\n\tstatic forAnchorDrag(doc: VectorDocument, anchors: readonly VectorAnchorRef[]): VectorSnapTargets {\n\t\tconst moving = new Map<string, Set<string>>();\n\t\tfor (const r of anchors) {\n\t\t\tconst set = moving.get(r.nodeId) ?? new Set<string>();\n\t\t\tset.add(`${r.subpath}:${r.index}`);\n\t\t\tmoving.set(r.nodeId, set);\n\t\t}\n\t\tconst t = VectorSnapTargets.collect(doc, new Set(moving.keys()), 'segments', false);\n\t\tt.pushPaths(doc, new Set(moving.keys()), (id, s, i) => !!moving.get(id)?.has(`${s}:${i}`), true);\n\t\treturn t.index();\n\t}\n\n\t/**\n\t * Targets for dragging a handle of path `nodeId`: the other art and that path's anchors\n\t * (its bounds and the segments through the handle move with it, so they would chase it).\n\t */\n\tstatic forHandle(doc: VectorDocument, nodeId: string): VectorSnapTargets {\n\t\tconst skip = new Set([nodeId]);\n\t\tconst t = VectorSnapTargets.collect(doc, skip, 'bounds', false);\n\t\tt.pushPaths(doc, skip, () => false, false);\n\t\treturn t.index();\n\t}\n\n\t/** The anchors of the paths `ids` as targets (on them and in line), and their segments when `segments`. */\n\tprivate pushPaths(doc: VectorDocument, ids: ReadonlySet<string>, moving: (id: string, subpath: number, index: number) => boolean, segments: boolean) {\n\t\tlet anchors = BUDGET;\n\t\tlet segmentBudget = segments ? BUDGET : 0;\n\t\tconst visit = (list: readonly VectorNode[], parent: AffineMatrix) => {\n\t\t\tfor (const n of list) {\n\t\t\t\tconst m = multiplyMatrices(nodeMatrix(n), parent);\n\t\t\t\tif (n.type === 'group') visit(n.children, m);\n\t\t\t\telse if (ids.has(n.id) && n.visible !== false) {\n\t\t\t\t\tn.subpaths.forEach((sp, s) => {\n\t\t\t\t\t\tsp.anchors.forEach((a, i) => {\n\t\t\t\t\t\t\tif (anchors <= 0 || moving(n.id, s, i)) return;\n\t\t\t\t\t\t\tthis.pushAnchor(applyMatrix(m, a));\n\t\t\t\t\t\t\tanchors--;\n\t\t\t\t\t\t});\n\t\t\t\t\t\tsegmentBudget = this.pushSegments(sp, m, (i) => moving(n.id, s, i), segmentBudget);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tvisit(doc.nodes, IDENTITY_MATRIX);\n\t}\n\n\tprivate pushAnchor(p: Vec2) {\n\t\tthis.points.push({ p, kind: 'anchor' });\n\t\tthis.xs.push({ v: p.x, from: p, kind: 'anchor' });\n\t\tthis.ys.push({ v: p.y, from: p, kind: 'anchor' });\n\t}\n\n\t/** The segments of `sp` (mapped by `m`) that stay put while the anchors `moving` accepts move. */\n\tprivate pushSegments(sp: VectorSubpath, m: AffineMatrix, moving: (index: number) => boolean, budget: number): number {\n\t\tconst n = sp.anchors.length;\n\t\tconst count = subpathSegmentCount(sp);\n\t\tfor (let i = 0; i < count && budget > 0; i++) {\n\t\t\tif (moving(i) || moving((i + 1) % n)) continue;\n\t\t\tconst seg = subpathSegment(sp, i).map((q) => toPoint(applyMatrix(m, toVec(q))));\n\t\t\tlet minX = Infinity;\n\t\t\tlet minY = Infinity;\n\t\t\tlet maxX = -Infinity;\n\t\t\tlet maxY = -Infinity;\n\t\t\tfor (const [x, y] of seg) {\n\t\t\t\tminX = Math.min(minX, x);\n\t\t\t\tminY = Math.min(minY, y);\n\t\t\t\tmaxX = Math.max(maxX, x);\n\t\t\t\tmaxY = Math.max(maxY, y);\n\t\t\t}\n\t\t\tthis.segments.push({ seg, minX, minY, maxX, maxY });\n\t\t\tbudget--;\n\t\t}\n\t\treturn budget;\n\t}\n\n\tprivate pushRect(r: VectorBounds, kind: TargetKind, centre: Vec2 | null) {\n\t\tconst corners = [\n\t\t\t{ x: r.x, y: r.y },\n\t\t\t{ x: r.x + r.width, y: r.y },\n\t\t\t{ x: r.x + r.width, y: r.y + r.height },\n\t\t\t{ x: r.x, y: r.y + r.height }\n\t\t];\n\t\tfor (const p of corners) {\n\t\t\tthis.xs.push({ v: p.x, from: p, kind });\n\t\t\tthis.ys.push({ v: p.y, from: p, kind });\n\t\t}\n\t\tif (centre) {\n\t\t\tthis.points.push({ p: centre, kind: 'centre' });\n\t\t\tthis.xs.push({ v: centre.x, from: centre, kind: 'centre' });\n\t\t\tthis.ys.push({ v: centre.y, from: centre, kind: 'centre' });\n\t\t}\n\t}\n\n\t/** Sorts the targets for `within` (stable: of targets alike, the first gathered wins). */\n\tprivate index(): this {\n\t\tthis.points.sort((a, b) => a.p.x - b.p.x);\n\t\tthis.xs.sort((a, b) => a.v - b.v);\n\t\tthis.ys.sort((a, b) => a.v - b.v);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Gathers targets from the artboard and every visible node but `exclude` (and what is inside\n\t * those): each leaf's anchors (also as lines for `drawing`), its segments (`segments`,\n\t * `drawing`), its bounds' corners as lines and its centre; and the top-level objects' boxes and\n\t * sizes (inside a group holding an excluded node, that group's other members).\n\t */\n\tprivate static collect(doc: VectorDocument, exclude: ReadonlySet<string>, gather: Gather, sort = true): VectorSnapTargets {\n\t\tconst self = new VectorSnapTargets();\n\t\tconst artboard = { x: 0, y: 0, width: doc.width, height: doc.height };\n\t\tself.pushRect(artboard, 'artboard', { x: doc.width / 2, y: doc.height / 2 });\n\t\tlet anchors = BUDGET;\n\t\tlet segments = BUDGET;\n\t\tconst visit = (list: readonly VectorNode[], parent: AffineMatrix) => {\n\t\t\tfor (const n of list) {\n\t\t\t\tif (exclude.has(n.id) || n.visible === false) continue;\n\t\t\t\tconst m = multiplyMatrices(nodeMatrix(n), parent);\n\t\t\t\tif (n.type === 'group') {\n\t\t\t\t\tvisit(n.children, m);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (anchors <= 0) continue;\n\t\t\t\tfor (const sp of n.subpaths) {\n\t\t\t\t\tfor (const a of sp.anchors) {\n\t\t\t\t\t\tif (anchors-- <= 0) break;\n\t\t\t\t\t\tconst p = applyMatrix(m, a);\n\t\t\t\t\t\tif (gather === 'drawing') self.pushAnchor(p);\n\t\t\t\t\t\telse self.points.push({ p, kind: 'anchor' });\n\t\t\t\t\t}\n\t\t\t\t\tif (gather !== 'bounds') segments = self.pushSegments(sp, m, () => false, segments);\n\t\t\t\t}\n\t\t\t\tconst b = vectorNodeBounds(n, parent);\n\t\t\t\tconst f = nodeFrame(n, parent, b);\n\t\t\t\tif (b) self.pushRect(b, 'edge', f?.centre ?? null);\n\t\t\t}\n\t\t};\n\t\tvisit(doc.nodes, IDENTITY_MATRIX);\n\t\t// Boxes to space evenly with and sizes to match: whole objects, opening groups that hold an excluded node.\n\t\tconst objects = (list: readonly VectorNode[], parent: AffineMatrix) => {\n\t\t\tfor (const n of list) {\n\t\t\t\tif (exclude.has(n.id) || n.visible === false || self.boxes.length >= BUDGET) continue;\n\t\t\t\tif (n.type === 'group' && contains(n, exclude)) {\n\t\t\t\t\tobjects(n.children, multiplyMatrices(nodeMatrix(n), parent));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst b = vectorNodeBounds(n, parent);\n\t\t\t\tif (b) self.boxes.push(b);\n\t\t\t\tconst f = nodeFrame(n, parent, b);\n\t\t\t\tif (f) self.sizes.push(f.width, f.height);\n\t\t\t}\n\t\t};\n\t\tobjects(doc.nodes, IDENTITY_MATRIX);\n\t\treturn sort ? self.index() : self;\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Points\n\t// -------------------------------------------------------------------------\n\n\t/** Snaps a single point (see `snapFrom`). */\n\tsnapPoint(p: Vec2, tol: number): VectorPointSnap {\n\t\treturn this.snapFrom(p, null, tol);\n\t}\n\n\t/**\n\t * Snaps a point `p`, drawn or dragged from `leave` when given. With `leave.constrain` it keeps\n\t * to its angle round `leave.at`, sliding along that way into line with the nearest target.\n\t * Otherwise it lands, in order, on an anchor or centre, an intersection of two paths, the\n\t * perpendicular foot or a tangent point from `leave.at`, a path, a construction guide\n\t * through `leave.at` (where a target's line crosses it if one does nearby), or else lines up\n\t * with targets on x and y.\n\t */\n\tsnapFrom(p: Vec2, leave: VectorSnapLeave | null | undefined, tol: number): VectorPointSnap {\n\t\tconst none = (q: Vec2): VectorPointSnap => ({ point: q, kind: null, x: false, y: false, lines: [], labels: [] });\n\t\tconst at = (q: Vec2, kind: VectorSnapKind, lines: VectorGuideLine[] = []): VectorPointSnap => ({\n\t\t\tpoint: q,\n\t\t\tkind,\n\t\t\tx: true,\n\t\t\ty: true,\n\t\t\tlines,\n\t\t\tlabels: [this.label(q, kind)]\n\t\t});\n\t\tif (leave?.constrain) {\n\t\t\tconst q = constrainToLeave(leave, p);\n\t\t\tconst hit = this.slide(leave.at, { x: q.x - leave.at.x, y: q.y - leave.at.y }, q, tol, true);\n\t\t\treturn hit ? { point: hit.point, x: true, y: true, ...this.linedUp(hit.point, hit.from) } : none(q);\n\t\t}\n\t\tconst point = this.nearestPoint(p, tol);\n\t\tif (point) return at(point.p, point.kind);\n\t\tconst near = this.segmentsNear(p, tol);\n\t\tconst crossing = this.crossing(near, p, tol);\n\t\tif (crossing) return at(crossing, 'intersect');\n\t\tif (leave && leave.curves !== false) {\n\t\t\tconst foot = this.curvePoint(near, leave.at, p, tol);\n\t\t\tif (foot) return at(foot.point, foot.kind, [line('construction', leave.at, foot.point)]);\n\t\t}\n\t\tconst on = this.onSegment(near);\n\t\tif (on) return at(on, 'path');\n\t\tif (leave?.angles?.length) {\n\t\t\tconst c = construction(leave, p, tol);\n\t\t\tif (c) {\n\t\t\t\tconst hit = this.slide(leave.at, c.dir, c.point, tol, false);\n\t\t\t\tif (hit) {\n\t\t\t\t\tconst lined = this.linedUp(hit.point, hit.from);\n\t\t\t\t\treturn { point: hit.point, x: true, y: true, kind: lined.kind, lines: [line('construction', leave.at, hit.point), ...lined.lines], labels: lined.labels };\n\t\t\t\t}\n\t\t\t\treturn { point: c.point, kind: 'construction', x: true, y: true, lines: [line('construction', leave.at, c.point)], labels: [] };\n\t\t\t}\n\t\t}\n\t\tconst nearest = (lines: readonly LineTarget[], v: number) => {\n\t\t\tlet best: LineTarget | null = null;\n\t\t\tfor (const l of linesNear(lines, v, tol)) if (!best || Math.abs(l.v - v) < Math.abs(best.v - v)) best = l;\n\t\t\treturn best;\n\t\t};\n\t\tconst bx = nearest(this.xs, p.x);\n\t\tconst by = nearest(this.ys, p.y);\n\t\tif (!bx && !by) return none(p);\n\t\tconst out = { x: bx ? bx.v : p.x, y: by ? by.v : p.y };\n\t\tconst lines: VectorGuideLine[] = [];\n\t\tif (bx) lines.push(line('align', bx.from, { x: out.x, y: out.y }));\n\t\tif (by) lines.push(line('align', by.from, { x: out.x, y: out.y }));\n\t\treturn { point: out, kind: 'align', x: !!bx, y: !!by, lines, labels: [this.label(out, 'align')] };\n\t}\n\n\tprivate label(p: Vec2, kind: VectorSnapKind, text = LABELS[kind]): VectorGuideLabel {\n\t\treturn { kind, x: p.x, y: p.y, text };\n\t}\n\n\t/** The anchor or centre nearest `p`, within `tol`. */\n\tprivate nearestPoint(p: Vec2, tol: number): PointTarget | null {\n\t\tlet best: PointTarget | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (const t of within(this.points, (e) => e.p.x, p.x, tol)) {\n\t\t\tconst d = distance(t.p, p);\n\t\t\tif (d <= tol && d < bestD) {\n\t\t\t\tbest = t;\n\t\t\t\tbestD = d;\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t}\n\n\t/**\n\t * Slides `q`, on the line through `at` along `dir` (beyond `at` only for a `ray`), to where\n\t * the nearest target line crosses it, at most twice `tol` away: where it lands and the\n\t * target point that line comes from.\n\t */\n\tprivate slide(at: Vec2, dir: Vec2, q: Vec2, tol: number, ray: boolean): { point: Vec2; from: Vec2 } | null {\n\t\tconst len2 = dir.x * dir.x + dir.y * dir.y;\n\t\tif (!Number.isFinite(len2) || len2 <= 1e-18) return null;\n\t\tconst reach = 2 * tol;\n\t\tlet best: { moved: number; point: Vec2; from: Vec2 } | null = null;\n\t\tfor (const vertical of [true, false]) {\n\t\t\tconst d = vertical ? dir.x : dir.y;\n\t\t\tif (Math.abs(d) <= 1e-9) continue;\n\t\t\tconst a = vertical ? at.x : at.y;\n\t\t\tfor (const l of linesNear(vertical ? this.xs : this.ys, vertical ? q.x : q.y, reach)) {\n\t\t\t\tconst s = (l.v - a) / d;\n\t\t\t\t// Exactly on the line, whatever the rounding along the way.\n\t\t\t\tconst hit = vertical ? { x: l.v, y: at.y + dir.y * s } : { x: at.x + dir.x * s, y: l.v };\n\t\t\t\tconst moved = distance(hit, q);\n\t\t\t\tif (moved <= reach && (!ray || s > 0) && (!best || moved < best.moved)) best = { moved, point: hit, from: l.from };\n\t\t\t}\n\t\t}\n\t\treturn best && { point: best.point, from: best.from };\n\t}\n\n\t/** The guides of a point `q` slid into line with the target at `from`: the line and \"align\", or the target's own label when `q` sits on it. */\n\tprivate linedUp(q: Vec2, from: Vec2): { kind: VectorSnapKind } & VectorSnapGuides {\n\t\tconst on = this.nearestPoint(q, 1e-9);\n\t\tif (on) return { kind: on.kind, lines: [], labels: [this.label(on.p, on.kind)] };\n\t\treturn { kind: 'align', lines: [line('align', from, q)], labels: [this.label(q, 'align')] };\n\t}\n\n\t/** Target segments whose control box reaches `p` and which pass within `tol` of it, nearest first. */\n\tprivate segmentsNear(p: Vec2, tol: number): { seg: Point[]; t: number; distance: number }[] {\n\t\tconst out: { seg: Point[]; t: number; distance: number }[] = [];\n\t\tconst pt = toPoint(p);\n\t\tfor (const s of this.segments) {\n\t\t\tif (p.x < s.minX - tol || p.x > s.maxX + tol || p.y < s.minY - tol || p.y > s.maxY + tol) continue;\n\t\t\tconst hit = segmentNearest(s.seg, pt);\n\t\t\tif (hit.distance <= tol) out.push({ seg: s.seg, t: hit.t, distance: hit.distance });\n\t\t}\n\t\treturn out.sort((a, b) => a.distance - b.distance);\n\t}\n\n\tprivate onSegment(near: readonly { seg: Point[]; t: number }[]): Vec2 | null {\n\t\treturn near.length ? toVec(segmentPoint(near[0].seg, near[0].t)) : null;\n\t}\n\n\t/** Where two of the target segments near `p` cross, the crossing nearest `p` within `tol`. */\n\tprivate crossing(near: readonly { seg: Point[] }[], p: Vec2, tol: number): Vec2 | null {\n\t\tconst list = near.slice(0, CROSSING_PAIRS);\n\t\tlet best: Vec2 | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (let i = 0; i < list.length; i++) {\n\t\t\tfor (let j = i + 1; j < list.length; j++) {\n\t\t\t\tfor (const hit of segmentIntersections(list[i].seg as BezierSegment, list[j].seg as BezierSegment)) {\n\t\t\t\t\tconst q = toVec(hit.point);\n\t\t\t\t\tconst d = distance(q, p);\n\t\t\t\t\tif (d <= tol && d < bestD) {\n\t\t\t\t\t\tbest = q;\n\t\t\t\t\t\tbestD = d;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t}\n\n\t/**\n\t * The foot of a perpendicular, or a tangent point, from `base` on a target segment near `p`\n\t * (within `tol` of it): roots of `(B(t) − base) · B′(t)` and `(B(t) − base) × B′(t)`\n\t * bracketed by sign changes of samples and narrowed by bisection.\n\t */\n\tprivate curvePoint(near: readonly { seg: Point[] }[], base: Vec2, p: Vec2, tol: number): { point: Vec2; kind: 'perpendicular' | 'tangent' } | null {\n\t\tlet best: { point: Vec2; kind: 'perpendicular' | 'tangent'; d: number } | null = null;\n\t\tfor (const { seg } of near) {\n\t\t\tfor (const kind of ['perpendicular', 'tangent'] as const) {\n\t\t\t\tif (kind === 'tangent' && seg.length === 2) continue;\n\t\t\t\tfor (const q of solveOnSegment(seg, base, kind === 'perpendicular' ? dotCondition : crossCondition)) {\n\t\t\t\t\tconst d = distance(q, p);\n\t\t\t\t\tif (d <= tol && (!best || d < best.d)) best = { point: q, kind, d };\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn best && { point: best.point, kind: best.kind };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Boxes\n\t// -------------------------------------------------------------------------\n\n\t/**\n\t * Snaps a moving box `r` (the moved selection's bounds): its edge or centre nearest a target\n\t * line on each axis (`axes` limits which may move). With `spacing`, an axis that lines up\n\t * with nothing spaces the box evenly in its row or column. Returns the correction and guides.\n\t */\n\tsnapRect(r: VectorBounds, tol: number, options: { spacing?: boolean; axes?: { x?: boolean; y?: boolean } } = {}): VectorRectSnap {\n\t\tconst axes = { x: options.axes?.x !== false, y: options.axes?.y !== false };\n\t\tconst nearest = (lines: readonly LineTarget[], values: number[]) => {\n\t\t\tlet best: { d: number; from: Vec2 } | null = null;\n\t\t\tfor (const v of values) for (const l of linesNear(lines, v, tol)) if (!best || Math.abs(l.v - v) < Math.abs(best.d)) best = { d: l.v - v, from: l.from };\n\t\t\treturn best;\n\t\t};\n\t\tconst bx = axes.x ? nearest(this.xs, [r.x, r.x + r.width / 2, r.x + r.width]) : null;\n\t\tconst by = axes.y ? nearest(this.ys, [r.y, r.y + r.height / 2, r.y + r.height]) : null;\n\t\tconst out: VectorRectSnap = { dx: bx?.d ?? 0, dy: by?.d ?? 0, x: !!bx, y: !!by, lines: [], labels: [] };\n\t\tconst done = { ...r, x: r.x + out.dx, y: r.y + out.dy };\n\t\tif (bx) {\n\t\t\tconst x = bx.from.x;\n\t\t\tout.lines.push({ kind: 'align', x1: x, y1: Math.min(bx.from.y, done.y), x2: x, y2: Math.max(bx.from.y, done.y + done.height) });\n\t\t}\n\t\tif (by) {\n\t\t\tconst y = by.from.y;\n\t\t\tout.lines.push({ kind: 'align', x1: Math.min(by.from.x, done.x), y1: y, x2: Math.max(by.from.x, done.x + done.width), y2: y });\n\t\t}\n\t\tif (options.spacing && this.boxes.length) {\n\t\t\tfor (const horizontal of [true, false]) {\n\t\t\t\tif (horizontal ? out.x || !axes.x : out.y || !axes.y) continue;\n\t\t\t\tconst moved = { ...r, x: r.x + out.dx, y: r.y + out.dy };\n\t\t\t\tconst even = this.evenSpacing(moved, horizontal, tol);\n\t\t\t\tif (!even) continue;\n\t\t\t\tif (horizontal) {\n\t\t\t\t\tout.dx += even.shift;\n\t\t\t\t\tout.x = true;\n\t\t\t\t} else {\n\t\t\t\t\tout.dy += even.shift;\n\t\t\t\t\tout.y = true;\n\t\t\t\t}\n\t\t\t\tfor (const gap of even.gaps) this.gapMarks(gap, horizontal, tol, out);\n\t\t\t}\n\t\t}\n\t\tif (bx || by) out.labels.unshift(this.label({ x: r.x + out.dx + r.width / 2, y: r.y + out.dy + r.height / 2 }, 'align'));\n\t\treturn out;\n\t}\n\n\t/**\n\t * Equal spacing along x (`horizontal`) or y for the moved box `r`, among the objects of its\n\t * row (column): the shift within `tol` that centres it between its neighbours, or leaves it\n\t * as far from the neighbour before or after it as two other objects of the row are apart;\n\t * and the gaps that are equal then, as (start, end, where across).\n\t */\n\tprivate evenSpacing(r: VectorBounds, horizontal: boolean, tol: number): { shift: number; gaps: [number, number, number][] } | null {\n\t\tconst span = (b: VectorBounds, x: boolean): [number, number] => (x ? [b.x, b.x + b.width] : [b.y, b.y + b.height]);\n\t\tconst [r0, r1] = span(r, horizontal);\n\t\tconst len = r1 - r0;\n\t\tconst [c0, c1] = span(r, !horizontal);\n\t\tconst row = this.boxes\n\t\t\t.map((b) => ({ b, a0: span(b, horizontal)[0], a1: span(b, horizontal)[1] }))\n\t\t\t.filter((e) => span(e.b, !horizontal)[0] < c1 && span(e.b, !horizontal)[1] > c0 && (e.a1 <= r0 + tol || e.a0 >= r1 - tol))\n\t\t\t.sort((a, b) => a.a0 - b.a0);\n\t\tif (!row.length) return null;\n\t\t// Across the middle of what two boxes share (or of the space between them).\n\t\tconst mid = (a: VectorBounds, b: VectorBounds) => (Math.max(span(a, !horizontal)[0], span(b, !horizontal)[0]) + Math.min(span(a, !horizontal)[1], span(b, !horizontal)[1])) / 2;\n\t\tconst pairs: { g: number; gap: [number, number, number] }[] = [];\n\t\tfor (const p of row) {\n\t\t\tconst next = bound(row, (e) => e.a0, p.a1, false);\n\t\t\tconst q = row[next];\n\t\t\tif (!q) continue;\n\t\t\tconst straddles = p.a1 <= r0 + tol && q.a0 >= r1 - tol;\n\t\t\tif (q.a0 > p.a1 && !straddles) pairs.push({ g: q.a0 - p.a1, gap: [p.a1, q.a0, mid(p.b, q.b)] });\n\t\t}\n\t\tlet before: (typeof row)[number] | null = null;\n\t\tlet after: (typeof row)[number] | null = null;\n\t\tfor (const e of row) {\n\t\t\tif (e.a1 <= r0 + tol && (!before || e.a1 > before.a1)) before = e;\n\t\t\tif (e.a0 >= r1 - tol && (!after || e.a0 < after.a0)) after = e;\n\t\t}\n\t\tconst starts: { start: number; repeats: number | null }[] = [];\n\t\tif (before && after && after.a0 - before.a1 > len) starts.push({ start: (before.a1 + after.a0 - len) / 2, repeats: null });\n\t\tfor (const { g } of pairs) {\n\t\t\tif (before) starts.push({ start: before.a1 + g, repeats: g });\n\t\t\tif (after) starts.push({ start: after.a0 - g - len, repeats: g });\n\t\t}\n\t\tlet pick: { start: number; repeats: number | null } | null = null;\n\t\tfor (const s of starts) if (Math.abs(s.start - r0) <= tol && (!pick || Math.abs(s.start - r0) < Math.abs(pick.start - r0))) pick = s;\n\t\tif (!pick) return null;\n\t\tconst { start, repeats } = pick;\n\t\tconst at = horizontal ? { ...r, x: start } : { ...r, y: start };\n\t\tconst end = start + len;\n\t\tconst gaps: [number, number, number][] = [];\n\t\tif (before && (repeats === null || Math.abs(start - before.a1 - repeats) <= EQUAL)) gaps.push([before.a1, start, mid(before.b, at)]);\n\t\tif (after && (repeats === null || Math.abs(after.a0 - end - repeats) <= EQUAL)) gaps.push([end, after.a0, mid(after.b, at)]);\n\t\tif (repeats !== null) for (const p of pairs) if (Math.abs(p.g - repeats) <= EQUAL) gaps.push(p.gap);\n\t\treturn { shift: start - r0, gaps };\n\t}\n\n\t/** A gap mark: a line across the gap with a tick at each end, and its length as a label. */\n\tprivate gapMarks([u0, u1, c]: [number, number, number], horizontal: boolean, tick: number, out: VectorSnapGuides) {\n\t\tconst pt = (u: number, v: number): Vec2 => (horizontal ? { x: u, y: v } : { x: v, y: u });\n\t\tout.lines.push(line('spacing', pt(u0, c), pt(u1, c)), line('spacing', pt(u0, c - tick), pt(u0, c + tick)), line('spacing', pt(u1, c - tick), pt(u1, c + tick)));\n\t\tout.labels.push(this.label(pt((u0 + u1) / 2, c), 'spacing', fmtLength(u1 - u0)));\n\t}\n\n\t/** The other objects' side length nearest `length`, within `tol`, or null. */\n\tmatchSize(length: number, tol: number): number | null {\n\t\tlet best: number | null = null;\n\t\tfor (const s of this.sizes) if (Math.abs(s - length) <= tol && (best === null || Math.abs(s - length) < Math.abs(best - length))) best = s;\n\t\treturn best;\n\t}\n\n\t/**\n\t * Snaps a selection-box resize. `sx / sy` are the scale `scaleFor` gave for dragging\n\t * `handle` of `frame` (in the box's own, possibly rotated frame), `mods.shift` keeps the\n\t * proportions and `mods.alt` scales about the centre. The handle lands on an anchor or\n\t * centre within `tol`, else the corner or the side it moves lines up with the nearest\n\t * target, whatever the box's angle; a handle with one way to go (a side, or a proportional\n\t * corner) slides along it until one of them is on a target. An axis that snaps to nothing\n\t * may match another object's width or height instead.\n\t */\n\tsnapScale(\n\t\tframe: VectorBounds & { angle: number },\n\t\thandle: Exclude<VectorTransformHandle, 'rotate'>,\n\t\tsx: number,\n\t\tsy: number,\n\t\tmods: { shift?: boolean; alt?: boolean },\n\t\ttol: number\n\t): VectorScaleSnap {\n\t\tconst toDoc = frame.angle ? rotateMatrix(frame.angle) : IDENTITY_MATRIX;\n\t\tconst toLocal = frame.angle ? rotateMatrix(-frame.angle) : IDENTITY_MATRIX;\n\t\tconst corner = handle.length === 2;\n\t\tconst proportional = !!mods.shift;\n\t\tconst centre = { x: frame.x + frame.width / 2, y: frame.y + frame.height / 2 };\n\t\tconst origin = mods.alt ? centre : handlePos(opposite(handle), frame);\n\t\tconst hp = handlePos(handle, frame);\n\t\tconst d0 = { x: hp.x - origin.x, y: hp.y - origin.y };\n\t\tconst valid = (n: number, s: number) => Number.isFinite(n) && n * s > 0;\n\t\tconst nearest = (v: number, lines: readonly LineTarget[]) => {\n\t\t\tlet best: LineTarget | null = null;\n\t\t\tfor (const l of linesNear(lines, v, tol)) if (!best || Math.abs(l.v - v) < Math.abs(best.v - v)) best = l;\n\t\t\treturn best;\n\t\t};\n\t\ttype Snap = { hx: LineTarget | null; hy: LineTarget | null; on: PointTarget | null };\n\t\tlet nx = sx;\n\t\tlet ny = sy;\n\t\tlet snap: Snap = { hx: null, hy: null, on: null };\n\t\tif (corner && !proportional) {\n\t\t\t// The corner goes anywhere: onto an anchor or centre, else it takes a target's x, its y, or both.\n\t\t\tconst p = applyMatrix(toDoc, { x: origin.x + d0.x * sx, y: origin.y + d0.y * sy });\n\t\t\tconst hx = nearest(p.x, this.xs);\n\t\t\tconst hy = nearest(p.y, this.ys);\n\t\t\tconst on = this.nearestPoint(p, tol);\n\t\t\tconst tries: { tx: number | null; ty: number | null; s: Snap }[] = [];\n\t\t\tif (on) tries.push({ tx: on.p.x, ty: on.p.y, s: { hx: null, hy: null, on } });\n\t\t\ttries.push({ tx: hx?.v ?? null, ty: hy?.v ?? null, s: { hx, hy, on: null } });\n\t\t\ttries.push({ tx: hx?.v ?? null, ty: null, s: { hx, hy: null, on: null } });\n\t\t\ttries.push({ tx: null, ty: hy?.v ?? null, s: { hx: null, hy, on: null } });\n\t\t\tfor (const { tx, ty, s } of tries) {\n\t\t\t\tif (tx === null && ty === null) continue;\n\t\t\t\tconst q = applyMatrix(toLocal, { x: tx ?? p.x, y: ty ?? p.y });\n\t\t\t\tlet cx = (q.x - origin.x) / d0.x;\n\t\t\t\tlet cy = (q.y - origin.y) / d0.y;\n\t\t\t\t// Square to the page, the axis without a target stays exactly where it was.\n\t\t\t\tif (!frame.angle) {\n\t\t\t\t\tif (tx === null) cx = sx;\n\t\t\t\t\tif (ty === null) cy = sy;\n\t\t\t\t}\n\t\t\t\tif (valid(cx, sx) && valid(cy, sy)) {\n\t\t\t\t\tnx = cx;\n\t\t\t\t\tny = cy;\n\t\t\t\t\tsnap = s;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// One parameter `s`: the scale is `c + s·e` on each axis.\n\t\t\tconst movesX = handle === 'e' || handle === 'w';\n\t\t\tlet e: Vec2;\n\t\t\tlet c: Vec2;\n\t\t\tlet s0: number;\n\t\t\tif (corner) [e, c, s0] = [{ x: Math.sign(sx), y: Math.sign(sy) }, { x: 0, y: 0 }, Math.abs(sx)];\n\t\t\telse if (movesX) [e, c, s0] = proportional ? [{ x: 1, y: Math.sign(sx) }, { x: 0, y: 0 }, sx] : [{ x: 1, y: 0 }, { x: 0, y: 1 }, sx];\n\t\t\telse [e, c, s0] = proportional ? [{ x: Math.sign(sy), y: 1 }, { x: 0, y: 0 }, sy] : [{ x: 0, y: 1 }, { x: 1, y: 0 }, sy];\n\t\t\t// The points that may land on a target: the handle, and the two ends of its side.\n\t\t\tconst i = RING.indexOf(handle);\n\t\t\tconst ends = corner ? [] : [RING[(i + 1) % 8], RING[(i + 7) % 8]];\n\t\t\t// How far the handle travels per unit of `s`: a snap may not drag it far from the pointer.\n\t\t\tconst travel = Math.hypot(e.x * d0.x, e.y * d0.y);\n\t\t\tlet best: { s: number; inLine: boolean; moved: number; snap: Snap } | null = null;\n\t\t\tconst consider = (s: number, inLine: boolean, found: Snap) => {\n\t\t\t\tconst moved = Math.abs(s - s0) * travel;\n\t\t\t\tif (!valid(s, s0) || moved > 2 * tol) return;\n\t\t\t\tif (!best || (inLine === best.inLine ? moved < best.moved : !inLine)) best = { s, inLine, moved, snap: found };\n\t\t\t};\n\t\t\tfor (const h of [handle, ...ends]) {\n\t\t\t\tconst hv = handlePos(h, frame);\n\t\t\t\tconst v = { x: hv.x - origin.x, y: hv.y - origin.y };\n\t\t\t\tconst base = applyMatrix(toDoc, { x: origin.x + c.x * v.x, y: origin.y + c.y * v.y });\n\t\t\t\tconst dir = applyMatrix(toDoc, { x: e.x * v.x, y: e.y * v.y });\n\t\t\t\tconst p = { x: base.x + dir.x * s0, y: base.y + dir.y * s0 };\n\t\t\t\tconst l2 = dir.x * dir.x + dir.y * dir.y;\n\t\t\t\tconst on = l2 > 1e-18 ? this.nearestPoint(p, tol) : null;\n\t\t\t\t// An anchor or centre beside its way: it stops at the nearest point of the way.\n\t\t\t\tif (on) consider(((on.p.x - base.x) * dir.x + (on.p.y - base.y) * dir.y) / l2, false, { hx: null, hy: null, on });\n\t\t\t\tif (Math.abs(dir.x) > 1e-9) {\n\t\t\t\t\tconst hit = nearest(p.x, this.xs);\n\t\t\t\t\tif (hit) consider((hit.v - base.x) / dir.x, true, { hx: hit, hy: null, on: null });\n\t\t\t\t}\n\t\t\t\tif (Math.abs(dir.y) > 1e-9) {\n\t\t\t\t\tconst hit = nearest(p.y, this.ys);\n\t\t\t\t\tif (hit) consider((hit.v - base.y) / dir.y, true, { hx: null, hy: hit, on: null });\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst found = best as { s: number; snap: Snap } | null;\n\t\t\tif (found) {\n\t\t\t\tnx = c.x + found.s * e.x;\n\t\t\t\tny = c.y + found.s * e.y;\n\t\t\t\tsnap = found.snap;\n\t\t\t}\n\t\t}\n\t\tconst out: VectorScaleSnap = { sx: nx, sy: ny, snapped: false, lines: [], labels: [] };\n\t\tconst handleAt = () => applyMatrix(toDoc, { x: origin.x + d0.x * out.sx, y: origin.y + d0.y * out.sy });\n\t\tif (snap.on) {\n\t\t\tout.snapped = true;\n\t\t\tout.labels.push(this.label(snap.on.p, snap.on.kind));\n\t\t\treturn out;\n\t\t}\n\t\t// Sides that line up with nothing may match another object's width or height.\n\t\tconst movesX = handle !== 'n' && handle !== 's';\n\t\tconst movesY = handle !== 'e' && handle !== 'w';\n\t\tconst sized: ('x' | 'y')[] = [];\n\t\tif (!proportional) {\n\t\t\tif (movesX && !snap.hx && !(frame.angle && snap.hy) && frame.width > 1e-9) {\n\t\t\t\tconst len = this.matchSize(Math.abs(out.sx) * frame.width, tol);\n\t\t\t\tif (len !== null && len > 0) {\n\t\t\t\t\tout.sx = Math.sign(out.sx || 1) * (len / frame.width);\n\t\t\t\t\tsized.push('x');\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (movesY && !snap.hy && !(frame.angle && snap.hx) && frame.height > 1e-9) {\n\t\t\t\tconst len = this.matchSize(Math.abs(out.sy) * frame.height, tol);\n\t\t\t\tif (len !== null && len > 0) {\n\t\t\t\t\tout.sy = Math.sign(out.sy || 1) * (len / frame.height);\n\t\t\t\t\tsized.push('y');\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// The resized box in its frame, and its corners on the page.\n\t\tconst x0 = origin.x + (frame.x - origin.x) * out.sx;\n\t\tconst x1 = origin.x + (frame.x + frame.width - origin.x) * out.sx;\n\t\tconst y0 = origin.y + (frame.y - origin.y) * out.sy;\n\t\tconst y1 = origin.y + (frame.y + frame.height - origin.y) * out.sy;\n\t\tconst box = { x0: Math.min(x0, x1), x1: Math.max(x0, x1), y0: Math.min(y0, y1), y1: Math.max(y0, y1) };\n\t\tconst page = [\n\t\t\t{ x: box.x0, y: box.y0 },\n\t\t\t{ x: box.x1, y: box.y0 },\n\t\t\t{ x: box.x1, y: box.y1 },\n\t\t\t{ x: box.x0, y: box.y1 }\n\t\t].map((q) => applyMatrix(toDoc, q));\n\t\tconst pminY = Math.min(...page.map((q) => q.y));\n\t\tconst pmaxY = Math.max(...page.map((q) => q.y));\n\t\tconst pminX = Math.min(...page.map((q) => q.x));\n\t\tconst pmaxX = Math.max(...page.map((q) => q.x));\n\t\tif (snap.hx) out.lines.push({ kind: 'align', x1: snap.hx.v, y1: Math.min(snap.hx.from.y, pminY), x2: snap.hx.v, y2: Math.max(snap.hx.from.y, pmaxY) });\n\t\tif (snap.hy) out.lines.push({ kind: 'align', x1: Math.min(snap.hy.from.x, pminX), y1: snap.hy.v, x2: Math.max(snap.hy.from.x, pmaxX), y2: snap.hy.v });\n\t\tif (snap.hx || snap.hy) {\n\t\t\tout.snapped = true;\n\t\t\tout.labels.push(this.label(handleAt(), 'align'));\n\t\t}\n\t\tfor (const axis of sized) {\n\t\t\tout.snapped = true;\n\t\t\t// Along the matched side, just outside the box.\n\t\t\tconst off = tol * 2;\n\t\t\tconst [a, b] = axis === 'x' ? [{ x: box.x0, y: box.y1 + off }, { x: box.x1, y: box.y1 + off }] : [{ x: box.x1 + off, y: box.y0 }, { x: box.x1 + off, y: box.y1 }];\n\t\t\tconst pa = applyMatrix(toDoc, a);\n\t\t\tconst pb = applyMatrix(toDoc, b);\n\t\t\tout.lines.push(line('size', pa, pb));\n\t\t\tout.labels.push(this.label({ x: (pa.x + pb.x) / 2, y: (pa.y + pb.y) / 2 }, 'size', `${axis === 'x' ? 'W' : 'H'} ${fmtLength(axis === 'x' ? box.x1 - box.x0 : box.y1 - box.y0)}`));\n\t\t}\n\t\treturn out;\n\t}\n}\n\n/** The eight resize handles clockwise from the top left (each side sits between its two corners). */\nconst RING: readonly Exclude<VectorTransformHandle, 'rotate'>[] = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'];\n\nfunction opposite(h: Exclude<VectorTransformHandle, 'rotate'>): Exclude<VectorTransformHandle, 'rotate'> {\n\treturn RING[(RING.indexOf(h) + 4) % 8];\n}\n\nfunction handlePos(h: Exclude<VectorTransformHandle, 'rotate'>, r: VectorBounds): Vec2 {\n\tconst x = h.includes('w') ? r.x : h.includes('e') ? r.x + r.width : r.x + r.width / 2;\n\tconst y = h.startsWith('n') ? r.y : h.startsWith('s') ? r.y + r.height : r.y + r.height / 2;\n\treturn { x, y };\n}\n\nfunction line(kind: VectorGuideKind, a: Vec2, b: Vec2): VectorGuideLine {\n\treturn { kind, x1: a.x, y1: a.y, x2: b.x, y2: b.y };\n}\n\n/** The construction guide through `leave.at` nearest `p`, within `tol` (and `p` farther than that from `at`): its direction and where `p` lands. */\nfunction construction(leave: VectorSnapLeave, p: Vec2, tol: number): { dir: Vec2; point: Vec2 } | null {\n\tconst v = { x: p.x - leave.at.x, y: p.y - leave.at.y };\n\tif (Math.hypot(v.x, v.y) <= tol) return null;\n\tlet best: { dir: Vec2; point: Vec2; d: number } | null = null;\n\tfor (const a of leave.angles ?? []) {\n\t\t// Counter-clockwise as seen on the y-down page.\n\t\tconst r = (a * Math.PI) / 180;\n\t\t// Exactly along an axis for multiples of 90°.\n\t\tconst exact = (n: number) => (Math.abs(n) < 1e-12 ? 0 : n);\n\t\tconst dir = { x: exact(Math.cos(r)), y: exact(-Math.sin(r)) };\n\t\tconst k = v.x * dir.x + v.y * dir.y;\n\t\tconst point = { x: leave.at.x + dir.x * k, y: leave.at.y + dir.y * k };\n\t\tconst d = distance(point, p);\n\t\tif (d <= tol && (!best || d < best.d)) best = { dir, point, d };\n\t}\n\treturn best && { dir: best.dir, point: best.point };\n}\n\nconst dotCondition = (r: Point, d: Point) => r[0] * d[0] + r[1] * d[1];\nconst crossCondition = (r: Point, d: Point) => r[0] * d[1] - r[1] * d[0];\n\n/**\n * The points of a segment where `cond(B(t) − base, B′(t))` is zero: sign changes of samples,\n * narrowed by bisection, kept when the normalised condition is (nearly) zero there.\n */\nfunction solveOnSegment(seg: readonly Point[], base: Vec2, cond: (r: Point, d: Point) => number): Vec2[] {\n\tconst b: Point = [base.x, base.y];\n\tconst g = (t: number) => {\n\t\tconst p = segmentPoint(seg, t);\n\t\treturn cond([p[0] - b[0], p[1] - b[1]], segmentDerivative(seg, t));\n\t};\n\tconst vals: number[] = [];\n\tlet scale = 0;\n\tfor (let i = 0; i <= CURVE_SAMPLES; i++) {\n\t\tconst t = i / CURVE_SAMPLES;\n\t\tconst p = segmentPoint(seg, t);\n\t\tconst d = segmentDerivative(seg, t);\n\t\tconst r: Point = [p[0] - b[0], p[1] - b[1]];\n\t\tvals.push(cond(r, d));\n\t\tscale = Math.max(scale, Math.hypot(r[0], r[1]) * Math.hypot(d[0], d[1]));\n\t}\n\t// Every point qualifies (a line seen from a point on it): no particular solution.\n\tif (!(scale > 0) || vals.every((v) => Math.abs(v) <= scale * 1e-12)) return [];\n\tconst out: Vec2[] = [];\n\tfor (let i = 0; i < CURVE_SAMPLES; i++) {\n\t\tconst ga = vals[i];\n\t\tconst gb = vals[i + 1];\n\t\tif (!(Number.isFinite(ga) && Number.isFinite(gb)) || (ga > 0 === gb > 0 && ga !== 0)) continue;\n\t\tlet lo = i / CURVE_SAMPLES;\n\t\tlet hi = (i + 1) / CURVE_SAMPLES;\n\t\tlet flo = ga;\n\t\tfor (let k = 0; k < BISECT; k++) {\n\t\t\tconst m = (lo + hi) / 2;\n\t\t\tconst fm = g(m);\n\t\t\tif (fm === 0) {\n\t\t\t\tlo = hi = m;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (fm > 0 === flo > 0) {\n\t\t\t\tlo = m;\n\t\t\t\tflo = fm;\n\t\t\t} else hi = m;\n\t\t}\n\t\tconst t = (lo + hi) / 2;\n\t\tconst p = segmentPoint(seg, t);\n\t\tconst dv = segmentDerivative(seg, t);\n\t\tconst r = Math.hypot(p[0] - b[0], p[1] - b[1]);\n\t\tconst dl = Math.hypot(dv[0], dv[1]);\n\t\tif (!(r > 1e-9 && dl > 0) || Math.abs(cond([p[0] - b[0], p[1] - b[1]], dv)) > 1e-6 * r * dl) continue;\n\t\tif (!out.some((q) => Math.hypot(q.x - p[0], q.y - p[1]) <= 1e-9 * (1 + r))) out.push({ x: p[0], y: p[1] });\n\t}\n\treturn out;\n}\n","/**\n * Path editing on subpaths in a node's own space: anchor deletion that keeps the shape,\n * segment bending, Curvature-tool anchor moves, cutting at anchors (Scissors), Join, Average,\n * Remove Redundant Points and Smooth.\n *\n * Portions ported from (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md):\n * - vectorcraft-main/crates/pathops/src/edit.rs (`remove_anchor`, `golden_min`, `smooth`,\n * `remove_redundant_points`, `merge_pair`, `average`, `join`)\n * - vectorcraft-main/crates/geom/src/path.rs (`SubPath::cut_at`)\n * - vectorcraft-main/crates/tools/src/draw2/curvature.rs (`curvature_move`)\n * - figcraft-main/crates/engine/src/vectoredit/ops.rs (`bend`)\n */\nimport type { Point } from '../canvas/types.js';\nimport { fitCubicWithTangents } from '../canvas/curveFit.js';\nimport { segmentPoint } from '../canvas/pathops/bezier.js';\nimport { cloneAnchor, inferAnchorType, insertAnchor, moveAnchorHandle, subpathSegment, subpathSegmentCount } from './geometry.js';\nimport type { VectorAnchor, VectorSubpath, Vec2 } from './types.js';\n\nconst EPS = 1e-9;\n\n// ---------------------------------------------------------------------------\n// Small helpers\n// ---------------------------------------------------------------------------\n\nconst unit = (x: number, y: number): Point | null => {\n\tconst l = Math.hypot(x, y);\n\treturn l > 1e-12 && Number.isFinite(l) ? [x / l, y / l] : null;\n};\n\n/** Segment `i` as four control points (a line has its controls at the thirds of its chord). */\nfunction cubicOf(sp: VectorSubpath, i: number): Point[] {\n\tconst s = subpathSegment(sp, i);\n\tif (s.length === 4) return s;\n\tconst [a, b] = s;\n\treturn [a, [a[0] + (b[0] - a[0]) / 3, a[1] + (b[1] - a[1]) / 3], [a[0] + (2 * (b[0] - a[0])) / 3, a[1] + (2 * (b[1] - a[1])) / 3], b];\n}\n\nconst isLine = (sp: VectorSubpath, i: number) => subpathSegment(sp, i).length === 2;\n\n/** Direction the curve leaves `c[0]`. */\nfunction startTangent(c: readonly Point[]): Point {\n\tfor (let k = 1; k < 4; k++) {\n\t\tconst u = unit(c[k][0] - c[0][0], c[k][1] - c[0][1]);\n\t\tif (u) return u;\n\t}\n\treturn [1, 0];\n}\n\n/** Direction the curve arrives at `c[3]` (forward along the curve). */\nfunction endTangent(c: readonly Point[]): Point {\n\tfor (let k = 2; k >= 0; k--) {\n\t\tconst u = unit(c[3][0] - c[k][0], c[3][1] - c[k][1]);\n\t\tif (u) return u;\n\t}\n\treturn [1, 0];\n}\n\n/** `n + 1` points of a cubic at even parameters (`withStart` false skips the first). */\nfunction sample(c: readonly Point[], n: number, out: Point[], withStart: boolean) {\n\tfor (let i = withStart ? 0 : 1; i <= n; i++) out.push(segmentPoint(c, i / n));\n}\n\nconst onAnchor = (a: VectorAnchor, h: Vec2 | null | undefined) => !h || (Math.abs(h.x - a.x) < EPS && Math.abs(h.y - a.y) < EPS);\n\n/** Drops handles that sit on their anchor and sets the type the handles show (a symmetric pair that is no longer equal becomes smooth). */\nfunction tidy(a: VectorAnchor, keepType = true): VectorAnchor {\n\tconst next = cloneAnchor(a);\n\tif (onAnchor(next, next.in)) delete next.in;\n\tif (onAnchor(next, next.out)) delete next.out;\n\tconst shown = inferAnchorType(next);\n\tconst type = keepType && a.type ? (a.type === 'symmetric' && shown !== 'symmetric' ? (shown === 'corner' ? 'corner' : 'smooth') : a.type === 'smooth' && shown === 'corner' ? 'corner' : a.type) : shown;\n\tif (type === 'corner') delete next.type;\n\telse next.type = type;\n\treturn next;\n}\n\n/** Index of the anchor before / after `i` (round the start of a closed subpath), or -1. */\nfunction neighbours(sp: VectorSubpath, i: number): [number, number] {\n\tconst n = sp.anchors.length;\n\tconst wrap = sp.closed && n > 1;\n\treturn [i > 0 ? i - 1 : wrap ? n - 1 : -1, i < n - 1 ? i + 1 : wrap ? 0 : -1];\n}\n\n// ---------------------------------------------------------------------------\n// Deleting anchors without changing the shape\n// ---------------------------------------------------------------------------\n\n/**\n * The value of `f` with the least error for an argument in [a, b], by a golden-section search\n * (a fixed number of steps). An error that is not a number never wins.\n */\nfunction goldenMin<T extends { error: number }>(f: (x: number) => T, a: number, b: number): T {\n\tconst R = 0.618033988749895;\n\tlet x1 = b - R * (b - a);\n\tlet x2 = a + R * (b - a);\n\tlet f1 = f(x1);\n\tlet f2 = f(x2);\n\tfor (let i = 0; i < 40; i++) {\n\t\tif (f1.error < f2.error || Number.isNaN(f2.error)) {\n\t\t\tb = x2;\n\t\t\tx2 = x1;\n\t\t\tf2 = f1;\n\t\t\tx1 = b - R * (b - a);\n\t\t\tf1 = f(x1);\n\t\t} else {\n\t\t\ta = x1;\n\t\t\tx1 = x2;\n\t\t\tf1 = f2;\n\t\t\tx2 = a + R * (b - a);\n\t\t\tf2 = f(x2);\n\t\t}\n\t}\n\treturn f1.error <= f2.error ? f1 : f2;\n}\n\n/**\n * One cubic through `pts`: `N + 1` samples of a left curve then `N` of a right one. The new\n * curve passes their joint at some parameter k: the left samples sit at k·i/N, the right ones\n * at k + (1 − k)·i/N. Searches k for the closest fit.\n */\nfunction fitAcross(pts: Point[], N: number, t0: Point, t1: Point) {\n\tconst fit = (k: number) => {\n\t\tconst u: number[] = [];\n\t\tfor (let i = 0; i <= N; i++) u.push((k * i) / N);\n\t\tfor (let i = 1; i <= N; i++) u.push(k + ((1 - k) * i) / N);\n\t\treturn fitCubicWithTangents(pts, u, t0, t1);\n\t};\n\treturn goldenMin(fit, 0, 1);\n}\n\n/**\n * Removes anchor `index` without opening the path: its neighbours keep their handle directions\n * and their facing handles are refitted so one cubic follows the two segments that met there\n * as closely as possible (least maximum error over where the new curve passes the removed\n * point). Two straight segments become one; removing an end of an open subpath drops its\n * segment. Returns the subpath unchanged (a copy) when `index` is out of range.\n */\nexport function removeAnchorKeepingShape(sp: VectorSubpath, index: number): VectorSubpath {\n\tconst anchors = sp.anchors.map(cloneAnchor);\n\tconst n = anchors.length;\n\tif (index < 0 || index >= n) return { anchors, closed: sp.closed };\n\tif ((sp.closed || (index > 0 && index < n - 1)) && n >= 3) {\n\t\tconst pi = (index + n - 1) % n;\n\t\tconst ni = (index + 1) % n;\n\t\tif (!(isLine(sp, pi) && isLine(sp, index))) {\n\t\t\tconst left = cubicOf(sp, pi);\n\t\t\tconst right = cubicOf(sp, index);\n\t\t\tconst N = 16;\n\t\t\tconst pts: Point[] = [];\n\t\t\tsample(left, N, pts, true);\n\t\t\tsample(right, N, pts, false);\n\t\t\tconst t0 = startTangent(left);\n\t\t\tconst t1 = endTangent(right);\n\t\t\tconst { curve } = fitAcross(pts, N, t0, t1);\n\t\t\tif ([curve.p1, curve.p2].every((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]))) {\n\t\t\t\tanchors[pi] = tidy({ ...anchors[pi], out: { x: curve.p1[0], y: curve.p1[1] } });\n\t\t\t\tanchors[ni] = tidy({ ...anchors[ni], in: { x: curve.p2[0], y: curve.p2[1] } });\n\t\t\t}\n\t\t}\n\t}\n\tanchors.splice(index, 1);\n\tlet closed = sp.closed;\n\tif (!closed && anchors.length) {\n\t\t// A new end has nothing beyond it.\n\t\tanchors[0] = tidy({ ...anchors[0], in: null });\n\t\tconst last = anchors.length - 1;\n\t\tanchors[last] = tidy({ ...anchors[last], out: null });\n\t}\n\tif (anchors.length < 3) closed = closed && anchors.length === 2 && anchors.some((a) => a.in || a.out);\n\treturn { anchors, closed };\n}\n\n/** Removes several anchors of a subpath, keeping the shape (see `removeAnchorKeepingShape`). */\nexport function removeAnchorsKeepingShape(sp: VectorSubpath, indices: readonly number[]): VectorSubpath {\n\tconst order = [...new Set(indices)].filter((i) => i >= 0 && i < sp.anchors.length).sort((a, b) => b - a);\n\treturn order.reduce((acc, i) => removeAnchorKeepingShape(acc, i), { anchors: sp.anchors.map(cloneAnchor), closed: sp.closed });\n}\n\n// ---------------------------------------------------------------------------\n// Bending a segment\n// ---------------------------------------------------------------------------\n\n/**\n * Bends segment `segment` so the curve passes through `p` at parameter `t` (clamped to\n * 0.05–0.95): its handles go to the thirds of the chord plus one shared offset, so\n * `B(t) = L(t) + 3t(1 − t)·offset` exactly. The end anchors keep their types (a smooth or\n * symmetric end turns its other handle to stay in line).\n */\nexport function bendSegment(sp: VectorSubpath, segment: number, t: number, p: Vec2): VectorSubpath {\n\tconst anchors = sp.anchors.map(cloneAnchor);\n\tconst n = anchors.length;\n\tif (segment < 0 || segment >= subpathSegmentCount(sp) || !Number.isFinite(t) || !Number.isFinite(p.x) || !Number.isFinite(p.y)) return { anchors, closed: sp.closed };\n\tconst tc = Math.min(0.95, Math.max(0.05, t));\n\tconst ia = segment;\n\tconst ib = (segment + 1) % n;\n\tconst a = anchors[ia];\n\tconst b = anchors[ib];\n\tconst k = 3 * tc * (1 - tc);\n\tconst ox = (p.x - (a.x + (b.x - a.x) * tc)) / k;\n\tconst oy = (p.y - (a.y + (b.y - a.y) * tc)) / k;\n\tconst c1 = { x: a.x + (b.x - a.x) / 3 + ox, y: a.y + (b.y - a.y) / 3 + oy };\n\tconst c2 = { x: b.x + (a.x - b.x) / 3 + ox, y: b.y + (a.y - b.y) / 3 + oy };\n\tanchors[ia] = moveAnchorHandle(a, 'out', c1);\n\tanchors[ib] = moveAnchorHandle(b, 'in', c2);\n\treturn { anchors, closed: sp.closed };\n}\n\n/** The point at parameter `t` of segment `segment` (for tests and previews). */\nexport function subpathPointAt(sp: VectorSubpath, segment: number, t: number): Vec2 {\n\tconst [x, y] = segmentPoint(subpathSegment(sp, segment), t);\n\treturn { x, y };\n}\n\n// ---------------------------------------------------------------------------\n// Curvature-tool anchor move\n// ---------------------------------------------------------------------------\n\n/**\n * Moves anchor `index` to `q` the way the Curvature tool drags a point: only the two segments\n * at it change. A smooth or symmetric anchor turns its handles along the line through its\n * neighbours; the neighbours' handles on those segments, and a corner's own handles, keep\n * their directions while their lengths scale with their segment's chord, so the segments\n * beyond don't move and a corner without handles keeps none.\n */\nexport function curvatureMoveAnchor(sp: VectorSubpath, index: number, q: Vec2): VectorSubpath {\n\tconst anchors = sp.anchors.map(cloneAnchor);\n\tconst a = sp.anchors[index];\n\tif (!a) return { anchors, closed: sp.closed };\n\tconst own: [Vec2 | null, Vec2 | null] = [\n\t\ta.in && !onAnchor(a, a.in) ? { x: a.in.x - a.x, y: a.in.y - a.y } : null,\n\t\ta.out && !onAnchor(a, a.out) ? { x: a.out.x - a.x, y: a.out.y - a.y } : null\n\t];\n\tconst ends: [Vec2 | null, Vec2 | null] = [null, null];\n\tneighbours(sp, index).forEach((j, side) => {\n\t\tif (j < 0 || j === index) return;\n\t\tconst b = anchors[j];\n\t\tconst old = Math.hypot(a.x - b.x, a.y - b.y);\n\t\tconst s = old > 1e-9 ? Math.hypot(q.x - b.x, q.y - b.y) / old : 1;\n\t\tconst key = side === 0 ? 'out' : 'in';\n\t\tconst h = b[key];\n\t\tif (h) b[key] = { x: b.x + (h.x - b.x) * s, y: b.y + (h.y - b.y) * s };\n\t\tconst o = own[side];\n\t\tif (o) own[side] = { x: o.x * s, y: o.y * s };\n\t\tends[side] = { x: b.x, y: b.y };\n\t});\n\tconst moved: VectorAnchor = { x: q.x, y: q.y };\n\tif (own[0]) moved.in = { x: q.x + own[0].x, y: q.y + own[0].y };\n\tif (own[1]) moved.out = { x: q.x + own[1].x, y: q.y + own[1].y };\n\tif (a.type) moved.type = a.type;\n\tif (a.corner) moved.corner = { ...a.corner };\n\tconst [prev, next] = ends;\n\tif (a.type && a.type !== 'corner' && prev && next) {\n\t\tconst dx = next.x - prev.x;\n\t\tconst dy = next.y - prev.y;\n\t\tconst l = Math.hypot(dx, dy);\n\t\tif (l > 1e-9) {\n\t\t\t// A handle it lacks comes out a third of the way to that side's neighbour.\n\t\t\tconst len = (h: Vec2 | null, to: Vec2) => (h ? Math.hypot(h.x, h.y) : Math.hypot(q.x - to.x, q.y - to.y) / 3);\n\t\t\tlet li = len(own[0], prev);\n\t\t\tlet lo = len(own[1], next);\n\t\t\tif (a.type === 'symmetric') li = lo = (li + lo) / 2;\n\t\t\tmoved.in = { x: q.x - (dx * li) / l, y: q.y - (dy * li) / l };\n\t\t\tmoved.out = { x: q.x + (dx * lo) / l, y: q.y + (dy * lo) / l };\n\t\t}\n\t}\n\tanchors[index] = moved;\n\treturn { anchors, closed: sp.closed };\n}\n\n// ---------------------------------------------------------------------------\n// Scissors\n// ---------------------------------------------------------------------------\n\n/**\n * Cuts a subpath at the anchors `at`: each becomes the end of one open piece and the start of\n * the next, its handle off each piece dropped (the shape doesn't change). A closed subpath\n * opens at its first cut, so one cut leaves one piece whose ends coincide. The ends of an open\n * subpath and indices out of range don't cut; with no cut left the subpath comes back as it is.\n */\nexport function cutSubpathAt(sp: VectorSubpath, at: readonly number[]): VectorSubpath[] {\n\tconst n = sp.anchors.length;\n\tconst cuts = [...new Set(at)].filter((i) => Number.isInteger(i) && i >= 0 && i < n && (sp.closed || (i > 0 && i < n - 1))).sort((a, b) => a - b);\n\tif (!cuts.length || n < 2) return [{ anchors: sp.anchors.map(cloneAnchor), closed: sp.closed }];\n\tconst first = cuts[0];\n\t// A closed subpath's anchors from the first cut round to it again; an open one's as they are.\n\tconst run = sp.closed ? Array.from({ length: n + 1 }, (_, i) => sp.anchors[(first + i) % n]) : sp.anchors;\n\tconst cutSet = new Set(sp.closed ? [...cuts.map((c) => (c - first + n) % n), n] : cuts);\n\tconst pieces: VectorSubpath[] = [];\n\tlet cur: VectorAnchor[] = [];\n\trun.forEach((a, i) => {\n\t\tif (!cutSet.has(i)) {\n\t\t\tcur.push(cloneAnchor(a));\n\t\t\treturn;\n\t\t}\n\t\tif (cur.length) {\n\t\t\tcur.push(tidy({ ...a, out: null }, false));\n\t\t\tpieces.push({ anchors: cur, closed: false });\n\t\t\tcur = [];\n\t\t}\n\t\tif (i < n) cur.push(tidy({ ...a, in: null }, false));\n\t});\n\tif (cur.length > 1) pieces.push({ anchors: cur, closed: false });\n\treturn pieces;\n}\n\n/**\n * Cuts a subpath at parameter `t` of segment `segment` (Scissors on a segment): an anchor is\n * inserted there without changing the shape, then cut. Within `endTolerance` of the segment's\n * ends (in parameter) the existing anchor is cut instead.\n */\nexport function splitSubpathAt(sp: VectorSubpath, segment: number, t: number, endTolerance = 1e-6): VectorSubpath[] {\n\tconst n = sp.anchors.length;\n\tif (segment < 0 || segment >= subpathSegmentCount(sp)) return [{ anchors: sp.anchors.map(cloneAnchor), closed: sp.closed }];\n\tif (t <= endTolerance) return cutSubpathAt(sp, [segment]);\n\tif (t >= 1 - endTolerance) return cutSubpathAt(sp, [(segment + 1) % n]);\n\tconst { subpath, index } = insertAnchor(sp, segment, t);\n\treturn cutSubpathAt(subpath, [index]);\n}\n\n// ---------------------------------------------------------------------------\n// Join\n// ---------------------------------------------------------------------------\n\nconst endOf = (sp: VectorSubpath, last: boolean): VectorAnchor => sp.anchors[last ? sp.anchors.length - 1 : 0];\nconst dist = (a: Vec2, b: Vec2) => Math.hypot(a.x - b.x, a.y - b.y);\n\nfunction reverse(sp: VectorSubpath): VectorSubpath {\n\treturn {\n\t\tclosed: sp.closed,\n\t\tanchors: sp.anchors\n\t\t\t.slice()\n\t\t\t.reverse()\n\t\t\t.map((a) => {\n\t\t\t\tconst next: VectorAnchor = { x: a.x, y: a.y };\n\t\t\t\tif (a.out) next.in = { ...a.out };\n\t\t\t\tif (a.in) next.out = { ...a.in };\n\t\t\t\tif (a.type) next.type = a.type;\n\t\t\t\tif (a.corner) next.corner = { ...a.corner };\n\t\t\t\treturn next;\n\t\t\t})\n\t};\n}\n\n/**\n * Join: open subpaths are joined nearest-endpoints-first into one open subpath (endpoints\n * within `tolerance` merge into one anchor, otherwise a straight segment connects them). A\n * single open subpath is closed instead (its ends merged when they meet). Closed subpaths and\n * lone anchors pass through unchanged, before the joined one.\n */\nexport function joinSubpaths(subpaths: readonly VectorSubpath[], tolerance: number): VectorSubpath[] {\n\tconst closed: VectorSubpath[] = [];\n\tlet open: VectorSubpath[] = [];\n\tfor (const sp of subpaths) {\n\t\tconst copy = { anchors: sp.anchors.map(cloneAnchor), closed: sp.closed };\n\t\tif (sp.closed || sp.anchors.length < 2) {\n\t\t\tif (sp.anchors.length) closed.push(copy);\n\t\t} else open.push(copy);\n\t}\n\tif (open.length === 1) {\n\t\tconst sp = open[0];\n\t\tconst first = sp.anchors[0];\n\t\tconst last = sp.anchors[sp.anchors.length - 1];\n\t\tif (sp.anchors.length > 2 && dist(first, last) <= tolerance) {\n\t\t\tsp.anchors.pop();\n\t\t\tsp.anchors[0] = tidy({ ...first, in: last.in ?? null }, false);\n\t\t} else {\n\t\t\tsp.anchors[0] = tidy({ ...first, in: null }, false);\n\t\t\tsp.anchors[sp.anchors.length - 1] = tidy({ ...sp.anchors[sp.anchors.length - 1], out: null }, false);\n\t\t}\n\t\tsp.closed = true;\n\t\treturn [...closed, sp];\n\t}\n\twhile (open.length > 1) {\n\t\t// The closest pair of endpoints on different subpaths.\n\t\tlet best = { d: Infinity, i: 0, j: 1, ei: true, ej: false };\n\t\tfor (let i = 0; i < open.length; i++) {\n\t\t\tfor (let j = i + 1; j < open.length; j++) {\n\t\t\t\tfor (const ei of [false, true]) {\n\t\t\t\t\tfor (const ej of [false, true]) {\n\t\t\t\t\t\tconst d = dist(endOf(open[i], ei), endOf(open[j], ej));\n\t\t\t\t\t\tif (d < best.d) best = { d, i, j, ei, ej };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tlet a = open[best.i];\n\t\tlet b = open[best.j];\n\t\topen = open.filter((_, k) => k !== best.j);\n\t\t// `a` ends at the meeting point, `b` starts there.\n\t\tif (!best.ei) a = reverse(a);\n\t\tif (best.ej) b = reverse(b);\n\t\tconst anchors = a.anchors;\n\t\tif (best.d <= tolerance) {\n\t\t\tconst [head, ...rest] = b.anchors;\n\t\t\tconst l = anchors[anchors.length - 1];\n\t\t\tanchors[anchors.length - 1] = tidy({ ...l, out: head.out ?? null }, false);\n\t\t\tanchors.push(...rest);\n\t\t} else {\n\t\t\tconst l = anchors[anchors.length - 1];\n\t\t\tanchors[anchors.length - 1] = tidy({ ...l, out: null }, false);\n\t\t\tanchors.push(tidy({ ...b.anchors[0], in: null }, false), ...b.anchors.slice(1));\n\t\t}\n\t\topen[best.i > best.j ? best.i - 1 : best.i] = { anchors, closed: false };\n\t}\n\treturn [...closed, ...open];\n}\n\n// ---------------------------------------------------------------------------\n// Smooth and Remove Redundant Points\n// ---------------------------------------------------------------------------\n\n/**\n * Smooth: pulls handles towards Catmull-Rom-like tangents (a third of the way to each\n * neighbour along the line through both). `amount` 0–1 (0 = unchanged, 1 = fully smooth).\n * Only the anchors in `only` change when it is given; endpoints of open subpaths keep their\n * handles. Subpaths of fewer than three anchors are unchanged.\n */\nexport function smoothSubpath(sp: VectorSubpath, amount = 1, only?: ReadonlySet<number>): VectorSubpath {\n\tconst t = Math.min(1, Math.max(0, amount));\n\tconst orig = sp.anchors;\n\tconst n = orig.length;\n\tconst anchors = orig.map(cloneAnchor);\n\tif (n < 3 || t === 0) return { anchors, closed: sp.closed };\n\tfor (let i = 0; i < n; i++) {\n\t\tif (!sp.closed && (i === 0 || i === n - 1)) continue;\n\t\tif (only && !only.has(i)) continue;\n\t\tconst prev = orig[(i + n - 1) % n];\n\t\tconst next = orig[(i + 1) % n];\n\t\tconst p = orig[i];\n\t\tconst dir = unit(next.x - prev.x, next.y - prev.y);\n\t\tif (!dir) continue;\n\t\tconst li = dist(p, prev) / 3;\n\t\tconst lo = dist(p, next) / 3;\n\t\tconst hin = p.in ?? p;\n\t\tconst hout = p.out ?? p;\n\t\tconst target = (h: Vec2, x: number, y: number) => ({ x: h.x + (x - h.x) * t, y: h.y + (y - h.y) * t });\n\t\tanchors[i] = tidy(\n\t\t\t{\n\t\t\t\tx: p.x,\n\t\t\t\ty: p.y,\n\t\t\t\tin: target(hin, p.x - dir[0] * li, p.y - dir[1] * li),\n\t\t\t\tout: target(hout, p.x + dir[0] * lo, p.y + dir[1] * lo)\n\t\t\t},\n\t\t\tfalse\n\t\t);\n\t}\n\treturn { anchors, closed: sp.closed };\n}\n\ninterface Seg {\n\tc: Point[];\n\tline: boolean;\n}\n\nfunction segsOf(sp: VectorSubpath): Seg[] {\n\tconst out: Seg[] = [];\n\tfor (let i = 0; i < subpathSegmentCount(sp); i++) {\n\t\tconst s = subpathSegment(sp, i);\n\t\tout.push(s.length === 2 ? { c: s, line: true } : { c: s, line: false });\n\t}\n\treturn out;\n}\n\n/** A subpath from consecutive segments (anchor types inferred; original types kept where they still hold). */\nfunction segsToSubpath(segs: readonly Seg[], closed: boolean, types: Map<string, VectorAnchor['type']>): VectorSubpath | null {\n\tif (!segs.length) return null;\n\tconst anchors: VectorAnchor[] = [];\n\tconst at = (p: Point): VectorAnchor => ({ x: p[0], y: p[1] });\n\tanchors.push(at(segs[0].c[0]));\n\tfor (const s of segs) {\n\t\tconst end = s.c[s.c.length - 1];\n\t\tif (!s.line) anchors[anchors.length - 1].out = { x: s.c[1][0], y: s.c[1][1] };\n\t\tconst next = at(end);\n\t\tif (!s.line) next.in = { x: s.c[2][0], y: s.c[2][1] };\n\t\tanchors.push(next);\n\t}\n\tif (closed) {\n\t\tconst last = anchors.pop()!;\n\t\tif (last.in) anchors[0].in = last.in;\n\t}\n\tconst typed = anchors.map((a) => {\n\t\tconst type = types.get(`${a.x},${a.y}`);\n\t\treturn tidy(type ? { ...a, type } : a, !!type);\n\t});\n\treturn { anchors: typed, closed };\n}\n\nconst isZeroSeg = (s: Seg) => s.c.every((p) => Math.abs(p[0] - s.c[0][0]) < 1e-9 && Math.abs(p[1] - s.c[0][1]) < 1e-9);\n\n/** One segment replacing `a` then `b` within `tol`, or null. */\nfunction mergePair(a: Seg, b: Seg, tol: number): Seg | null {\n\tconst a0 = a.c[0];\n\tconst a3 = a.c[a.c.length - 1];\n\tconst b3 = b.c[b.c.length - 1];\n\tif (a.line && b.line) {\n\t\tconst cx = b3[0] - a0[0];\n\t\tconst cy = b3[1] - a0[1];\n\t\tconst len = Math.hypot(cx, cy);\n\t\tif (len < 1e-12) return null;\n\t\tconst mx = a3[0] - a0[0];\n\t\tconst my = a3[1] - a0[1];\n\t\tconst along = (mx * cx + my * cy) / len;\n\t\treturn Math.abs((mx * cy - my * cx) / len) <= tol && along >= 0 && along <= len ? { c: [a0, b3], line: true } : null;\n\t}\n\tconst ca = a.line ? [a0, a0, a3, a3] : a.c;\n\tconst cb = b.line ? [a3, a3, b3, b3] : b.c;\n\tconst ta = endTangent(ca);\n\tconst tb = startTangent(cb);\n\t// Only merge across (near-)smooth joints.\n\tif (ta[0] * tb[0] + ta[1] * tb[1] < 0.99) return null;\n\tconst pts: Point[] = [];\n\tsample(ca, 16, pts, true);\n\tsample(cb, 16, pts, false);\n\tconst { curve, error } = fitAcross(pts, 16, startTangent(ca), endTangent(cb));\n\treturn error <= tol ? { c: [curve.p0, curve.p1, curve.p2, curve.p3], line: false } : null;\n}\n\n/**\n * Remove Redundant Points: drops anchors that can go without changing the shape by more than\n * `tolerance` (collinear corners, duplicate points, and smooth joints that one cubic can\n * replace).\n */\nexport function removeRedundantPoints(sp: VectorSubpath, tolerance: number): VectorSubpath {\n\tconst tol = Math.max(tolerance, 1e-9);\n\tconst types = new Map(sp.anchors.filter((a) => a.type).map((a) => [`${a.x},${a.y}`, a.type] as const));\n\tconst segs = segsOf(sp).filter((s) => !isZeroSeg(s));\n\tif (!segs.length) return { anchors: sp.anchors.map(cloneAnchor), closed: sp.closed };\n\tconst minSegs = sp.closed ? 2 : 1;\n\tlet changed = true;\n\twhile (changed && segs.length > minSegs) {\n\t\tchanged = false;\n\t\tconst n = segs.length;\n\t\tconst joints = sp.closed ? n : n - 1;\n\t\tfor (let j = 0; j < joints; j++) {\n\t\t\tconst [i0, i1] = sp.closed ? [(j + n - 1) % n, j] : [j, j + 1];\n\t\t\tconst m = mergePair(segs[i0], segs[i1], tol);\n\t\t\tif (!m) continue;\n\t\t\tsegs[i0] = m;\n\t\t\tsegs.splice(i1, 1);\n\t\t\t// The merged segment now starts the loop.\n\t\t\tif (sp.closed && i1 === 0) segs.unshift(segs.pop()!);\n\t\t\tchanged = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn segsToSubpath(segs, sp.closed, types) ?? { anchors: sp.anchors.map(cloneAnchor), closed: sp.closed };\n}\n","/**\n * Knife and eraser on Bézier paths, built on the curve booleans and `outlineStroke`.\n *\n * The knife cuts filled regions along a polyline with no gap: each stretch of the polyline\n * that crosses a region from boundary to boundary (a chord) splits the boundary loop it starts\n * and ends on into two loops sharing that chord, or, when it joins two loops (an outline and a\n * hole), merges them into one. Crossings are exact (line–cubic roots), and the pieces share\n * the cut edge exactly.\n *\n * The eraser removes the area of a round-capped stroke along a polyline: filled shapes lose it\n * by a boolean difference; outlines are cut where they cross the stroke's outline (exact\n * curve–curve intersections) and keep the parts outside it.\n *\n * Modelled on vectorcraft-main/crates/engine/src/cmd/draw2.rs (`knife`, `erase_region`,\n * `erase_outline`, `cut_subpath`; MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md), without its fixed knife slit and its sampled crossing search.\n */\nimport type { Point } from '../canvas/types.js';\nimport {\n\tbezierPathBounds,\n\tcloseContour,\n\tcontourSignedArea,\n\tcontoursToPath,\n\tpathToContours,\n\tpointInBezierPath,\n\tsegmentBounds,\n\tsegmentPoint,\n\tsubSegment,\n\twindingNumber,\n\ttype BezierPath,\n\ttype BezierPathInput\n} from '../canvas/pathops/bezier.js';\nimport { normalizeBezierPath, pathBoolean, segmentIntersections } from '../canvas/pathops/boolean.js';\nimport { outlineStroke } from '../canvas/pathops/stroke.js';\nimport { inferAnchorType, subpathSegment, subpathSegmentCount } from './geometry.js';\nimport type { VectorAnchor, VectorSubpath } from './types.js';\n\ntype FillRule = 'nonzero' | 'evenodd';\n\n// ---------------------------------------------------------------------------\n// Faces: an outer loop with its holes\n// ---------------------------------------------------------------------------\n\ninterface Loop {\n\tsegs: Point[][];\n\t/** Which segments came from a knife chord (not sampled for containment). */\n\tchord: boolean[];\n}\n\ninterface Face {\n\tloops: Loop[];\n}\n\nconst loopArea = (l: Loop) => contourSignedArea(l.segs);\n\n/** A point on the loop that is not on a chord (chords are shared with a neighbouring piece). */\nfunction loopSample(l: Loop): Point {\n\tconst k = l.chord.findIndex((c) => !c);\n\treturn segmentPoint(l.segs[k >= 0 ? k : 0], 0.5);\n}\n\nconst contains = (l: Loop, p: Point) => windingNumber([l.segs], p) !== 0;\n\n/**\n * Groups non-crossing loops into faces: loops turning like the largest one are outlines, the\n * others holes of the smallest outline around them.\n */\nfunction groupFaces(loops: Loop[]): Face[] {\n\tconst usable = loops.filter((l) => l.segs.length && Math.abs(loopArea(l)) > 1e-12);\n\tif (!usable.length) return [];\n\tconst largest = usable.reduce((a, b) => (Math.abs(loopArea(b)) > Math.abs(loopArea(a)) ? b : a));\n\tconst sign = Math.sign(loopArea(largest));\n\tconst outers = usable.filter((l) => Math.sign(loopArea(l)) === sign).sort((a, b) => Math.abs(loopArea(a)) - Math.abs(loopArea(b)));\n\tconst faces = new Map<Loop, Face>(outers.map((o) => [o, { loops: [o] }]));\n\tfor (const hole of usable.filter((l) => Math.sign(loopArea(l)) !== sign)) {\n\t\tconst p = loopSample(hole);\n\t\tconst parent = outers.find((o) => Math.abs(loopArea(o)) > Math.abs(loopArea(hole)) && contains(o, p));\n\t\tif (parent) faces.get(parent)!.loops.push(hole);\n\t}\n\treturn outers.reverse().map((o) => faces.get(o)!);\n}\n\nfunction faceToPath(face: Face): BezierPath {\n\treturn contoursToPath(face.loops.map((l) => ({ segments: l.segs, closed: true })));\n}\n\n/** Simple, consistently oriented faces of a filled path. */\nfunction facesOf(path: BezierPathInput, fillRule: FillRule): Face[] {\n\tconst normalized = normalizeBezierPath(path, fillRule);\n\tconst loops = pathToContours(normalized).map((c) => {\n\t\tconst segs = closeContour(c, true).map((s) => s.slice());\n\t\treturn { segs, chord: segs.map(() => false) };\n\t});\n\treturn groupFaces(loops);\n}\n\n/** One path per face (an outline with its holes) of a filled path, largest first. */\nexport function splitIntoFaces(path: BezierPathInput, fillRule: FillRule = 'nonzero'): BezierPath[] {\n\treturn facesOf(path, fillRule).map(faceToPath);\n}\n\n// ---------------------------------------------------------------------------\n// Line × segment crossings\n// ---------------------------------------------------------------------------\n\n/** Real roots in [0, 1] of `a·t³ + b·t² + c·t + d` (monotone pieces, bisection). */\nfunction rootsInUnit(a: number, b: number, c: number, d: number, scale: number): number[] {\n\tconst f = (t: number) => ((a * t + b) * t + c) * t + d;\n\tconst tol = 1e-12 * Math.max(1, scale);\n\t// Critical points split [0, 1] into monotone pieces.\n\tconst cuts = [0];\n\tconst qa = 3 * a;\n\tconst qb = 2 * b;\n\tif (Math.abs(qa) > 1e-18) {\n\t\tconst disc = qb * qb - 4 * qa * c;\n\t\tif (disc >= 0) {\n\t\t\tconst r = Math.sqrt(disc);\n\t\t\tfor (const t of [(-qb - r) / (2 * qa), (-qb + r) / (2 * qa)].sort((x, y) => x - y)) if (t > 0 && t < 1) cuts.push(t);\n\t\t}\n\t} else if (Math.abs(qb) > 1e-18) {\n\t\tconst t = -c / qb;\n\t\tif (t > 0 && t < 1) cuts.push(t);\n\t}\n\tcuts.push(1);\n\tconst roots: number[] = [];\n\tconst push = (t: number) => {\n\t\tif (!roots.some((r) => Math.abs(r - t) < 1e-9)) roots.push(t);\n\t};\n\tfor (let i = 0; i < cuts.length - 1; i++) {\n\t\tlet lo = cuts[i];\n\t\tlet hi = cuts[i + 1];\n\t\tlet flo = f(lo);\n\t\tconst fhi = f(hi);\n\t\tif (Math.abs(flo) <= tol) push(lo);\n\t\tif (Math.abs(fhi) <= tol) push(hi);\n\t\tif (flo * fhi >= 0) continue;\n\t\tfor (let k = 0; k < 80; k++) {\n\t\t\tconst m = (lo + hi) / 2;\n\t\t\tconst fm = f(m);\n\t\t\tif (fm === 0) {\n\t\t\t\tlo = hi = m;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (fm * flo < 0) hi = m;\n\t\t\telse {\n\t\t\t\tlo = m;\n\t\t\t\tflo = fm;\n\t\t\t}\n\t\t}\n\t\tpush((lo + hi) / 2);\n\t}\n\treturn roots.sort((x, y) => x - y);\n}\n\n/** Where the line `p → q` crosses a segment: `s` on the line (0–1), `t` on the segment. Parallel overlaps are not crossings. */\nfunction lineHits(p: Point, q: Point, seg: readonly Point[]): { s: number; t: number; point: Point }[] {\n\tconst dx = q[0] - p[0];\n\tconst dy = q[1] - p[1];\n\tconst len2 = dx * dx + dy * dy;\n\tif (len2 < 1e-24) return [];\n\t// Signed distance (times |d|) of the segment from the line, as a polynomial in t.\n\tconst h = (pt: Point) => (pt[0] - p[0]) * -dy + (pt[1] - p[1]) * dx;\n\tlet coeffs: [number, number, number, number];\n\tif (seg.length === 2) coeffs = [0, 0, h(seg[1]) - h(seg[0]), h(seg[0])];\n\telse {\n\t\tconst [h0, h1, h2, h3] = seg.map(h);\n\t\tcoeffs = [-h0 + 3 * h1 - 3 * h2 + h3, 3 * h0 - 6 * h1 + 3 * h2, -3 * h0 + 3 * h1, h0];\n\t}\n\tif (coeffs.every((c) => Math.abs(c) < 1e-12 * Math.max(1, len2))) return [];\n\tconst scale = Math.sqrt(len2) * Math.max(1, ...seg.map((pt) => Math.abs(pt[0]) + Math.abs(pt[1])));\n\tconst out: { s: number; t: number; point: Point }[] = [];\n\tfor (const t of rootsInUnit(...coeffs, scale)) {\n\t\tconst point = segmentPoint(seg, t);\n\t\tconst s = ((point[0] - p[0]) * dx + (point[1] - p[1]) * dy) / len2;\n\t\tif (s >= -1e-9 && s <= 1 + 1e-9) out.push({ s: Math.min(1, Math.max(0, s)), t, point });\n\t}\n\treturn out;\n}\n\n// ---------------------------------------------------------------------------\n// Knife\n// ---------------------------------------------------------------------------\n\ninterface Hit {\n\t/** Knife position: segment index + parameter. */\n\ts: number;\n\tloop: number;\n\tseg: number;\n\tt: number;\n\tpoint: Point;\n}\n\nconst near = (a: Point, b: Point, eps: number) => Math.abs(a[0] - b[0]) <= eps && Math.abs(a[1] - b[1]) <= eps;\nconst degenerate = (seg: readonly Point[], eps: number) => seg.every((p) => near(p, seg[0], eps));\n\n/** The loop's pieces from (seg a, t a) forward to (seg b, t b); `full` goes all the way round when they coincide. */\nfunction arc(l: Loop, a: { seg: number; t: number }, b: { seg: number; t: number }, eps: number): { segs: Point[][]; chord: boolean[] } {\n\tconst n = l.segs.length;\n\tconst segs: Point[][] = [];\n\tconst chord: boolean[] = [];\n\tconst push = (k: number, t0: number, t1: number) => {\n\t\tconst piece = t0 <= 0 && t1 >= 1 ? l.segs[k].slice() : subSegment(l.segs[k], t0, t1);\n\t\tif (!degenerate(piece, eps)) {\n\t\t\tsegs.push(piece);\n\t\t\tchord.push(l.chord[k]);\n\t\t}\n\t};\n\tif (a.seg === b.seg && b.t >= a.t + 1e-12) {\n\t\tpush(a.seg, a.t, b.t);\n\t\treturn { segs, chord };\n\t}\n\tpush(a.seg, a.t, 1);\n\tfor (let k = (a.seg + 1) % n; k !== b.seg; k = (k + 1) % n) push(k, 0, 1);\n\tpush(b.seg, 0, b.t);\n\treturn { segs, chord };\n}\n\n/** Line segments through `points`. */\nfunction polySegs(points: readonly Point[], eps: number): Point[][] {\n\tconst out: Point[][] = [];\n\tfor (let i = 1; i < points.length; i++) if (!near(points[i - 1], points[i], eps)) out.push([points[i - 1], points[i]]);\n\treturn out;\n}\n\n/**\n * Cuts the filled path along the open polyline `knife`. Returns one path per resulting face\n * (an outline with its holes), or null when the knife crossed nothing from edge to edge. A\n * stretch of the knife that starts or ends inside the shape does not cut.\n */\nexport function knifePath(path: BezierPathInput, fillRule: FillRule, knife: readonly Point[]): BezierPath[] | null {\n\tconst pts = knife.filter((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]));\n\tif (pts.length < 2) return null;\n\tlet faces = facesOf(path, fillRule);\n\tif (!faces.length) return null;\n\tconst b = bezierPathBounds(path);\n\tconst size = b ? Math.max(b.maxX - b.minX, b.maxY - b.minY, 1) : 1;\n\tconst eps = size * 1e-9;\n\tlet cursor = -Infinity;\n\tlet cuts = 0;\n\tfor (let guard = 0; guard < 512; guard++) {\n\t\tlet best: { face: number; from: Hit; to: Hit } | null = null;\n\t\tfaces.forEach((face, fi) => {\n\t\t\tconst hits: Hit[] = [];\n\t\t\tfor (let m = 0; m < pts.length - 1; m++) {\n\t\t\t\tif (m + 1 < cursor - 1e-9) continue;\n\t\t\t\tconst kb = { minX: Math.min(pts[m][0], pts[m + 1][0]), maxX: Math.max(pts[m][0], pts[m + 1][0]), minY: Math.min(pts[m][1], pts[m + 1][1]), maxY: Math.max(pts[m][1], pts[m + 1][1]) };\n\t\t\t\tface.loops.forEach((l, li) =>\n\t\t\t\t\tl.segs.forEach((seg, si) => {\n\t\t\t\t\t\tconst sb = segmentBounds(seg);\n\t\t\t\t\t\tif (sb.maxX < kb.minX - eps || sb.minX > kb.maxX + eps || sb.maxY < kb.minY - eps || sb.minY > kb.maxY + eps) return;\n\t\t\t\t\t\tfor (const h of lineHits(pts[m], pts[m + 1], seg)) {\n\t\t\t\t\t\t\tconst s = m + h.s;\n\t\t\t\t\t\t\tif (s >= cursor - 1e-9) hits.push({ s, loop: li, seg: si, t: h.t, point: h.point });\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\t}\n\t\t\thits.sort((x, y) => x.s - y.s);\n\t\t\tconst unique = hits.filter((h, i) => i === 0 || h.s - hits[i - 1].s > 1e-9 || !near(h.point, hits[i - 1].point, eps * 10));\n\t\t\tconst inside = (s: number) => {\n\t\t\t\tconst m = Math.min(pts.length - 2, Math.floor(s));\n\t\t\t\tconst u = s - m;\n\t\t\t\tconst q: Point = [pts[m][0] + (pts[m + 1][0] - pts[m][0]) * u, pts[m][1] + (pts[m + 1][1] - pts[m][1]) * u];\n\t\t\t\treturn windingNumber(face.loops.map((l) => l.segs), q) !== 0;\n\t\t\t};\n\t\t\tfor (let i = 0; i < unique.length - 1; i++) {\n\t\t\t\tconst from = unique[i];\n\t\t\t\tconst to = unique[i + 1];\n\t\t\t\tif (near(from.point, to.point, eps * 10) || !inside((from.s + to.s) / 2)) continue;\n\t\t\t\tif (!best || from.s < best.from.s) best = { face: fi, from, to };\n\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t\tif (!best) break;\n\t\tconst { face: fi, from, to } = best as { face: number; from: Hit; to: Hit };\n\t\tconst face = faces[fi];\n\t\t// The chord: the crossing points with the knife's corners between them.\n\t\tconst corners: Point[] = [from.point];\n\t\tfor (let m = Math.floor(from.s) + 1; m <= to.s - 1e-12 && m < pts.length; m++) if (m > from.s) corners.push(pts[m]);\n\t\tcorners.push(to.point);\n\t\tconst forward = polySegs(corners, eps);\n\t\tconst back = polySegs(corners.slice().reverse(), eps);\n\t\tconst la = face.loops[from.loop];\n\t\tconst loops = face.loops.filter((_, i) => i !== from.loop && i !== to.loop);\n\t\tif (from.loop === to.loop) {\n\t\t\tconst ab = arc(la, from, to, eps);\n\t\t\tconst ba = arc(la, to, from, eps);\n\t\t\tloops.push(\n\t\t\t\t{ segs: [...ab.segs, ...back], chord: [...ab.chord, ...back.map(() => true)] },\n\t\t\t\t{ segs: [...ba.segs, ...forward], chord: [...ba.chord, ...forward.map(() => true)] }\n\t\t\t);\n\t\t} else {\n\t\t\t// The chord joins two loops into one, with the chord on both sides of a zero-width slit.\n\t\t\tconst lb = face.loops[to.loop];\n\t\t\tconst roundA = arc(la, from, from, eps);\n\t\t\tconst roundB = arc(lb, to, to, eps);\n\t\t\tloops.push({\n\t\t\t\tsegs: [...roundA.segs, ...forward, ...roundB.segs, ...back],\n\t\t\t\tchord: [...roundA.chord, ...forward.map(() => true), ...roundB.chord, ...back.map(() => true)]\n\t\t\t});\n\t\t}\n\t\tfaces = [...faces.slice(0, fi), ...groupFaces(loops), ...faces.slice(fi + 1)];\n\t\tcursor = to.s;\n\t\tcuts++;\n\t}\n\treturn cuts ? faces.map(faceToPath) : null;\n}\n\n// ---------------------------------------------------------------------------\n// Eraser\n// ---------------------------------------------------------------------------\n\n/** The area a round eraser of diameter `width` covers along `points` (a disc for one point). */\nexport function eraserRegion(points: readonly Point[], width: number): BezierPath {\n\tconst pts = points.filter((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]));\n\tconst r = width / 2;\n\tif (!pts.length || !(r > 0)) return [];\n\tconst moved = pts.some((p) => !near(p, pts[0], 1e-9));\n\tif (!moved) {\n\t\tconst [cx, cy] = pts[0];\n\t\tconst k = r * 0.5522847498307936;\n\t\treturn [\n\t\t\t{ type: 'M', x: cx, y: cy - r },\n\t\t\t{ type: 'C', x1: cx + k, y1: cy - r, x2: cx + r, y2: cy - k, x: cx + r, y: cy },\n\t\t\t{ type: 'C', x1: cx + r, y1: cy + k, x2: cx + k, y2: cy + r, x: cx, y: cy + r },\n\t\t\t{ type: 'C', x1: cx - k, y1: cy + r, x2: cx - r, y2: cy + k, x: cx - r, y: cy },\n\t\t\t{ type: 'C', x1: cx - r, y1: cy - k, x2: cx - k, y2: cy - r, x: cx, y: cy - r },\n\t\t\t{ type: 'Z' }\n\t\t];\n\t}\n\tconst line: BezierPath = [{ type: 'M', x: pts[0][0], y: pts[0][1] }, ...pts.slice(1).map((p) => ({ type: 'L' as const, x: p[0], y: p[1] }))];\n\treturn outlineStroke(line, { width, cap: 'round', join: 'round' });\n}\n\n/**\n * A filled path with `region` removed: one path per remaining face, or null when the region\n * does not overlap the fill.\n */\nexport function eraseFromFill(path: BezierPathInput, fillRule: FillRule, region: BezierPathInput): BezierPath[] | null {\n\tconst overlap = pathBoolean('intersection', [{ path, fillRule }, { path: region }]).path;\n\tif (!pathToContours(overlap).some((c) => Math.abs(contourSignedArea(closeContour(c, true))) > 1e-9)) return null;\n\tconst rest = pathBoolean('difference', [{ path, fillRule }, { path: region }]).path;\n\treturn splitIntoFaces(rest);\n}\n\n/**\n * The parts of a subpath's outline outside `region`, as open subpaths that keep the original\n * curves exactly; null when the outline does not enter the region. A closed subpath's last\n * and first parts join at its first anchor.\n */\nexport function eraseFromOutline(sp: VectorSubpath, region: BezierPathInput): VectorSubpath[] | null {\n\tconst regionSegs = pathToContours(region).flatMap((c) => closeContour(c, true));\n\tif (!regionSegs.length) return null;\n\tconst rb = bezierPathBounds(region);\n\tconst count = subpathSegmentCount(sp);\n\tif (!rb || count === 0) return null;\n\tconst removed = (p: Point) => pointInBezierPath(region, p, 'nonzero');\n\ttype Piece = { seg: number; t0: number; t1: number };\n\tconst runs: Piece[][] = [];\n\tlet cur: Piece[] = [];\n\tlet any = false;\n\tfor (let i = 0; i < count; i++) {\n\t\tconst seg = subpathSegment(sp, i);\n\t\tconst sb = segmentBounds(seg);\n\t\tconst ts = [0, 1];\n\t\tif (!(sb.maxX < rb.minX || sb.minX > rb.maxX || sb.maxY < rb.minY || sb.minY > rb.maxY)) {\n\t\t\tfor (const r of regionSegs) {\n\t\t\t\tconst b = segmentBounds(r);\n\t\t\t\tif (b.maxX < sb.minX || b.minX > sb.maxX || b.maxY < sb.minY || b.minY > sb.maxY) continue;\n\t\t\t\tfor (const hit of segmentIntersections(seg, r)) if (hit.ta > 1e-9 && hit.ta < 1 - 1e-9) ts.push(hit.ta);\n\t\t\t}\n\t\t}\n\t\tts.sort((a, b) => a - b);\n\t\tfor (let k = 0; k < ts.length - 1; k++) {\n\t\t\tconst t0 = ts[k];\n\t\t\tconst t1 = ts[k + 1];\n\t\t\tif (t1 - t0 < 1e-9) continue;\n\t\t\tif (removed(segmentPoint(seg, (t0 + t1) / 2))) {\n\t\t\t\tany = true;\n\t\t\t\tif (cur.length) runs.push(cur);\n\t\t\t\tcur = [];\n\t\t\t} else cur.push({ seg: i, t0, t1 });\n\t\t}\n\t}\n\tif (cur.length) runs.push(cur);\n\tif (!any) return null;\n\t// A closed path's last and first runs meet at anchor 0.\n\tif (sp.closed && runs.length >= 2) {\n\t\tconst first = runs[0][0];\n\t\tconst lastRun = runs[runs.length - 1];\n\t\tconst last = lastRun[lastRun.length - 1];\n\t\tif (first.seg === 0 && first.t0 === 0 && last.seg === count - 1 && last.t1 === 1) lastRun.push(...runs.shift()!);\n\t}\n\tconst out: VectorSubpath[] = [];\n\tfor (const run of runs) {\n\t\tconst anchors: VectorAnchor[] = [];\n\t\tfor (const { seg, t0, t1 } of run) {\n\t\t\tconst c = subSegment(subpathSegment(sp, seg), t0, t1);\n\t\t\tconst line = c.length === 2;\n\t\t\tconst start = c[0];\n\t\t\tconst end = c[c.length - 1];\n\t\t\tif (!anchors.length) anchors.push({ x: start[0], y: start[1] });\n\t\t\tif (!line) anchors[anchors.length - 1].out = { x: c[1][0], y: c[1][1] };\n\t\t\tconst next: VectorAnchor = { x: end[0], y: end[1] };\n\t\t\tif (!line) next.in = { x: c[2][0], y: c[2][1] };\n\t\t\tanchors.push(next);\n\t\t}\n\t\tif (anchors.length < 2) continue;\n\t\tfor (const a of anchors) {\n\t\t\tconst type = inferAnchorType(a);\n\t\t\tif (type !== 'corner') a.type = type;\n\t\t}\n\t\tout.push({ anchors, closed: false });\n\t}\n\treturn out;\n}\n\n/** Bounds of a point list (for picking the paths a knife or eraser stroke can reach). */\nexport function polylineBounds(points: readonly Point[], pad = 0): { x: number; y: number; width: number; height: number } | null {\n\tif (!points.length) return null;\n\tlet minX = Infinity;\n\tlet minY = Infinity;\n\tlet maxX = -Infinity;\n\tlet maxY = -Infinity;\n\tfor (const [x, y] of points) {\n\t\tminX = Math.min(minX, x);\n\t\tminY = Math.min(minY, y);\n\t\tmaxX = Math.max(maxX, x);\n\t\tmaxY = Math.max(maxY, y);\n\t}\n\treturn { x: minX - pad, y: minY - pad, width: maxX - minX + 2 * pad, height: maxY - minY + 2 * pad };\n}\n\n/** Ramer–Douglas–Peucker reduction of a polyline (keeps both ends). */\nexport function simplifyPolyline(points: readonly Point[], tolerance: number): Point[] {\n\tconst n = points.length;\n\tif (n < 3) return points.slice();\n\tconst keep = new Array<boolean>(n).fill(false);\n\tkeep[0] = keep[n - 1] = true;\n\tconst stack: [number, number][] = [[0, n - 1]];\n\twhile (stack.length) {\n\t\tconst [a, b] = stack.pop()!;\n\t\tconst [ax, ay] = points[a];\n\t\tconst dx = points[b][0] - ax;\n\t\tconst dy = points[b][1] - ay;\n\t\tconst len = Math.hypot(dx, dy);\n\t\tlet far = -1;\n\t\tlet farD = 0;\n\t\tfor (let i = a + 1; i < b; i++) {\n\t\t\tconst [px, py] = points[i];\n\t\t\tconst d = len < 1e-12 ? Math.hypot(px - ax, py - ay) : Math.abs((px - ax) * dy - (py - ay) * dx) / len;\n\t\t\tif (d > farD) {\n\t\t\t\tfarD = d;\n\t\t\t\tfar = i;\n\t\t\t}\n\t\t}\n\t\tif (far >= 0 && farD > tolerance) {\n\t\t\tkeep[far] = true;\n\t\t\tstack.push([a, far], [far, b]);\n\t\t}\n\t}\n\treturn points.filter((_, i) => keep[i]);\n}\n\n","/**\n * Pencil helpers: lazy-mouse smoothing (a pulled string between the pointer and the pen) and\n * ink-to-shape recognition (a hand-drawn stroke that is a line, rectangle, ellipse or polygon).\n *\n * Portions ported from (MIT OR Apache-2.0, © ArtCraft Team and contributors; see\n * THIRD_PARTY_NOTICES.md):\n * - photocraft-main/crates/paint/src/dynamics.rs (`Smoother`: pulled-string mode, `string`,\n * `finish` with catch-up on stroke end)\n * - wordcraft-main/crates/engine/src/cmd/ink_shape.rs (`recognise`, `ellipse_rms`,\n * `snap_square`, `corners`, `turning`, `rdp`, `upright`)\n */\nimport type { Point } from '../canvas/types.js';\n\n// ---------------------------------------------------------------------------\n// Lazy mouse\n// ---------------------------------------------------------------------------\n\n/**\n * Pulled-string smoothing: the pen stays put until the pointer is more than `length` away,\n * then follows it at that distance, so small wobbles never reach the stroke. Feed pointer\n * positions to `push`; it returns the pen positions to draw through (possibly none).\n */\nexport class LazyMouse {\n\tprivate pos: Point | null = null;\n\tprivate last: Point | null = null;\n\n\t/** `length` is the string length in the units of the points (0 turns smoothing off). */\n\tconstructor(readonly length: number) {}\n\n\tpush(p: Point): Point[] {\n\t\tthis.last = p;\n\t\tif (!(this.length > 0)) return [p];\n\t\tconst pos = this.pos;\n\t\tif (!pos) {\n\t\t\tthis.pos = p;\n\t\t\treturn [p];\n\t\t}\n\t\tconst dx = p[0] - pos[0];\n\t\tconst dy = p[1] - pos[1];\n\t\tconst d = Math.hypot(dx, dy);\n\t\tif (d <= this.length) return [];\n\t\tconst k = (d - this.length) / d;\n\t\tconst next: Point = [pos[0] + dx * k, pos[1] + dy * k];\n\t\tthis.pos = next;\n\t\treturn [next];\n\t}\n\n\t/** The string from the pen to the pointer while they are apart, else null. */\n\tstring(): [Point, Point] | null {\n\t\tconst { pos, last } = this;\n\t\tif (!(this.length > 0) || !pos || !last || (pos[0] === last[0] && pos[1] === last[1])) return null;\n\t\treturn [pos, last];\n\t}\n\n\t/** End of stroke: the pen catches up with the pointer (the point to add, if it lagged). */\n\tfinish(): Point[] {\n\t\tconst { pos, last } = this;\n\t\tif (!(this.length > 0) || !pos || !last || (pos[0] === last[0] && pos[1] === last[1])) return [];\n\t\tthis.pos = last;\n\t\treturn [last];\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Ink to shape\n// ---------------------------------------------------------------------------\n\n/** A shape recognised in a stroke, in the stroke's coordinates. */\nexport type VectorInkShape =\n\t| { kind: 'line'; a: Point; b: Point }\n\t| { kind: 'rect'; x: number; y: number; width: number; height: number }\n\t| { kind: 'ellipse'; x: number; y: number; width: number; height: number }\n\t| { kind: 'polygon'; points: Point[] };\n\nexport interface RecognizeInkOptions {\n\t/** Strokes whose longer side is smaller than this stay ink (default 6). */\n\tminSize?: number;\n}\n\n/** Most corners a recognised polygon may have. */\nexport const VECTOR_INK_MAX_CORNERS = 8;\nconst MAX_POINTS = 100_000;\n\n/** \"line\", \"square\", \"rectangle\", \"circle\", \"ellipse\", \"triangle\" or \"polygon\". */\nexport function vectorInkShapeName(shape: VectorInkShape): string {\n\tswitch (shape.kind) {\n\t\tcase 'line':\n\t\t\treturn 'line';\n\t\tcase 'rect':\n\t\t\treturn shape.width === shape.height ? 'square' : 'rectangle';\n\t\tcase 'ellipse':\n\t\t\treturn shape.width === shape.height ? 'circle' : 'ellipse';\n\t\tcase 'polygon':\n\t\t\treturn shape.points.length === 3 ? 'triangle' : 'polygon';\n\t}\n}\n\nconst dist = (a: Point, b: Point) => Math.hypot(b[0] - a[0], b[1] - a[1]);\n\nfunction bbox(pts: readonly Point[]): [number, number, number, number] {\n\tif (!pts.length) return [0, 0, 0, 0];\n\tlet [x0, y0] = pts[0];\n\tlet [x1, y1] = pts[0];\n\tfor (const [x, y] of pts) {\n\t\tx0 = Math.min(x0, x);\n\t\ty0 = Math.min(y0, y);\n\t\tx1 = Math.max(x1, x);\n\t\ty1 = Math.max(y1, y);\n\t}\n\treturn [x0, y0, x1 - x0, y1 - y0];\n}\n\nfunction segDistance(a: Point, b: Point, p: Point): number {\n\tconst dx = b[0] - a[0];\n\tconst dy = b[1] - a[1];\n\tconst len2 = dx * dx + dy * dy;\n\tconst t = len2 > 0 ? Math.min(1, Math.max(0, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / len2)) : 0;\n\treturn dist([a[0] + t * dx, a[1] + t * dy], p);\n}\n\nfunction polygonDistance(c: readonly Point[], p: Point): number {\n\tlet best = Infinity;\n\tfor (let i = 0; i < c.length; i++) best = Math.min(best, segDistance(c[i], c[(i + 1) % c.length], p));\n\treturn best;\n}\n\n/** RMS of each point's normalised radius minus one on the ellipse inscribed in the box (0 on it). */\nfunction ellipseRms(p: readonly Point[], x0: number, y0: number, w: number, h: number): number {\n\tconst rx = w / 2;\n\tconst ry = h / 2;\n\tif (rx <= 0 || ry <= 0 || !p.length) return Infinity;\n\tconst cx = x0 + rx;\n\tconst cy = y0 + ry;\n\tlet sum = 0;\n\tfor (const [x, y] of p) sum += (Math.hypot((x - cx) / rx, (y - cy) / ry) - 1) ** 2;\n\treturn Math.sqrt(sum / p.length);\n}\n\n/** A box drawn nearly square made square (same centre). */\nfunction snapSquare(x: number, y: number, w: number, h: number): [number, number, number, number] {\n\tif (Math.abs(w - h) <= 0.12 * Math.max(w, h)) {\n\t\tconst s = (w + h) / 2;\n\t\treturn [x + (w - s) / 2, y + (h - s) / 2, s, s];\n\t}\n\treturn [x, y, w, h];\n}\n\n/** How far the path turns at `b` coming from `a` towards `c`, in degrees (0 = straight on). */\nfunction turning(a: Point, b: Point, c: Point): number {\n\tconst u = [b[0] - a[0], b[1] - a[1]];\n\tconst v = [c[0] - b[0], c[1] - b[1]];\n\tconst lu = Math.hypot(u[0], u[1]);\n\tconst lv = Math.hypot(v[0], v[1]);\n\tif (lu <= 0 || lv <= 0) return 0;\n\treturn (Math.acos(Math.min(1, Math.max(-1, (u[0] * v[0] + u[1] * v[1]) / (lu * lv)))) * 180) / Math.PI;\n}\n\n/** Ramer–Douglas–Peucker reduction of an open polyline (iterative), keeping both ends. */\nfunction rdp(p: readonly Point[], eps: number): Point[] {\n\tconst n = p.length;\n\tif (n < 3) return p.slice();\n\tconst keep = new Array<boolean>(n).fill(false);\n\tkeep[0] = keep[n - 1] = true;\n\tconst stack: [number, number][] = [[0, n - 1]];\n\twhile (stack.length) {\n\t\tconst [a, b] = stack.pop()!;\n\t\tlet far = a;\n\t\tlet farD = 0;\n\t\tfor (let i = a + 1; i < b; i++) {\n\t\t\tconst d = segDistance(p[a], p[b], p[i]);\n\t\t\tif (d > farD) {\n\t\t\t\tfarD = d;\n\t\t\t\tfar = i;\n\t\t\t}\n\t\t}\n\t\tif (farD > eps) {\n\t\t\tkeep[far] = true;\n\t\t\tstack.push([a, far], [far, b]);\n\t\t}\n\t}\n\treturn p.filter((_, i) => keep[i]);\n}\n\n/** Corners of the closed path through `p`: RDP split at the point farthest from the start, then flat and crowded corners merged away. */\nfunction corners(p: readonly Point[], diag: number): Point[] {\n\tconst eps = 0.05 * diag;\n\tconst start = p[0];\n\tlet far = 0;\n\tlet farD = 0;\n\tp.forEach((q, i) => {\n\t\tconst d = dist(start, q);\n\t\tif (d > farD) {\n\t\t\tfarD = d;\n\t\t\tfar = i;\n\t\t}\n\t});\n\tconst a = p.slice(0, far);\n\tconst b = p.slice(far);\n\tconst ring = rdp([...a, ...b.slice(0, 1)], eps);\n\tconst back = rdp([...b, start], eps);\n\t// The halves share the far point and the start.\n\tring.pop();\n\tback.pop();\n\tring.push(...back);\n\twhile (ring.length > 3) {\n\t\tconst n = ring.length;\n\t\tconst turn = (i: number) => turning(ring[(i + n - 1) % n], ring[i], ring[(i + 1) % n]);\n\t\tlet flat = 0;\n\t\tlet flatT = Infinity;\n\t\tfor (let i = 0; i < n; i++) {\n\t\t\tconst t = turn(i);\n\t\t\tif (t < flatT) {\n\t\t\t\tflatT = t;\n\t\t\t\tflat = i;\n\t\t\t}\n\t\t}\n\t\tlet short = -1;\n\t\tfor (let j = 0; j < n; j++) {\n\t\t\tif (dist(ring[j], ring[(j + 1) % n]) < 0.1 * diag) {\n\t\t\t\tshort = j;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (flatT < 30) ring.splice(flat, 1);\n\t\telse if (short >= 0) {\n\t\t\t// Of the two crowded corners keep the sharper.\n\t\t\tconst k = turn(short) < turn((short + 1) % n) ? short : (short + 1) % n;\n\t\t\tring.splice(k, 1);\n\t\t} else break;\n\t}\n\treturn ring;\n}\n\n/** A quadrilateral whose sides run (nearly) across and down, alternately. */\nfunction upright(c: readonly Point[]): boolean {\n\tconst n = c.length;\n\tconst dirs = c.map((a, i) => {\n\t\tconst b = c[(i + 1) % n];\n\t\tconst deg = ((((Math.atan2(b[1] - a[1], b[0] - a[0]) * 180) / Math.PI) % 180) + 180) % 180;\n\t\tif (deg <= 15 || deg >= 165) return 'across';\n\t\tif (deg >= 75 && deg <= 105) return 'down';\n\t\treturn null;\n\t});\n\treturn dirs.every((d) => d !== null) && dirs.every((d, i) => d !== dirs[(i + 1) % n]);\n}\n\n/**\n * The shape a hand-drawn stroke draws, if it is one: an open stroke is a line when it stays\n * close to the chord between its ends; a closed one is an ellipse when its points sit on the\n * ellipse inscribed in their bounds, else a polygon of 3–8 corners when that polygon stays\n * close to every point (an upright four-cornered one is a rectangle). Nearly square boxes\n * become squares and circles. Anything else (scribbles, curves, letters) is null.\n */\nexport function recognizeInkShape(points: readonly Point[], options: RecognizeInkOptions = {}): VectorInkShape | null {\n\tconst minSize = options.minSize ?? 6;\n\tconst p: Point[] = [];\n\tfor (const q of points.slice(0, MAX_POINTS)) {\n\t\tif (!Number.isFinite(q[0]) || !Number.isFinite(q[1]) || Math.abs(q[0]) >= 1e9 || Math.abs(q[1]) >= 1e9) continue;\n\t\tconst last = p[p.length - 1];\n\t\tif (!last || last[0] !== q[0] || last[1] !== q[1]) p.push([q[0], q[1]]);\n\t}\n\tif (p.length < 2) return null;\n\tconst first = p[0];\n\tconst last = p[p.length - 1];\n\tconst [x0, y0, w, h] = bbox(p);\n\tconst size = Math.max(w, h);\n\tconst diag = Math.hypot(w, h);\n\tif (size < minSize) return null;\n\tlet length = 0;\n\tfor (let i = 1; i < p.length; i++) length += dist(p[i - 1], p[i]);\n\tconst gap = dist(first, last);\n\t// A line: the stroke barely leaves the chord between its ends and doesn't double back.\n\tif (gap > 0.85 * length && gap >= minSize) {\n\t\tconst off = Math.max(...p.map((q) => segDistance(first, last, q)));\n\t\tif (off <= Math.max(0.06 * gap, (1.5 * minSize) / 6)) return { kind: 'line', a: first, b: last };\n\t}\n\t// Other shapes are closed: the stroke ends near where it began and goes around.\n\tif (gap > 0.2 * size || length < 2 * size) return null;\n\tconst rms = ellipseRms(p, x0, y0, w, h);\n\tconst roundish = w > 0.2 * size && h > 0.2 * size;\n\tconst ellipse = (): VectorInkShape => {\n\t\tconst [x, y, sw, sh] = snapSquare(x0, y0, w, h);\n\t\treturn { kind: 'ellipse', x, y, width: sw, height: sh };\n\t};\n\tif (roundish && rms < 0.06) return ellipse();\n\tconst c = corners(p, diag);\n\tconst fits = c.length >= 3 && p.every((q) => polygonDistance(c, q) <= 0.08 * diag);\n\tif (fits && c.length === 4 && upright(c)) {\n\t\tconst [bx, by, bw, bh] = bbox(c);\n\t\tconst [x, y, sw, sh] = snapSquare(bx, by, bw, bh);\n\t\treturn { kind: 'rect', x, y, width: sw, height: sh };\n\t}\n\tif (fits && c.length <= VECTOR_INK_MAX_CORNERS) return { kind: 'polygon', points: c };\n\t// A wobbly round stroke is still an ellipse.\n\treturn roundish && rms < 0.1 ? ellipse() : null;\n}\n","/**\n * Pathfinder operands, the Shape Builder and fill regions over a vector document.\n *\n * Everything works in document space: each path is mapped through its own transform and its\n * parents', with live corners cut (`subpathsToBezier`), so rotated nodes and nodes inside\n * rotated groups take part as drawn. The controller maps results back into the space of the node\n * that receives them.\n *\n * - **Pathfinder operands**: a filled path is its fill area (every subpath closed); an unfilled\n * path with a stroke is the area its stroke paints (alignment, caps, joins and arrowheads\n * included) and results from it are filled with the stroke's paint; for Divide an unfilled open\n * path is a cutting line instead.\n * - **Shape Builder**: the planar map of the selected paths (`PlanarMap`). Closed subpaths bound\n * faces whatever their paint (a stroke-only shape's inside is a face), filled open subpaths that\n * enclose an area are closed by an invisible edge, and unfilled open paths cut the faces they\n * cross; their pieces between junctions can be erased. Merging faces unites them along the\n * map's own edges and takes the area away from every shape covering them. Erasing (Alt) also\n * takes the edges of the other outlines, cut where paths meet: a closed subpath opens there,\n * an open one splits, and an edge bounding a face deleted in the same gesture goes with it.\n * - **Fill regions** (paint bucket): the planar map of every visible outline; the region around a\n * point is traced from a ray (`PlanarMap.regionAt`).\n *\n * The Shape Builder follows vectorcraft-main/crates/tools/src/builder.rs (`BuilderMap`, `hit`,\n * `sides`, `line_between`, `erased_edges`, `Hit::Edge`, `shape_builder_shapes`, `sample_polyline`)\n * and crates/engine/src/cmd/buildcmds.rs (`sb_merge`), with figcraft-main/crates/engine/src/shapebuilder.rs\n * (strokes as their outlined area). MIT OR Apache-2.0, © ArtCraft Team and contributors. See\n * THIRD_PARTY_NOTICES.md.\n */\nimport type { Point } from '../canvas/types.js';\nimport {\n\tbezierPathBounds,\n\tcontourSignedArea,\n\tcloseContour,\n\tdistanceToBezierPath,\n\tpathToContours,\n\tsegmentPoint,\n\tsegmentTangent,\n\tcontoursToPath,\n\ttype BezierPath,\n\ttype BezierSegment\n} from '../canvas/pathops/bezier.js';\nimport { PlanarMap, cutOutPiece, type PlanarChain } from '../canvas/pathops/planar.js';\nimport type { PathfinderOperation, PathfinderShape } from '../canvas/pathops/pathfinder.js';\nimport { hasPaint, multiplyMatrices, nodeMatrix, subpathsToBezier, vectorPathWorldBezier, vectorStrokeOutline, IDENTITY_MATRIX, type AffineMatrix } from './geometry.js';\nimport type { Vec2, VectorDocument, VectorNode, VectorPaint, VectorPathNode, VectorSubpath } from './types.js';\n\n/** A path node with the matrix of its parent space (parent → document). */\nexport interface VectorPathEntry {\n\tnode: VectorPathNode;\n\tparent: AffineMatrix;\n}\n\n/**\n * The path nodes inside `roots` (or every node when `roots` is null), bottom to top, with their\n * parent matrices. Hidden nodes are skipped, and locked ones unless `locked` is true.\n */\nexport function vectorPathEntries(doc: VectorDocument, roots: readonly string[] | null, options: { locked?: boolean } = {}): VectorPathEntry[] {\n\tconst out: VectorPathEntry[] = [];\n\tconst visit = (node: VectorNode, parent: AffineMatrix, inside: boolean) => {\n\t\tif (node.visible === false || (node.locked && !options.locked)) return;\n\t\tconst picked = inside || roots === null || roots.includes(node.id);\n\t\tif (node.type === 'group') {\n\t\t\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\t\t\tfor (const c of node.children) visit(c, m, picked);\n\t\t} else if (picked) out.push({ node, parent });\n\t};\n\tfor (const n of doc.nodes) visit(n, IDENTITY_MATRIX, false);\n\treturn out;\n}\n\nconst usable = (sp: VectorSubpath) => sp.anchors.length > 1;\n\n/** The entry's outline in document space with the given subpaths. */\nfunction worldOf(entry: VectorPathEntry, subpaths: VectorSubpath[]): BezierPath {\n\treturn vectorPathWorldBezier({ ...entry.node, subpaths }, entry.parent);\n}\n\n/** Whether a subpath, closed, encloses an area (rather than retracing itself). */\nexport function subpathEnclosesArea(sp: VectorSubpath): boolean {\n\tconst contour = pathToContours(subpathsToBezier([{ ...sp, closed: true }]))[0];\n\tif (!contour) return false;\n\tconst segs = closeContour(contour, true);\n\tconst b = bezierPathBounds(contoursToPath([{ segments: segs, closed: true }]));\n\tif (!b) return false;\n\tconst w = b.maxX - b.minX;\n\tconst h = b.maxY - b.minY;\n\treturn Math.abs(contourSignedArea(segs)) > 1e-9 * (w * w + h * h);\n}\n\n/** How an operand takes part in a Pathfinder operation: its fill, its stroke's area, a cutting line or its bare outline. */\nexport type VectorPathfinderPaint = 'fill' | 'stroke' | 'line' | 'outline';\n\nconst paintKey = (paint: VectorPaint | undefined) => (typeof paint === 'string' ? paint.trim().toLowerCase() : JSON.stringify(paint ?? null));\n\n/** The Pathfinder shape of a path (document space), and what it stands for. */\nexport function vectorPathfinderShape(entry: VectorPathEntry, op: PathfinderOperation): PathfinderShape & { paint: VectorPathfinderPaint } {\n\tconst { node } = entry;\n\tconst subpaths = node.subpaths.filter(usable);\n\tconst closed = subpaths.map((s) => ({ ...s, closed: true }));\n\tconst fillRule = node.fillRule ?? 'nonzero';\n\tif (hasPaint(node.fill)) return { path: worldOf(entry, closed), fillRule, key: `fill:${paintKey(node.fill)}`, paint: 'fill' };\n\tconst open = subpaths.length > 0 && subpaths.every((s) => !s.closed);\n\tif (op === 'divide' && open) return { path: worldOf(entry, subpaths), line: true, paint: 'line' };\n\tif (hasPaint(node.stroke) && (node.strokeWidth ?? 1) > 0) {\n\t\t// Node transforms are rigid, so the stroke laid out in document space keeps its width.\n\t\tconst path = vectorStrokeOutline({ ...node, subpaths }, entry.parent);\n\t\treturn { path, fillRule: 'nonzero', key: `fill:${paintKey(node.stroke)}`, paint: 'stroke' };\n\t}\n\treturn { path: worldOf(entry, closed), fillRule, key: 'none', paint: 'outline' };\n}\n\nconst STROKE_KEYS = [\n\t'stroke',\n\t'strokeWidth',\n\t'strokeLinecap',\n\t'strokeLinejoin',\n\t'strokeDasharray',\n\t'strokeAlign',\n\t'startArrow',\n\t'endArrow',\n\t'arrowAlign',\n\t'startArrowScale',\n\t'endArrowScale',\n\t'strokeWidthProfile'\n] as const;\n\n/**\n * Style of a Pathfinder or Shape Builder result taken from `node`: the node's own style for a\n * filled area, the stroke's paint as a fill for a stroke's area, or (for Outline edges) a stroke\n * in the paint of the area the edge bounds. Never carries the node's id, transform or geometry.\n */\nexport function vectorResultStyle(node: VectorPathNode, paint: VectorPathfinderPaint, edge = false): Omit<VectorPathNode, 'id' | 'subpaths'> {\n\tconst { id: _id, subpaths: _s, transform: _t, ...rest } = node;\n\tconst base: Omit<VectorPathNode, 'id' | 'subpaths'> = { ...rest, fillRule: 'nonzero' };\n\tif (edge) {\n\t\tfor (const k of STROKE_KEYS) delete (base as Record<string, unknown>)[k];\n\t\tconst stroke = paint === 'stroke' || !hasPaint(node.fill) ? node.stroke : node.fill;\n\t\treturn { ...base, fill: null, stroke: stroke ?? '#000000', strokeWidth: node.strokeWidth ?? 1 };\n\t}\n\tif (paint === 'stroke') {\n\t\tfor (const k of STROKE_KEYS) delete (base as Record<string, unknown>)[k];\n\t\treturn { ...base, fill: node.stroke ?? null, stroke: null };\n\t}\n\treturn base;\n}\n\n// ---------------------------------------------------------------------------\n// Shape Builder\n// ---------------------------------------------------------------------------\n\n/**\n * A run of a path between the points where other paths meet it (or it ends): a piece of an\n * unfilled open path, or an edge of another path's outline.\n */\nexport interface VectorBuilderLinePiece {\n\tpath: BezierPath;\n\tsegments: BezierSegment[];\n\t/** A loop with no junction on it (the whole subpath). */\n\tclosed: boolean;\n\t/** Index of the entry it belongs to (the front-most where outlines coincide). */\n\tsource: number;\n\tbounds: { minX: number; minY: number; maxX: number; maxY: number };\n}\n\n/** The Shape Builder's planar map of a set of paths. */\nexport interface VectorShapeBuilderMap {\n\tentries: VectorPathEntry[];\n\tmap: PlanarMap;\n\t/** Entries with no closed subpath (cutting lines; their pieces can be erased). */\n\tlines: boolean[];\n\tpieces: VectorBuilderLinePiece[];\n\t/** The edges of the other entries' outlines, cut where paths meet (built on first use: erasing). */\n\treadonly edges: VectorBuilderLinePiece[];\n\t/** How far an edge may lie from the outline it came from (document units). */\n\ttolerance: number;\n}\n\n/** What a Shape Builder gesture touches at a point. */\nexport type VectorBuilderHit = { face: number } | { line: number } | { edge: number };\n\n/** The faces, line pieces and edges a gesture touched, in the order touched. */\nexport interface VectorBuilderTouched {\n\tfaces: number[];\n\tlines: number[];\n\tedges: number[];\n}\n\n/**\n * The Shape Builder map of `entries` (bottom to top). Filled open subpaths that enclose an area\n * are closed. Null when nothing can be mapped.\n */\nexport function vectorShapeBuilderMap(entries: readonly VectorPathEntry[]): VectorShapeBuilderMap | null {\n\tconst lines: boolean[] = [];\n\tconst inputs = entries.map((entry) => {\n\t\tconst filled = hasPaint(entry.node.fill);\n\t\tconst subpaths = entry.node.subpaths.filter(usable).map((sp) => (!sp.closed && filled && subpathEnclosesArea(sp) ? { ...sp, closed: true } : sp));\n\t\tlines.push(!subpaths.some((s) => s.closed));\n\t\treturn { path: worldOf(entry, subpaths), fillRule: entry.node.fillRule ?? 'nonzero' };\n\t});\n\tconst map = PlanarMap.build(inputs);\n\tif (!map) return null;\n\tlet chains: PlanarChain[] | null = null;\n\tconst runs = (line: boolean) =>\n\t\t(chains ??= map.chains())\n\t\t\t.filter((c) => lines[c.source] === line && !(line && c.closed))\n\t\t\t.map((c) => {\n\t\t\t\tconst path = contoursToPath([{ segments: c.segments, closed: c.closed }]);\n\t\t\t\treturn { path, segments: c.segments, closed: c.closed, source: c.source, bounds: bezierPathBounds(path)! };\n\t\t\t});\n\tconst pieces = lines.some(Boolean) ? runs(true) : [];\n\tlet edges: VectorBuilderLinePiece[] | null = null;\n\tlet size = 0;\n\tfor (const input of inputs) {\n\t\tconst b = bezierPathBounds(input.path);\n\t\tif (b) size = Math.max(size, b.maxX - b.minX, b.maxY - b.minY);\n\t}\n\treturn {\n\t\tentries: [...entries],\n\t\tmap,\n\t\tlines,\n\t\tpieces,\n\t\tget edges() {\n\t\t\treturn (edges ??= runs(false));\n\t\t},\n\t\ttolerance: 0.2 * Math.max(size / 2000, 0.25)\n\t};\n}\n\n/** The run of `pieces` nearest `p` within `tol`, with its distance. */\nfunction pieceNear(pieces: readonly VectorBuilderLinePiece[], p: Vec2, tol: number): { index: number; d: number } | null {\n\tconst point: Point = [p.x, p.y];\n\tlet best: { index: number; d: number } | null = null;\n\tpieces.forEach((piece, index) => {\n\t\tconst b = piece.bounds;\n\t\tif (p.x < b.minX - tol || p.x > b.maxX + tol || p.y < b.minY - tol || p.y > b.maxY + tol) return;\n\t\tconst d = distanceToBezierPath(piece.path, point);\n\t\tif (d <= tol && (!best || d < best.d)) best = { index, d };\n\t});\n\treturn best;\n}\n\n/**\n * The face under `p`, or with `lineTolerance` (erasing) first the nearer of the line piece and\n * the outline edge that close.\n */\nexport function vectorShapeBuilderHit(m: VectorShapeBuilderMap, p: Vec2, lineTolerance: number | null = null): VectorBuilderHit | null {\n\tif (lineTolerance !== null && lineTolerance > 0) {\n\t\tconst line = pieceNear(m.pieces, p, lineTolerance);\n\t\tconst edge = pieceNear(m.edges, p, lineTolerance);\n\t\tif (edge && (!line || edge.d < line.d)) return { edge: edge.index };\n\t\tif (line) return { line: line.index };\n\t}\n\tconst face = m.map.faceAt([p.x, p.y]);\n\treturn face >= 0 ? { face } : null;\n}\n\n/** Points along a polyline no more than `step` apart (the pointer's path through faces). */\nexport function samplePolyline(points: readonly Vec2[], step: number): Vec2[] {\n\tconst out: Vec2[] = [];\n\tconst s = Math.max(step, 1e-3);\n\tpoints.forEach((p, i) => {\n\t\tif (i > 0) {\n\t\t\tconst a = points[i - 1];\n\t\t\tconst n = Math.min(4000, Math.ceil(Math.hypot(p.x - a.x, p.y - a.y) / s));\n\t\t\tfor (let k = 1; k < n; k++) out.push({ x: a.x + ((p.x - a.x) * k) / n, y: a.y + ((p.y - a.y) * k) / n });\n\t\t}\n\t\tout.push(p);\n\t});\n\treturn out;\n}\n\n/** Adds what a point hits to `touched` (each face or piece once). */\nexport function addBuilderHit(touched: VectorBuilderTouched, hit: VectorBuilderHit | null): boolean {\n\tif (!hit) return false;\n\tconst [list, i] = 'face' in hit ? [touched.faces, hit.face] : 'line' in hit ? [touched.lines, hit.line] : [touched.edges, hit.edge];\n\tif (list.includes(i)) return false;\n\tlist.push(i);\n\treturn true;\n}\n\n/** The faces just either side of the middle of a line piece (-1 outside every face). */\nfunction sides(m: VectorShapeBuilderMap, piece: VectorBuilderLinePiece): [number, number] {\n\tconst seg = piece.segments[Math.floor(piece.segments.length / 2)];\n\tconst mid = segmentPoint(seg, 0.5);\n\tconst t = segmentTangent(seg, 0.5);\n\tconst chord = Math.hypot(seg[seg.length - 1][0] - seg[0][0], seg[seg.length - 1][1] - seg[0][1]);\n\tconst off = Math.max(1e-6, Math.min(0.05, 0.05 * chord));\n\treturn [m.map.faceAt([mid[0] - t[1] * off, mid[1] + t[0] * off]), m.map.faceAt([mid[0] + t[1] * off, mid[1] - t[0] * off])];\n}\n\n/**\n * The edges a gesture deletes: those it touched that bound none of the faces it touched (an edge\n * of a deleted or merged face goes with the face, so an erase drag that crosses an edge into a\n * face deletes the face).\n */\nexport function vectorBuilderErasedEdges(m: VectorShapeBuilderMap, touched: VectorBuilderTouched): number[] {\n\tif (!touched.edges.length) return [];\n\tconst faces = new Set(touched.faces);\n\treturn touched.edges.filter((k) => m.edges[k] && !sides(m, m.edges[k]).some((f) => f >= 0 && faces.has(f)));\n}\n\n/**\n * What becomes of one entry: unchanged (absent), removed (`null`), or new outlines (document\n * space). `fill`: what is left of its area, filled non-zero (subpaths an erased edge opened stay\n * open); `outline`: its own outline with erased edges cut out, its fill rule kept; `pieces`: the\n * pieces of a cutting line that stay, each its own path.\n */\nexport type VectorBuilderReplacement = { kind: 'fill'; path: BezierPath } | { kind: 'outline'; path: BezierPath } | { kind: 'pieces'; paths: BezierPath[] } | null;\n\nexport interface VectorShapeBuilderPlan {\n\treplace: Map<number, VectorBuilderReplacement>;\n\t/** The merged shape (document space), styled like entry `style`; `currentFill` when only outlines enclosed it. */\n\tmerged: { path: BezierPath; style: number; currentFill: boolean } | null;\n}\n\n/**\n * What a gesture does: merging (or with `erase`, deleting) the touched faces takes them away\n * from every shape covering them; line pieces touched (erasing) or lying between touched faces\n * go; erased edges (`vectorBuilderErasedEdges`) are cut out of every outline they lie on;\n * merging adds the union of the faces as a new shape styled like the top-most shape over the\n * first face touched (or, for a face only outlines enclose, the top-most shape with the current\n * fill).\n */\nexport function planShapeBuilder(m: VectorShapeBuilderMap, touched: VectorBuilderTouched, erase: boolean): VectorShapeBuilderPlan {\n\tconst replace = new Map<number, VectorBuilderReplacement>();\n\tconst picked = new Set(touched.faces);\n\tconst faces = m.map.faces;\n\tconst sourcesOf = faces.map((_, i) => m.map.faceSources(i));\n\tconst cuts = erase ? vectorBuilderErasedEdges(m, touched).map((k) => m.edges[k]) : [];\n\tm.entries.forEach((entry, i) => {\n\t\tif (m.lines[i]) {\n\t\t\tconst own = m.pieces.flatMap((piece, k) => (piece.source === i ? [k] : []));\n\t\t\tconst keep = own.filter((k) => !touched.lines.includes(k) && !sides(m, m.pieces[k]).every((f) => f >= 0 && picked.has(f)));\n\t\t\tif (keep.length === own.length) return;\n\t\t\treplace.set(i, keep.length ? { kind: 'pieces', paths: keep.map((k) => m.pieces[k].path) } : null);\n\t\t\treturn;\n\t\t}\n\t\tconst inUnion = touched.faces.some((f) => sourcesOf[f].includes(i));\n\t\tif (!inUnion && !cuts.length) return;\n\t\tlet rest: BezierPath;\n\t\tif (inUnion) {\n\t\t\tconst kept = faces.flatMap((_, f) => (sourcesOf[f].includes(i) && !picked.has(f) ? [f] : []));\n\t\t\trest = kept.length ? m.map.merge(kept) : [];\n\t\t} else rest = worldOf(entry, entry.node.subpaths.filter(usable));\n\t\t// Each erased edge comes off every outline it lies on (shared edges from each shape).\n\t\tconst fillCloses = hasPaint(entry.node.fill);\n\t\tlet cut = false;\n\t\tfor (const piece of cuts) {\n\t\t\tconst r = rest.length ? cutOutPiece(rest, piece, fillCloses, m.tolerance) : null;\n\t\t\tif (r) {\n\t\t\t\trest = r;\n\t\t\t\tcut = true;\n\t\t\t}\n\t\t}\n\t\tif (!inUnion && !cut) return;\n\t\treplace.set(i, rest.length ? { kind: inUnion ? 'fill' : 'outline', path: rest } : null);\n\t});\n\tlet merged: VectorShapeBuilderPlan['merged'] = null;\n\tif (!erase && touched.faces.length) {\n\t\tconst path = m.map.merge(touched.faces);\n\t\tconst covered = touched.faces.map((f) => sourcesOf[f]).find((s) => s.length);\n\t\tconst lastShape = m.lines.lastIndexOf(false);\n\t\tconst style = covered ? covered[covered.length - 1] : lastShape >= 0 ? lastShape : m.entries.length - 1;\n\t\tif (path.length) merged = { path, style, currentFill: !covered };\n\t}\n\treturn { replace, merged };\n}\n\n// ---------------------------------------------------------------------------\n// Fill regions\n// ---------------------------------------------------------------------------\n\n/**\n * The planar map of every visible path's outline as drawn (locked ones included), for the paint\n * bucket. `gap` closes gaps up to that distance between loose ends.\n */\nexport function vectorFillMap(doc: VectorDocument, gap = 0): PlanarMap | null {\n\tconst entries = vectorPathEntries(doc, null, { locked: true });\n\treturn PlanarMap.build(\n\t\tentries.map((e) => ({ path: worldOf(e, e.node.subpaths.filter(usable)), fills: false })),\n\t\t{ gap, maxSegments: 20000 }\n\t);\n}\n","import { HistoryManager } from '../history/HistoryManager.js';\nimport type { Command } from '../history/types.js';\nimport { fitCubics } from '../canvas/curveFit.js';\nimport { pathBoolean } from '../canvas/pathops/boolean.js';\nimport { pathfinder as runPathfinder } from '../canvas/pathops/pathfinder.js';\nimport type { PlanarMap } from '../canvas/pathops/planar.js';\nimport { bezierPathBounds, bezierPathToSvg, transformBezierPath, type BezierPath } from '../canvas/pathops/bezier.js';\nimport type { Point } from '../canvas/types.js';\nimport {\n\tbezierToSubpaths,\n\tboundsFromPoints,\n\tboundsIntersect,\n\tcloneVectorDocument,\n\tcloneVectorNode,\n\tcollectPathNodes,\n\tconvertAnchor,\n\tellipseSubpath,\n\tfindVectorNode,\n\thitTestVectorNode,\n\thitTestVectorNodes,\n\tinsertAnchor,\n\tlineSubpath,\n\tlocateVectorNode,\n\tmoveAnchorHandle,\n\tnearestSegment,\n\thasPaint,\n\tnodeMatrix,\n\tinvertMatrix,\n\tapplyMatrix,\n\tapplyMatrixLinear,\n\tmultiplyMatrices,\n\tmatrixRotation,\n\tvectorWorldMatrix,\n\tvectorParentMatrix,\n\tvectorPathWorldBezier,\n\tIDENTITY_MATRIX,\n\tpolygonSubpath,\n\trectSubpath,\n\tremoveAnchors,\n\treverseSubpath,\n\trotateMatrix,\n\tscaleMatrix,\n\tstarSubpath,\n\tsubpathsToBezier,\n\ttransformVectorNode,\n\ttranslateAnchor,\n\ttranslateMatrix,\n\tunionBounds,\n\tvectorNodeBounds,\n\twalkVectorNodes,\n\ttype AffineMatrix\n} from './geometry.js';\nimport {\n\tcornerBisectorPoint,\n\tcornerRadiusChange,\n\tfitCornerRadius,\n\tnextVectorCornerKind,\n\tsetAnchorCorner,\n\tsetSubpathCorners,\n\tvectorCorners,\n\ttype VectorCornerInfo\n} from './corners.js';\nimport { strokeWidthProfileOf, vectorStrokeOutlinePath, vectorStrokeParts } from './stroke.js';\nimport { nearestStrokePosition, strokePositionPoint } from './varstroke.js';\nimport {\n\tgenerateWidthProfile,\n\tinsertWidthPoint,\n\tpressureWidthProfile,\n\tremoveWidthPoints,\n\treverseWidthProfile,\n\tsanitizeWidthProfile,\n\tsetWidthPoint,\n\twidthProfileAt,\n\twidthProfileMaxScale,\n\twidthProfilePreset,\n\ttype VectorTaperOptions,\n\ttype VectorWaveOptions,\n\ttype VectorWidthPreset\n} from './width.js';\nimport { parseVectorSvg, vectorDocumentToSvg, type VectorSvgExportOptions } from './svg.js';\nimport { constrainToLeave, VECTOR_CONSTRUCTION_ANGLES, VectorSnapTargets, type VectorSnapGuides, type VectorSnapLeave } from './snap.js';\nimport {\n\tbendSegment as bendSubpathSegment,\n\tcurvatureMoveAnchor,\n\tcutSubpathAt,\n\tjoinSubpaths,\n\tremoveAnchorsKeepingShape,\n\tremoveRedundantPoints as removeRedundantSubpathPoints,\n\tsmoothSubpath,\n\tsplitSubpathAt\n} from './pathEdit.js';\nimport { eraseFromFill, eraseFromOutline, eraserRegion, knifePath, polylineBounds, simplifyPolyline } from './pathCut.js';\nimport { LazyMouse, recognizeInkShape, vectorInkShapeName, type VectorInkShape } from './ink.js';\nimport {\n\taddBuilderHit,\n\tplanShapeBuilder,\n\tsamplePolyline,\n\tvectorFillMap,\n\tvectorPathEntries,\n\tvectorPathfinderShape,\n\tvectorResultStyle,\n\tvectorBuilderErasedEdges,\n\tvectorShapeBuilderHit,\n\tvectorShapeBuilderMap,\n\ttype VectorBuilderTouched,\n\ttype VectorShapeBuilderMap\n} from './builder.js';\nimport type {\n\tVec2,\n\tVectorAlign,\n\tVectorAnchor,\n\tVectorAnchorRef,\n\tVectorAnchorType,\n\tVectorArrange,\n\tVectorAverageAxis,\n\tVectorBooleanOperation,\n\tVectorBounds,\n\tVectorCornerKind,\n\tVectorDefaults,\n\tVectorDistribute,\n\tVectorDocument,\n\tVectorGroupNode,\n\tVectorHandleRef,\n\tVectorModifiers,\n\tVectorNode,\n\tVectorPathfinderOperation,\n\tVectorPathNode,\n\tVectorSegmentRef,\n\tVectorStyle,\n\tVectorSubpath,\n\tVectorTool,\n\tVectorTransformHandle,\n\tVectorViewport,\n\tVectorWidthPoint\n} from './types.js';\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport interface VectorSnapOptions {\n\t/** Grid size in document units (0 = off, default 0). Points and boxes that snap to no object snap to it. */\n\tgrid: number;\n\t/**\n\t * Snap to other objects (default true): anchors, paths and their intersections, bounding-box\n\t * edges and centres, the artboard, construction angles, equal spacing and matching sizes.\n\t */\n\tobjects: boolean;\n\t/** Show smart guide lines and labels while snapping (default true). */\n\tguides: boolean;\n\t/** How near a target pulls, in screen pixels (default 5). */\n\tthreshold: number;\n\t/** Construction guide angles through the point a drawn point leaves from, in degrees (default 0, 45, 90, 135). */\n\tangles: readonly number[];\n}\n\n/** Snap options new editors start with. Hold Cmd / Ctrl (`mod`) during a drag to bypass snapping. */\nexport const DEFAULT_VECTOR_SNAP: Readonly<VectorSnapOptions> = { grid: 0, objects: true, guides: true, threshold: 5, angles: VECTOR_CONSTRUCTION_ANGLES };\n\n/** How path-editing gestures and the pencil, knife and eraser behave. */\nexport interface VectorPathEditOptions {\n\t/**\n\t * Deleting anchors refits the neighbouring handles so the shape stays (default true). Off,\n\t * the neighbours are joined with their handles as they are.\n\t */\n\tkeepShapeOnDelete: boolean;\n\t/**\n\t * Dragging one anchor with the direct tool bends its two segments like the Curvature tool,\n\t * keeping the segments beyond still (default false). Alt held during the drag flips it.\n\t */\n\tcurvatureMoves: boolean;\n\t/** Pencil lazy-mouse smoothing, 0–1: the pulled string is up to 100 screen pixels long (default 0, off). */\n\tpencilSmoothing: number;\n\t/** Pencil strokes that look like a line, rectangle, ellipse or polygon become that shape (default false). */\n\trecognizeShapes: boolean;\n\t/** Eraser diameter in document units (default 10). */\n\teraserSize: number;\n\t/**\n\t * Record pointer pressure on pencil strokes as a width profile: `pen` (default) for pen input\n\t * only, `all` for any pointer that reports pressure, `off` never.\n\t */\n\tpencilPressure: 'pen' | 'all' | 'off';\n\t/**\n\t * Paint bucket: gaps up to this distance (document units) between loose ends of outlines are\n\t * closed when finding the region to fill (default 0, off).\n\t */\n\tfillGap: number;\n}\n\n/** The gap the toolbars' \"Close gaps\" toggle sets (document units). */\nexport const VECTOR_FILL_GAP = 6;\n\n/** Path-editing options new editors start with. */\nexport const DEFAULT_VECTOR_PATH_EDIT: Readonly<VectorPathEditOptions> = {\n\tkeepShapeOnDelete: true,\n\tcurvatureMoves: false,\n\tpencilSmoothing: 0,\n\trecognizeShapes: false,\n\teraserSize: 10,\n\tpencilPressure: 'pen',\n\tfillGap: 0\n};\n\n/** Longest pencil lazy-mouse string (at smoothing 1), in screen pixels. */\nexport const VECTOR_PENCIL_STRING_PX = 100;\n\nexport interface VectorEditorOptions {\n\tdocument?: VectorDocument;\n\t/** History to record into, e.g. one shared with the rest of the app (default: a new one). */\n\thistory?: HistoryManager;\n\t/** Starting tool (default `select`). */\n\ttool?: VectorTool;\n\t/** Style and settings for new shapes and paths. */\n\tdefaults?: VectorDefaults;\n\tviewport?: Partial<VectorViewport>;\n\tsnap?: Partial<VectorSnapOptions>;\n\tediting?: Partial<VectorPathEditOptions>;\n\t/** Pick distance for anchors, handles and outlines in screen pixels (default 6). */\n\thitRadius?: number;\n\t/** Id factory for new nodes. */\n\tcreateId?: () => string;\n\t/** Called after the document changes (edits, undo, redo, load). */\n\tonChange?: (document: VectorDocument) => void;\n}\n\n/** A pointer event as the controller needs it. Positions are in screen pixels relative to the canvas. */\nexport interface VectorPointerInput extends VectorModifiers {\n\t/** 0 = primary, 1 = middle (pans), 2 = secondary. Default 0. */\n\tbutton?: number;\n\t/** `PointerEvent.pressure` (0–1), recorded on pencil strokes. */\n\tpressure?: number;\n\t/** `PointerEvent.pointerType` (`mouse`, `pen`, `touch`). */\n\tpointerType?: string;\n}\n\n/** One width point of a path's stroke profile; `subpath` is the subpath it is shown on. */\nexport interface VectorWidthPointRef {\n\tnodeId: string;\n\tindex: number;\n\tsubpath: number;\n}\n\n/** A spot on a stroke (width tool): where a drag would add a width point. Positions in document units. */\nexport interface VectorStrokeSpot {\n\tnodeId: string;\n\tsubpath: number;\n\t/** Position along the subpath by length, 0–1. */\n\tt: number;\n\tpoint: Vec2;\n\t/** Ends of the stroke's width across the path there. */\n\tleft: Vec2;\n\tright: Vec2;\n}\n\n/** A key press as the controller needs it. */\nexport interface VectorKeyInput extends VectorModifiers {\n\t/** `KeyboardEvent.key`. */\n\tkey: string;\n}\n\n/** What the pointer is over. */\nexport interface VectorHover {\n\tnodeId: string | null;\n\tanchor?: VectorAnchorRef;\n\thandle?: VectorHandleRef;\n\t/** A segment under the pointer (direct tool and scissors); `point` is in document space. */\n\tsegment?: { nodeId: string; subpath: number; segment: number; t: number; point: Vec2 };\n\ttransformHandle?: VectorTransformHandle;\n\t/** A live corner widget (direct tool): the corner's anchor. */\n\tcorner?: VectorAnchorRef;\n\t/** A width point (width tool): its centre or the end of its left / right side. */\n\twidthPoint?: VectorWidthPointRef & { part: 'center' | 'left' | 'right' };\n\t/** A spot on a stroke away from its width points (width tool). */\n\tstrokeSpot?: VectorStrokeSpot;\n}\n\n/** The drag in progress, for overlays and status text. */\nexport type VectorInteraction =\n\t| { type: 'marquee'; bounds: VectorBounds }\n\t| { type: 'move'; dx: number; dy: number }\n\t| { type: 'scale'; handle: VectorTransformHandle; sx: number; sy: number }\n\t| { type: 'rotate'; angle: number }\n\t| { type: 'anchors'; dx: number; dy: number }\n\t| { type: 'handle'; ref: VectorHandleRef }\n\t| { type: 'bend'; ref: VectorSegmentRef }\n\t| { type: 'corner'; ref: VectorAnchorRef; radius: number }\n\t| { type: 'draw'; tool: VectorTool; nodeId: string; bounds: VectorBounds; string?: [Vec2, Vec2] }\n\t| { type: 'stroke'; tool: 'knife' | 'eraser'; points: Vec2[]; width: number }\n\t| { type: 'builder'; mode: 'merge' | 'erase'; points: Vec2[] }\n\t| { type: 'width'; ref: VectorWidthPointRef; mode: 'width' | 'move'; width: number }\n\t| { type: 'pen'; nodeId: string }\n\t| { type: 'pan' };\n\n/** A snapshot of the editor. The same object is returned until something changes. */\nexport interface VectorEditorState {\n\tdocument: VectorDocument;\n\ttool: VectorTool;\n\t/** Selected node ids (top-level nodes or group members picked with the direct tool). */\n\tselection: readonly string[];\n\t/** Selected anchors (direct tool). */\n\tselectedAnchors: readonly VectorAnchorRef[];\n\t/** The selected width point (width tool); Delete removes it. */\n\tselectedWidthPoint: VectorWidthPointRef | null;\n\t/** The path whose anchors are being edited, if any. */\n\teditingId: string | null;\n\t/** Axis-aligned bounds of the selected nodes in document units. */\n\tselectionBounds: VectorBounds | null;\n\t/** The selection box, rotated with the selection when its nodes share a rotation. */\n\tselectionFrame: VectorSelectionFrame | null;\n\tviewport: VectorViewport;\n\tdefaults: Readonly<Required<Pick<VectorDefaults, 'polygonSides' | 'starPoints' | 'starInnerRatio' | 'cornerRadius'>> & Pick<VectorDefaults, 'cornerKind'> & VectorStyle>;\n\tsnap: VectorSnapOptions;\n\tediting: VectorPathEditOptions;\n\t/** Smart guides of the snap in progress, in document units (null when there are none). */\n\tguides: VectorSnapGuides | null;\n\thitRadius: number;\n\thover: VectorHover | null;\n\t/** A CSS cursor for the canvas. */\n\tcursor: string;\n\tinteraction: VectorInteraction | null;\n\t/** The path the pen tool is adding to. */\n\tpen: { nodeId: string; subpath: number } | null;\n\t/** Last pointer position in document units (for the pen preview), or null when outside. */\n\tpointer: Vec2 | null;\n\t/** Shape Builder and paint bucket highlight: faces, line pieces and the gesture's trail. */\n\tbuilder: VectorBuilderPreview | null;\n\tcanUndo: boolean;\n\tcanRedo: boolean;\n\tundoLabel: string;\n\tredoLabel: string;\n\t/** Bumped on every change. */\n\trevision: number;\n}\n\nexport type VectorActionResult = { ok: true } | { ok: false; message: string };\n\n/**\n * What the Shape Builder or paint bucket highlights, in document units: the faces (filled paths\n * as SVG path data) under the pointer or touched by the drag, the line pieces an erase would\n * delete, and the drag's trail. `mode` is `merge`, `erase` (Alt) or `fill` (paint bucket).\n */\nexport interface VectorBuilderPreview {\n\tmode: 'merge' | 'erase' | 'fill';\n\tfaces: BezierPath[];\n\tlines: BezierPath[];\n\ttrail: Vec2[] | null;\n}\n\n/** Result of a Shape Builder gesture. */\nexport interface VectorShapeBuilderResult {\n\tok: boolean;\n\tmessage?: string;\n\t/** Id of the merged shape (none when erasing). */\n\tmerged: string | null;\n\tfaces: number;\n\tlines: number;\n\t/** Outline edges erased (cut out of the paths they lie on). */\n\tedges: number;\n}\n\n/** A face of the Shape Builder map (document units). */\nexport interface VectorShapeBuilderFace {\n\tindex: number;\n\t/** SVG path data. */\n\td: string;\n\tarea: number;\n\t/** Ids of the paths whose fill covers it, bottom to top (empty for an area only outlines enclose). */\n\tsources: string[];\n\t/** A point inside it. */\n\tpoint: Vec2 | null;\n}\n\nexport interface AddVectorNodeOptions {\n\t/** Group to add into (default: the root). */\n\tparentId?: string;\n\t/** Position in the parent's list (default: on top). */\n\tindex?: number;\n\t/** Select the new node (default true). */\n\tselect?: boolean;\n\t/** Undo step label. */\n\tlabel?: string;\n}\n\n/** A shape description for `addShape` (and the agent command of the same name). */\nexport interface VectorShapeInput extends VectorStyle {\n\tkind: 'rect' | 'ellipse' | 'polygon' | 'star' | 'line';\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n\t/** Live corner radius of a rectangle, polygon or star (default: the editor default). */\n\tcornerRadius?: number;\n\tcornerKind?: VectorCornerKind;\n\tsides?: number;\n\tpoints?: number;\n\tinnerRatio?: number;\n\tname?: string;\n}\n\n/** Every field of `VectorStyle`, in the order style panels and commands list them. */\nexport const VECTOR_STYLE_KEYS = [\n\t'fill',\n\t'stroke',\n\t'strokeWidth',\n\t'strokeLinecap',\n\t'strokeLinejoin',\n\t'strokeDasharray',\n\t'fillRule',\n\t'strokeAlign',\n\t'startArrow',\n\t'endArrow',\n\t'arrowAlign',\n\t'startArrowScale',\n\t'endArrowScale',\n\t'strokeWidthProfile'\n] as const satisfies readonly (keyof VectorStyle)[];\n\n/** Clipboard payload type written by `copy()`. */\nexport const VECTOR_CLIPBOARD_TYPE = 'pixerate/vector';\n\nconst DEFAULT_DEFAULTS = {\n\tfill: '#d4d4d8',\n\tstroke: '#18181b',\n\tstrokeWidth: 2,\n\tpolygonSides: 6,\n\tstarPoints: 5,\n\tstarInnerRatio: 0.5,\n\tcornerRadius: 0\n};\n\nconst MIN_ZOOM = 0.05;\nconst MAX_ZOOM = 64;\n/** Screen distance of the rotation handle above the selection box. */\nexport const VECTOR_ROTATE_HANDLE_OFFSET = 24;\n\n// ---------------------------------------------------------------------------\n// Helpers shared with the render module\n// ---------------------------------------------------------------------------\n\nconst sameRef = (a: VectorAnchorRef, b: VectorAnchorRef) => a.nodeId === b.nodeId && a.subpath === b.subpath && a.index === b.index;\n\n/** Ids of the path nodes whose anchors are shown (the edited path plus selected paths). */\nexport function getEditablePathIds(state: Pick<VectorEditorState, 'document' | 'selection' | 'editingId' | 'tool' | 'pen'>): string[] {\n\tif (state.tool !== 'direct' && state.tool !== 'pen') return [];\n\tconst ids = new Set<string>();\n\tif (state.pen) ids.add(state.pen.nodeId);\n\tif (state.tool === 'direct') {\n\t\tif (state.editingId) ids.add(state.editingId);\n\t\tfor (const id of state.selection) {\n\t\t\tconst node = findVectorNode(state.document.nodes, id);\n\t\t\tif (node && !node.locked) for (const p of collectPathNodes(node)) if (!p.locked) ids.add(p.id);\n\t\t}\n\t}\n\treturn [...ids].filter((id) => findVectorNode(state.document.nodes, id)?.type === 'path');\n}\n\n/** Every anchor drawn on the canvas. */\nexport function getVisibleAnchors(state: Pick<VectorEditorState, 'document' | 'selection' | 'editingId' | 'tool' | 'pen'>): VectorAnchorRef[] {\n\tconst out: VectorAnchorRef[] = [];\n\tfor (const id of getEditablePathIds(state)) {\n\t\tconst node = findVectorNode(state.document.nodes, id) as VectorPathNode;\n\t\tnode.subpaths.forEach((sp, s) => sp.anchors.forEach((_, i) => out.push({ nodeId: id, subpath: s, index: i })));\n\t}\n\treturn out;\n}\n\n/**\n * Handles drawn on the canvas: those of selected anchors and of the segments next to them\n * (direct tool), or of the last anchor of the pen path.\n */\nexport function getVisibleHandles(\n\tstate: Pick<VectorEditorState, 'document' | 'selection' | 'editingId' | 'tool' | 'pen' | 'selectedAnchors'>\n): VectorHandleRef[] {\n\tconst out: VectorHandleRef[] = [];\n\tconst seen = new Set<string>();\n\tconst push = (node: VectorPathNode, s: number, i: number, handle: 'in' | 'out') => {\n\t\tconst sp = node.subpaths[s];\n\t\tconst a = sp?.anchors[i];\n\t\tif (!a || !a[handle]) return;\n\t\tconst key = `${node.id}:${s}:${i}:${handle}`;\n\t\tif (seen.has(key)) return;\n\t\tseen.add(key);\n\t\tout.push({ nodeId: node.id, subpath: s, index: i, handle });\n\t};\n\tif (state.tool === 'pen' && state.pen) {\n\t\tconst node = findVectorNode(state.document.nodes, state.pen.nodeId);\n\t\tconst sp = node?.type === 'path' ? node.subpaths[state.pen.subpath] : undefined;\n\t\tif (node?.type === 'path' && sp) {\n\t\t\tconst last = sp.anchors.length - 1;\n\t\t\tpush(node, state.pen.subpath, last, 'in');\n\t\t\tpush(node, state.pen.subpath, last, 'out');\n\t\t}\n\t\treturn out;\n\t}\n\tif (state.tool !== 'direct') return out;\n\tconst editable = new Set(getEditablePathIds(state));\n\tfor (const ref of state.selectedAnchors) {\n\t\tif (!editable.has(ref.nodeId)) continue;\n\t\tconst node = findVectorNode(state.document.nodes, ref.nodeId) as VectorPathNode;\n\t\tconst sp = node.subpaths[ref.subpath];\n\t\tif (!sp) continue;\n\t\tconst n = sp.anchors.length;\n\t\tpush(node, ref.subpath, ref.index, 'in');\n\t\tpush(node, ref.subpath, ref.index, 'out');\n\t\tconst prev = ref.index > 0 ? ref.index - 1 : sp.closed ? n - 1 : -1;\n\t\tconst next = ref.index < n - 1 ? ref.index + 1 : sp.closed ? 0 : -1;\n\t\tif (prev >= 0) push(node, ref.subpath, prev, 'out');\n\t\tif (next >= 0) push(node, ref.subpath, next, 'in');\n\t}\n\treturn out;\n}\n\n/** Live corner widgets sit at least this far inside their corner (screen px along each side of a right angle). */\nexport const VECTOR_CORNER_WIDGET_INSET = 10;\n\n/** A live corner widget of the direct tool: drag it to round the corners, Alt-click to change their kind. */\nexport interface VectorCornerWidget {\n\tref: VectorAnchorRef;\n\t/** Document position of the widget. */\n\tx: number;\n\ty: number;\n\t/** The radius stored on the anchor and the radius drawn (no larger than fits). */\n\tradius: number;\n\tdrawnRadius: number;\n\tkind: VectorCornerKind;\n\t/** The corner in its node's own space. */\n\tcorner: VectorCornerInfo;\n}\n\n/**\n * The live corner widgets the direct tool shows: on each editable path, at its selected corner\n * anchors (or at every corner when none of its anchors is selected). Corners whose sides are\n * shorter than three insets on screen hide theirs. Dragging one sets the radius of all of them.\n * Ported from ArtCraft vectorcraft `crates/tools/src/corners.rs` (MIT OR Apache-2.0, see\n * THIRD_PARTY_NOTICES.md), as is the `corner` drag below.\n */\nexport function getVectorCornerWidgets(\n\tstate: Pick<VectorEditorState, 'document' | 'selection' | 'editingId' | 'tool' | 'pen' | 'selectedAnchors' | 'viewport'>\n): VectorCornerWidget[] {\n\tif (state.tool !== 'direct' || state.pen) return [];\n\tconst zoom = state.viewport.zoom;\n\tconst out: VectorCornerWidget[] = [];\n\tfor (const id of getEditablePathIds(state)) {\n\t\tconst node = findVectorNode(state.document.nodes, id) as VectorPathNode;\n\t\tconst picked = state.selectedAnchors.filter((r) => r.nodeId === id);\n\t\tconst m = vectorWorldMatrix(state.document.nodes, id) ?? IDENTITY_MATRIX;\n\t\tfor (const c of vectorCorners(node.subpaths)) {\n\t\t\tif (picked.length && !picked.some((r) => r.subpath === c.subpath && r.index === c.index)) continue;\n\t\t\tconst side = Math.min(c.lu, c.lv);\n\t\t\tif (side * zoom < 3 * VECTOR_CORNER_WIDGET_INSET) continue;\n\t\t\tconst a = node.subpaths[c.subpath].anchors[c.index];\n\t\t\tconst radius = a.corner?.radius ?? 0;\n\t\t\tconst drawn = fitCornerRadius(c, radius);\n\t\t\t// On the bisector at the centre of the arc as drawn, at least the inset in and at most half the shorter side.\n\t\t\tconst k = Math.min(Math.max(drawn / c.sin, VECTOR_CORNER_WIDGET_INSET / (zoom * Math.sqrt(1 + c.cos))), side / 2);\n\t\t\tconst p = applyMatrix(m, cornerBisectorPoint(c, k));\n\t\t\tout.push({ ref: { nodeId: id, subpath: c.subpath, index: c.index }, x: p.x, y: p.y, radius, drawnRadius: drawn, kind: a.corner?.kind ?? 'round', corner: c });\n\t\t}\n\t}\n\treturn out;\n}\n\n/**\n * The line a path's stroke follows (node space; shortened under `tip` arrowheads) and the\n * distance a side scale of 1 reaches from it (half the drawn width: twice the stroke width for\n * inside / outside strokes). Null for paths without a visible stroke.\n */\nexport function vectorStrokeWidthGeometry(node: VectorPathNode): { line: BezierPath; unit: number } | null {\n\tif (!hasPaint(node.stroke) || !((node.strokeWidth ?? 1) > 0)) return null;\n\tconst parts = vectorStrokeParts(subpathsToBezier(node.subpaths), node);\n\treturn parts.line.length ? { line: parts.line, unit: parts.drawWidth / 2 } : null;\n}\n\n/** A width point of the width tool, in document units. */\nexport interface VectorWidthHandle {\n\tref: VectorWidthPointRef;\n\t/** The point on the path. */\n\tx: number;\n\ty: number;\n\t/** Ends of its left and right sides. */\n\tleft: Vec2;\n\tright: Vec2;\n\tt: number;\n\t/** Side scales (multiples of half the stroke width). */\n\tleftScale: number;\n\trightScale: number;\n\tselected: boolean;\n}\n\n/**\n * The width points the width tool shows: every profile point on every subpath of the stroke\n * under the pointer, the selected paths and the stroke being edited. Ported from ArtCraft\n * vectorcraft `crates/tools/src/distort/width.rs` (MIT OR Apache-2.0, see\n * THIRD_PARTY_NOTICES.md), as are the `width` drag and hover below.\n */\nexport function getVectorWidthHandles(\n\tstate: Pick<VectorEditorState, 'document' | 'selection' | 'tool' | 'hover' | 'interaction' | 'selectedWidthPoint'>\n): VectorWidthHandle[] {\n\tif (state.tool !== 'width') return [];\n\tconst ids = new Set<string>();\n\tfor (const id of state.selection) {\n\t\tconst n = findVectorNode(state.document.nodes, id);\n\t\tif (n) for (const p of collectPathNodes(n)) ids.add(p.id);\n\t}\n\tif (state.hover?.nodeId) ids.add(state.hover.nodeId);\n\tif (state.interaction?.type === 'width') ids.add(state.interaction.ref.nodeId);\n\tif (state.selectedWidthPoint) ids.add(state.selectedWidthPoint.nodeId);\n\tconst out: VectorWidthHandle[] = [];\n\tfor (const id of ids) {\n\t\tconst node = findVectorNode(state.document.nodes, id);\n\t\tif (node?.type !== 'path' || node.visible === false || !node.strokeWidthProfile?.length) continue;\n\t\tconst g = vectorStrokeWidthGeometry(node);\n\t\tif (!g) continue;\n\t\tconst profile = sanitizeWidthProfile(node.strokeWidthProfile);\n\t\tconst m = vectorWorldMatrix(state.document.nodes, id) ?? IDENTITY_MATRIX;\n\t\tconst contours = node.subpaths.length;\n\t\tfor (let sp = 0; sp < contours; sp++) {\n\t\t\tprofile.forEach((w, index) => {\n\t\t\t\tconst at = strokePositionPoint(g.line, sp, w.t);\n\t\t\t\tif (!at) return;\n\t\t\t\tconst n = { x: at.tangent[1], y: -at.tangent[0] };\n\t\t\t\tconst c = { x: at.point[0], y: at.point[1] };\n\t\t\t\tconst p = applyMatrix(m, c);\n\t\t\t\tconst l = applyMatrix(m, { x: c.x + n.x * w.left * g.unit, y: c.y + n.y * w.left * g.unit });\n\t\t\t\tconst r = applyMatrix(m, { x: c.x - n.x * w.right * g.unit, y: c.y - n.y * w.right * g.unit });\n\t\t\t\tconst sel = state.selectedWidthPoint;\n\t\t\t\tout.push({\n\t\t\t\t\tref: { nodeId: id, index, subpath: sp },\n\t\t\t\t\tx: p.x,\n\t\t\t\t\ty: p.y,\n\t\t\t\t\tleft: l,\n\t\t\t\t\tright: r,\n\t\t\t\t\tt: w.t,\n\t\t\t\t\tleftScale: w.left,\n\t\t\t\t\trightScale: w.right,\n\t\t\t\t\tselected: !!sel && sel.nodeId === id && sel.index === index\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\t}\n\treturn out;\n}\n\n/** Looks up an anchor (positions in its node's own space). */\nexport function getAnchor(doc: VectorDocument, ref: VectorAnchorRef): VectorAnchor | undefined {\n\tconst node = findVectorNode(doc.nodes, ref.nodeId);\n\treturn node?.type === 'path' ? node.subpaths[ref.subpath]?.anchors[ref.index] : undefined;\n}\n\n/** An anchor with its position and handles in document space (its node's transforms applied). */\nexport function getAnchorWorld(doc: VectorDocument, ref: VectorAnchorRef): { x: number; y: number; in?: Vec2; out?: Vec2; type?: VectorAnchorType } | undefined {\n\tconst a = getAnchor(doc, ref);\n\tif (!a) return undefined;\n\tconst m = vectorWorldMatrix(doc.nodes, ref.nodeId) ?? IDENTITY_MATRIX;\n\tconst p = applyMatrix(m, a);\n\treturn { x: p.x, y: p.y, ...(a.in ? { in: applyMatrix(m, a.in) } : {}), ...(a.out ? { out: applyMatrix(m, a.out) } : {}), ...(a.type ? { type: a.type } : {}) };\n}\n\n/**\n * The selection box: `angle` is the shared rotation of the selected nodes (0 when they\n * differ), `x / y / width / height` the bounds in the box's own frame (document space\n * rotated by −angle). A frame point `q` is at `rotateMatrix(angle)` applied to `q`.\n */\nexport interface VectorSelectionFrame {\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n\tangle: number;\n}\n\n/** The selection frame of nodes `ids` (see `VectorSelectionFrame`), or null when they have no points. */\nexport function getVectorSelectionFrame(doc: VectorDocument, ids: readonly string[]): VectorSelectionFrame | null {\n\tconst nodes = ids.map((id) => ({ node: findVectorNode(doc.nodes, id), parent: vectorParentMatrix(doc.nodes, id) ?? IDENTITY_MATRIX })).filter((n) => n.node);\n\tif (!nodes.length) return null;\n\tconst angles = nodes.map((n) => matrixRotation(multiplyMatrices(nodeMatrix(n.node!), n.parent)));\n\tconst same = angles.every((a) => Math.abs(normalizeAngle(a - angles[0])) < 1e-6);\n\tconst angle = same ? angles[0] : 0;\n\tconst unrotate = rotateMatrix(-angle);\n\tconst b = unionBounds(nodes.map((n) => vectorNodeBounds(n.node!, multiplyMatrices(n.parent, unrotate))));\n\treturn b ? { ...b, angle } : null;\n}\n\nconst normalizeAngle = (a: number) => ((((a + 180) % 360) + 360) % 360) - 180;\n\n/** Screen positions of the selection box handles for a box given in screen pixels. */\nexport function getTransformHandlePositions(box: VectorBounds): { handle: VectorTransformHandle; x: number; y: number }[] {\n\tconst { x, y, width: w, height: h } = box;\n\treturn [\n\t\t{ handle: 'nw', x, y },\n\t\t{ handle: 'n', x: x + w / 2, y },\n\t\t{ handle: 'ne', x: x + w, y },\n\t\t{ handle: 'e', x: x + w, y: y + h / 2 },\n\t\t{ handle: 'se', x: x + w, y: y + h },\n\t\t{ handle: 's', x: x + w / 2, y: y + h },\n\t\t{ handle: 'sw', x, y: y + h },\n\t\t{ handle: 'w', x, y: y + h / 2 },\n\t\t{ handle: 'rotate', x: x + w / 2, y: y - VECTOR_ROTATE_HANDLE_OFFSET }\n\t];\n}\n\n/**\n * Screen geometry of a selection box. `box` and each handle's `x / y` are the unrotated box\n * in screen pixels; draw them inside a group with `transform` (a `rotate(angle cx cy)`),\n * or use `screen` for the true on-screen positions (hit-testing).\n */\nexport interface VectorSelectionBoxGeometry {\n\tbox: VectorBounds;\n\tangle: number;\n\ttransform: string;\n\thandles: { handle: VectorTransformHandle; x: number; y: number; screen: Vec2 }[];\n\t/** The four corners on screen, clockwise from the top left. */\n\tcorners: Vec2[];\n}\n\nexport function getVectorSelectionBoxGeometry(frame: VectorSelectionFrame, viewport: VectorViewport): VectorSelectionBoxGeometry {\n\tconst z = viewport.zoom;\n\tconst box = { x: frame.x * z + viewport.x, y: frame.y * z + viewport.y, width: frame.width * z, height: frame.height * z };\n\tconst rot = rotateMatrix(frame.angle, { x: viewport.x, y: viewport.y });\n\tconst toScreen = (p: Vec2): Vec2 => (frame.angle ? applyMatrix(rot, p) : { x: p.x, y: p.y });\n\tconst handles = getTransformHandlePositions(box).map((h) => ({ ...h, screen: toScreen(h) }));\n\tconst corners = [\n\t\t{ x: box.x, y: box.y },\n\t\t{ x: box.x + box.width, y: box.y },\n\t\t{ x: box.x + box.width, y: box.y + box.height },\n\t\t{ x: box.x, y: box.y + box.height }\n\t].map(toScreen);\n\tconst r = (n: number) => Math.round(n * 1000) / 1000;\n\treturn { box, angle: frame.angle, transform: frame.angle ? `rotate(${r(frame.angle)} ${r(viewport.x)} ${r(viewport.y)})` : '', handles, corners };\n}\n\nconst RESIZE_CURSOR_ORDER = ['ew-resize', 'nwse-resize', 'ns-resize', 'nesw-resize'];\nconst HANDLE_ANGLES: Partial<Record<VectorTransformHandle, number>> = { e: 0, se: 45, s: 90, sw: 135, w: 180, nw: 225, n: 270, ne: 315 };\n\n/** The resize cursor for a handle of a box rotated by `angle` degrees. */\nexport function vectorResizeCursor(handle: VectorTransformHandle, angle = 0): string {\n\tif (handle === 'rotate') return 'grab';\n\tconst a = (((HANDLE_ANGLES[handle]! + angle) % 180) + 180) % 180;\n\treturn RESIZE_CURSOR_ORDER[Math.round(a / 45) % 4];\n}\n\n\nconst TOOL_LABELS: Record<VectorTool, string> = {\n\tselect: 'Select',\n\tdirect: 'Direct Select',\n\tpen: 'Pen',\n\tpencil: 'Pencil',\n\trect: 'Rectangle',\n\tellipse: 'Ellipse',\n\tpolygon: 'Polygon',\n\tstar: 'Star',\n\tline: 'Line',\n\tscissors: 'Scissors',\n\tknife: 'Knife',\n\teraser: 'Eraser',\n\twidth: 'Width',\n\tshapeBuilder: 'Shape Builder',\n\tpaintBucket: 'Paint Bucket'\n};\n\nconst TOOL_KEYS: Record<string, VectorTool> = {\n\tv: 'select',\n\ta: 'direct',\n\tp: 'pen',\n\tn: 'pencil',\n\tr: 'rect',\n\to: 'ellipse',\n\ty: 'polygon',\n\ts: 'star',\n\tl: 'line',\n\tc: 'scissors',\n\tk: 'knife',\n\te: 'eraser',\n\tw: 'width',\n\tm: 'shapeBuilder',\n\tb: 'paintBucket'\n};\n\nexport function vectorToolLabel(tool: VectorTool): string {\n\treturn TOOL_LABELS[tool];\n}\n\n/** Keyboard shortcut of each tool (single letters, no modifiers). */\nexport const VECTOR_TOOL_SHORTCUTS: Readonly<Record<VectorTool, string>> = {\n\tselect: 'V',\n\tdirect: 'A',\n\tpen: 'P',\n\tpencil: 'N',\n\trect: 'R',\n\tellipse: 'O',\n\tpolygon: 'Y',\n\tstar: 'S',\n\tline: 'L',\n\tscissors: 'C',\n\tknife: 'K',\n\teraser: 'E',\n\twidth: 'W',\n\tshapeBuilder: 'M',\n\tpaintBucket: 'B'\n};\n\n/** Short glyphs for tool buttons (pair them with `vectorToolLabel` for the accessible name). */\nexport const VECTOR_TOOL_GLYPHS: Readonly<Record<VectorTool, string>> = {\n\tselect: '↖',\n\tdirect: '⌖',\n\tpen: '✒',\n\tpencil: '✎',\n\trect: '▭',\n\tellipse: '◯',\n\tpolygon: '⬡',\n\tstar: '☆',\n\tline: '╱',\n\tscissors: '✂',\n\tknife: '⟋',\n\teraser: '⌫',\n\twidth: '⇹',\n\tshapeBuilder: '⊕',\n\tpaintBucket: '◍'\n};\n\n/** Tools that drag out a shape (they snap while hovering). */\nconst SHAPE_TOOLS: ReadonlySet<VectorTool> = new Set(['rect', 'ellipse', 'polygon', 'star', 'line']);\n\nconst BOOLEAN_OPS: Record<VectorBooleanOperation, 'union' | 'difference' | 'intersection' | 'xor'> = {\n\tunion: 'union',\n\tsubtract: 'difference',\n\tintersect: 'intersection',\n\texclude: 'xor'\n};\n\nconst BOOLEAN_LABELS: Record<VectorBooleanOperation, string> = { union: 'Union', subtract: 'Subtract', intersect: 'Intersect', exclude: 'Exclude' };\n\n/** Names of the Pathfinder operations (undo steps, groups and buttons). */\nexport const VECTOR_PATHFINDER_LABELS: Readonly<Record<VectorPathfinderOperation, string>> = {\n\tdivide: 'Divide',\n\ttrim: 'Trim',\n\tmerge: 'Merge',\n\tcrop: 'Crop',\n\toutline: 'Outline',\n\tminusBack: 'Minus Back'\n};\n\n/** Replaces nodes by id anywhere in the tree (structural sharing for untouched branches). */\nfunction mapTree(nodes: readonly VectorNode[], fn: (node: VectorNode) => VectorNode | null): VectorNode[] {\n\tlet changed = false;\n\tconst out: VectorNode[] = [];\n\tfor (const node of nodes) {\n\t\tlet next = fn(node);\n\t\tif (next && next.type === 'group') {\n\t\t\tconst children = mapTree(next.children, fn);\n\t\t\tif (children !== next.children) next = { ...next, children };\n\t\t}\n\t\tif (next !== node) changed = true;\n\t\tif (next) out.push(next);\n\t}\n\treturn changed ? out : (nodes as VectorNode[]);\n}\n\n/** Replaces node `id` anywhere in the tree with `replacements` (none removes it). */\nfunction spliceTree(nodes: readonly VectorNode[], id: string, replacements: readonly VectorNode[]): VectorNode[] {\n\tlet changed = false;\n\tconst out: VectorNode[] = [];\n\tfor (const node of nodes) {\n\t\tif (node.id === id) {\n\t\t\tchanged = true;\n\t\t\tout.push(...replacements);\n\t\t\tcontinue;\n\t\t}\n\t\tif (node.type === 'group') {\n\t\t\tconst children = spliceTree(node.children, id, replacements);\n\t\t\tif (children !== node.children) {\n\t\t\t\tchanged = true;\n\t\t\t\tout.push({ ...node, children });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tout.push(node);\n\t}\n\treturn changed ? out : (nodes as VectorNode[]);\n}\n\nconst toPoint = (p: Vec2): Point => [p.x, p.y];\n\nconst isRoot = (m: AffineMatrix) => m === IDENTITY_MATRIX || (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1 && m[4] === 0 && m[5] === 0);\n\nlet idCounter = 0;\nconst defaultCreateId = () => `vn-${Date.now().toString(36)}${(++idCounter).toString(36)}`;\n\n// ---------------------------------------------------------------------------\n// Controller\n// ---------------------------------------------------------------------------\n\ninterface Snapshot {\n\tdoc: VectorDocument;\n\tselection: string[];\n\tanchors: VectorAnchorRef[];\n\teditingId: string | null;\n\tpen: { nodeId: string; subpath: number } | null;\n}\n\n/** Snap targets of a drag, gathered on its first move that needs them. */\ntype DragTargets = { targets?: VectorSnapTargets };\n\ntype Drag =\n\t| ({ kind: 'move'; start: Vec2; origin: VectorBounds | null; before: Snapshot; base: VectorDocument; moved: boolean; duplicated: boolean; clickId: string | null } & DragTargets)\n\t| ({ kind: 'scale'; handle: VectorTransformHandle; start: Vec2; frame: VectorSelectionFrame; before: Snapshot; base: VectorDocument } & DragTargets)\n\t| { kind: 'rotate'; start: Vec2; center: Vec2; before: Snapshot; base: VectorDocument }\n\t| { kind: 'marquee'; start: Vec2; base: string[]; baseAnchors: VectorAnchorRef[]; anchorsMode: boolean }\n\t| ({ kind: 'anchors'; start: Vec2; before: Snapshot; base: VectorDocument; moved: boolean; clickRef: VectorAnchorRef | null; lead: VectorAnchorRef | null } & DragTargets)\n\t| ({ kind: 'handle'; ref: VectorHandleRef; before: Snapshot; base: VectorDocument } & DragTargets)\n\t| { kind: 'bend'; ref: VectorSegmentRef; t: number; start: Vec2; before: Snapshot; base: VectorDocument; moved: boolean }\n\t| { kind: 'corner'; widget: VectorCornerWidget; refs: VectorAnchorRef[]; start: Vec2; before: Snapshot; base: VectorDocument; moved: boolean; alt: boolean; shift: boolean }\n\t| { kind: 'stroke'; tool: 'knife' | 'eraser'; points: Vec2[]; before: Snapshot }\n\t| { kind: 'builder'; erase: boolean; points: Vec2[]; touched: VectorBuilderTouched; map: VectorShapeBuilderMap }\n\t| { kind: 'pull'; ref: VectorAnchorRef; before: Snapshot; base: VectorDocument; label: string; outOnly: boolean; closing: boolean; altBreaks: boolean }\n\t| ({ kind: 'shape'; tool: VectorTool; start: Vec2; nodeId: string; before: Snapshot } & DragTargets)\n\t| { kind: 'pencil'; nodeId: string; points: Point[]; before: Snapshot; lazy: LazyMouse; pressures: number[] | null; pressure: number }\n\t| {\n\t\t\tkind: 'width';\n\t\t\tref: VectorWidthPointRef;\n\t\t\tmode: 'width' | 'move';\n\t\t\tside: 'both' | 'left' | 'right';\n\t\t\t/** The stroke line's point and left normal where the drag started (node space). */\n\t\t\torigin: Vec2;\n\t\t\tnormal: Vec2;\n\t\t\t/** Half the drawn stroke width: side scale 1 reaches this far. */\n\t\t\tunit: number;\n\t\t\tprofile: VectorWidthPoint[];\n\t\t\tbefore: Snapshot;\n\t\t\tbase: VectorDocument;\n\t\t\tstart: Vec2;\n\t\t\tmoved: boolean;\n\t\t\tcreated: boolean;\n\t }\n\t| { kind: 'pan'; start: Vec2; viewport: VectorViewport };\n\n/**\n * Headless state for a vector editor: a document of paths and groups, select / direct /\n * pen / pencil / shape tools driven by pointer and key events, undo, transforms, boolean\n * operations, alignment, grouping, SVG import / export and a viewport. Any UI forwards\n * pointer events (in canvas pixels) and renders `getState()`; `getState()` returns the same\n * object until something changes, so it works with `useSyncExternalStore` and Svelte runes.\n */\nexport class VectorEditorController {\n\treadonly history: HistoryManager;\n\tprivate doc: VectorDocument;\n\tprivate selection: string[] = [];\n\tprivate anchors: VectorAnchorRef[] = [];\n\tprivate widthPoint: VectorWidthPointRef | null = null;\n\tprivate editingId: string | null = null;\n\tprivate pen: { nodeId: string; subpath: number } | null = null;\n\tprivate tool: VectorTool;\n\tprivate defaults: VectorEditorState['defaults'];\n\tprivate viewport: VectorViewport;\n\tprivate snap: VectorSnapOptions;\n\tprivate editing: VectorPathEditOptions;\n\tprivate hitRadius: number;\n\tprivate hover: VectorHover | null = null;\n\tprivate pointer: Vec2 | null = null;\n\tprivate drag: Drag | null = null;\n\tprivate interaction: VectorInteraction | null = null;\n\tprivate guides: VectorSnapGuides | null = null;\n\t/** Whether the last `snapDrawn` landed on an object (guides may be hidden). */\n\tprivate snappedToObject = false;\n\t/** Drawing targets for hovering the pen and shape tools, kept while the document and the excluded path stay the same. */\n\tprivate hoverTargets: { doc: VectorDocument; exclude: string; targets: VectorSnapTargets } | null = null;\n\tprivate spaceHeld = false;\n\tprivate clipboard: VectorNode[] | null = null;\n\t/** Shape Builder map of the selection, kept while the document and the selection stay the same. */\n\tprivate builderCache: { doc: VectorDocument; key: string; map: VectorShapeBuilderMap | null } | null = null;\n\t/** Paint bucket map of the visible outlines. */\n\tprivate fillCache: { doc: VectorDocument; gap: number; map: PlanarMap | null } | null = null;\n\tprivate builderPreview: VectorBuilderPreview | null = null;\n\t/** What the highlight shows, to skip notifying when the pointer stays over the same face. */\n\tprivate builderHoverKey: string | null = null;\n\tprivate readonly createId: () => string;\n\tprivate readonly onChange?: (document: VectorDocument) => void;\n\tprivate readonly listeners = new Set<(state: VectorEditorState) => void>();\n\tprivate readonly cleanups: Array<() => void> = [];\n\tprivate applying = false;\n\t/** Set while a commit records a change that was already applied, so `restore` still reports it. */\n\tprivate committing = false;\n\tprivate revision = 0;\n\tprivate state!: VectorEditorState;\n\n\tconstructor(options: VectorEditorOptions = {}) {\n\t\tthis.history = options.history ?? new HistoryManager();\n\t\tthis.doc = options.document ? cloneVectorDocument(options.document) : { width: 800, height: 600, nodes: [] };\n\t\tthis.tool = options.tool ?? 'select';\n\t\tthis.defaults = { ...DEFAULT_DEFAULTS, ...(options.defaults ?? {}) } as VectorEditorState['defaults'];\n\t\tthis.viewport = { x: 0, y: 0, zoom: 1, ...(options.viewport ?? {}) };\n\t\tthis.snap = { ...DEFAULT_VECTOR_SNAP, ...(options.snap ?? {}) };\n\t\tthis.editing = { ...DEFAULT_VECTOR_PATH_EDIT, ...(options.editing ?? {}) };\n\t\tthis.hitRadius = options.hitRadius ?? 6;\n\t\tthis.createId = options.createId ?? defaultCreateId;\n\t\tthis.onChange = options.onChange;\n\t\tthis.state = this.computeState();\n\t\tthis.cleanups.push(\n\t\t\tthis.history.subscribe((h) => {\n\t\t\t\tconst s = this.state;\n\t\t\t\tif (this.applying || (s.canUndo === h.canUndo && s.canRedo === h.canRedo && s.undoLabel === h.undoName && s.redoLabel === h.redoName)) return;\n\t\t\t\tthis.notify();\n\t\t\t})\n\t\t);\n\t}\n\n\t/** Stops listening to the history. */\n\tdestroy(): void {\n\t\tthis.cleanups.splice(0).forEach((fn) => fn());\n\t\tthis.listeners.clear();\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// State\n\t// -------------------------------------------------------------------------\n\n\t/** The current snapshot (stable until the next change). */\n\tgetState = (): VectorEditorState => this.state;\n\n\t/** Calls `listener` after every change. Returns an unsubscribe function. */\n\tsubscribe = (listener: (state: VectorEditorState) => void): (() => void) => {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t};\n\n\tgetDocument(): VectorDocument {\n\t\treturn this.doc;\n\t}\n\n\tgetNode(id: string): VectorNode | undefined {\n\t\treturn findVectorNode(this.doc.nodes, id);\n\t}\n\n\tprivate computeState(): VectorEditorState {\n\t\tconst h = this.history.getState();\n\t\treturn {\n\t\t\tdocument: this.doc,\n\t\t\ttool: this.tool,\n\t\t\tselection: this.selection,\n\t\t\tselectedAnchors: this.anchors,\n\t\t\tselectedWidthPoint: this.widthPoint,\n\t\t\teditingId: this.editingId,\n\t\t\tselectionBounds: this.boundsOf(this.selection),\n\t\t\tselectionFrame: this.frameOf(this.selectedRoots()),\n\t\t\tviewport: this.viewport,\n\t\t\tdefaults: this.defaults,\n\t\t\tsnap: this.snap,\n\t\t\tediting: this.editing,\n\t\t\tguides: this.guides,\n\t\t\thitRadius: this.hitRadius,\n\t\t\thover: this.hover,\n\t\t\tcursor: this.cursorFor(),\n\t\t\tinteraction: this.interaction,\n\t\t\tpen: this.pen,\n\t\t\tpointer: this.pointer,\n\t\t\tbuilder: this.builderPreview,\n\t\t\tcanUndo: h.canUndo,\n\t\t\tcanRedo: h.canRedo,\n\t\t\tundoLabel: h.undoName,\n\t\t\tredoLabel: h.redoName,\n\t\t\trevision: this.revision\n\t\t};\n\t}\n\n\tprivate notify(docChanged = false) {\n\t\tthis.revision++;\n\t\tthis.state = this.computeState();\n\t\tif (docChanged) this.onChange?.(this.doc);\n\t\tconst state = this.state;\n\t\tthis.listeners.forEach((listener) => {\n\t\t\ttry {\n\t\t\t\tlistener(state);\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error('[VectorEditorController] Error in state listener:', error);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate boundsOf(ids: readonly string[]): VectorBounds | null {\n\t\treturn unionBounds(\n\t\t\tids.map((id) => {\n\t\t\t\tconst n = this.getNode(id);\n\t\t\t\treturn n ? vectorNodeBounds(n, vectorParentMatrix(this.doc.nodes, id) ?? IDENTITY_MATRIX) : null;\n\t\t\t})\n\t\t);\n\t}\n\n\tprivate frameOf(ids: readonly string[]): VectorSelectionFrame | null {\n\t\treturn getVectorSelectionFrame(this.doc, ids);\n\t}\n\n\t/** Local → document matrix of a node in `doc` (default: the current document). */\n\tprivate worldOf(id: string, doc: VectorDocument = this.doc): AffineMatrix {\n\t\treturn vectorWorldMatrix(doc.nodes, id) ?? IDENTITY_MATRIX;\n\t}\n\n\t/** A document point in node `id`'s own space. */\n\tprivate toLocal(id: string, p: Vec2, doc: VectorDocument = this.doc): Vec2 {\n\t\treturn applyMatrix(invertMatrix(this.worldOf(id, doc)), p);\n\t}\n\n\tprivate cursorFor(): string {\n\t\tif (this.drag?.kind === 'pan' || this.spaceHeld) return this.drag ? 'grabbing' : 'grab';\n\t\tif (this.drag?.kind === 'rotate') return 'grabbing';\n\t\tif (this.drag?.kind === 'move') return 'move';\n\t\tconst h = this.hover;\n\t\tswitch (this.tool) {\n\t\t\tcase 'select':\n\t\t\t\tif (h?.transformHandle) return vectorResizeCursor(h.transformHandle, this.frameOf(this.selectedRoots())?.angle ?? 0);\n\t\t\t\treturn h?.nodeId ? 'move' : 'default';\n\t\t\tcase 'direct':\n\t\t\t\tif (h?.anchor || h?.handle || h?.corner) return 'pointer';\n\t\t\t\tif (h?.segment) return 'copy';\n\t\t\t\treturn h?.nodeId ? 'move' : 'default';\n\t\t\tcase 'pen':\n\t\t\t\treturn h?.anchor ? 'pointer' : 'crosshair';\n\t\t\tcase 'width':\n\t\t\t\tif (this.drag?.kind === 'width') return this.drag.mode === 'move' ? 'grabbing' : 'ew-resize';\n\t\t\t\tif (h?.widthPoint) return h.widthPoint.part === 'center' ? 'grab' : 'ew-resize';\n\t\t\t\treturn h?.strokeSpot ? 'copy' : 'default';\n\t\t\tcase 'shapeBuilder':\n\t\t\t\tif (!this.builderPreview?.faces.length && !this.builderPreview?.lines.length) return 'crosshair';\n\t\t\t\treturn this.builderPreview.mode === 'erase' ? 'not-allowed' : 'cell';\n\t\t\tcase 'paintBucket':\n\t\t\t\treturn this.builderPreview ? 'cell' : 'crosshair';\n\t\t\tdefault:\n\t\t\t\treturn 'crosshair';\n\t\t}\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Undoable changes\n\t// -------------------------------------------------------------------------\n\n\tprivate snapshot(): Snapshot {\n\t\treturn { doc: this.doc, selection: this.selection, anchors: this.anchors, editingId: this.editingId, pen: this.pen };\n\t}\n\n\tprivate restore(s: Snapshot) {\n\t\tconst docChanged = s.doc !== this.doc || this.committing;\n\t\tthis.committing = false;\n\t\tthis.applying = true;\n\t\ttry {\n\t\t\tthis.doc = s.doc;\n\t\t\tthis.selection = s.selection.filter((id) => this.getNode(id));\n\t\t\tthis.anchors = s.anchors.filter((r) => getAnchor(this.doc, r));\n\t\t\tthis.editingId = s.editingId && this.getNode(s.editingId) ? s.editingId : null;\n\t\t\tthis.pen = s.pen && (this.getNode(s.pen.nodeId) as VectorPathNode | undefined)?.subpaths?.[s.pen.subpath] ? s.pen : null;\n\t\t} finally {\n\t\t\tthis.applying = false;\n\t\t}\n\t\tthis.notify(docChanged);\n\t}\n\n\t/** Records the change from `before` to the current state as one undo step. */\n\tprivate commit(name: string, before: Snapshot) {\n\t\tconst after = this.snapshot();\n\t\tif (before.doc === after.doc) {\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst command: Command = {\n\t\t\tname,\n\t\t\texecute: () => this.restore(after),\n\t\t\tundo: () => this.restore(before),\n\t\t\tredo: () => this.restore(after)\n\t\t};\n\t\tthis.committing = true;\n\t\tthis.history.execute(command);\n\t\tthis.committing = false;\n\t}\n\n\t/** Runs `fn` (which updates fields) and records it as one undo step. */\n\tprivate change(name: string, fn: () => void): void {\n\t\tconst before = this.snapshot();\n\t\tfn();\n\t\tthis.commit(name, before);\n\t}\n\n\tprivate setDoc(nodes: VectorNode[]) {\n\t\tif (nodes !== this.doc.nodes) this.doc = { ...this.doc, nodes };\n\t}\n\n\tprivate replaceNode(id: string, next: VectorNode | null) {\n\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === id ? next : n)));\n\t}\n\n\tprivate freshIds<T extends VectorNode>(node: T): T {\n\t\tconst copy = cloneVectorNode(node);\n\t\tconst used = new Set<string>();\n\t\twalkVectorNodes(this.doc.nodes, (n) => used.add(n.id));\n\t\tconst next = () => {\n\t\t\tlet id = this.createId();\n\t\t\twhile (used.has(id)) id = this.createId();\n\t\t\tused.add(id);\n\t\t\treturn id;\n\t\t};\n\t\tconst assign = (n: VectorNode) => {\n\t\t\tn.id = next();\n\t\t\tif (n.type === 'group') n.children.forEach(assign);\n\t\t};\n\t\tassign(copy);\n\t\treturn copy;\n\t}\n\n\tprivate newId(): string {\n\t\tlet id = this.createId();\n\t\twhile (this.getNode(id)) id = this.createId();\n\t\treturn id;\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Viewport\n\t// -------------------------------------------------------------------------\n\n\tscreenToDocument(p: Vec2): Vec2 {\n\t\tconst v = this.viewport;\n\t\treturn { x: (p.x - v.x) / v.zoom, y: (p.y - v.y) / v.zoom };\n\t}\n\n\tdocumentToScreen(p: Vec2): Vec2 {\n\t\tconst v = this.viewport;\n\t\treturn { x: p.x * v.zoom + v.x, y: p.y * v.zoom + v.y };\n\t}\n\n\tsetViewport(viewport: Partial<VectorViewport>): void {\n\t\tconst next = { ...this.viewport, ...viewport };\n\t\tnext.zoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, next.zoom));\n\t\tif (next.x === this.viewport.x && next.y === this.viewport.y && next.zoom === this.viewport.zoom) return;\n\t\tthis.viewport = next;\n\t\tthis.notify();\n\t}\n\n\t/** Zooms by `factor` keeping the document point under `screen` in place. */\n\tzoomAt(screen: Vec2, factor: number): void {\n\t\tconst zoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, this.viewport.zoom * factor));\n\t\tconst doc = this.screenToDocument(screen);\n\t\tthis.setViewport({ zoom, x: screen.x - doc.x * zoom, y: screen.y - doc.y * zoom });\n\t}\n\n\tpanBy(dx: number, dy: number): void {\n\t\tthis.setViewport({ x: this.viewport.x + dx, y: this.viewport.y + dy });\n\t}\n\n\t/** Fits the artboard (or `bounds`) into a canvas of `size` screen pixels. */\n\tzoomToFit(size: { width: number; height: number }, options: { padding?: number; bounds?: VectorBounds } = {}): void {\n\t\tconst padding = options.padding ?? 40;\n\t\tconst b = options.bounds ?? { x: 0, y: 0, width: this.doc.width, height: this.doc.height };\n\t\tconst zoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, Math.min((size.width - padding * 2) / (b.width || 1), (size.height - padding * 2) / (b.height || 1))));\n\t\tthis.setViewport({ zoom, x: (size.width - b.width * zoom) / 2 - b.x * zoom, y: (size.height - b.height * zoom) / 2 - b.y * zoom });\n\t}\n\n\t/** Zoom at the canvas centre-ish: positive `delta` zooms out (wheel convention). Use with `wheel`. */\n\twheel(screen: Vec2, delta: { x: number; y: number }, mods: VectorModifiers = {}): void {\n\t\tif (mods.mod) this.zoomAt(screen, Math.exp(-delta.y * 0.01));\n\t\telse this.panBy(-(mods.shift ? delta.y : delta.x), -(mods.shift ? 0 : delta.y));\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Settings\n\t// -------------------------------------------------------------------------\n\n\tsetTool(tool: VectorTool): void {\n\t\tif (tool === this.tool) return;\n\t\tthis.finishPath();\n\t\tthis.cancelDrag();\n\t\tthis.tool = tool;\n\t\tthis.hover = null;\n\t\tthis.guides = null;\n\t\tthis.widthPoint = null;\n\t\tthis.builderPreview = null;\n\t\tthis.builderHoverKey = null;\n\t\tif (tool !== 'direct') {\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t}\n\t\tthis.notify();\n\t}\n\n\tsetDefaults(defaults: Partial<VectorDefaults>): void {\n\t\tthis.defaults = { ...this.defaults, ...defaults };\n\t\tthis.notify();\n\t}\n\n\tsetSnap(snap: Partial<VectorSnapOptions>): void {\n\t\tthis.snap = { ...this.snap, ...snap };\n\t\tif (!this.snap.guides || !this.snap.objects) this.guides = null;\n\t\tthis.notify();\n\t}\n\n\t/** Changes how deleting, dragging anchors, the pencil and the eraser behave. */\n\tsetEditing(editing: Partial<VectorPathEditOptions>): void {\n\t\tconst next = { ...this.editing, ...editing };\n\t\tnext.pencilSmoothing = Math.min(1, Math.max(0, Number.isFinite(next.pencilSmoothing) ? next.pencilSmoothing : 0));\n\t\tif (!(next.eraserSize > 0)) next.eraserSize = this.editing.eraserSize;\n\t\tthis.editing = next;\n\t\tthis.notify();\n\t}\n\n\t/** Turns object snapping on or off (the toolbar's snapping toggle). */\n\ttoggleSnapping(on: boolean = !this.snap.objects): void {\n\t\tthis.setSnap({ objects: on });\n\t}\n\n\tprivate gridValue(v: number): number {\n\t\tconst g = this.snap.grid;\n\t\treturn g > 0 ? Math.round(v / g) * g : v;\n\t}\n\n\tprivate snapPoint(p: Vec2): Vec2 {\n\t\treturn { x: this.gridValue(p.x), y: this.gridValue(p.y) };\n\t}\n\n\t/** The pull distance in document units. */\n\tprivate snapTolerance(): number {\n\t\treturn this.snap.threshold / this.viewport.zoom;\n\t}\n\n\tprivate setGuides(guides: VectorSnapGuides | null) {\n\t\tthis.guides = guides && this.snap.guides && (guides.lines.length || guides.labels.length) ? guides : null;\n\t}\n\n\t/**\n\t * Where a drawn or dragged point `p` goes: onto the smart guide `targets` (gathered by\n\t * `gather` when missing), else onto the grid, kept to `leave`'s constraint. Cmd / Ctrl\n\t * bypasses snapping.\n\t */\n\tprivate snapDrawn(p: Vec2, leave: VectorSnapLeave | null, input: VectorModifiers, targets: () => VectorSnapTargets): Vec2 {\n\t\tthis.snappedToObject = false;\n\t\tif (input.mod) {\n\t\t\tthis.setGuides(null);\n\t\t\treturn constrainToLeave(leave, p);\n\t\t}\n\t\tif (this.snap.objects) {\n\t\t\tconst withAngles = leave ? { ...leave, angles: this.snap.angles } : null;\n\t\t\tconst res = targets().snapFrom(p, withAngles, this.snapTolerance());\n\t\t\tif (res.kind) {\n\t\t\t\tthis.snappedToObject = true;\n\t\t\t\tthis.setGuides(res);\n\t\t\t\t// An axis lined up with nothing still goes to the grid.\n\t\t\t\treturn leave?.constrain ? res.point : { x: res.x ? res.point.x : this.gridValue(res.point.x), y: res.y ? res.point.y : this.gridValue(res.point.y) };\n\t\t\t}\n\t\t}\n\t\tthis.setGuides(null);\n\t\treturn constrainToLeave(leave, this.snapPoint(p));\n\t}\n\n\t/** Drawing targets for the pen and shape tools, reused while the document stays the same. */\n\tprivate drawingTargets(exclude: string | null): VectorSnapTargets {\n\t\tconst key = exclude ?? '';\n\t\tconst cached = this.hoverTargets;\n\t\tif (cached && cached.doc === this.doc && cached.exclude === key) return cached.targets;\n\t\tconst targets = VectorSnapTargets.forDrawing(this.doc, exclude ? [exclude] : []);\n\t\tthis.hoverTargets = { doc: this.doc, exclude: key, targets };\n\t\treturn targets;\n\t}\n\n\t/** Where the pointer at `p` would place a point with the pen or a shape tool (and the guides showing why). */\n\tprivate hoverSnap(p: Vec2, input: VectorModifiers): Vec2 {\n\t\tif (this.tool === 'pen') {\n\t\t\tconst sp = this.pen ? (this.getNode(this.pen.nodeId) as VectorPathNode | undefined)?.subpaths[this.pen.subpath] : undefined;\n\t\t\tif (this.pen && sp && this.hover?.anchor) {\n\t\t\t\tthis.setGuides(null);\n\t\t\t\treturn p;\n\t\t\t}\n\t\t\tconst last = this.pen && sp ? getAnchorWorld(this.doc, { nodeId: this.pen.nodeId, subpath: this.pen.subpath, index: sp.anchors.length - 1 }) : undefined;\n\t\t\tconst leave = last ? { at: { x: last.x, y: last.y }, constrain: input.shift ? ('angle' as const) : null } : null;\n\t\t\treturn this.snapDrawn(p, leave, input, () => this.drawingTargets(this.pen?.nodeId ?? null));\n\t\t}\n\t\tif (SHAPE_TOOLS.has(this.tool)) return this.snapDrawn(p, null, input, () => this.drawingTargets(null));\n\t\tthis.setGuides(null);\n\t\treturn p;\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Document\n\t// -------------------------------------------------------------------------\n\n\t/** Replaces the document. Undoable unless `{ history: false }` (then history is cleared). */\n\tsetDocument(doc: VectorDocument, options: { history?: boolean; label?: string } = {}): void {\n\t\tthis.cancelDrag();\n\t\tconst next = cloneVectorDocument(doc);\n\t\tif (options.history === false) {\n\t\t\tthis.doc = next;\n\t\t\tthis.selection = [];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t\tthis.pen = null;\n\t\t\tthis.history.clear();\n\t\t\tthis.notify(true);\n\t\t\treturn;\n\t\t}\n\t\tthis.change(options.label ?? 'Replace Document', () => {\n\t\t\tthis.doc = next;\n\t\t\tthis.selection = [];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t\tthis.pen = null;\n\t\t});\n\t}\n\n\t/** Changes the artboard size or background. */\n\tsetArtboard(patch: Partial<Pick<VectorDocument, 'width' | 'height' | 'background'>>): void {\n\t\tthis.change('Change Artboard', () => {\n\t\t\tthis.doc = { ...this.doc, ...patch };\n\t\t});\n\t}\n\n\t/** Replaces the document with parsed SVG markup (one undo step). */\n\tloadSvg(svg: string, options: { history?: boolean } = {}): VectorActionResult {\n\t\ttry {\n\t\t\tconst doc = parseVectorSvg(svg, { createId: () => this.createId() });\n\t\t\tthis.setDocument(doc, { history: options.history, label: 'Import SVG' });\n\t\t\treturn { ok: true };\n\t\t} catch (error) {\n\t\t\treturn { ok: false, message: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n\n\t/** Adds the nodes of SVG markup on top of the document, selected. */\n\timportSvg(svg: string): VectorActionResult {\n\t\ttry {\n\t\t\tconst parsed = parseVectorSvg(svg);\n\t\t\tconst nodes = parsed.nodes.map((n) => this.freshIds(n));\n\t\t\tif (!nodes.length) return { ok: false, message: 'The SVG has no shapes the editor can read.' };\n\t\t\tthis.change('Import SVG', () => {\n\t\t\t\tthis.setDoc([...this.doc.nodes, ...nodes]);\n\t\t\t\tthis.selection = nodes.map((n) => n.id);\n\t\t\t\tthis.anchors = [];\n\t\t\t});\n\t\t\treturn { ok: true };\n\t\t} catch (error) {\n\t\t\treturn { ok: false, message: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n\n\ttoSvg(options?: VectorSvgExportOptions): string {\n\t\treturn vectorDocumentToSvg(this.doc, options);\n\t}\n\n\ttoJSON(): VectorDocument {\n\t\treturn cloneVectorDocument(this.doc);\n\t}\n\n\t/** Adds a node (ids are kept unless taken). Returns its id. */\n\taddNode(node: VectorNode, options: AddVectorNodeOptions = {}): string {\n\t\tconst taken = (() => {\n\t\t\tlet clash = false;\n\t\t\twalkVectorNodes([node], (n) => {\n\t\t\t\tif (this.getNode(n.id)) clash = true;\n\t\t\t});\n\t\t\treturn clash;\n\t\t})();\n\t\tconst next = taken ? this.freshIds(node) : cloneVectorNode(node);\n\t\tthis.change(options.label ?? `Add ${next.type === 'group' ? 'Group' : (next.name ?? 'Path')}`, () => {\n\t\t\tconst insert = (list: VectorNode[]) => {\n\t\t\t\tconst copy = list.slice();\n\t\t\t\tcopy.splice(options.index ?? copy.length, 0, next);\n\t\t\t\treturn copy;\n\t\t\t};\n\t\t\tif (options.parentId) {\n\t\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === options.parentId && n.type === 'group' ? { ...n, children: insert(n.children) } : n)));\n\t\t\t} else this.setDoc(insert(this.doc.nodes));\n\t\t\tif (options.select !== false) {\n\t\t\t\tthis.selection = [next.id];\n\t\t\t\tthis.anchors = [];\n\t\t\t}\n\t\t});\n\t\treturn next.id;\n\t}\n\n\t/** Builds a path node for a shape with the current defaults (not added). */\n\tcreateShapeNode(input: VectorShapeInput): VectorPathNode {\n\t\tconst b = { x: input.x, y: input.y, width: input.width, height: input.height };\n\t\tconst d = this.defaults;\n\t\tlet subpath: VectorSubpath;\n\t\tswitch (input.kind) {\n\t\t\tcase 'rect':\n\t\t\t\tsubpath = rectSubpath(b);\n\t\t\t\tbreak;\n\t\t\tcase 'ellipse':\n\t\t\t\tsubpath = ellipseSubpath(b);\n\t\t\t\tbreak;\n\t\t\tcase 'polygon':\n\t\t\t\tsubpath = polygonSubpath(b, input.sides ?? d.polygonSides);\n\t\t\t\tbreak;\n\t\t\tcase 'star':\n\t\t\t\tsubpath = starSubpath(b, input.points ?? d.starPoints, input.innerRatio ?? d.starInnerRatio);\n\t\t\t\tbreak;\n\t\t\tcase 'line':\n\t\t\t\tsubpath = lineSubpath({ x: b.x, y: b.y }, { x: b.x + b.width, y: b.y + b.height });\n\t\t\t\tbreak;\n\t\t}\n\t\tconst radius = input.cornerRadius ?? d.cornerRadius;\n\t\tconst kind = input.cornerKind ?? d.cornerKind;\n\t\t// Live corners: the shape keeps its sharp anchors, so the radius stays editable.\n\t\tif ((input.kind === 'rect' || input.kind === 'polygon' || input.kind === 'star') && radius > 0) subpath = setSubpathCorners(subpath, radius, kind);\n\t\tconst names = { rect: 'Rectangle', ellipse: 'Ellipse', polygon: 'Polygon', star: 'Star', line: 'Line' };\n\t\tconst style = this.styleFor(input.kind === 'line');\n\t\tconst own: VectorStyle = {};\n\t\tfor (const key of VECTOR_STYLE_KEYS) {\n\t\t\tif (input[key] !== undefined) (own as any)[key] = input[key];\n\t\t}\n\t\treturn { id: this.newId(), type: 'path', name: input.name ?? names[input.kind], ...style, ...own, subpaths: [subpath] };\n\t}\n\n\t/** Adds a shape drawn with the current defaults. Returns its id. */\n\taddShape(input: VectorShapeInput, options: AddVectorNodeOptions = {}): string {\n\t\tconst node = this.createShapeNode(input);\n\t\treturn this.addNode(node, { label: `Add ${node.name}`, ...options });\n\t}\n\n\t/** Adds a path from SVG path data. Returns its id. */\n\taddPath(d: string, style: VectorStyle & { name?: string } = {}, options: AddVectorNodeOptions = {}): string {\n\t\tconst subpaths = bezierToSubpaths(d);\n\t\tconst node: VectorPathNode = { id: this.newId(), type: 'path', name: style.name ?? 'Path', ...this.styleFor(false), ...style, subpaths };\n\t\treturn this.addNode(node, { label: 'Add Path', ...options });\n\t}\n\n\tprivate styleFor(open: boolean): VectorStyle {\n\t\tconst d = this.defaults;\n\t\tconst out: VectorStyle = { fill: open ? null : (d.fill ?? null), stroke: d.stroke ?? null, strokeWidth: d.strokeWidth ?? 1 };\n\t\tif (d.strokeLinecap) out.strokeLinecap = d.strokeLinecap;\n\t\tif (d.strokeLinejoin) out.strokeLinejoin = d.strokeLinejoin;\n\t\tif (d.strokeDasharray) out.strokeDasharray = d.strokeDasharray;\n\t\tif (d.fillRule) out.fillRule = d.fillRule;\n\t\tif (d.strokeAlign && d.strokeAlign !== 'center') out.strokeAlign = d.strokeAlign;\n\t\tfor (const key of ['startArrow', 'endArrow', 'arrowAlign', 'startArrowScale', 'endArrowScale'] as const) if (d[key]) (out as any)[key] = d[key];\n\t\tif (d.strokeWidthProfile?.length) out.strokeWidthProfile = d.strokeWidthProfile.map((p) => ({ ...p }));\n\t\treturn out;\n\t}\n\n\t/** Merges `patch` into a node (paths take style and geometry; groups name / visibility / opacity). */\n\tupdateNode(id: string, patch: Partial<VectorPathNode> | Partial<VectorGroupNode>, options: { label?: string } = {}): VectorActionResult {\n\t\tconst node = this.getNode(id);\n\t\tif (!node) return { ok: false, message: `There is no node \"${id}\".` };\n\t\tconst { id: _id, type: _type, ...rest } = patch as any;\n\t\tthis.change(options.label ?? 'Edit Node', () => this.replaceNode(id, { ...node, ...rest } as VectorNode));\n\t\treturn { ok: true };\n\t}\n\n\t/** Applies style (and opacity) to the selected (or given) nodes; groups pass it to every path inside. */\n\tsetStyle(style: VectorStyle & { opacity?: number }, ids: readonly string[] = this.selection, options: { label?: string } = {}): VectorActionResult {\n\t\tconst targets = new Set<string>();\n\t\tfor (const id of ids) {\n\t\t\tconst node = this.getNode(id);\n\t\t\tif (!node) return { ok: false, message: `There is no node \"${id}\".` };\n\t\t\tfor (const p of collectPathNodes(node)) targets.add(p.id);\n\t\t}\n\t\tif (!targets.size) return { ok: false, message: 'Nothing is selected.' };\n\t\tthis.change(options.label ?? 'Change Style', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (targets.has(n.id) ? withStyle(n as VectorPathNode, style) : n)));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/**\n\t * Sets the variable-width profile of the selected (or given) paths: a preset id\n\t * (`uniform` removes the profile), points, or a parametric taper / wave. Returns an error for\n\t * an unknown preset.\n\t */\n\tsetWidthProfile(\n\t\tprofile: VectorWidthPreset | readonly VectorWidthPoint[] | { taper?: VectorTaperOptions; wave?: VectorWaveOptions } | null,\n\t\toptions: { ids?: readonly string[] } = {}\n\t): VectorActionResult {\n\t\tlet points: VectorWidthPoint[];\n\t\tif (profile === null) points = [];\n\t\telse if (typeof profile === 'string') {\n\t\t\tconst preset = widthProfilePreset(profile);\n\t\t\tif (!preset) return { ok: false, message: `There is no width profile \"${profile}\".` };\n\t\t\tpoints = preset;\n\t\t} else if (Array.isArray(profile)) points = sanitizeWidthProfile(profile);\n\t\telse {\n\t\t\tconst p = profile as { taper?: VectorTaperOptions; wave?: VectorWaveOptions };\n\t\t\tpoints = p.taper || p.wave ? generateWidthProfile(p) : [];\n\t\t}\n\t\tthis.widthPoint = null;\n\t\treturn this.setStyle({ strokeWidthProfile: points.length ? points : null }, options.ids ?? this.selection, { label: points.length ? 'Width Profile' : 'Uniform Width' });\n\t}\n\n\t/** Removes one width point of a path's profile (the width tool's Delete). */\n\tremoveWidthPoint(ref: Pick<VectorWidthPointRef, 'nodeId' | 'index'>): VectorActionResult {\n\t\tconst node = this.getNode(ref.nodeId);\n\t\tif (node?.type !== 'path' || !node.strokeWidthProfile?.[ref.index]) return { ok: false, message: 'There is no such width point.' };\n\t\tconst rest = removeWidthPoints(sanitizeWidthProfile(node.strokeWidthProfile), [ref.index]);\n\t\tthis.widthPoint = null;\n\t\tthis.change('Delete Width Point', () => this.replaceNode(node.id, withStyle(node, { strokeWidthProfile: rest.length ? rest : null })));\n\t\treturn { ok: true };\n\t}\n\n\t/**\n\t * Sets the live corner radius (and optionally the kind) of anchors: `refs`, else the selected\n\t * anchors (direct tool), else every anchor of the `ids` / selected paths. Radius 0 makes the\n\t * corners sharp again. Corners shrink to fit when drawn, so any radius is accepted.\n\t */\n\tsetCornerRadius(radius: number, options: { kind?: VectorCornerKind; refs?: readonly VectorAnchorRef[]; ids?: readonly string[] } = {}): VectorActionResult {\n\t\tif (!Number.isFinite(radius) || radius < 0) return { ok: false, message: 'The radius must be a number of at least 0.' };\n\t\tconst refs = this.cornerTargets(options);\n\t\tif (!refs.length) return { ok: false, message: 'Nothing is selected.' };\n\t\tthis.change(radius > 0 ? 'Corner Radius' : 'Sharpen Corners', () => {\n\t\t\tthis.doc = this.updateAnchors(this.doc, refs, (a) => setAnchorCorner(a, radius, options.kind));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Sets the live corner kind of the same anchors as `setCornerRadius`, keeping their radii. */\n\tsetCornerKind(kind: VectorCornerKind, options: { refs?: readonly VectorAnchorRef[]; ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst refs = this.cornerTargets(options);\n\t\tif (!refs.length) return { ok: false, message: 'Nothing is selected.' };\n\t\tthis.change('Corner Kind', () => {\n\t\t\tthis.doc = this.updateAnchors(this.doc, refs, (a) => setAnchorCorner(a, a.corner?.radius ?? 0, kind));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Anchors a corner change applies to (see `setCornerRadius`). */\n\tprivate cornerTargets(options: { refs?: readonly VectorAnchorRef[]; ids?: readonly string[] }): VectorAnchorRef[] {\n\t\tif (options.refs) return options.refs.filter((r) => getAnchor(this.doc, r));\n\t\tif (!options.ids && this.tool === 'direct' && this.anchors.length) return this.anchors.slice();\n\t\tconst out: VectorAnchorRef[] = [];\n\t\tfor (const id of options.ids ?? this.selection) {\n\t\t\tconst node = this.getNode(id);\n\t\t\tif (!node) continue;\n\t\t\tfor (const p of collectPathNodes(node)) {\n\t\t\t\tif (p.locked) continue;\n\t\t\t\tp.subpaths.forEach((sp, s) => sp.anchors.forEach((_, i) => out.push({ nodeId: p.id, subpath: s, index: i })));\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n\t/**\n\t * Outline Stroke: replaces each selected (or given) path's stroke with a filled path of the\n\t * area it paints (alignment, joins, caps, dashes and arrowheads included), placed above a copy\n\t * of the path that keeps the fill (left out when there is none). Returns the new paths' ids.\n\t */\n\toutlineStroke(options: { ids?: readonly string[] } = {}): string[] {\n\t\tconst roots = options.ids ?? this.selectedRoots();\n\t\tconst paths: VectorPathNode[] = [];\n\t\tfor (const id of roots) {\n\t\t\tconst node = this.getNode(id);\n\t\t\tif (node) for (const p of collectPathNodes(node)) if (!p.locked && hasPaint(p.stroke) && (p.strokeWidth ?? 1) > 0) paths.push(p);\n\t\t}\n\t\tif (!paths.length) return [];\n\t\tconst created: string[] = [];\n\t\tconst replace = new Map<string, VectorNode[]>();\n\t\tfor (const p of paths) {\n\t\t\t// In the node's own space: the new paths keep its transform.\n\t\t\tconst outline = bezierToSubpaths(vectorStrokeOutlinePath(subpathsToBezier(p.subpaths), p));\n\t\t\tif (!outline.length) continue;\n\t\t\tconst {\n\t\t\t\tstroke,\n\t\t\t\tstrokeWidth: _w,\n\t\t\t\tstrokeLinecap: _c,\n\t\t\t\tstrokeLinejoin: _j,\n\t\t\t\tstrokeDasharray: _d,\n\t\t\t\tstrokeAlign: _a,\n\t\t\t\tstartArrow: _s,\n\t\t\t\tendArrow: _e,\n\t\t\t\tarrowAlign: _al,\n\t\t\t\tstartArrowScale: _ss,\n\t\t\t\tendArrowScale: _es,\n\t\t\t\tstrokeWidthProfile: _wp,\n\t\t\t\t...rest\n\t\t\t} = cloneVectorNode(p);\n\t\t\tconst id = this.newId();\n\t\t\tconst strokeNode: VectorPathNode = { ...rest, id, name: `${p.name ?? 'Path'} Stroke`, subpaths: outline, fill: stroke ?? null, stroke: null, fillRule: 'nonzero' };\n\t\t\tconst list: VectorNode[] = hasPaint(p.fill) ? [{ ...rest, stroke: null }, strokeNode] : [strokeNode];\n\t\t\tcreated.push(id);\n\t\t\treplace.set(p.id, list);\n\t\t}\n\t\tif (!created.length) return [];\n\t\tthis.change('Outline Stroke', () => {\n\t\t\tlet nodes = this.doc.nodes;\n\t\t\tfor (const [id, list] of replace) nodes = spliceTree(nodes, id, list);\n\t\t\tthis.setDoc(nodes);\n\t\t\tthis.selection = created;\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn created;\n\t}\n\n\trename(id: string, name: string): VectorActionResult {\n\t\treturn this.updateNode(id, { name }, { label: 'Rename' });\n\t}\n\n\tsetVisible(id: string, visible: boolean): VectorActionResult {\n\t\treturn this.updateNode(id, { visible }, { label: visible ? 'Show' : 'Hide' });\n\t}\n\n\tsetLocked(id: string, locked: boolean): VectorActionResult {\n\t\tconst result = this.updateNode(id, { locked }, { label: locked ? 'Lock' : 'Unlock' });\n\t\tif (locked && result.ok && this.selection.includes(id)) {\n\t\t\tthis.selection = this.selection.filter((s) => s !== id);\n\t\t\tthis.notify();\n\t\t}\n\t\treturn result;\n\t}\n\n\t/** Removes nodes by id. */\n\tremoveNodes(ids: readonly string[], options: { label?: string } = {}): VectorActionResult {\n\t\tconst drop = new Set(ids.filter((id) => this.getNode(id)));\n\t\tif (!drop.size) return { ok: false, message: 'Nothing to delete.' };\n\t\tthis.change(options.label ?? 'Delete', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (drop.has(n.id) ? null : n)));\n\t\t\tthis.selection = this.selection.filter((id) => !drop.has(id) && this.getNode(id));\n\t\t\tthis.anchors = this.anchors.filter((r) => getAnchor(this.doc, r));\n\t\t\tif (this.editingId && !this.getNode(this.editingId)) this.editingId = null;\n\t\t\tif (this.pen && !this.getNode(this.pen.nodeId)) this.pen = null;\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Selection\n\t// -------------------------------------------------------------------------\n\n\tselect(ids: readonly string[], options: { add?: boolean; toggle?: boolean } = {}): void {\n\t\tconst valid = ids.filter((id) => this.getNode(id));\n\t\tlet next: string[];\n\t\tif (options.toggle) {\n\t\t\tconst set = new Set(this.selection);\n\t\t\tfor (const id of valid) set.has(id) ? set.delete(id) : set.add(id);\n\t\t\tnext = [...set];\n\t\t} else next = options.add ? [...new Set([...this.selection, ...valid])] : valid;\n\t\tthis.selection = next;\n\t\tif (!options.add && !options.toggle) this.anchors = this.anchors.filter((r) => next.includes(r.nodeId));\n\t\tthis.notify();\n\t}\n\n\tselectAll(): void {\n\t\tif (this.tool === 'direct' && this.editingId) {\n\t\t\tthis.anchors = getVisibleAnchors(this.view());\n\t\t} else {\n\t\t\tthis.selection = this.doc.nodes.filter((n) => !n.locked && n.visible !== false).map((n) => n.id);\n\t\t}\n\t\tthis.notify();\n\t}\n\n\tclearSelection(): void {\n\t\tif (!this.selection.length && !this.anchors.length && !this.editingId) return;\n\t\tthis.selection = [];\n\t\tthis.anchors = [];\n\t\tthis.editingId = null;\n\t\tthis.notify();\n\t}\n\n\tselectAnchors(refs: readonly VectorAnchorRef[], options: { add?: boolean } = {}): void {\n\t\tconst valid = refs.filter((r) => getAnchor(this.doc, r));\n\t\tthis.anchors = options.add ? [...this.anchors, ...valid.filter((r) => !this.anchors.some((a) => sameRef(a, r)))] : valid;\n\t\tif (valid.length && !this.editingId) this.editingId = valid[0].nodeId;\n\t\tthis.notify();\n\t}\n\n\t/** Top-level ids of the selection (members of selected groups are covered by the group). */\n\tprivate selectedRoots(): string[] {\n\t\treturn this.selection.filter((id) => {\n\t\t\tlet covered = false;\n\t\t\tconst loc = locateVectorNode(this.doc.nodes, id);\n\t\t\tlet parent = loc?.parent ?? null;\n\t\t\twhile (parent) {\n\t\t\t\tif (this.selection.includes(parent.id)) covered = true;\n\t\t\t\tparent = locateVectorNode(this.doc.nodes, parent.id)?.parent ?? null;\n\t\t\t}\n\t\t\treturn !covered;\n\t\t});\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Transforms\n\t// -------------------------------------------------------------------------\n\n\t/** `m`, given in a frame rotated by `angle`, as a document-space matrix. */\n\tprivate inFrame(angle: number, m: AffineMatrix): AffineMatrix {\n\t\tif (!angle) return m;\n\t\treturn multiplyMatrices(multiplyMatrices(rotateMatrix(-angle), m), rotateMatrix(angle));\n\t}\n\n\t/** Applies a matrix to the selected (or given) nodes as one undo step. */\n\ttransform(matrix: AffineMatrix, options: { ids?: readonly string[]; label?: string } = {}): VectorActionResult {\n\t\tconst ids = new Set(options.ids ?? this.selectedRoots());\n\t\tif (!ids.size) return { ok: false, message: 'Nothing is selected.' };\n\t\tthis.change(options.label ?? 'Transform', () => {\n\t\t\tthis.doc = this.transformed(this.doc, ids, matrix);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** `doc` with nodes `ids` moved by `m`, given in document space. */\n\tprivate transformed(doc: VectorDocument, ids: ReadonlySet<string>, m: AffineMatrix): VectorDocument {\n\t\tconst visit = (list: readonly VectorNode[], parent: AffineMatrix): VectorNode[] => {\n\t\t\tlet changed = false;\n\t\t\tconst out = list.map((n) => {\n\t\t\t\tlet next = n;\n\t\t\t\tif (ids.has(n.id) && !n.locked) {\n\t\t\t\t\t// `m` in the node's parent space: parent → document, m, document → parent.\n\t\t\t\t\tconst local = isRoot(parent) ? m : multiplyMatrices(multiplyMatrices(parent, m), invertMatrix(parent));\n\t\t\t\t\tnext = transformVectorNode(n, local);\n\t\t\t\t} else if (n.type === 'group') {\n\t\t\t\t\tconst children = visit(n.children, multiplyMatrices(nodeMatrix(n), parent));\n\t\t\t\t\tif (children !== n.children) next = { ...n, children };\n\t\t\t\t}\n\t\t\t\tif (next !== n) changed = true;\n\t\t\t\treturn next;\n\t\t\t});\n\t\t\treturn changed ? out : (list as VectorNode[]);\n\t\t};\n\t\tconst nodes = visit(doc.nodes, IDENTITY_MATRIX);\n\t\treturn nodes === doc.nodes ? doc : { ...doc, nodes };\n\t}\n\n\ttranslate(dx: number, dy: number, options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tif (this.tool === 'direct' && this.anchors.length && !options.ids) {\n\t\t\tthis.change('Move Points', () => {\n\t\t\t\tthis.doc = this.movedAnchors(this.doc, this.anchors, dx, dy);\n\t\t\t});\n\t\t\treturn { ok: true };\n\t\t}\n\t\treturn this.transform(translateMatrix(dx, dy), { ids: options.ids, label: 'Move' });\n\t}\n\n\t/** The selection frame's centre in document space. */\n\tprivate frameCenter(frame: VectorSelectionFrame): Vec2 {\n\t\treturn applyMatrix(rotateMatrix(frame.angle), { x: frame.x + frame.width / 2, y: frame.y + frame.height / 2 });\n\t}\n\n\t/**\n\t * Scales along the selection box's own axes (rotated with the selection when its nodes\n\t * share a rotation) around `origin` (default: the box centre, in document space).\n\t */\n\tscale(sx: number, sy: number = sx, options: { ids?: readonly string[]; origin?: Vec2 } = {}): VectorActionResult {\n\t\tconst frame = this.frameOf(options.ids ?? this.selectedRoots());\n\t\tif (!frame) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst origin = applyMatrix(rotateMatrix(-frame.angle), options.origin ?? this.frameCenter(frame));\n\t\treturn this.transform(this.inFrame(frame.angle, scaleMatrix(sx, sy, origin)), { ids: options.ids, label: 'Scale' });\n\t}\n\n\t/** Rotates clockwise by `degrees` around `origin` (default: the selection centre). */\n\trotate(degrees: number, options: { ids?: readonly string[]; origin?: Vec2 } = {}): VectorActionResult {\n\t\tconst frame = this.frameOf(options.ids ?? this.selectedRoots());\n\t\tif (!frame) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst origin = options.origin ?? this.frameCenter(frame);\n\t\treturn this.transform(rotateMatrix(degrees, origin), { ids: options.ids, label: 'Rotate' });\n\t}\n\n\t/** Sets each selected (or given) node's rotation to `degrees`, turning it around its own centre. */\n\tsetRotation(degrees: number, options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tif (!ids.length) return { ok: false, message: 'Nothing is selected.' };\n\t\tthis.change('Set Rotation', () => {\n\t\t\tfor (const id of ids) {\n\t\t\t\tconst frame = this.frameOf([id]);\n\t\t\t\tif (!frame) continue;\n\t\t\t\tconst delta = normalizeAngle(degrees - frame.angle);\n\t\t\t\tif (Math.abs(delta) > 1e-9) this.doc = this.transformed(this.doc, new Set([id]), rotateMatrix(delta, this.frameCenter(frame)));\n\t\t\t}\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Mirrors along the selection box's own axes. */\n\tflip(axis: 'horizontal' | 'vertical', options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst frame = this.frameOf(options.ids ?? this.selectedRoots());\n\t\tif (!frame) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst c = { x: frame.x + frame.width / 2, y: frame.y + frame.height / 2 };\n\t\tconst m = axis === 'horizontal' ? scaleMatrix(-1, 1, c) : scaleMatrix(1, -1, c);\n\t\treturn this.transform(this.inFrame(frame.angle, m), { ids: options.ids, label: axis === 'horizontal' ? 'Flip Horizontal' : 'Flip Vertical' });\n\t}\n\n\t/**\n\t * Aligns the selected nodes to their combined bounds, or to the artboard when one node is\n\t * selected (or `to: 'artboard'`).\n\t */\n\talign(edge: VectorAlign, options: { ids?: readonly string[]; to?: 'selection' | 'artboard' } = {}): VectorActionResult {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tif (!ids.length) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst target = options.to === 'artboard' || ids.length === 1 ? { x: 0, y: 0, width: this.doc.width, height: this.doc.height } : this.boundsOf(ids)!;\n\t\tthis.change(`Align ${edge[0].toUpperCase()}${edge.slice(1)}`, () => {\n\t\t\tfor (const id of ids) {\n\t\t\t\tconst b = this.boundsOf([id]);\n\t\t\t\tif (!b) continue;\n\t\t\t\tlet dx = 0;\n\t\t\t\tlet dy = 0;\n\t\t\t\tif (edge === 'left') dx = target.x - b.x;\n\t\t\t\tif (edge === 'center') dx = target.x + target.width / 2 - (b.x + b.width / 2);\n\t\t\t\tif (edge === 'right') dx = target.x + target.width - (b.x + b.width);\n\t\t\t\tif (edge === 'top') dy = target.y - b.y;\n\t\t\t\tif (edge === 'middle') dy = target.y + target.height / 2 - (b.y + b.height / 2);\n\t\t\t\tif (edge === 'bottom') dy = target.y + target.height - (b.y + b.height);\n\t\t\t\tif (dx || dy) this.doc = this.transformed(this.doc, new Set([id]), translateMatrix(dx, dy));\n\t\t\t}\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Spaces three or more selected nodes evenly (equal gaps). */\n\tdistribute(direction: VectorDistribute, options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tconst items = ids.map((id) => ({ id, b: this.boundsOf([id]) })).filter((i): i is { id: string; b: VectorBounds } => !!i.b);\n\t\tif (items.length < 3) return { ok: false, message: 'Select at least three objects to distribute.' };\n\t\tconst horizontal = direction === 'horizontal';\n\t\tconst pos = (b: VectorBounds) => (horizontal ? b.x : b.y);\n\t\tconst size = (b: VectorBounds) => (horizontal ? b.width : b.height);\n\t\titems.sort((a, b) => pos(a.b) - pos(b.b));\n\t\tconst first = items[0].b;\n\t\tconst last = items[items.length - 1].b;\n\t\tconst total = pos(last) + size(last) - pos(first);\n\t\tconst gap = (total - items.reduce((s, i) => s + size(i.b), 0)) / (items.length - 1);\n\t\tthis.change(horizontal ? 'Distribute Horizontally' : 'Distribute Vertically', () => {\n\t\t\tlet cursor = pos(first);\n\t\t\tfor (const item of items) {\n\t\t\t\tconst d = cursor - pos(item.b);\n\t\t\t\tif (Math.abs(d) > 1e-9) this.doc = this.transformed(this.doc, new Set([item.id]), horizontal ? translateMatrix(d, 0) : translateMatrix(0, d));\n\t\t\t\tcursor += size(item.b) + gap;\n\t\t\t}\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Structure\n\t// -------------------------------------------------------------------------\n\n\t/** Copies the selection (offset by `offset`, default 10, 10) on top of each original. */\n\tduplicate(options: { ids?: readonly string[]; offset?: Vec2 } = {}): string[] {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tconst offset = options.offset ?? { x: 10, y: 10 };\n\t\tconst created: string[] = [];\n\t\tif (!ids.length) return created;\n\t\tthis.change('Duplicate', () => {\n\t\t\tthis.doc = this.withDuplicates(this.doc, ids, offset, created);\n\t\t\tthis.selection = created;\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn created;\n\t}\n\n\tprivate withDuplicates(doc: VectorDocument, ids: readonly string[], offset: Vec2, created: string[]): VectorDocument {\n\t\tconst set = new Set(ids);\n\t\tconst m = translateMatrix(offset.x, offset.y);\n\t\tconst insert = (list: readonly VectorNode[]): VectorNode[] => {\n\t\t\tconst out: VectorNode[] = [];\n\t\t\tfor (const node of list) {\n\t\t\t\tconst n = node.type === 'group' ? { ...node, children: insert(node.children) } : node;\n\t\t\t\tout.push(n);\n\t\t\t\tif (set.has(node.id)) {\n\t\t\t\t\tconst copy = transformVectorNode(this.freshIds(node), m);\n\t\t\t\t\tcreated.push(copy.id);\n\t\t\t\t\tout.push(copy);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn out;\n\t\t};\n\t\treturn { ...doc, nodes: insert(doc.nodes) };\n\t}\n\n\t/** Groups the selected nodes (they must share a parent). Returns the group id. */\n\tgroup(options: { ids?: readonly string[]; name?: string } = {}): string | null {\n\t\tconst ids = options.ids ?? this.selectedRoots();\n\t\tif (!ids.length) return null;\n\t\tconst locs = ids.map((id) => locateVectorNode(this.doc.nodes, id));\n\t\tif (locs.some((l) => !l)) return null;\n\t\tconst parent = locs[0]!.parent?.id ?? null;\n\t\tif (locs.some((l) => (l!.parent?.id ?? null) !== parent)) return null;\n\t\tconst id = this.newId();\n\t\tthis.change('Group', () => {\n\t\t\tconst set = new Set(ids);\n\t\t\tconst regroup = (list: readonly VectorNode[]): VectorNode[] => {\n\t\t\t\tconst members = list.filter((n) => set.has(n.id));\n\t\t\t\tconst top = Math.max(...members.map((m) => list.indexOf(m)));\n\t\t\t\tconst out: VectorNode[] = [];\n\t\t\t\tlist.forEach((n, i) => {\n\t\t\t\t\tif (i === top) out.push({ id, type: 'group', name: options.name ?? 'Group', children: members });\n\t\t\t\t\tif (!set.has(n.id)) out.push(n);\n\t\t\t\t});\n\t\t\t\treturn out;\n\t\t\t};\n\t\t\tif (parent === null) this.setDoc(regroup(this.doc.nodes));\n\t\t\telse this.setDoc(mapTree(this.doc.nodes, (n) => (n.id === parent && n.type === 'group' ? { ...n, children: regroup(n.children) } : n)));\n\t\t\tthis.selection = [id];\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn id;\n\t}\n\n\t/** Replaces selected groups with their children. */\n\tungroup(options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst groups = (options.ids ?? this.selection).map((id) => this.getNode(id)).filter((n): n is VectorGroupNode => n?.type === 'group');\n\t\tif (!groups.length) return { ok: false, message: 'Select a group to ungroup.' };\n\t\tconst set = new Set(groups.map((g) => g.id));\n\t\tthis.change('Ungroup', () => {\n\t\t\tconst flatten = (list: readonly VectorNode[]): VectorNode[] => {\n\t\t\t\tconst out: VectorNode[] = [];\n\t\t\t\tlet changed = false;\n\t\t\t\tfor (const n of list) {\n\t\t\t\t\tif (set.has(n.id) && n.type === 'group') {\n\t\t\t\t\t\tchanged = true;\n\t\t\t\t\t\tconst opacity = n.opacity;\n\t\t\t\t\t\tconst m = nodeMatrix(n);\n\t\t\t\t\t\tout.push(\n\t\t\t\t\t\t\t...n.children\n\t\t\t\t\t\t\t\t.map((c) => (n.transform ? transformVectorNode(c, m) : c))\n\t\t\t\t\t\t\t\t.map((c) => (opacity !== undefined && opacity < 1 ? { ...c, opacity: (c.opacity ?? 1) * opacity } : c))\n\t\t\t\t\t\t);\n\t\t\t\t\t} else if (n.type === 'group') {\n\t\t\t\t\t\tconst children = flatten(n.children);\n\t\t\t\t\t\tif (children !== n.children) changed = true;\n\t\t\t\t\t\tout.push(children !== n.children ? { ...n, children } : n);\n\t\t\t\t\t} else out.push(n);\n\t\t\t\t}\n\t\t\t\treturn changed ? out : (list as VectorNode[]);\n\t\t\t};\n\t\t\tthis.setDoc(flatten(this.doc.nodes));\n\t\t\tthis.selection = groups.flatMap((g) => g.children.map((c) => c.id));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Changes stacking order within each node's parent. */\n\tarrange(op: VectorArrange, options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst set = new Set(options.ids ?? this.selectedRoots());\n\t\tif (!set.size) return { ok: false, message: 'Nothing is selected.' };\n\t\tconst reorder = (list: readonly VectorNode[]): VectorNode[] => {\n\t\t\tconst out = list.map((n) => (n.type === 'group' ? { ...n, children: reorder(n.children) } : n));\n\t\t\tif (op === 'front') return [...out.filter((n) => !set.has(n.id)), ...out.filter((n) => set.has(n.id))];\n\t\t\tif (op === 'back') return [...out.filter((n) => set.has(n.id)), ...out.filter((n) => !set.has(n.id))];\n\t\t\tif (op === 'forward') {\n\t\t\t\tfor (let i = out.length - 2; i >= 0; i--) if (set.has(out[i].id) && !set.has(out[i + 1].id)) [out[i], out[i + 1]] = [out[i + 1], out[i]];\n\t\t\t} else {\n\t\t\t\tfor (let i = 1; i < out.length; i++) if (set.has(out[i].id) && !set.has(out[i - 1].id)) [out[i], out[i - 1]] = [out[i - 1], out[i]];\n\t\t\t}\n\t\t\treturn out;\n\t\t};\n\t\tconst labels = { front: 'Bring to Front', forward: 'Bring Forward', backward: 'Send Backward', back: 'Send to Back' };\n\t\tthis.change(labels[op], () => this.setDoc(reorder(this.doc.nodes)));\n\t\treturn { ok: true };\n\t}\n\n\t/**\n\t * Combines the selected paths (two or more) into one with a boolean operation. `subtract`\n\t * removes the upper shapes from the lowest one. The result takes the lowest shape's style\n\t * and place.\n\t */\n\tbooleanOp(op: VectorBooleanOperation, options: { ids?: readonly string[] } = {}): string | null {\n\t\tconst roots = options.ids ?? this.selectedRoots();\n\t\tconst order: string[] = [];\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (roots.includes(n.id)) for (const p of collectPathNodes(n)) order.push(p.id);\n\t\t});\n\t\tconst paths = [...new Set(order)].map((id) => this.getNode(id) as VectorPathNode);\n\t\tif (paths.length < 2) return null;\n\t\tconst result = pathBoolean(\n\t\t\tBOOLEAN_OPS[op],\n\t\t\tpaths.map((p) => ({\n\t\t\t\tpath: vectorPathWorldBezier(\n\t\t\t\t\t{ ...p, subpaths: p.subpaths.filter((s) => s.anchors.length > 1).map((s) => ({ ...s, closed: true })) },\n\t\t\t\t\tvectorParentMatrix(this.doc.nodes, p.id) ?? IDENTITY_MATRIX\n\t\t\t\t),\n\t\t\t\tfillRule: p.fillRule ?? 'nonzero'\n\t\t\t}))\n\t\t);\n\t\tconst base = paths[0];\n\t\tconst anchorRoot = roots.find((r) => findVectorNode([this.getNode(r)!], base.id)) ?? base.id;\n\t\tconst subpaths = bezierToSubpaths(this.intoParentSpace(anchorRoot, result.path));\n\t\tif (result.error || !subpaths.length) return null;\n\t\tconst id = this.newId();\n\t\tconst { transform: _t, ...baseRest } = cloneVectorNode(base);\n\t\tconst node: VectorPathNode = { ...baseRest, id, name: BOOLEAN_LABELS[op], subpaths };\n\t\tconst drop = new Set([...paths.map((p) => p.id), ...roots]);\n\t\tthis.change(BOOLEAN_LABELS[op], () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === anchorRoot ? node : drop.has(n.id) ? null : n)));\n\t\t\tthis.selection = [id];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn id;\n\t}\n\n\t/** Joins the selected paths into one compound path (subpaths kept, lowest style). */\n\tcombine(options: { ids?: readonly string[] } = {}): string | null {\n\t\tconst roots = options.ids ?? this.selectedRoots();\n\t\tconst paths: VectorPathNode[] = [];\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (roots.includes(n.id)) paths.push(...collectPathNodes(n));\n\t\t});\n\t\tif (paths.length < 2) return null;\n\t\tconst id = this.newId();\n\t\tconst first = roots.find((r) => findVectorNode([this.getNode(r)!], paths[0].id)) ?? paths[0].id;\n\t\tconst subpaths = paths.flatMap((p) => bezierToSubpaths(this.intoParentSpace(first, vectorPathWorldBezier(p, vectorParentMatrix(this.doc.nodes, p.id) ?? IDENTITY_MATRIX))));\n\t\tconst { transform: _t, ...baseRest } = cloneVectorNode(paths[0]);\n\t\tconst node: VectorPathNode = { ...baseRest, id, name: 'Compound Path', subpaths };\n\t\tconst drop = new Set([...paths.map((p) => p.id), ...roots]);\n\t\tthis.change('Combine', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === first ? node : drop.has(n.id) ? null : n)));\n\t\t\tthis.selection = [id];\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn id;\n\t}\n\n\t/** A document-space path mapped into the parent space of node `id`. */\n\tprivate intoParentSpace(id: string, path: BezierPath): BezierPath {\n\t\tconst parent = vectorParentMatrix(this.doc.nodes, id) ?? IDENTITY_MATRIX;\n\t\treturn isRoot(parent) ? path : transformBezierPath(path, invertMatrix(parent));\n\t}\n\n\t/** Splits selected compound paths into one path per subpath. */\n\tbreakApart(options: { ids?: readonly string[] } = {}): VectorActionResult {\n\t\tconst paths = (options.ids ?? this.selection).map((id) => this.getNode(id)).filter((n): n is VectorPathNode => n?.type === 'path' && n.subpaths.length > 1);\n\t\tif (!paths.length) return { ok: false, message: 'Select a compound path to break apart.' };\n\t\tconst created: string[] = [];\n\t\tconst set = new Set(paths.map((p) => p.id));\n\t\tthis.change('Break Apart', () => {\n\t\t\tconst split = (list: readonly VectorNode[]): VectorNode[] =>\n\t\t\t\tlist.flatMap((n): VectorNode[] => {\n\t\t\t\t\tif (n.type === 'group') return [{ ...n, children: split(n.children) }];\n\t\t\t\t\tif (!set.has(n.id)) return [n];\n\t\t\t\t\treturn n.subpaths.map((sp, i) => {\n\t\t\t\t\t\tconst id = i === 0 ? n.id : this.newId();\n\t\t\t\t\t\tcreated.push(id);\n\t\t\t\t\t\treturn { ...n, id, subpaths: [sp] };\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\tthis.setDoc(split(this.doc.nodes));\n\t\t\tthis.selection = created;\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Pathfinder, Shape Builder and paint bucket\n\t// -------------------------------------------------------------------------\n\n\t/**\n\t * Pathfinder: Divide, Trim, Merge, Crop, Outline or Minus Back over the selected (or given)\n\t * paths, in document space (rotated nodes and groups included, live corners cut). Unfilled\n\t * stroked paths take part as the area their stroke paints (Divide: open ones cut instead).\n\t * The results replace the operands at the place of the top-most one, grouped when there are\n\t * several; each keeps the style of the operand whose area it is. Returns the new path ids,\n\t * or an empty list when nothing came out.\n\t */\n\tpathfinder(op: VectorPathfinderOperation, options: { ids?: readonly string[] } = {}): string[] {\n\t\tconst roots = options.ids ?? this.selectedRoots();\n\t\tconst entries = vectorPathEntries(this.doc, roots);\n\t\tif (entries.length < (op === 'divide' || op === 'outline' ? 1 : 2)) return [];\n\t\tconst shapes = entries.map((e) => vectorPathfinderShape(e, op));\n\t\tconst result = runPathfinder(op, shapes);\n\t\tif (result.error || !result.pieces.length) return [];\n\t\tconst last = entries[entries.length - 1].node.id;\n\t\tconst topRoot = [...roots].reverse().find((r) => { const n = this.getNode(r); return !!n && !!findVectorNode([n], last); }) ?? last;\n\t\tconst nodes: VectorPathNode[] = [];\n\t\tfor (const piece of result.pieces) {\n\t\t\tconst subpaths = bezierToSubpaths(this.intoParentSpace(topRoot, piece.path)).map((sp) => (piece.open ? { ...sp, closed: false } : sp));\n\t\t\tif (!subpaths.length) continue;\n\t\t\tconst source = entries[piece.source].node;\n\t\t\tconst style = vectorResultStyle(source, shapes[piece.source].paint, op === 'outline');\n\t\t\tnodes.push({ ...style, type: 'path', id: this.newId(), name: source.name ?? 'Path', subpaths });\n\t\t}\n\t\tif (!nodes.length) return [];\n\t\tconst label = VECTOR_PATHFINDER_LABELS[op];\n\t\tconst container: VectorNode = nodes.length > 1 ? { id: this.newId(), type: 'group', name: label, children: nodes } : nodes[0];\n\t\tconst drop = new Set([...entries.map((e) => e.node.id), ...roots]);\n\t\tthis.change(label, () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === topRoot ? container : drop.has(n.id) ? null : n)));\n\t\t\tthis.selection = [container.id];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn nodes.map((n) => n.id);\n\t}\n\n\t/** The Shape Builder map of the selected (or given) paths, cached per document and selection. */\n\tprivate shapeBuilderMap(ids?: readonly string[]): VectorShapeBuilderMap | null {\n\t\tconst roots = ids ?? this.selectedRoots();\n\t\tconst key = roots.join('\\u0000');\n\t\tif (this.builderCache?.doc === this.doc && this.builderCache.key === key) return this.builderCache.map;\n\t\tconst entries = roots.length ? vectorPathEntries(this.doc, roots) : [];\n\t\tconst map = entries.length ? vectorShapeBuilderMap(entries) : null;\n\t\tthis.builderCache = { doc: this.doc, key, map };\n\t\treturn map;\n\t}\n\n\t/** The faces the Shape Builder offers for the selected (or given) paths (document units). */\n\tgetShapeBuilderFaces(options: { ids?: readonly string[] } = {}): VectorShapeBuilderFace[] {\n\t\tconst m = this.shapeBuilderMap(options.ids);\n\t\tif (!m) return [];\n\t\treturn m.map.faces.map((f, index) => {\n\t\t\tconst p = m.map.faceInterior(index);\n\t\t\treturn {\n\t\t\t\tindex,\n\t\t\t\td: bezierPathToSvg(f.path, { precision: 3 }),\n\t\t\t\tarea: f.area,\n\t\t\t\tsources: m.map.faceSources(index).map((i) => m.entries[i].node.id),\n\t\t\t\tpoint: p ? { x: p[0], y: p[1] } : null\n\t\t\t};\n\t\t});\n\t}\n\n\t/** Pick distance of the Shape Builder's erase for line pieces (document units). */\n\tprivate builderLineTolerance(): number {\n\t\treturn Math.max(this.hitRadius, 4) / this.viewport.zoom;\n\t}\n\n\t/**\n\t * Shape Builder gesture along `points` (document units; one point is a click) over the faces\n\t * the selected (or given) paths make. Merges the faces touched into one shape styled like the\n\t * top-most shape over the first face (the current fill for a face only outlines enclose);\n\t * with `erase` deletes them, the pieces of unfilled open paths and the edges of other outlines\n\t * (cut where paths meet) within `tolerance`: a deleted edge opens a closed subpath there,\n\t * splits an open one or takes a subpath it runs all the way round, and edges bounding a face\n\t * deleted in the same gesture go with the face. Every shape covering a touched face loses\n\t * that area; paths keep their own transforms. One undo step.\n\t */\n\tshapeBuilder(points: readonly Vec2[], options: { ids?: readonly string[]; erase?: boolean; tolerance?: number } = {}): VectorShapeBuilderResult {\n\t\tconst none = (message: string): VectorShapeBuilderResult => ({ ok: false, message, merged: null, faces: 0, lines: 0, edges: 0 });\n\t\tif (!points.length || !points.every((p) => Number.isFinite(p.x) && Number.isFinite(p.y))) return none('Give the points of the gesture.');\n\t\tconst m = this.shapeBuilderMap(options.ids);\n\t\tif (!m) return none('Select paths that make faces.');\n\t\tconst erase = !!options.erase;\n\t\tconst tol = erase ? (options.tolerance ?? this.builderLineTolerance()) : null;\n\t\tconst touched: VectorBuilderTouched = { faces: [], lines: [], edges: [] };\n\t\tconst size = m.map.faces.reduce((s, f) => Math.max(s, f.bounds.maxX - f.bounds.minX, f.bounds.maxY - f.bounds.minY), 1);\n\t\tfor (const p of samplePolyline(points, Math.max(size / 2000, 0.25 / this.viewport.zoom))) addBuilderHit(touched, vectorShapeBuilderHit(m, p, tol));\n\t\tif (!touched.faces.length && !touched.lines.length && !touched.edges.length) return none('There is no face under the pointer.');\n\t\treturn this.applyShapeBuilder(m, touched, erase);\n\t}\n\n\tprivate applyShapeBuilder(m: VectorShapeBuilderMap, touched: VectorBuilderTouched, erase: boolean): VectorShapeBuilderResult {\n\t\tconst plan = planShapeBuilder(m, touched, erase);\n\t\tlet mergedId: string | null = null;\n\t\tconst created = new Map<string, string[]>();\n\t\tthis.change(erase ? 'Shape Builder Delete' : 'Shape Builder', () => {\n\t\t\tlet nodes = this.doc.nodes;\n\t\t\tm.entries.forEach((entry, i) => {\n\t\t\t\tconst node = entry.node;\n\t\t\t\tconst toLocal = (path: BezierPath) => transformBezierPath(path, invertMatrix(multiplyMatrices(nodeMatrix(node), entry.parent)));\n\t\t\t\tconst list: VectorNode[] = [];\n\t\t\t\tconst r = plan.replace.get(i);\n\t\t\t\tif (r === undefined) list.push(node);\n\t\t\t\telse if (r?.kind === 'fill') list.push({ ...node, fillRule: 'nonzero', subpaths: bezierToSubpaths(toLocal(r.path)) });\n\t\t\t\telse if (r?.kind === 'outline') list.push({ ...node, subpaths: bezierToSubpaths(toLocal(r.path)) });\n\t\t\t\telse if (r?.kind === 'pieces') {\n\t\t\t\t\tr.paths.forEach((path, k) =>\n\t\t\t\t\t\tlist.push({ ...node, id: k === 0 ? node.id : this.newId(), subpaths: bezierToSubpaths(toLocal(path)).map((sp) => ({ ...sp, closed: false })) })\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (plan.merged && plan.merged.style === i) {\n\t\t\t\t\tmergedId = this.newId();\n\t\t\t\t\tconst merged: VectorPathNode = {\n\t\t\t\t\t\t...vectorResultStyle(node, 'fill'),\n\t\t\t\t\t\ttype: 'path',\n\t\t\t\t\t\tid: mergedId,\n\t\t\t\t\t\tname: 'Shape',\n\t\t\t\t\t\t...(node.transform ? { transform: node.transform } : {}),\n\t\t\t\t\t\tsubpaths: bezierToSubpaths(toLocal(plan.merged.path))\n\t\t\t\t\t};\n\t\t\t\t\tif (plan.merged.currentFill || !hasPaint(merged.fill)) merged.fill = hasPaint(this.defaults.fill) ? this.defaults.fill! : '#808080';\n\t\t\t\t\tlist.push(merged);\n\t\t\t\t}\n\t\t\t\tif (r === undefined && list.length === 1) return;\n\t\t\t\tcreated.set(node.id, list.map((n) => n.id));\n\t\t\t\tnodes = spliceTree(nodes, node.id, list);\n\t\t\t});\n\t\t\tthis.setDoc(nodes);\n\t\t\t// The shapes stay selected so the next gesture works on them too.\n\t\t\tconst selection = this.selection.flatMap((id) => created.get(id) ?? [id]);\n\t\t\tif (mergedId && !selection.includes(mergedId)) selection.push(mergedId);\n\t\t\tthis.selection = selection.filter((id, k) => !!this.getNode(id) && selection.indexOf(id) === k);\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\tthis.builderCache = null;\n\t\treturn { ok: true, merged: mergedId, faces: touched.faces.length, lines: touched.lines.length, edges: erase ? vectorBuilderErasedEdges(m, touched).length : 0 };\n\t}\n\n\t/** The paint bucket's map of the visible outlines, cached per document and gap. */\n\tprivate fillMap(gap: number): PlanarMap | null {\n\t\tif (this.fillCache?.doc === this.doc && this.fillCache.gap === gap) return this.fillCache.map;\n\t\tconst map = vectorFillMap(this.doc, gap);\n\t\tthis.fillCache = { doc: this.doc, gap, map };\n\t\treturn map;\n\t}\n\n\t/**\n\t * Paint bucket: the region the visible outlines enclose around `point` (document units),\n\t * crossings split and islands left as holes, becomes a new path filled with the current fill\n\t * default, placed just below the selection (or on top when nothing is selected). `gap`\n\t * (default `editing.fillGap`) closes gaps up to that size between loose ends. Returns the new\n\t * path's id, or null when nothing encloses the point.\n\t */\n\tfillRegion(point: Vec2, options: { gap?: number } = {}): string | null {\n\t\tif (!Number.isFinite(point.x) || !Number.isFinite(point.y)) return null;\n\t\tconst region = this.fillMap(options.gap ?? this.editing.fillGap)?.regionAt([point.x, point.y]);\n\t\tif (!region?.length) return null;\n\t\t// Below the lowest selected node, in its parent.\n\t\tlet below: string | null = null;\n\t\tconst roots = new Set(this.selectedRoots());\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (!below && roots.has(n.id)) below = n.id;\n\t\t});\n\t\tconst subpaths = bezierToSubpaths(below ? this.intoParentSpace(below, region) : region);\n\t\tif (!subpaths.length) return null;\n\t\tconst id = this.newId();\n\t\tconst node: VectorPathNode = { id, type: 'path', name: 'Fill', ...this.styleFor(false), stroke: null, fillRule: 'nonzero', subpaths };\n\t\tif (!hasPaint(node.fill)) node.fill = '#808080';\n\t\tconst target = below as string | null;\n\t\tthis.change('Fill Region', () => {\n\t\t\tif (target) {\n\t\t\t\tconst current = this.getNode(target)!;\n\t\t\t\tthis.setDoc(spliceTree(this.doc.nodes, target, [node, current]));\n\t\t\t} else this.setDoc([...this.doc.nodes, node]);\n\t\t\tif (!target) this.selection = [id];\n\t\t\tthis.anchors = [];\n\t\t\tthis.editingId = null;\n\t\t});\n\t\treturn id;\n\t}\n\n\t/** Updates the Shape Builder / paint bucket highlight for the pointer at `p`; true when it changed. */\n\tprivate hoverBuilder(p: Vec2, alt: boolean): boolean {\n\t\tif (this.tool === 'paintBucket') {\n\t\t\tconst region = this.fillMap(this.editing.fillGap)?.regionAt([p.x, p.y]) ?? null;\n\t\t\tconst key = region ? bezierPathToSvg(region, { precision: 2 }) : null;\n\t\t\tif (key === this.builderHoverKey) return false;\n\t\t\tthis.builderHoverKey = key;\n\t\t\tthis.builderPreview = region ? { mode: 'fill', faces: [region], lines: [], trail: null } : null;\n\t\t\treturn true;\n\t\t}\n\t\tconst m = this.selectedRoots().length ? this.shapeBuilderMap() : null;\n\t\tconst hit = m ? vectorShapeBuilderHit(m, p, alt ? this.builderLineTolerance() : null) : null;\n\t\tconst key = hit ? `${alt ? 'erase' : 'merge'}:${JSON.stringify(hit)}` : null;\n\t\tif (key === this.builderHoverKey) return false;\n\t\tthis.builderHoverKey = key;\n\t\tconst touched: VectorBuilderTouched = { faces: [], lines: [], edges: [] };\n\t\taddBuilderHit(touched, hit);\n\t\tthis.builderPreview = hit && m ? this.builderPreviewOf(m, touched, alt, null) : null;\n\t\treturn true;\n\t}\n\n\tprivate builderPreviewOf(m: VectorShapeBuilderMap, touched: VectorBuilderTouched, erase: boolean, trail: Vec2[] | null): VectorBuilderPreview {\n\t\tconst faces = m.map.faces;\n\t\treturn {\n\t\t\tmode: erase ? 'erase' : 'merge',\n\t\t\tfaces: touched.faces.map((f) => faces[f].path),\n\t\t\t// Edges bounding a face touched too go with the face, so they are not shown apart.\n\t\t\tlines: [...touched.lines.map((k) => m.pieces[k].path), ...(erase ? vectorBuilderErasedEdges(m, touched).map((k) => m.edges[k].path) : [])],\n\t\t\ttrail\n\t\t};\n\t}\n\n\tprivate downBuilder(p: Vec2, input: VectorPointerInput) {\n\t\tthis.builderHoverKey = null;\n\t\tif (this.tool === 'paintBucket') {\n\t\t\tthis.fillRegion(p);\n\t\t\tthis.builderPreview = null;\n\t\t\tthis.hoverBuilder(p, false);\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst m = this.selectedRoots().length ? this.shapeBuilderMap() : null;\n\t\tif (!m) return;\n\t\tconst erase = !!input.alt;\n\t\tconst touched: VectorBuilderTouched = { faces: [], lines: [], edges: [] };\n\t\taddBuilderHit(touched, vectorShapeBuilderHit(m, p, erase ? this.builderLineTolerance() : null));\n\t\tthis.drag = { kind: 'builder', erase, points: [p], touched, map: m };\n\t\tthis.interaction = { type: 'builder', mode: erase ? 'erase' : 'merge', points: [p] };\n\t\tthis.builderPreview = this.builderPreviewOf(m, touched, erase, [p]);\n\t\tthis.notify();\n\t}\n\n\tprivate moveBuilder(drag: Extract<Drag, { kind: 'builder' }>, p: Vec2) {\n\t\tconst last = drag.points[drag.points.length - 1];\n\t\tif (Math.hypot(p.x - last.x, p.y - last.y) * this.viewport.zoom < 1) return;\n\t\tconst tol = drag.erase ? this.builderLineTolerance() : null;\n\t\tfor (const q of samplePolyline([last, p], 2 / this.viewport.zoom)) addBuilderHit(drag.touched, vectorShapeBuilderHit(drag.map, q, tol));\n\t\tdrag.points.push(p);\n\t\tthis.interaction = { type: 'builder', mode: drag.erase ? 'erase' : 'merge', points: drag.points.slice() };\n\t\tthis.builderPreview = this.builderPreviewOf(drag.map, drag.touched, drag.erase, drag.points.slice());\n\t\tthis.notify();\n\t}\n\n\tprivate upBuilder(drag: Extract<Drag, { kind: 'builder' }>) {\n\t\tthis.builderPreview = null;\n\t\tthis.builderHoverKey = null;\n\t\tif (!drag.touched.faces.length && !drag.touched.lines.length && !drag.touched.edges.length) {\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tthis.applyShapeBuilder(drag.map, drag.touched, drag.erase);\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Anchor editing\n\t// -------------------------------------------------------------------------\n\n\tprivate updateAnchors(doc: VectorDocument, refs: readonly VectorAnchorRef[], fn: (a: VectorAnchor, ref: VectorAnchorRef) => VectorAnchor): VectorDocument {\n\t\tconst byNode = new Map<string, VectorAnchorRef[]>();\n\t\tfor (const r of refs) byNode.set(r.nodeId, [...(byNode.get(r.nodeId) ?? []), r]);\n\t\tconst nodes = mapTree(doc.nodes, (n) => {\n\t\t\tconst list = byNode.get(n.id);\n\t\t\tif (!list || n.type !== 'path' || n.locked) return n;\n\t\t\tconst subpaths = n.subpaths.map((sp, s) => {\n\t\t\t\tconst hits = list.filter((r) => r.subpath === s);\n\t\t\t\tif (!hits.length) return sp;\n\t\t\t\treturn { closed: sp.closed, anchors: sp.anchors.map((a, i) => (hits.some((r) => r.index === i) ? fn(a, { nodeId: n.id, subpath: s, index: i }) : a)) };\n\t\t\t});\n\t\t\treturn { ...n, subpaths };\n\t\t});\n\t\treturn nodes === doc.nodes ? doc : { ...doc, nodes };\n\t}\n\n\t/** Moves anchors by a document-space offset (converted into each node's own space). */\n\tprivate movedAnchors(doc: VectorDocument, refs: readonly VectorAnchorRef[], dx: number, dy: number): VectorDocument {\n\t\tconst local = new Map<string, Vec2>();\n\t\tfor (const r of refs) if (!local.has(r.nodeId)) local.set(r.nodeId, applyMatrixLinear(invertMatrix(this.worldOf(r.nodeId, doc)), { x: dx, y: dy }));\n\t\treturn this.updateAnchors(doc, refs, (a, ref) => {\n\t\t\tconst d = local.get(ref.nodeId)!;\n\t\t\treturn translateAnchor(a, d.x, d.y);\n\t\t});\n\t}\n\n\t/**\n\t * Moves one anchor to a document position. Its handles follow; with `curvature` (default:\n\t * the `curvatureMoves` setting) its two segments bend instead, as the Curvature tool does.\n\t */\n\tmoveAnchor(ref: VectorAnchorRef, to: Vec2, options: { curvature?: boolean } = {}): VectorActionResult {\n\t\tconst a = getAnchorWorld(this.doc, ref);\n\t\tif (!a) return { ok: false, message: 'There is no such anchor.' };\n\t\tconst curvature = options.curvature ?? this.editing.curvatureMoves;\n\t\tthis.change('Move Point', () => {\n\t\t\tthis.doc = curvature ? this.curvatureMoved(this.doc, ref, to) : this.movedAnchors(this.doc, [ref], to.x - a.x, to.y - a.y);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** `doc` with anchor `ref` moved to document point `to` by a Curvature-tool move. */\n\tprivate curvatureMoved(doc: VectorDocument, ref: VectorAnchorRef, to: Vec2): VectorDocument {\n\t\tconst node = findVectorNode(doc.nodes, ref.nodeId);\n\t\tif (node?.type !== 'path' || node.locked || !node.subpaths[ref.subpath]) return doc;\n\t\tconst q = this.toLocal(ref.nodeId, to, doc);\n\t\tconst subpaths = node.subpaths.map((sp, i) => (i === ref.subpath ? curvatureMoveAnchor(sp, ref.index, q) : sp));\n\t\tconst nodes = mapTree(doc.nodes, (n) => (n.id === ref.nodeId ? { ...node, subpaths } : n));\n\t\treturn { ...doc, nodes };\n\t}\n\n\t/** `doc` with segment `ref` bent through document point `p` at parameter `t`. */\n\tprivate bent(doc: VectorDocument, ref: VectorSegmentRef, t: number, p: Vec2): VectorDocument {\n\t\tconst node = findVectorNode(doc.nodes, ref.nodeId);\n\t\tif (node?.type !== 'path' || node.locked || !node.subpaths[ref.subpath]) return doc;\n\t\tconst q = this.toLocal(ref.nodeId, p, doc);\n\t\tconst subpaths = node.subpaths.map((sp, i) => (i === ref.subpath ? bendSubpathSegment(sp, ref.segment, t, q) : sp));\n\t\treturn { ...doc, nodes: mapTree(doc.nodes, (n) => (n.id === ref.nodeId ? { ...node, subpaths } : n)) };\n\t}\n\n\t/**\n\t * Bends a segment so the curve passes through document point `to` at parameter `t`\n\t * (default 0.5, clamped to 0.05–0.95); see `bendSegment` in `pathEdit`.\n\t */\n\tbendSegment(ref: VectorSegmentRef, to: Vec2, t = 0.5): VectorActionResult {\n\t\tconst node = this.getNode(ref.nodeId);\n\t\tconst sp = node?.type === 'path' ? node.subpaths[ref.subpath] : undefined;\n\t\tif (!sp || ref.segment < 0 || ref.segment >= (sp.closed ? sp.anchors.length : sp.anchors.length - 1) || sp.anchors.length < 2) return { ok: false, message: 'There is no such segment.' };\n\t\tif (node!.locked) return { ok: false, message: 'The path is locked.' };\n\t\tthis.change('Bend Segment', () => {\n\t\t\tthis.doc = this.bent(this.doc, ref, t, to);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Moves one handle to a document position (see `moveAnchorHandle` for how the opposite handle follows). */\n\tmoveHandle(ref: VectorHandleRef, to: Vec2, options: { breakHandles?: boolean } = {}): VectorActionResult {\n\t\tif (!getAnchor(this.doc, ref)) return { ok: false, message: 'There is no such anchor.' };\n\t\tconst local = this.toLocal(ref.nodeId, to);\n\t\tthis.change('Move Handle', () => {\n\t\t\tthis.doc = this.updateAnchors(this.doc, [ref], (a) => moveAnchorHandle(a, ref.handle, local, options.breakHandles));\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Converts the selected (or given) anchors between corner, smooth and symmetric. */\n\tconvertAnchors(type: VectorAnchorType, refs: readonly VectorAnchorRef[] = this.anchors): VectorActionResult {\n\t\tif (!refs.length) return { ok: false, message: 'Select points to convert.' };\n\t\tthis.change(type === 'corner' ? 'Make Corner' : 'Make Smooth', () => {\n\t\t\tconst nodes = mapTree(this.doc.nodes, (n) => {\n\t\t\t\tif (n.type !== 'path') return n;\n\t\t\t\tconst mine = refs.filter((r) => r.nodeId === n.id);\n\t\t\t\tif (!mine.length) return n;\n\t\t\t\tconst subpaths = n.subpaths.map((sp, s) => mine.filter((r) => r.subpath === s).reduce((acc, r) => convertAnchor(acc, r.index, type), sp));\n\t\t\t\treturn { ...n, subpaths };\n\t\t\t});\n\t\t\tthis.setDoc(nodes);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Adds an anchor on the nearest segment of `nodeId` to document point `point` (shape unchanged). */\n\tinsertAnchorAt(nodeId: string, point: Vec2): VectorAnchorRef | null {\n\t\tconst node = this.getNode(nodeId);\n\t\tif (node?.type !== 'path') return null;\n\t\tconst hit = nearestSegment(node, this.toLocal(nodeId, point));\n\t\tif (!hit) return null;\n\t\tconst { subpath, index } = insertAnchor(node.subpaths[hit.subpath], hit.segment, hit.t);\n\t\tconst ref = { nodeId, subpath: hit.subpath, index };\n\t\tthis.change('Add Point', () => {\n\t\t\tthis.replaceNode(nodeId, { ...node, subpaths: node.subpaths.map((sp, i) => (i === hit.subpath ? subpath : sp)) });\n\t\t\tthis.editingId = nodeId;\n\t\t\tthis.anchors = [ref];\n\t\t});\n\t\treturn ref;\n\t}\n\n\t/**\n\t * Deletes the selected (or given) anchors; subpaths left with one anchor and empty paths go\n\t * too. With `keepShape` (default: the `keepShapeOnDelete` setting, on) the neighbours'\n\t * handles are refitted so the path keeps its shape; off, the neighbours are joined as they are.\n\t */\n\tdeleteAnchors(refs: readonly VectorAnchorRef[] = this.anchors, options: { keepShape?: boolean } = {}): VectorActionResult {\n\t\tif (!refs.length) return { ok: false, message: 'Select points to delete.' };\n\t\tconst keepShape = options.keepShape ?? this.editing.keepShapeOnDelete;\n\t\tthis.change('Delete Points', () => {\n\t\t\tconst nodes = mapTree(this.doc.nodes, (n) => {\n\t\t\t\tif (n.type !== 'path' || n.locked) return n;\n\t\t\t\tconst mine = refs.filter((r) => r.nodeId === n.id);\n\t\t\t\tif (!mine.length) return n;\n\t\t\t\tconst subpaths = n.subpaths\n\t\t\t\t\t.map((sp, s) => {\n\t\t\t\t\t\tconst indices = mine.filter((r) => r.subpath === s).map((r) => r.index);\n\t\t\t\t\t\tif (!indices.length) return sp;\n\t\t\t\t\t\treturn keepShape ? removeAnchorsKeepingShape(sp, indices) : removeAnchors(sp, indices);\n\t\t\t\t\t})\n\t\t\t\t\t.filter((sp) => sp.anchors.length > 1);\n\t\t\t\treturn subpaths.length ? { ...n, subpaths } : null;\n\t\t\t});\n\t\t\tthis.setDoc(nodes);\n\t\t\tthis.anchors = [];\n\t\t\tthis.selection = this.selection.filter((id) => this.getNode(id));\n\t\t\tif (this.editingId && !this.getNode(this.editingId)) this.editingId = null;\n\t\t\tif (this.pen && !this.getNode(this.pen.nodeId)) this.pen = null;\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Opens or closes the subpaths that contain selected anchors (or all subpaths of `nodeId`). */\n\tsetClosed(closed: boolean, nodeId?: string): VectorActionResult {\n\t\tconst targets = nodeId\n\t\t\t? (() => {\n\t\t\t\t\tconst n = this.getNode(nodeId);\n\t\t\t\t\treturn n?.type === 'path' ? n.subpaths.map((_, s) => ({ nodeId, subpath: s })) : [];\n\t\t\t\t})()\n\t\t\t: this.anchors.map((r) => ({ nodeId: r.nodeId, subpath: r.subpath }));\n\t\tif (!targets.length) return { ok: false, message: 'Select a path or points.' };\n\t\tthis.change(closed ? 'Close Path' : 'Open Path', () => {\n\t\t\tthis.setDoc(\n\t\t\t\tmapTree(this.doc.nodes, (n) =>\n\t\t\t\t\tn.type === 'path' && targets.some((t) => t.nodeId === n.id)\n\t\t\t\t\t\t? { ...n, subpaths: n.subpaths.map((sp, s) => (targets.some((t) => t.nodeId === n.id && t.subpath === s) ? { ...sp, closed } : sp)) }\n\t\t\t\t\t\t: n\n\t\t\t\t)\n\t\t\t);\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Reverses the direction of every subpath of the selected paths. */\n\treversePaths(ids: readonly string[] = this.selection): VectorActionResult {\n\t\tconst set = new Set(ids.flatMap((id) => (this.getNode(id) ? collectPathNodes(this.getNode(id)!) : [])).map((p) => p.id));\n\t\tif (!set.size) return { ok: false, message: 'Select a path.' };\n\t\tthis.change('Reverse Path', () => {\n\t\t\tthis.setDoc(\n\t\t\t\tmapTree(this.doc.nodes, (n) =>\n\t\t\t\t\tn.type === 'path' && set.has(n.id)\n\t\t\t\t\t\t? { ...n, subpaths: n.subpaths.map(reverseSubpath), ...(n.strokeWidthProfile?.length ? { strokeWidthProfile: reverseWidthProfile(n.strokeWidthProfile) } : {}) }\n\t\t\t\t\t\t: n\n\t\t\t\t)\n\t\t\t);\n\t\t\tthis.anchors = [];\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Path clean-up, Scissors, Knife and Eraser\n\t// -------------------------------------------------------------------------\n\n\t/** Unlocked path nodes in the given roots (default: the paths being edited, else the selection). */\n\tprivate pathTargets(ids?: readonly string[]): VectorPathNode[] {\n\t\tconst roots = ids ?? (this.tool === 'direct' && this.anchors.length ? [...new Set(this.anchors.map((r) => r.nodeId))] : this.selection);\n\t\tconst out = new Map<string, VectorPathNode>();\n\t\tfor (const id of roots) {\n\t\t\tconst node = this.getNode(id);\n\t\t\tif (node && !node.locked) for (const p of collectPathNodes(node)) if (!p.locked) out.set(p.id, p);\n\t\t}\n\t\t// Document order, bottom to top.\n\t\tconst order: string[] = [];\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (out.has(n.id)) order.push(n.id);\n\t\t});\n\t\treturn order.map((id) => out.get(id)!);\n\t}\n\n\t/** Subpaths of node `from` mapped into node `to`'s own space. */\n\tprivate subpathsIn(from: VectorPathNode, to: string): VectorSubpath[] {\n\t\tconst m = multiplyMatrices(this.worldOf(from.id), invertMatrix(this.worldOf(to)));\n\t\tif (isRoot(m)) return from.subpaths;\n\t\tconst map = (p: Vec2) => applyMatrix(m, p);\n\t\treturn from.subpaths.map((sp) => ({\n\t\t\tclosed: sp.closed,\n\t\t\tanchors: sp.anchors.map((a) => ({ ...map(a), ...(a.in ? { in: map(a.in) } : {}), ...(a.out ? { out: map(a.out) } : {}), ...(a.type ? { type: a.type } : {}), ...(a.corner ? { corner: { ...a.corner } } : {}) }))\n\t\t}));\n\t}\n\n\t/**\n\t * Replaces a path with pieces: each entry becomes one path (the first keeps the node's id and\n\t * place, the others go just above it with the same style). No pieces removes the path.\n\t * Returns the ids of the paths now standing in for it.\n\t */\n\tprivate replaceWithPieces(node: VectorPathNode, pieces: readonly VectorSubpath[][]): string[] {\n\t\tconst nodes = pieces.filter((p) => p.length).map((subpaths, i) => ({ ...node, id: i === 0 ? node.id : this.newId(), subpaths }) as VectorPathNode);\n\t\tthis.setDoc(spliceTree(this.doc.nodes, node.id, nodes));\n\t\treturn nodes.map((n) => n.id);\n\t}\n\n\t/** Clears anchor selections, editing and pen state that no longer point at anything. */\n\tprivate dropStaleRefs() {\n\t\tthis.selection = this.selection.filter((id) => this.getNode(id));\n\t\tthis.anchors = this.anchors.filter((r) => getAnchor(this.doc, r));\n\t\tif (this.editingId && !this.getNode(this.editingId)) this.editingId = null;\n\t\tif (this.pen && !this.getNode(this.pen.nodeId)) this.pen = null;\n\t}\n\n\t/**\n\t * Join: the open subpaths of the selected (or given) paths become one open path, joined\n\t * nearest endpoints first (ends within `tolerance` document units merge into one anchor,\n\t * others get a straight segment); a single open subpath is closed. The result replaces the\n\t * lowest path, in its space and style. Default tolerance: the pick distance.\n\t */\n\tjoinPaths(options: { ids?: readonly string[]; tolerance?: number } = {}): VectorActionResult {\n\t\tconst paths = this.pathTargets(options.ids);\n\t\tif (!paths.length) return { ok: false, message: 'Select paths to join.' };\n\t\tconst base = paths[0];\n\t\tconst all = paths.flatMap((p) => this.subpathsIn(p, base.id));\n\t\tif (!all.some((sp) => !sp.closed && sp.anchors.length > 1)) return { ok: false, message: 'There are no open paths to join.' };\n\t\tconst subpaths = joinSubpaths(all, options.tolerance ?? this.tolerance());\n\t\tconst drop = new Set(paths.slice(1).map((p) => p.id));\n\t\tthis.change('Join', () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.id === base.id ? { ...base, subpaths } : drop.has(n.id) ? null : n)));\n\t\t\tthis.selection = [base.id];\n\t\t\tthis.anchors = [];\n\t\t\tif (this.editingId && drop.has(this.editingId)) this.editingId = base.id;\n\t\t\tthis.dropStaleRefs();\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Average: moves the selected (or given) anchors onto their average position along `axis`, in document space. */\n\taverageAnchors(axis: VectorAverageAxis = 'both', refs: readonly VectorAnchorRef[] = this.anchors): VectorActionResult {\n\t\tconst points = refs.map((r) => ({ ref: r, at: getAnchorWorld(this.doc, r) })).filter((p): p is { ref: VectorAnchorRef; at: NonNullable<ReturnType<typeof getAnchorWorld>> } => !!p.at);\n\t\tif (points.length < 2) return { ok: false, message: 'Select at least two points to average.' };\n\t\tconst cx = points.reduce((s, p) => s + p.at.x, 0) / points.length;\n\t\tconst cy = points.reduce((s, p) => s + p.at.y, 0) / points.length;\n\t\tthis.change('Average', () => {\n\t\t\tfor (const { ref, at } of points) {\n\t\t\t\tconst dx = axis === 'horizontal' ? 0 : cx - at.x;\n\t\t\t\tconst dy = axis === 'vertical' ? 0 : cy - at.y;\n\t\t\t\tif (dx || dy) this.doc = this.movedAnchors(this.doc, [ref], dx, dy);\n\t\t\t}\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/** Applies `fn` to every subpath of the target paths as one undo step. */\n\tprivate editSubpaths(label: string, ids: readonly string[] | undefined, fn: (sp: VectorSubpath, node: VectorPathNode, index: number) => VectorSubpath): VectorActionResult {\n\t\tconst paths = this.pathTargets(ids);\n\t\tif (!paths.length) return { ok: false, message: 'Select a path.' };\n\t\tconst set = new Set(paths.map((p) => p.id));\n\t\tthis.change(label, () => {\n\t\t\tthis.setDoc(mapTree(this.doc.nodes, (n) => (n.type === 'path' && set.has(n.id) ? { ...n, subpaths: n.subpaths.map((sp, i) => fn(sp, n, i)) } : n)));\n\t\t\tthis.dropStaleRefs();\n\t\t});\n\t\treturn { ok: true };\n\t}\n\n\t/**\n\t * Remove Redundant Points: drops anchors of the selected (or given) paths that can go\n\t * without moving the outline more than `tolerance` document units (default 0.5).\n\t */\n\tremoveRedundantPoints(options: { ids?: readonly string[]; tolerance?: number } = {}): VectorActionResult {\n\t\tconst tolerance = options.tolerance ?? 0.5;\n\t\treturn this.editSubpaths('Remove Redundant Points', options.ids, (sp) => removeRedundantSubpathPoints(sp, tolerance));\n\t}\n\n\t/**\n\t * Smooth: pulls handles towards smooth tangents by `amount` (0–1, default 1). With the direct\n\t * tool and points selected, only those points change.\n\t */\n\tsmoothPaths(options: { ids?: readonly string[]; amount?: number; refs?: readonly VectorAnchorRef[] } = {}): VectorActionResult {\n\t\tconst refs = options.refs ?? (!options.ids && this.tool === 'direct' && this.anchors.length ? this.anchors : null);\n\t\tconst ids = options.ids ?? (refs ? [...new Set(refs.map((r) => r.nodeId))] : undefined);\n\t\treturn this.editSubpaths('Smooth', ids, (sp, node, i) => {\n\t\t\tconst only = refs ? new Set(refs.filter((r) => r.nodeId === node.id && r.subpath === i).map((r) => r.index)) : undefined;\n\t\t\treturn only && !only.size ? sp : smoothSubpath(sp, options.amount ?? 1, only);\n\t\t});\n\t}\n\n\t/** Splits a cut subpath into pieces: separate paths for a one-subpath node, subpaths in place for a compound one. */\n\tprivate applyCuts(node: VectorPathNode, cut: (sp: VectorSubpath, index: number) => VectorSubpath[] | null): string[] | null {\n\t\tconst results = node.subpaths.map((sp, i) => cut(sp, i));\n\t\tif (results.every((r) => !r)) return null;\n\t\tconst subpaths = node.subpaths.flatMap((sp, i) => results[i] ?? [sp]);\n\t\tif (node.subpaths.length === 1) return this.replaceWithPieces(node, subpaths.map((sp) => [sp]));\n\t\tthis.replaceNode(node.id, { ...node, subpaths });\n\t\treturn [node.id];\n\t}\n\n\t/**\n\t * Scissors: cuts path `nodeId` at the outline point nearest document point `point` (at an\n\t * anchor when within the pick distance of one). A closed subpath opens there; an open one\n\t * splits in two (a one-subpath path becomes two paths). Returns the ids of the paths.\n\t */\n\tcutPathAt(nodeId: string, point: Vec2): string[] | null {\n\t\tconst node = this.getNode(nodeId);\n\t\tif (node?.type !== 'path' || node.locked) return null;\n\t\tconst local = this.toLocal(nodeId, point);\n\t\tconst hit = nearestSegment(node, local);\n\t\tif (!hit) return null;\n\t\tconst sp = node.subpaths[hit.subpath];\n\t\tconst n = sp.anchors.length;\n\t\tconst near = [hit.segment, (hit.segment + 1) % n].find((i) => Math.hypot(sp.anchors[i].x - hit.point.x, sp.anchors[i].y - hit.point.y) <= this.tolerance());\n\t\tif (!sp.closed && n > 1 && (near === 0 || near === n - 1) && !(hit.t > 1e-6 && hit.t < 1 - 1e-6)) return null;\n\t\tlet ids: string[] | null = null;\n\t\tthis.change('Cut Path', () => {\n\t\t\tids = this.applyCuts(node, (s, i) => (i !== hit.subpath ? null : near !== undefined ? cutSubpathAt(s, [near]) : splitSubpathAt(s, hit.segment, hit.t)));\n\t\t\tif (ids) {\n\t\t\t\tthis.selection = ids;\n\t\t\t\tthis.anchors = [];\n\t\t\t\tif (this.editingId === nodeId) this.editingId = null;\n\t\t\t}\n\t\t\tthis.dropStaleRefs();\n\t\t});\n\t\treturn ids;\n\t}\n\n\t/** Scissors on the selected (or given) anchors: each cuts its subpath there (see `cutPathAt`). */\n\tcutAtAnchors(refs: readonly VectorAnchorRef[] = this.anchors): VectorActionResult {\n\t\tconst byNode = new Map<string, VectorAnchorRef[]>();\n\t\tfor (const r of refs) if (getAnchor(this.doc, r)) byNode.set(r.nodeId, [...(byNode.get(r.nodeId) ?? []), r]);\n\t\tif (!byNode.size) return { ok: false, message: 'Select points to cut at.' };\n\t\tconst created: string[] = [];\n\t\tthis.change('Cut Path', () => {\n\t\t\tfor (const [id, list] of byNode) {\n\t\t\t\tconst node = this.getNode(id) as VectorPathNode;\n\t\t\t\tif (node.locked) continue;\n\t\t\t\tconst ids = this.applyCuts(node, (sp, i) => {\n\t\t\t\t\tconst at = list.filter((r) => r.subpath === i).map((r) => r.index);\n\t\t\t\t\tconst pieces = at.length ? cutSubpathAt(sp, at) : null;\n\t\t\t\t\treturn pieces && !(pieces.length === 1 && pieces[0].closed === sp.closed) ? pieces : null;\n\t\t\t\t});\n\t\t\t\tif (ids) created.push(...ids);\n\t\t\t}\n\t\t\tif (created.length) this.selection = created;\n\t\t\tthis.anchors = [];\n\t\t\tthis.dropStaleRefs();\n\t\t});\n\t\treturn created.length ? { ok: true } : { ok: false, message: 'Points at the ends of open paths do not cut.' };\n\t}\n\n\t/** Visible, unlocked paths a stroke over `points` can reach: in `ids`, the selection, or (with neither) any whose bounds it crosses. */\n\tprivate strokeTargets(points: readonly Vec2[], ids: readonly string[] | undefined, pad: number): VectorPathNode[] {\n\t\tconst blocked = new Set<string>();\n\t\twalkVectorNodes(this.doc.nodes, (n, parent) => {\n\t\t\tif (n.visible === false || n.locked || (parent && blocked.has(parent.id))) blocked.add(n.id);\n\t\t});\n\t\tconst visible = (p: VectorPathNode) => !blocked.has(p.id);\n\t\tif (ids?.length || this.selection.length) return this.pathTargets(ids ?? this.selection).filter(visible);\n\t\tconst box = polylineBounds(points.map(toPoint), pad);\n\t\tif (!box) return [];\n\t\tconst out: VectorPathNode[] = [];\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (n.type !== 'path' || !visible(n)) return;\n\t\t\tconst b = vectorNodeBounds(n, vectorParentMatrix(this.doc.nodes, n.id) ?? IDENTITY_MATRIX);\n\t\t\tif (b && boundsIntersect(b, box)) out.push(n);\n\t\t});\n\t\treturn out;\n\t}\n\n\t/** A stroke's points in node `id`'s own space. */\n\tprivate localPoints(id: string, points: readonly Vec2[]): Point[] {\n\t\tconst inv = invertMatrix(this.worldOf(id));\n\t\treturn points.map((p) => toPoint(applyMatrix(inv, p)));\n\t}\n\n\t/**\n\t * Knife: cuts closed paths along the polyline `points` (document space) wherever it crosses\n\t * them from edge to edge, with no gap between the pieces. It cuts the given paths, the\n\t * selection, or (with neither) every path it crosses. Returns the ids of the pieces (empty\n\t * when nothing was cut).\n\t */\n\tknife(points: readonly Vec2[], options: { ids?: readonly string[] } = {}): string[] {\n\t\tconst pts = simplifyPolyline(points.map(toPoint), 0.25 / this.viewport.zoom).map(([x, y]) => ({ x, y }));\n\t\tif (pts.length < 2) return [];\n\t\tconst plan: { node: VectorPathNode; pieces: VectorSubpath[][] }[] = [];\n\t\tfor (const node of this.strokeTargets(pts, options.ids, 0)) {\n\t\t\tconst closed = node.subpaths.filter((sp) => sp.anchors.length > 1);\n\t\t\tif (!closed.length || closed.some((sp) => !sp.closed)) continue;\n\t\t\tconst result = knifePath(subpathsToBezier(closed), node.fillRule ?? 'nonzero', this.localPoints(node.id, pts));\n\t\t\tif (result) plan.push({ node, pieces: result.map((path) => bezierToSubpaths(path)) });\n\t\t}\n\t\tif (!plan.length) return [];\n\t\tconst created: string[] = [];\n\t\tthis.change('Knife', () => {\n\t\t\tfor (const { node, pieces } of plan) created.push(...this.replaceWithPieces(node, pieces));\n\t\t\tthis.selection = created;\n\t\t\tthis.anchors = [];\n\t\t\tthis.dropStaleRefs();\n\t\t});\n\t\treturn created;\n\t}\n\n\t/**\n\t * Eraser: rubs out a round stroke of diameter `size` (default: the `eraserSize` setting)\n\t * along `points` (document space). Filled closed paths lose that area (pieces that come\n\t * apart become separate paths); outlines are cut where they pass under it. It erases from\n\t * the given paths, the selection, or (with neither) every path it reaches. Returns the ids\n\t * of the paths it changed or created.\n\t */\n\terase(points: readonly Vec2[], options: { ids?: readonly string[]; size?: number } = {}): string[] {\n\t\tconst width = options.size ?? this.editing.eraserSize;\n\t\tif (!(width > 0) || !points.length) return [];\n\t\tconst pts = simplifyPolyline(points.map(toPoint), Math.min(width * 0.05, 0.25 / this.viewport.zoom));\n\t\tconst region = eraserRegion(pts, width);\n\t\tif (!region.length) return [];\n\t\tconst plan: { node: VectorPathNode; pieces: VectorSubpath[][] }[] = [];\n\t\tconst rb = bezierPathBounds(region);\n\t\tconst reach = rb ? [{ x: rb.minX, y: rb.minY }, { x: rb.maxX, y: rb.maxY }] : points;\n\t\tfor (const node of this.strokeTargets(reach, options.ids, 0)) {\n\t\t\tconst local = transformBezierPath(region, invertMatrix(this.worldOf(node.id)));\n\t\t\tconst live = node.subpaths.filter((sp) => sp.anchors.length > 1);\n\t\t\tif (!live.length) continue;\n\t\t\tif (hasPaint(node.fill) && live.every((sp) => sp.closed)) {\n\t\t\t\tconst faces = eraseFromFill(subpathsToBezier(live), node.fillRule ?? 'nonzero', local);\n\t\t\t\tif (faces) plan.push({ node, pieces: faces.map((f) => bezierToSubpaths(f)) });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst results = live.map((sp) => eraseFromOutline(sp, local));\n\t\t\tif (results.every((r) => !r)) continue;\n\t\t\tconst subpaths = live.flatMap((sp, i) => results[i] ?? [sp]);\n\t\t\tplan.push({ node, pieces: live.length === 1 ? subpaths.map((sp) => [sp]) : [subpaths] });\n\t\t}\n\t\tif (!plan.length) return [];\n\t\tconst changed: string[] = [];\n\t\tthis.change('Erase', () => {\n\t\t\tfor (const { node, pieces } of plan) changed.push(...this.replaceWithPieces(node, pieces));\n\t\t\tthis.anchors = [];\n\t\t\tthis.dropStaleRefs();\n\t\t\tif (this.selection.length || options.ids) this.selection = [...new Set([...this.selection, ...changed.filter((id) => this.getNode(id))])];\n\t\t});\n\t\treturn changed;\n\t}\n\n\t/** Ends the pen path being drawn (a lone anchor is removed). */\n\tfinishPath(): void {\n\t\tif (!this.pen) return;\n\t\tconst node = this.getNode(this.pen.nodeId) as VectorPathNode | undefined;\n\t\tconst sp = node?.subpaths[this.pen.subpath];\n\t\tconst pen = this.pen;\n\t\tthis.pen = null;\n\t\tthis.pointer = null;\n\t\tif (node && sp && sp.anchors.length < 2) {\n\t\t\tconst subpaths = node.subpaths.filter((_, i) => i !== pen.subpath);\n\t\t\tthis.change('Delete Path', () => {\n\t\t\t\tthis.replaceNode(node.id, subpaths.length ? { ...node, subpaths } : null);\n\t\t\t\tif (!subpaths.length) {\n\t\t\t\t\tthis.selection = this.selection.filter((id) => id !== node.id);\n\t\t\t\t\tif (this.editingId === node.id) this.editingId = null;\n\t\t\t\t}\n\t\t\t\tthis.anchors = [];\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tthis.notify();\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Clipboard\n\t// -------------------------------------------------------------------------\n\n\t/** Copies the selection. Returns JSON text for the system clipboard (or null). */\n\tcopy(): string | null {\n\t\tconst nodes = this.selectedRoots()\n\t\t\t.map((id) => this.getNode(id))\n\t\t\t.filter((n): n is VectorNode => !!n)\n\t\t\t.map((n) => cloneVectorNode(n));\n\t\tif (!nodes.length) return null;\n\t\tthis.clipboard = nodes;\n\t\treturn JSON.stringify({ type: VECTOR_CLIPBOARD_TYPE, nodes });\n\t}\n\n\tcut(): string | null {\n\t\tconst text = this.copy();\n\t\tif (text) this.removeNodes(this.selectedRoots(), { label: 'Cut' });\n\t\treturn text;\n\t}\n\n\t/**\n\t * Pastes `text` (from `copy()`, or SVG markup) or the internal clipboard, offset by 10, 10.\n\t * Returns the new ids.\n\t */\n\tpaste(text?: string, options: { offset?: Vec2 } = {}): string[] {\n\t\tlet nodes: VectorNode[] | null = null;\n\t\tif (text) {\n\t\t\tconst trimmed = text.trim();\n\t\t\tif (trimmed.startsWith('{')) {\n\t\t\t\ttry {\n\t\t\t\t\tconst data = JSON.parse(trimmed);\n\t\t\t\t\tif (data?.type === VECTOR_CLIPBOARD_TYPE && Array.isArray(data.nodes)) nodes = data.nodes;\n\t\t\t\t} catch {\n\t\t\t\t\tnodes = null;\n\t\t\t\t}\n\t\t\t} else if (/<svg[\\s>]/i.test(trimmed)) {\n\t\t\t\ttry {\n\t\t\t\t\tnodes = parseVectorSvg(trimmed).nodes;\n\t\t\t\t} catch {\n\t\t\t\t\tnodes = null;\n\t\t\t\t}\n\t\t\t}\n\t\t} else nodes = this.clipboard;\n\t\tif (!nodes?.length) return [];\n\t\tconst offset = options.offset ?? (text && !text.trim().startsWith('{') ? { x: 0, y: 0 } : { x: 10, y: 10 });\n\t\tconst copies = nodes.map((n) => transformVectorNode(this.freshIds(n), translateMatrix(offset.x, offset.y)));\n\t\tthis.change('Paste', () => {\n\t\t\tthis.setDoc([...this.doc.nodes, ...copies]);\n\t\t\tthis.selection = copies.map((n) => n.id);\n\t\t\tthis.anchors = [];\n\t\t});\n\t\tif (!text) this.clipboard = copies.map((n) => cloneVectorNode(n));\n\t\treturn copies.map((n) => n.id);\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Undo\n\t// -------------------------------------------------------------------------\n\n\tundo(): boolean {\n\t\tthis.cancelDrag();\n\t\tthis.pen = null;\n\t\treturn this.history.undo();\n\t}\n\n\tredo(): boolean {\n\t\tthis.cancelDrag();\n\t\treturn this.history.redo();\n\t}\n\n\t/** Deletes selected anchors (direct tool) or nodes. */\n\tdeleteSelection(): VectorActionResult {\n\t\tif (this.tool === 'direct' && this.anchors.length) return this.deleteAnchors();\n\t\treturn this.removeNodes(this.selectedRoots());\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Pointer input\n\t// -------------------------------------------------------------------------\n\n\t/** The fields the anchor / handle helpers read, without building a full state. */\n\tprivate view() {\n\t\treturn { document: this.doc, selection: this.selection, editingId: this.editingId, tool: this.tool, pen: this.pen, selectedAnchors: this.anchors };\n\t}\n\n\tprivate tolerance() {\n\t\treturn this.hitRadius / this.viewport.zoom;\n\t}\n\n\tprivate hitTransformHandle(screen: Vec2): VectorTransformHandle | null {\n\t\tif (this.tool !== 'select' || !this.selection.length) return null;\n\t\tconst frame = this.frameOf(this.selectedRoots());\n\t\tif (!frame) return null;\n\t\tconst { box, handles } = getVectorSelectionBoxGeometry(frame, this.viewport);\n\t\tconst r = this.hitRadius + 2;\n\t\t// Tiny boxes: only corners and rotation, so the box can still be grabbed.\n\t\tconst usable = box.width < 2 * r || box.height < 2 * r ? handles.filter((h) => h.handle.length === 2 || h.handle === 'rotate') : handles;\n\t\tfor (const h of usable) if (Math.hypot(h.screen.x - screen.x, h.screen.y - screen.y) <= r * Math.SQRT2) return h.handle;\n\t\treturn null;\n\t}\n\n\tprivate hitHandle(screen: Vec2): VectorHandleRef | null {\n\t\tfor (const ref of getVisibleHandles(this.view()).reverse()) {\n\t\t\tconst a = getAnchorWorld(this.doc, ref);\n\t\t\tconst h = a?.[ref.handle];\n\t\t\tif (!h) continue;\n\t\t\tconst s = this.documentToScreen(h);\n\t\t\tif (Math.hypot(s.x - screen.x, s.y - screen.y) <= this.hitRadius) return ref;\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate cornerView() {\n\t\treturn { ...this.view(), viewport: this.viewport };\n\t}\n\n\tprivate hitCornerWidget(screen: Vec2): VectorCornerWidget | null {\n\t\tlet best: VectorCornerWidget | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (const w of getVectorCornerWidgets(this.cornerView())) {\n\t\t\tconst s = this.documentToScreen(w);\n\t\t\tconst d = Math.hypot(s.x - screen.x, s.y - screen.y);\n\t\t\tif (d <= this.hitRadius && d < bestD) {\n\t\t\t\tbest = w;\n\t\t\t\tbestD = d;\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t}\n\n\tprivate hitAnchor(screen: Vec2, refs: readonly VectorAnchorRef[]): VectorAnchorRef | null {\n\t\tlet best: VectorAnchorRef | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (const ref of refs) {\n\t\t\tconst a = getAnchorWorld(this.doc, ref);\n\t\t\tif (!a) continue;\n\t\t\tconst s = this.documentToScreen(a);\n\t\t\tconst d = Math.hypot(s.x - screen.x, s.y - screen.y);\n\t\t\tif (d <= this.hitRadius && d < bestD) {\n\t\t\t\tbest = ref;\n\t\t\t\tbestD = d;\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t}\n\n\t/** Deepest unlocked visible path under `p`. */\n\tprivate hitPath(p: Vec2): VectorPathNode | null {\n\t\tconst tol = this.tolerance();\n\t\tconst search = (list: readonly VectorNode[], parent: AffineMatrix): VectorPathNode | null => {\n\t\t\tfor (let i = list.length - 1; i >= 0; i--) {\n\t\t\t\tconst n = list[i];\n\t\t\t\tif (n.visible === false || n.locked) continue;\n\t\t\t\tif (n.type === 'group') {\n\t\t\t\t\tconst found = search(n.children, multiplyMatrices(nodeMatrix(n), parent));\n\t\t\t\t\tif (found) return found;\n\t\t\t\t} else if (hitTestVectorNode(n, p, tol, parent)) return n;\n\t\t\t}\n\t\t\treturn null;\n\t\t};\n\t\treturn search(this.doc.nodes, IDENTITY_MATRIX);\n\t}\n\n\t/** Endpoints of open subpaths of unlocked visible paths (pen tool resumes from them). */\n\tprivate openEndpoints(): VectorAnchorRef[] {\n\t\tconst out: VectorAnchorRef[] = [];\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (n.type !== 'path' || n.locked || n.visible === false) return;\n\t\t\tn.subpaths.forEach((sp, s) => {\n\t\t\t\tif (sp.closed || sp.anchors.length < 1) return;\n\t\t\t\tout.push({ nodeId: n.id, subpath: s, index: 0 });\n\t\t\t\tif (sp.anchors.length > 1) out.push({ nodeId: n.id, subpath: s, index: sp.anchors.length - 1 });\n\t\t\t});\n\t\t});\n\t\treturn out;\n\t}\n\n\tprivate computeHover(screen: Vec2): VectorHover | null {\n\t\tconst p = this.screenToDocument(screen);\n\t\tswitch (this.tool) {\n\t\t\tcase 'select': {\n\t\t\t\tconst handle = this.hitTransformHandle(screen);\n\t\t\t\tif (handle) return { nodeId: null, transformHandle: handle };\n\t\t\t\tconst node = hitTestVectorNodes(this.doc.nodes, p, this.tolerance());\n\t\t\t\treturn node ? { nodeId: node.id } : null;\n\t\t\t}\n\t\t\tcase 'direct': {\n\t\t\t\tconst handle = this.hitHandle(screen);\n\t\t\t\tif (handle) return { nodeId: handle.nodeId, handle };\n\t\t\t\tconst anchor = this.hitAnchor(screen, getVisibleAnchors(this.view()));\n\t\t\t\tif (anchor) return { nodeId: anchor.nodeId, anchor };\n\t\t\t\tconst widget = this.hitCornerWidget(screen);\n\t\t\t\tif (widget) return { nodeId: widget.ref.nodeId, corner: widget.ref };\n\t\t\t\tfor (const id of getEditablePathIds(this.view())) {\n\t\t\t\t\tconst node = this.getNode(id) as VectorPathNode;\n\t\t\t\t\tconst seg = nearestSegment(node, this.toLocal(id, p));\n\t\t\t\t\tif (seg && seg.distance <= this.tolerance()) {\n\t\t\t\t\t\tconst point = applyMatrix(this.worldOf(id), seg.point);\n\t\t\t\t\t\treturn { nodeId: id, segment: { nodeId: id, subpath: seg.subpath, segment: seg.segment, t: seg.t, point } };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst path = this.hitPath(p);\n\t\t\t\treturn path ? { nodeId: path.id } : null;\n\t\t\t}\n\t\t\tcase 'pen': {\n\t\t\t\tconst refs = this.pen ? [{ nodeId: this.pen.nodeId, subpath: this.pen.subpath, index: 0 }] : this.openEndpoints();\n\t\t\t\tconst anchor = this.hitAnchor(screen, refs);\n\t\t\t\treturn anchor ? { nodeId: anchor.nodeId, anchor } : null;\n\t\t\t}\n\t\t\tcase 'scissors': {\n\t\t\t\tconst seg = this.nearestOutline(p);\n\t\t\t\treturn seg ? { nodeId: seg.nodeId, segment: seg } : null;\n\t\t\t}\n\t\t\tcase 'width': {\n\t\t\t\tconst hit = this.hitWidthHandle(screen);\n\t\t\t\tif (hit) return { nodeId: hit.ref.nodeId, widthPoint: hit.ref };\n\t\t\t\tconst spot = this.strokeSpotAt(p);\n\t\t\t\treturn spot ? { nodeId: spot.nodeId, strokeSpot: spot } : null;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate widthView() {\n\t\treturn { document: this.doc, selection: this.selection, tool: this.tool, hover: this.hover, interaction: this.interaction, selectedWidthPoint: this.widthPoint };\n\t}\n\n\t/** The width point centre or side end under `screen` (width tool). */\n\tprivate hitWidthHandle(screen: Vec2): { ref: VectorWidthPointRef & { part: 'center' | 'left' | 'right' } } | null {\n\t\tlet best: { ref: VectorWidthPointRef & { part: 'center' | 'left' | 'right' } } | null = null;\n\t\tlet bestD = Infinity;\n\t\tfor (const h of getVectorWidthHandles(this.widthView())) {\n\t\t\tfor (const [part, q] of [['center', h], ['left', h.left], ['right', h.right]] as const) {\n\t\t\t\tconst s = this.documentToScreen(q);\n\t\t\t\tconst d = Math.hypot(s.x - screen.x, s.y - screen.y);\n\t\t\t\t// Ties go to the centre (listed first), so a zero-width point can still be moved.\n\t\t\t\tif (d <= this.hitRadius && d < bestD - 1e-9) {\n\t\t\t\t\tbest = { ref: { ...h.ref, part } };\n\t\t\t\t\tbestD = d;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t}\n\n\t/** The nearest stroked, unlocked visible path whose stroke is under document point `p` (width tool). */\n\tprivate strokeSpotAt(p: Vec2): VectorStrokeSpot | null {\n\t\tlet best: (VectorStrokeSpot & { distance: number }) | null = null;\n\t\tconst tol = this.tolerance();\n\t\twalkVectorNodes(this.doc.nodes, (n) => {\n\t\t\tif (n.type !== 'path' || n.visible === false || n.locked) return;\n\t\t\tif (hiddenOrLocked(this.doc.nodes, n.id)) return;\n\t\t\tconst g = vectorStrokeWidthGeometry(n);\n\t\t\tif (!g) return;\n\t\t\tconst m = this.worldOf(n.id);\n\t\t\tconst local = applyMatrix(invertMatrix(m), p);\n\t\t\tconst near = nearestStrokePosition(g.line, [local.x, local.y]);\n\t\t\tif (!near) return;\n\t\t\tconst profile = strokeWidthProfileOf(n);\n\t\t\tconst w = widthProfileAt(profile, near.t);\n\t\t\tconst reach = Math.max(near.side === 'left' ? w.left : w.right, 0) * g.unit + tol;\n\t\t\tif (near.distance > reach || near.distance > widthProfileMaxScale(profile) * g.unit + tol) return;\n\t\t\tif (best && near.distance >= best.distance) return;\n\t\t\tconst nx = near.tangent[1];\n\t\t\tconst ny = -near.tangent[0];\n\t\t\tconst [cx, cy] = near.point;\n\t\t\tbest = {\n\t\t\t\tnodeId: n.id,\n\t\t\t\tsubpath: near.contour,\n\t\t\t\tt: near.t,\n\t\t\t\tpoint: applyMatrix(m, { x: cx, y: cy }),\n\t\t\t\tleft: applyMatrix(m, { x: cx + nx * w.left * g.unit, y: cy + ny * w.left * g.unit }),\n\t\t\t\tright: applyMatrix(m, { x: cx - nx * w.right * g.unit, y: cy - ny * w.right * g.unit }),\n\t\t\t\tdistance: near.distance\n\t\t\t};\n\t\t});\n\t\tif (!best) return null;\n\t\tconst { distance: _d, ...spot } = best as VectorStrokeSpot & { distance: number };\n\t\treturn spot;\n\t}\n\n\tprivate downWidth(screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tconst hit = this.hitWidthHandle(screen);\n\t\tconst spot = hit ? null : this.strokeSpotAt(p);\n\t\tconst nodeId = hit?.ref.nodeId ?? spot?.nodeId;\n\t\tconst node = nodeId ? this.getNode(nodeId) : undefined;\n\t\tconst g = node?.type === 'path' ? vectorStrokeWidthGeometry(node) : null;\n\t\tif (!node || node.type !== 'path' || !g) {\n\t\t\tif (this.widthPoint) {\n\t\t\t\tthis.widthPoint = null;\n\t\t\t\tthis.notify();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tconst before = this.snapshot();\n\t\tconst local = this.toLocal(node.id, p);\n\t\tlet profile: VectorWidthPoint[];\n\t\tlet ref: VectorWidthPointRef;\n\t\tlet mode: 'width' | 'move' = 'width';\n\t\tlet side: 'both' | 'left' | 'right' = 'both';\n\t\tlet t: number;\n\t\tlet subpath: number;\n\t\tif (hit) {\n\t\t\tprofile = sanitizeWidthProfile(node.strokeWidthProfile);\n\t\t\tref = { nodeId: node.id, index: hit.ref.index, subpath: hit.ref.subpath };\n\t\t\tt = profile[ref.index]?.t ?? 0;\n\t\t\tsubpath = hit.ref.subpath;\n\t\t\tif (hit.ref.part === 'center') mode = 'move';\n\t\t\telse if (input.alt) side = hit.ref.part;\n\t\t} else {\n\t\t\tconst near = nearestStrokePosition(g.line, [local.x, local.y])!;\n\t\t\tconst inserted = insertWidthPoint(strokeWidthProfileOf(node), near.t);\n\t\t\tprofile = inserted.points;\n\t\t\tsubpath = near.contour;\n\t\t\tt = near.t;\n\t\t\tref = { nodeId: node.id, index: inserted.index, subpath };\n\t\t\tif (input.alt) side = near.side;\n\t\t}\n\t\tconst at = strokePositionPoint(g.line, subpath, t);\n\t\tif (!at) return;\n\t\tconst base = { ...this.doc, nodes: mapTree(this.doc.nodes, (n) => (n.id === node.id ? { ...(n as VectorPathNode), strokeWidthProfile: profile } : n)) };\n\t\tthis.doc = base;\n\t\tthis.widthPoint = { nodeId: node.id, index: ref.index, subpath };\n\t\tthis.drag = {\n\t\t\tkind: 'width',\n\t\t\tref,\n\t\t\tmode,\n\t\t\tside,\n\t\t\torigin: { x: at.point[0], y: at.point[1] },\n\t\t\tnormal: { x: at.tangent[1], y: -at.tangent[0] },\n\t\t\tunit: g.unit,\n\t\t\tprofile,\n\t\t\tbefore,\n\t\t\tbase,\n\t\t\tstart: p,\n\t\t\tmoved: false,\n\t\t\tcreated: !hit\n\t\t};\n\t\tconst w = profile[ref.index];\n\t\tthis.interaction = { type: 'width', ref, mode, width: (w.left + w.right) * g.unit };\n\t\tthis.notify(!hit);\n\t}\n\n\t/** The nearest outline point of any visible, unlocked path within the pick distance of document point `p`. */\n\tprivate nearestOutline(p: Vec2): NonNullable<VectorHover['segment']> | null {\n\t\tlet best: (NonNullable<VectorHover['segment']> & { distance: number }) | null = null;\n\t\tconst tol = this.tolerance();\n\t\tconst visit = (list: readonly VectorNode[], parent: AffineMatrix) => {\n\t\t\tfor (let i = list.length - 1; i >= 0; i--) {\n\t\t\t\tconst n = list[i];\n\t\t\t\tif (n.visible === false || n.locked) continue;\n\t\t\t\tconst m = multiplyMatrices(nodeMatrix(n), parent);\n\t\t\t\tif (n.type === 'group') {\n\t\t\t\t\tvisit(n.children, m);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst hit = nearestSegment(n, applyMatrix(invertMatrix(m), p));\n\t\t\t\t// Node matrices are rigid, so local distances are document distances.\n\t\t\t\tif (hit && hit.distance <= tol && (!best || hit.distance < best.distance - 1e-9)) {\n\t\t\t\t\tbest = { nodeId: n.id, subpath: hit.subpath, segment: hit.segment, t: hit.t, point: applyMatrix(m, hit.point), distance: hit.distance };\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tvisit(this.doc.nodes, IDENTITY_MATRIX);\n\t\tif (!best) return null;\n\t\tconst { distance: _d, ...seg } = best as NonNullable<VectorHover['segment']> & { distance: number };\n\t\treturn seg;\n\t}\n\n\tprivate sameHover(a: VectorHover | null, b: VectorHover | null): boolean {\n\t\treturn JSON.stringify(a) === JSON.stringify(b);\n\t}\n\n\t/** Primary button down on the canvas at `screen` (pixels relative to the canvas). */\n\tpointerDown(screen: Vec2, input: VectorPointerInput = {}): void {\n\t\tthis.cancelDrag();\n\t\tif (input.button === 1 || this.spaceHeld) {\n\t\t\tthis.drag = { kind: 'pan', start: screen, viewport: this.viewport };\n\t\t\tthis.interaction = { type: 'pan' };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (input.button !== undefined && input.button !== 0) return;\n\t\tconst p = this.screenToDocument(screen);\n\t\tthis.pointer = p;\n\t\tswitch (this.tool) {\n\t\t\tcase 'select':\n\t\t\t\treturn this.downSelect(screen, p, input);\n\t\t\tcase 'direct':\n\t\t\t\treturn this.downDirect(screen, p, input);\n\t\t\tcase 'pen':\n\t\t\t\treturn this.downPen(screen, p, input);\n\t\t\tcase 'pencil':\n\t\t\t\treturn this.downPencil(p, input);\n\t\t\tcase 'width':\n\t\t\t\treturn this.downWidth(screen, p, input);\n\t\t\tcase 'shapeBuilder':\n\t\t\tcase 'paintBucket':\n\t\t\t\treturn this.downBuilder(p, input);\n\t\t\tcase 'scissors': {\n\t\t\t\tconst seg = this.nearestOutline(p);\n\t\t\t\tif (seg) this.cutPathAt(seg.nodeId, seg.point);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'knife':\n\t\t\tcase 'eraser':\n\t\t\t\tthis.drag = { kind: 'stroke', tool: this.tool, points: [p], before: this.snapshot() };\n\t\t\t\tthis.interaction = { type: 'stroke', tool: this.tool, points: [p], width: this.tool === 'eraser' ? this.editing.eraserSize : 0 };\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\tdefault:\n\t\t\t\treturn this.downShape(p, input);\n\t\t}\n\t}\n\n\tprivate downSelect(screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tconst handle = this.hitTransformHandle(screen);\n\t\tif (handle) {\n\t\t\tconst frame = this.frameOf(this.selectedRoots())!;\n\t\t\tconst before = this.snapshot();\n\t\t\tconst center = applyMatrix(rotateMatrix(frame.angle), { x: frame.x + frame.width / 2, y: frame.y + frame.height / 2 });\n\t\t\tthis.drag =\n\t\t\t\thandle === 'rotate'\n\t\t\t\t\t? { kind: 'rotate', start: p, center, before, base: this.doc }\n\t\t\t\t\t: { kind: 'scale', handle, start: p, frame, before, base: this.doc };\n\t\t\tthis.interaction = handle === 'rotate' ? { type: 'rotate', angle: 0 } : { type: 'scale', handle, sx: 1, sy: 1 };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst node = hitTestVectorNodes(this.doc.nodes, p, this.tolerance());\n\t\tif (node) {\n\t\t\tconst selected = this.selection.includes(node.id);\n\t\t\tif (input.shift) {\n\t\t\t\tthis.selection = selected ? this.selection.filter((id) => id !== node.id) : [...this.selection, node.id];\n\t\t\t\tif (selected) {\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else if (!selected) this.selection = [node.id];\n\t\t\tthis.anchors = [];\n\t\t\tconst before = this.snapshot();\n\t\t\tthis.drag = {\n\t\t\t\tkind: 'move',\n\t\t\t\tstart: p,\n\t\t\t\torigin: this.boundsOf(this.selectedRoots()),\n\t\t\t\tbefore,\n\t\t\t\tbase: this.doc,\n\t\t\t\tmoved: false,\n\t\t\t\tduplicated: false,\n\t\t\t\tclickId: selected && !input.shift ? node.id : null\n\t\t\t};\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (!input.shift) this.selection = [];\n\t\tthis.drag = { kind: 'marquee', start: p, base: this.selection, baseAnchors: [], anchorsMode: false };\n\t\tthis.interaction = { type: 'marquee', bounds: { x: p.x, y: p.y, width: 0, height: 0 } };\n\t\tthis.notify();\n\t}\n\n\tprivate downDirect(screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tconst handle = this.hitHandle(screen);\n\t\tif (handle) {\n\t\t\tthis.drag = { kind: 'handle', ref: handle, before: this.snapshot(), base: this.doc };\n\t\t\tthis.interaction = { type: 'handle', ref: handle };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst anchor = this.hitAnchor(screen, getVisibleAnchors(this.view()));\n\t\tif (anchor) {\n\t\t\tconst selected = this.anchors.some((a) => sameRef(a, anchor));\n\t\t\tthis.editingId = anchor.nodeId;\n\t\t\tif (input.alt) {\n\t\t\t\t// Alt-drag an anchor pulls out fresh symmetric handles.\n\t\t\t\tthis.anchors = [anchor];\n\t\t\t\tthis.drag = { kind: 'pull', ref: anchor, before: this.snapshot(), base: this.doc, label: 'Make Smooth', outOnly: false, closing: false, altBreaks: false };\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (input.shift) {\n\t\t\t\tthis.anchors = selected ? this.anchors.filter((a) => !sameRef(a, anchor)) : [...this.anchors, anchor];\n\t\t\t\tif (selected) {\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else if (!selected) this.anchors = [anchor];\n\t\t\tthis.drag = { kind: 'anchors', start: p, before: this.snapshot(), base: this.doc, moved: false, clickRef: selected && !input.shift ? anchor : null, lead: anchor };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst widget = this.hitCornerWidget(screen);\n\t\tif (widget) {\n\t\t\tconst refs = getVectorCornerWidgets(this.cornerView()).map((w) => w.ref);\n\t\t\tthis.drag = { kind: 'corner', widget, refs, start: p, before: this.snapshot(), base: this.doc, moved: false, alt: !!input.alt, shift: !!input.shift };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tfor (const id of getEditablePathIds(this.view())) {\n\t\t\tconst node = this.getNode(id) as VectorPathNode;\n\t\t\tconst seg = nearestSegment(node, this.toLocal(id, p));\n\t\t\tif (!seg || seg.distance > this.tolerance()) continue;\n\t\t\tconst sp = node.subpaths[seg.subpath];\n\t\t\tif (input.alt) {\n\t\t\t\tconst before = this.snapshot();\n\t\t\t\tconst { subpath, index } = insertAnchor(sp, seg.segment, seg.t);\n\t\t\t\tthis.replaceNode(id, { ...node, subpaths: node.subpaths.map((s, i) => (i === seg.subpath ? subpath : s)) });\n\t\t\t\tconst ref = { nodeId: id, subpath: seg.subpath, index };\n\t\t\t\tthis.anchors = [ref];\n\t\t\t\tthis.editingId = id;\n\t\t\t\tthis.drag = { kind: 'anchors', start: p, before, base: this.doc, moved: true, clickRef: null, lead: ref };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// A click selects the segment's anchors; a drag bends it through the pointer.\n\t\t\tconst a = { nodeId: id, subpath: seg.subpath, index: seg.segment };\n\t\t\tconst b = { nodeId: id, subpath: seg.subpath, index: (seg.segment + 1) % sp.anchors.length };\n\t\t\tthis.anchors = input.shift ? [...this.anchors.filter((r) => !sameRef(r, a) && !sameRef(r, b)), a, b] : [a, b];\n\t\t\tthis.editingId = id;\n\t\t\tthis.drag = { kind: 'bend', ref: { nodeId: id, subpath: seg.subpath, segment: seg.segment }, t: seg.t, start: p, before: this.snapshot(), base: this.doc, moved: false };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tconst path = this.hitPath(p);\n\t\tif (path) {\n\t\t\tthis.editingId = path.id;\n\t\t\tif (!input.shift) this.selection = [path.id];\n\t\t\telse if (!this.selection.includes(path.id)) this.selection = [...this.selection, path.id];\n\t\t\tthis.anchors = path.subpaths.flatMap((sp, s) => sp.anchors.map((_, i) => ({ nodeId: path.id, subpath: s, index: i })));\n\t\t\tthis.drag = { kind: 'anchors', start: p, before: this.snapshot(), base: this.doc, moved: false, clickRef: null, lead: null };\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (!input.shift) {\n\t\t\tthis.anchors = [];\n\t\t}\n\t\tthis.drag = { kind: 'marquee', start: p, base: this.selection, baseAnchors: this.anchors, anchorsMode: getEditablePathIds(this.view()).length > 0 };\n\t\tthis.interaction = { type: 'marquee', bounds: { x: p.x, y: p.y, width: 0, height: 0 } };\n\t\tthis.notify();\n\t}\n\n\tprivate downPen(screen: Vec2, p: Vec2, input: VectorPointerInput) {\n\t\tconst before = this.snapshot();\n\t\tconst sp = this.pen ? (this.getNode(this.pen.nodeId) as VectorPathNode | undefined)?.subpaths[this.pen.subpath] : undefined;\n\t\tif (this.pen && sp) {\n\t\t\tconst pen = this.pen;\n\t\t\tconst first = { nodeId: pen.nodeId, subpath: pen.subpath, index: 0 };\n\t\t\tif (sp.anchors.length >= 2 && this.hitAnchor(screen, [first])) {\n\t\t\t\tconst node = this.getNode(pen.nodeId) as VectorPathNode;\n\t\t\t\tthis.replaceNode(pen.nodeId, { ...node, subpaths: node.subpaths.map((s, i) => (i === pen.subpath ? { ...s, closed: true } : s)) });\n\t\t\t\tthis.drag = { kind: 'pull', ref: first, before, base: this.doc, label: 'Close Path', outOnly: false, closing: true, altBreaks: true };\n\t\t\t\tthis.interaction = { type: 'pen', nodeId: pen.nodeId };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst last = getAnchorWorld(this.doc, { nodeId: pen.nodeId, subpath: pen.subpath, index: sp.anchors.length - 1 })!;\n\t\t\tconst leave = { at: { x: last.x, y: last.y }, constrain: input.shift ? ('angle' as const) : null };\n\t\t\tlet pt = this.snapDrawn(p, leave, input, () => this.drawingTargets(pen.nodeId));\n\t\t\tpt = this.toLocal(pen.nodeId, pt);\n\t\t\tconst node = this.getNode(pen.nodeId) as VectorPathNode;\n\t\t\tconst anchors = [...sp.anchors, { x: pt.x, y: pt.y }];\n\t\t\tthis.replaceNode(pen.nodeId, { ...node, subpaths: node.subpaths.map((s, i) => (i === pen.subpath ? { ...s, anchors } : s)) });\n\t\t\tconst ref = { nodeId: pen.nodeId, subpath: pen.subpath, index: anchors.length - 1 };\n\t\t\tthis.anchors = [ref];\n\t\t\tthis.drag = { kind: 'pull', ref, before, base: this.doc, label: 'Add Point', outOnly: false, closing: false, altBreaks: true };\n\t\t\tthis.interaction = { type: 'pen', nodeId: pen.nodeId };\n\t\t\tthis.notify(true);\n\t\t\treturn;\n\t\t}\n\t\tconst endpoint = this.hitAnchor(screen, this.openEndpoints());\n\t\tif (endpoint) {\n\t\t\tlet node = this.getNode(endpoint.nodeId) as VectorPathNode;\n\t\t\tlet index = endpoint.index;\n\t\t\tif (index === 0 && node.subpaths[endpoint.subpath].anchors.length > 1) {\n\t\t\t\tnode = { ...node, subpaths: node.subpaths.map((s, i) => (i === endpoint.subpath ? reverseSubpath(s) : s)) };\n\t\t\t\tthis.replaceNode(node.id, node);\n\t\t\t\tindex = node.subpaths[endpoint.subpath].anchors.length - 1;\n\t\t\t}\n\t\t\tthis.pen = { nodeId: node.id, subpath: endpoint.subpath };\n\t\t\tthis.selection = [node.id];\n\t\t\tthis.editingId = node.id;\n\t\t\tconst ref = { nodeId: node.id, subpath: endpoint.subpath, index };\n\t\t\tthis.anchors = [ref];\n\t\t\tthis.drag = { kind: 'pull', ref, before, base: this.doc, label: 'Continue Path', outOnly: true, closing: false, altBreaks: true };\n\t\t\tthis.interaction = { type: 'pen', nodeId: node.id };\n\t\t\tthis.notify(this.doc !== before.doc);\n\t\t\treturn;\n\t\t}\n\t\tconst pt = this.snapDrawn(p, null, input, () => this.drawingTargets(null));\n\t\tconst node: VectorPathNode = { id: this.newId(), type: 'path', name: 'Path', ...this.styleFor(true), subpaths: [{ anchors: [{ x: pt.x, y: pt.y }], closed: false }] };\n\t\tthis.setDoc([...this.doc.nodes, node]);\n\t\tthis.pen = { nodeId: node.id, subpath: 0 };\n\t\tthis.selection = [node.id];\n\t\tthis.editingId = node.id;\n\t\tconst ref = { nodeId: node.id, subpath: 0, index: 0 };\n\t\tthis.anchors = [ref];\n\t\tthis.drag = { kind: 'pull', ref, before, base: this.doc, label: 'Start Path', outOnly: false, closing: false, altBreaks: true };\n\t\tthis.interaction = { type: 'pen', nodeId: node.id };\n\t\tthis.notify(true);\n\t}\n\n\tprivate downPencil(p: Vec2, input: VectorPointerInput = {}) {\n\t\tconst before = this.snapshot();\n\t\tconst node: VectorPathNode = {\n\t\t\tid: this.newId(),\n\t\t\ttype: 'path',\n\t\t\tname: 'Pencil',\n\t\t\t...this.styleFor(true),\n\t\t\tstrokeLinecap: this.defaults.strokeLinecap ?? 'round',\n\t\t\tstrokeLinejoin: this.defaults.strokeLinejoin ?? 'round',\n\t\t\tsubpaths: [{ anchors: [{ x: p.x, y: p.y }], closed: false }]\n\t\t};\n\t\tthis.setDoc([...this.doc.nodes, node]);\n\t\tconst lazy = new LazyMouse((this.editing.pencilSmoothing * VECTOR_PENCIL_STRING_PX) / this.viewport.zoom);\n\t\tlazy.push([p.x, p.y]);\n\t\tconst mode = this.editing.pencilPressure;\n\t\tconst hasPressure = typeof input.pressure === 'number' && Number.isFinite(input.pressure);\n\t\tconst record = hasPressure && (mode === 'all' || (mode === 'pen' && input.pointerType === 'pen'));\n\t\tconst pressure = hasPressure ? input.pressure! : 0.5;\n\t\tthis.drag = { kind: 'pencil', nodeId: node.id, points: [[p.x, p.y]], before, lazy, pressures: record ? [pressure] : null, pressure };\n\t\tthis.interaction = { type: 'draw', tool: 'pencil', nodeId: node.id, bounds: { x: p.x, y: p.y, width: 0, height: 0 } };\n\t\tthis.notify(true);\n\t}\n\n\tprivate downShape(p: Vec2, input: VectorPointerInput) {\n\t\tconst before = this.snapshot();\n\t\t// The targets are gathered before the new shape joins the document, and kept for the drag.\n\t\tconst targets = this.drawingTargets(null);\n\t\tconst start = this.snapDrawn(p, null, input, () => targets);\n\t\tconst kind = this.tool as VectorShapeInput['kind'];\n\t\tconst node = this.createShapeNode({ kind, x: start.x, y: start.y, width: 0, height: 0 });\n\t\tthis.setDoc([...this.doc.nodes, node]);\n\t\tthis.drag = { kind: 'shape', tool: this.tool, start, nodeId: node.id, before, targets };\n\t\tthis.interaction = { type: 'draw', tool: this.tool, nodeId: node.id, bounds: { x: start.x, y: start.y, width: 0, height: 0 } };\n\t\tthis.notify(true);\n\t}\n\n\t/** Pointer moved over the canvas (with or without a button down). */\n\tpointerMove(screen: Vec2, input: VectorPointerInput = {}): void {\n\t\tconst p = this.screenToDocument(screen);\n\t\tconst drag = this.drag;\n\t\tif (!drag && (this.tool === 'shapeBuilder' || this.tool === 'paintBucket')) {\n\t\t\tthis.pointer = p;\n\t\t\tif (this.hoverBuilder(p, !!input.alt)) this.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (!drag) {\n\t\t\tconst hover = this.computeHover(screen);\n\t\t\tconst pointerMatters = this.tool === 'pen' && !!this.pen;\n\t\t\tconst guides = this.guides;\n\t\t\tthis.hover = hover;\n\t\t\tconst pointer = this.hoverSnap(p, input);\n\t\t\tif (this.sameHover(hover, this.state.hover) && !pointerMatters && JSON.stringify(guides) === JSON.stringify(this.guides)) return;\n\t\t\tthis.pointer = pointer;\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tthis.pointer = p;\n\t\tswitch (drag.kind) {\n\t\t\tcase 'pan':\n\t\t\t\tthis.viewport = { ...drag.viewport, x: drag.viewport.x + screen.x - drag.start.x, y: drag.viewport.y + screen.y - drag.start.y };\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\tcase 'move': {\n\t\t\t\tlet dx = p.x - drag.start.x;\n\t\t\t\tlet dy = p.y - drag.start.y;\n\t\t\t\tif (!drag.moved && Math.hypot(dx, dy) * this.viewport.zoom < 2) return;\n\t\t\t\tdrag.moved = true;\n\t\t\t\tif (input.shift) Math.abs(dx) > Math.abs(dy) ? (dy = 0) : (dx = 0);\n\t\t\t\tif (input.alt && !drag.duplicated) {\n\t\t\t\t\tdrag.duplicated = true;\n\t\t\t\t\tconst created: string[] = [];\n\t\t\t\t\tdrag.base = this.withDuplicates(drag.base, this.selectedRoots(), { x: 0, y: 0 }, created);\n\t\t\t\t\tthis.selection = created;\n\t\t\t\t\t// The originals stay behind as targets.\n\t\t\t\t\tdrag.targets = undefined;\n\t\t\t\t}\n\t\t\t\t({ dx, dy } = this.snapMove(drag, dx, dy, input));\n\t\t\t\tthis.doc = this.transformed(drag.base, new Set(this.selectedRoots()), translateMatrix(dx, dy));\n\t\t\t\tthis.interaction = { type: 'move', dx, dy };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'scale': {\n\t\t\t\t// Scale in the box's own (possibly rotated) frame.\n\t\t\t\tconst angle = drag.frame.angle;\n\t\t\t\tconst q = angle ? applyMatrix(rotateMatrix(-angle), p) : p;\n\t\t\t\tlet { sx, sy, origin } = scaleFor(drag.handle, drag.frame, q, input);\n\t\t\t\tif (this.snap.objects && !input.mod && drag.handle !== 'rotate') {\n\t\t\t\t\tdrag.targets ??= VectorSnapTargets.forResize(drag.base, this.selectedRoots());\n\t\t\t\t\tconst res = drag.targets.snapScale(drag.frame, drag.handle, sx, sy, input, this.snapTolerance());\n\t\t\t\t\t({ sx, sy } = res);\n\t\t\t\t\tthis.setGuides(res);\n\t\t\t\t} else this.setGuides(null);\n\t\t\t\tconst ids = new Set(this.selectedRoots());\n\t\t\t\tthis.doc = this.transformed(drag.base, ids, this.inFrame(angle, scaleMatrix(sx, sy, origin)));\n\t\t\t\tthis.interaction = { type: 'scale', handle: drag.handle, sx, sy };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'rotate': {\n\t\t\t\tconst a0 = Math.atan2(drag.start.y - drag.center.y, drag.start.x - drag.center.x);\n\t\t\t\tconst a1 = Math.atan2(p.y - drag.center.y, p.x - drag.center.x);\n\t\t\t\tlet angle = ((a1 - a0) * 180) / Math.PI;\n\t\t\t\tif (input.shift) angle = Math.round(angle / 15) * 15;\n\t\t\t\tthis.doc = this.transformed(drag.base, new Set(this.selectedRoots()), rotateMatrix(angle, drag.center));\n\t\t\t\tthis.interaction = { type: 'rotate', angle };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'marquee': {\n\t\t\t\tconst bounds = boundsFromPoints(drag.start, p);\n\t\t\t\tthis.interaction = { type: 'marquee', bounds };\n\t\t\t\tif (drag.anchorsMode) {\n\t\t\t\t\tconst inside = getVisibleAnchors(this.view()).filter((r) => {\n\t\t\t\t\t\tconst a = getAnchorWorld(this.doc, r)!;\n\t\t\t\t\t\treturn a.x >= bounds.x && a.x <= bounds.x + bounds.width && a.y >= bounds.y && a.y <= bounds.y + bounds.height;\n\t\t\t\t\t});\n\t\t\t\t\tthis.anchors = [...drag.baseAnchors, ...inside.filter((r) => !drag.baseAnchors.some((b) => sameRef(b, r)))];\n\t\t\t\t} else {\n\t\t\t\t\tconst hits = this.doc.nodes\n\t\t\t\t\t\t.filter((n) => !n.locked && n.visible !== false)\n\t\t\t\t\t\t.filter((n) => {\n\t\t\t\t\t\t\tconst b = vectorNodeBounds(n);\n\t\t\t\t\t\t\treturn b && boundsIntersect(b, bounds);\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.map((n) => n.id);\n\t\t\t\t\tthis.selection = [...new Set([...drag.base, ...hits])];\n\t\t\t\t}\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'anchors': {\n\t\t\t\tlet dx = p.x - drag.start.x;\n\t\t\t\tlet dy = p.y - drag.start.y;\n\t\t\t\tif (!drag.moved && Math.hypot(dx, dy) * this.viewport.zoom < 2) return;\n\t\t\t\tdrag.moved = true;\n\t\t\t\tconst lead = this.leadAnchor(drag);\n\t\t\t\tif (lead) {\n\t\t\t\t\t// The grabbed (or nearest) anchor snaps; the others move with it.\n\t\t\t\t\tconst leave = input.shift ? { at: lead, constrain: 'axis' as const, curves: false } : null;\n\t\t\t\t\tconst q = this.snapDrawn({ x: lead.x + dx, y: lead.y + dy }, leave, input, () => (drag.targets ??= VectorSnapTargets.forAnchorDrag(drag.base, this.anchors)));\n\t\t\t\t\tdx = q.x - lead.x;\n\t\t\t\t\tdy = q.y - lead.y;\n\t\t\t\t} else if (input.shift) Math.abs(dx) > Math.abs(dy) ? (dy = 0) : (dx = 0);\n\t\t\t\tconst single = this.anchors.length === 1 ? this.anchors[0] : null;\n\t\t\t\tconst from = single ? getAnchorWorld(drag.base, single) : undefined;\n\t\t\t\t// A lone point bends its segments with the Curvature setting (Alt held flips it).\n\t\t\t\tif (single && from && this.editing.curvatureMoves !== !!input.alt) this.doc = this.curvatureMoved(drag.base, single, { x: from.x + dx, y: from.y + dy });\n\t\t\t\telse this.doc = this.movedAnchors(drag.base, this.anchors, dx, dy);\n\t\t\t\tthis.interaction = { type: 'anchors', dx, dy };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'handle': {\n\t\t\t\tconst anchor = getAnchorWorld(drag.base, drag.ref);\n\t\t\t\tconst leave = anchor ? { at: { x: anchor.x, y: anchor.y }, constrain: input.shift ? ('angle' as const) : null } : null;\n\t\t\t\tconst pt = this.snapDrawn(p, leave, input, () => (drag.targets ??= VectorSnapTargets.forHandle(drag.base, drag.ref.nodeId)));\n\t\t\t\tconst local = this.toLocal(drag.ref.nodeId, pt, drag.base);\n\t\t\t\tthis.doc = this.updateAnchors(drag.base, [drag.ref], (a) => moveAnchorHandle(a, drag.ref.handle, local, input.alt));\n\t\t\t\tthis.interaction = { type: 'handle', ref: drag.ref };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'corner': {\n\t\t\t\tif (!drag.moved && Math.hypot(p.x - drag.start.x, p.y - drag.start.y) * this.viewport.zoom < 3) return;\n\t\t\t\tdrag.moved = true;\n\t\t\t\tconst c = drag.widget.corner;\n\t\t\t\tconst inv = invertMatrix(this.worldOf(drag.widget.ref.nodeId, drag.base));\n\t\t\t\tconst d = applyMatrixLinear(inv, { x: p.x - drag.start.x, y: p.y - drag.start.y });\n\t\t\t\tconst radius = Math.max(0, Math.min(c.maxRadius, drag.widget.drawnRadius + cornerRadiusChange(c, d)));\n\t\t\t\tthis.doc = this.updateAnchors(drag.base, drag.refs, (a) => setAnchorCorner(a, radius));\n\t\t\t\tthis.interaction = { type: 'corner', ref: drag.widget.ref, radius };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'bend': {\n\t\t\t\tif (!drag.moved && Math.hypot(p.x - drag.start.x, p.y - drag.start.y) * this.viewport.zoom < 2) return;\n\t\t\t\tdrag.moved = true;\n\t\t\t\tthis.doc = this.bent(drag.base, drag.ref, drag.t, p);\n\t\t\t\tthis.interaction = { type: 'bend', ref: drag.ref };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'builder':\n\t\t\t\treturn this.moveBuilder(drag, p);\n\t\t\tcase 'stroke': {\n\t\t\t\tconst last = drag.points[drag.points.length - 1];\n\t\t\t\tif (Math.hypot(p.x - last.x, p.y - last.y) * this.viewport.zoom < 1.5) return;\n\t\t\t\tdrag.points.push(p);\n\t\t\t\tthis.interaction = { type: 'stroke', tool: drag.tool, points: drag.points.slice(), width: drag.tool === 'eraser' ? this.editing.eraserSize : 0 };\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'pull': {\n\t\t\t\tconst anchor = getAnchorWorld(drag.base, drag.ref);\n\t\t\t\tif (!anchor) return;\n\t\t\t\tif (Math.hypot(p.x - anchor.x, p.y - anchor.y) * this.viewport.zoom < 2) {\n\t\t\t\t\tthis.doc = drag.base;\n\t\t\t\t\tthis.notify(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.guides = null;\n\t\t\t\tlet pt = p;\n\t\t\t\tif (input.shift) pt = constrain45(anchor, pt);\n\t\t\t\tconst side = drag.closing ? 'in' : 'out';\n\t\t\t\t// Dragging out of the closing anchor pulls its incoming handle toward the pointer's mirror.\n\t\t\t\tconst pos = this.toLocal(drag.ref.nodeId, drag.closing ? { x: 2 * anchor.x - pt.x, y: 2 * anchor.y - pt.y } : pt, drag.base);\n\t\t\t\tthis.doc = this.updateAnchors(drag.base, [drag.ref], (a) => {\n\t\t\t\t\tif (drag.outOnly || (drag.altBreaks && input.alt)) return moveAnchorHandle(a, side, pos, true);\n\t\t\t\t\treturn moveAnchorHandle({ ...a, type: 'symmetric' }, side, pos);\n\t\t\t\t});\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'shape': {\n\t\t\t\tconst node = this.getNode(drag.nodeId);\n\t\t\t\tif (node?.type !== 'path') return;\n\t\t\t\tconst leave = { at: drag.start, constrain: input.shift ? (drag.tool === 'line' ? ('angle' as const) : ('square' as const)) : null, curves: false };\n\t\t\t\tlet end = this.snapDrawn(p, leave, input, () => (drag.targets ??= this.drawingTargets(null)));\n\t\t\t\tif (!this.snappedToObject && drag.tool !== 'line' && !input.shift && !input.mod && this.snap.objects && drag.targets) end = this.matchShapeSize(drag.targets, drag.start, end, input.alt);\n\t\t\t\tlet start = drag.start;\n\t\t\t\tlet bounds: VectorBounds;\n\t\t\t\tif (drag.tool === 'line') {\n\t\t\t\t\tif (input.shift) end = constrain45(start, end);\n\t\t\t\t\tif (input.alt) start = { x: 2 * start.x - end.x, y: 2 * start.y - end.y };\n\t\t\t\t\tbounds = { x: start.x, y: start.y, width: end.x - start.x, height: end.y - start.y };\n\t\t\t\t} else {\n\t\t\t\t\tlet w = end.x - start.x;\n\t\t\t\t\tlet h = end.y - start.y;\n\t\t\t\t\tif (input.shift) {\n\t\t\t\t\t\tconst s = Math.max(Math.abs(w), Math.abs(h));\n\t\t\t\t\t\tw = Math.sign(w || 1) * s;\n\t\t\t\t\t\th = Math.sign(h || 1) * s;\n\t\t\t\t\t}\n\t\t\t\t\tif (input.alt) start = { x: start.x - w, y: start.y - h };\n\t\t\t\t\tconst x2 = drag.start.x + w;\n\t\t\t\t\tconst y2 = drag.start.y + h;\n\t\t\t\t\tbounds = boundsFromPoints(start, { x: x2, y: y2 });\n\t\t\t\t}\n\t\t\t\tconst shaped = this.createShapeNode({ kind: drag.tool as VectorShapeInput['kind'], ...bounds });\n\t\t\t\tthis.replaceNode(drag.nodeId, { ...node, subpaths: shaped.subpaths });\n\t\t\t\tthis.interaction = { type: 'draw', tool: drag.tool, nodeId: drag.nodeId, bounds };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'width': {\n\t\t\t\tif (!drag.moved && Math.hypot(p.x - drag.start.x, p.y - drag.start.y) * this.viewport.zoom < 2) return;\n\t\t\t\tdrag.moved = true;\n\t\t\t\tconst node = findVectorNode(drag.base.nodes, drag.ref.nodeId) as VectorPathNode;\n\t\t\t\tconst local = this.toLocal(node.id, p, drag.base);\n\t\t\t\tlet profile: VectorWidthPoint[];\n\t\t\t\tif (drag.mode === 'move') {\n\t\t\t\t\tconst g = vectorStrokeWidthGeometry(node);\n\t\t\t\t\tconst near = g ? nearestStrokePosition(g.line, [local.x, local.y], drag.ref.subpath) : null;\n\t\t\t\t\tif (!near) return;\n\t\t\t\t\tprofile = setWidthPoint(drag.profile, drag.ref.index, { t: near.t });\n\t\t\t\t} else {\n\t\t\t\t\tconst off = ((local.x - drag.origin.x) * drag.normal.x + (local.y - drag.origin.y) * drag.normal.y) / drag.unit;\n\t\t\t\t\tconst patch =\n\t\t\t\t\t\tdrag.side === 'both' ? { left: Math.abs(off), right: Math.abs(off) } : drag.side === 'left' ? { left: Math.max(0, off) } : { right: Math.max(0, -off) };\n\t\t\t\t\tprofile = setWidthPoint(drag.profile, drag.ref.index, patch);\n\t\t\t\t}\n\t\t\t\tthis.doc = { ...drag.base, nodes: mapTree(drag.base.nodes, (n) => (n.id === node.id ? { ...(n as VectorPathNode), strokeWidthProfile: profile } : n)) };\n\t\t\t\tconst w = profile[drag.ref.index];\n\t\t\t\tthis.interaction = { type: 'width', ref: drag.ref, mode: drag.mode, width: (w.left + w.right) * drag.unit };\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'pencil': {\n\t\t\t\tconst last = drag.points[drag.points.length - 1];\n\t\t\t\tlet moved = false;\n\t\t\t\tif (typeof input.pressure === 'number' && Number.isFinite(input.pressure)) drag.pressure = input.pressure;\n\t\t\t\tfor (const q of drag.lazy.push([p.x, p.y])) {\n\t\t\t\t\tif (Math.hypot(q[0] - last[0], q[1] - last[1]) * this.viewport.zoom < 1.5) continue;\n\t\t\t\t\tdrag.points.push(q);\n\t\t\t\t\tdrag.pressures?.push(drag.pressure);\n\t\t\t\t\tmoved = true;\n\t\t\t\t}\n\t\t\t\tconst string = drag.lazy.string();\n\t\t\t\tconst node = this.getNode(drag.nodeId);\n\t\t\t\tif (node?.type !== 'path') return;\n\t\t\t\tif (!moved) {\n\t\t\t\t\tif (string && this.interaction?.type === 'draw') {\n\t\t\t\t\t\tthis.interaction = { ...this.interaction, string: [{ x: string[0][0], y: string[0][1] }, { x: string[1][0], y: string[1][1] }] };\n\t\t\t\t\t\tthis.notify();\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.replaceNode(drag.nodeId, { ...node, subpaths: [{ anchors: drag.points.map(([x, y]) => ({ x, y })), closed: false }] });\n\t\t\t\tconst xs = drag.points.map((q) => q[0]);\n\t\t\t\tconst ys = drag.points.map((q) => q[1]);\n\t\t\t\tthis.interaction = {\n\t\t\t\t\ttype: 'draw',\n\t\t\t\t\ttool: 'pencil',\n\t\t\t\t\tnodeId: drag.nodeId,\n\t\t\t\t\tbounds: { x: Math.min(...xs), y: Math.min(...ys), width: Math.max(...xs) - Math.min(...xs), height: Math.max(...ys) - Math.min(...ys) },\n\t\t\t\t\t...(string ? { string: [{ x: string[0][0], y: string[0][1] }, { x: string[1][0], y: string[1][1] }] as [Vec2, Vec2] } : {})\n\t\t\t\t};\n\t\t\t\tthis.notify(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Snaps a move of the selection by (dx, dy): its bounds line up with targets or space evenly, else go to the grid. */\n\tprivate snapMove(drag: Extract<Drag, { kind: 'move' }>, dx: number, dy: number, input: VectorModifiers): { dx: number; dy: number } {\n\t\tconst origin = drag.origin;\n\t\tif (input.mod || !origin) {\n\t\t\tthis.setGuides(null);\n\t\t\treturn { dx, dy };\n\t\t}\n\t\t// A Shift-locked axis stays put.\n\t\tconst axes = { x: !input.shift || dx !== 0, y: !input.shift || dy !== 0 };\n\t\tlet res = null;\n\t\tif (this.snap.objects) {\n\t\t\tdrag.targets ??= VectorSnapTargets.forMove(drag.base, this.selectedRoots());\n\t\t\tres = drag.targets.snapRect({ ...origin, x: origin.x + dx, y: origin.y + dy }, this.snapTolerance(), { spacing: true, axes });\n\t\t}\n\t\tthis.setGuides(res);\n\t\treturn {\n\t\t\tdx: res?.x ? dx + res.dx : axes.x ? this.gridValue(origin.x + dx) - origin.x : dx,\n\t\t\tdy: res?.y ? dy + res.dy : axes.y ? this.gridValue(origin.y + dy) - origin.y : dy\n\t\t};\n\t}\n\n\t/** The anchor a point drag snaps by, where it started: the grabbed one, else the moving one nearest the press. */\n\tprivate leadAnchor(drag: Extract<Drag, { kind: 'anchors' }>): Vec2 | null {\n\t\tconst ref = drag.lead && this.anchors.some((a) => sameRef(a, drag.lead!)) ? drag.lead : null;\n\t\tif (ref) {\n\t\t\tconst a = getAnchorWorld(drag.base, ref);\n\t\t\treturn a ? { x: a.x, y: a.y } : null;\n\t\t}\n\t\tlet best: Vec2 | null = null;\n\t\tfor (const r of this.anchors) {\n\t\t\tconst a = getAnchorWorld(drag.base, r);\n\t\t\tif (a && (!best || Math.hypot(a.x - drag.start.x, a.y - drag.start.y) < Math.hypot(best.x - drag.start.x, best.y - drag.start.y))) best = { x: a.x, y: a.y };\n\t\t}\n\t\treturn best;\n\t}\n\n\t/** A shape's dragged corner moved so its width or height matches another object's, when one is within reach. */\n\tprivate matchShapeSize(targets: VectorSnapTargets, start: Vec2, end: Vec2, fromCentre = false): Vec2 {\n\t\t// Dragged from the centre, the shape is twice as large as the drag.\n\t\tconst k = fromCentre ? 2 : 1;\n\t\tconst tol = this.snapTolerance() * k;\n\t\tconst out = { ...end };\n\t\tconst guides: VectorSnapGuides = { lines: [], labels: [] };\n\t\tfor (const axis of ['x', 'y'] as const) {\n\t\t\tconst d = end[axis] - start[axis];\n\t\t\tconst len = Math.abs(d) > 1e-9 ? targets.matchSize(Math.abs(d) * k, tol) : null;\n\t\t\tif (len === null || len <= 0) continue;\n\t\t\tout[axis] = start[axis] + (Math.sign(d) * len) / k;\n\t\t\tconst from = { ...out, [axis]: fromCentre ? 2 * start[axis] - out[axis] : start[axis] };\n\t\t\tguides.lines.push({ kind: 'size', x1: from.x, y1: from.y, x2: out.x, y2: out.y });\n\t\t\tguides.labels.push({ kind: 'size', x: (from.x + out.x) / 2, y: (from.y + out.y) / 2, text: `${axis === 'x' ? 'W' : 'H'} ${Math.round(len * 100) / 100}` });\n\t\t}\n\t\tthis.setGuides(guides);\n\t\treturn out;\n\t}\n\n\t/** Primary button released. */\n\tpointerUp(screen?: Vec2, input: VectorPointerInput = {}): void {\n\t\t// A pen reports no pressure as it lifts: keep the last pressure for the final move.\n\t\tif (screen && this.drag && this.drag.kind !== 'pan') this.pointerMove(screen, { ...input, pressure: undefined });\n\t\tconst drag = this.drag;\n\t\tthis.drag = null;\n\t\tthis.interaction = null;\n\t\tthis.guides = null;\n\t\tif (!drag) return;\n\t\tswitch (drag.kind) {\n\t\t\tcase 'pan':\n\t\t\tcase 'marquee':\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\tcase 'move':\n\t\t\t\tif (!drag.moved) {\n\t\t\t\t\tif (drag.clickId) this.selection = [drag.clickId];\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn this.commit(drag.duplicated ? 'Duplicate' : 'Move', drag.before);\n\t\t\tcase 'scale':\n\t\t\t\treturn this.commit('Scale', drag.before);\n\t\t\tcase 'rotate':\n\t\t\t\treturn this.commit('Rotate', drag.before);\n\t\t\tcase 'anchors':\n\t\t\t\tif (!drag.moved) {\n\t\t\t\t\tif (drag.clickRef) this.anchors = [drag.clickRef];\n\t\t\t\t\tif (drag.before.doc !== this.doc) return this.commit('Add Point', drag.before);\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn this.commit(drag.before.doc !== drag.base ? 'Add Point' : 'Move Points', drag.before);\n\t\t\tcase 'handle':\n\t\t\t\treturn this.commit('Move Handle', drag.before);\n\t\t\tcase 'bend':\n\t\t\t\tif (!drag.moved) {\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn this.commit('Bend Segment', drag.before);\n\t\t\tcase 'corner': {\n\t\t\t\tif (drag.moved) return this.commit('Corner Radius', drag.before);\n\t\t\t\tif (drag.alt) {\n\t\t\t\t\tconst kind = nextVectorCornerKind(drag.widget.kind);\n\t\t\t\t\tthis.doc = this.updateAnchors(drag.base, drag.refs, (a) => setAnchorCorner(a, a.corner?.radius ?? 0, kind));\n\t\t\t\t\treturn this.commit('Corner Kind', drag.before);\n\t\t\t\t}\n\t\t\t\t// A click selects the widget's corner, so the next drag rounds that corner alone.\n\t\t\t\tconst ref = drag.widget.ref;\n\t\t\t\tconst has = this.anchors.some((a) => sameRef(a, ref));\n\t\t\t\tthis.editingId = ref.nodeId;\n\t\t\t\tthis.anchors = drag.shift ? (has ? this.anchors.filter((a) => !sameRef(a, ref)) : [...this.anchors, ref]) : [ref];\n\t\t\t\tthis.notify();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'width': {\n\t\t\t\tif (drag.moved) return this.commit(drag.mode === 'move' ? 'Move Width Point' : 'Width Point', drag.before);\n\t\t\t\t// A click adds nothing; on a width point it selects it.\n\t\t\t\tif (drag.created) {\n\t\t\t\t\tthis.doc = drag.before.doc;\n\t\t\t\t\tthis.widthPoint = null;\n\t\t\t\t\tthis.notify(true);\n\t\t\t\t} else this.notify();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'builder':\n\t\t\t\treturn this.upBuilder(drag);\n\t\t\tcase 'stroke': {\n\t\t\t\tthis.notify();\n\t\t\t\tif (drag.tool === 'knife') this.knife(drag.points);\n\t\t\t\telse this.erase(drag.points);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'pull':\n\t\t\t\tif (drag.closing) this.pen = null;\n\t\t\t\treturn this.commit(drag.label, drag.before);\n\t\t\tcase 'shape': {\n\t\t\t\tconst node = this.getNode(drag.nodeId);\n\t\t\t\tconst b = node ? vectorNodeBounds(node) : null;\n\t\t\t\tconst min = 2 / this.viewport.zoom;\n\t\t\t\tif (!b || (b.width < min && b.height < min)) {\n\t\t\t\t\tthis.doc = drag.before.doc;\n\t\t\t\t\tthis.notify(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.selection = [drag.nodeId];\n\t\t\t\tthis.anchors = [];\n\t\t\t\tthis.tool = 'select';\n\t\t\t\treturn this.commit(`Draw ${TOOL_LABELS[drag.tool]}`, drag.before);\n\t\t\t}\n\t\t\tcase 'pencil': {\n\t\t\t\tconst node = this.getNode(drag.nodeId);\n\t\t\t\tif (node?.type !== 'path' || drag.points.length < 2) {\n\t\t\t\t\tthis.doc = drag.before.doc;\n\t\t\t\t\tthis.notify(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tfor (const q of drag.lazy.finish()) {\n\t\t\t\t\tdrag.points.push(q);\n\t\t\t\t\tdrag.pressures?.push(drag.pressure);\n\t\t\t\t}\n\t\t\t\tconst shape = this.editing.recognizeShapes ? recognizeInkShape(drag.points, { minSize: 6 / this.viewport.zoom }) : null;\n\t\t\t\tif (shape) {\n\t\t\t\t\tthis.replaceNode(drag.nodeId, { ...node, name: inkShapeLabel(shape), subpaths: [inkShapeSubpath(shape)] });\n\t\t\t\t\tthis.selection = [drag.nodeId];\n\t\t\t\t\treturn this.commit(`Draw ${inkShapeLabel(shape)}`, drag.before);\n\t\t\t\t}\n\t\t\t\tconst fitted = fitCubics(drag.points, 1.5 / this.viewport.zoom, { cornerAngleDeg: 60 });\n\t\t\t\tconst anchors: VectorAnchor[] = [];\n\t\t\t\tfor (const c of fitted) {\n\t\t\t\t\tif (!anchors.length) anchors.push({ x: c.p0[0], y: c.p0[1] });\n\t\t\t\t\tanchors[anchors.length - 1].out = { x: c.p1[0], y: c.p1[1] };\n\t\t\t\t\tanchors.push({ x: c.p3[0], y: c.p3[1], in: { x: c.p2[0], y: c.p2[1] } });\n\t\t\t\t}\n\t\t\t\tconst subpaths = anchors.length > 1 ? bezierToSubpaths(subpathsToBezier([{ anchors, closed: false }])) : node.subpaths;\n\t\t\t\tconst profile = drag.pressures ? pencilPressureProfile(drag.points, drag.pressures) : [];\n\t\t\t\tthis.replaceNode(drag.nodeId, { ...node, subpaths, ...(profile.length ? { strokeWidthProfile: profile } : {}) });\n\t\t\t\tthis.selection = [drag.nodeId];\n\t\t\t\treturn this.commit('Draw', drag.before);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** The pointer left the canvas. */\n\tpointerLeave(): void {\n\t\tif (this.drag) return;\n\t\tif (!this.hover && !this.pointer && !this.guides) return;\n\t\tthis.hover = null;\n\t\tthis.pointer = null;\n\t\tthis.guides = null;\n\t\tthis.notify();\n\t}\n\n\t/** Abandons the drag in progress (Escape, lost capture). */\n\tcancelDrag(): void {\n\t\tconst drag = this.drag;\n\t\tif (!drag) return;\n\t\tthis.drag = null;\n\t\tthis.interaction = null;\n\t\tthis.guides = null;\n\t\tif (drag.kind === 'pan' || drag.kind === 'builder') {\n\t\t\tif (drag.kind === 'builder') this.builderPreview = null;\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (drag.kind === 'marquee') {\n\t\t\tthis.selection = drag.base;\n\t\t\tthis.anchors = drag.baseAnchors;\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tthis.restore(drag.before);\n\t}\n\n\t/** Double click: select tool enters path editing, direct tool toggles an anchor or adds one. */\n\tdoubleClick(screen: Vec2): void {\n\t\tconst p = this.screenToDocument(screen);\n\t\tif (this.tool === 'select') {\n\t\t\tconst path = this.hitPath(p);\n\t\t\tif (!path) return;\n\t\t\tthis.tool = 'direct';\n\t\t\tthis.selection = [path.id];\n\t\t\tthis.editingId = path.id;\n\t\t\tthis.anchors = [];\n\t\t\tthis.notify();\n\t\t\treturn;\n\t\t}\n\t\tif (this.tool === 'direct') {\n\t\t\tconst anchor = this.hitAnchor(screen, getVisibleAnchors(this.view()));\n\t\t\tif (anchor) {\n\t\t\t\tconst a = getAnchor(this.doc, anchor)!;\n\t\t\t\tthis.convertAnchors(a.in || a.out ? 'corner' : 'smooth', [anchor]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst id = this.hover?.segment?.nodeId ?? this.editingId;\n\t\t\tif (id) {\n\t\t\t\tconst node = this.getNode(id) as VectorPathNode | undefined;\n\t\t\t\tconst seg = node ? nearestSegment(node, this.toLocal(id, p)) : null;\n\t\t\t\tif (seg && seg.distance <= this.tolerance()) this.insertAnchorAt(id, p);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (this.tool === 'pen') this.finishPath();\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Keyboard input\n\t// -------------------------------------------------------------------------\n\n\t/**\n\t * Handles editor shortcuts. Returns true when the key was used (call `preventDefault`).\n\t * Do not forward keys typed into text inputs.\n\t */\n\tkeyDown(input: VectorKeyInput): boolean {\n\t\tconst key = input.key;\n\t\tconst lower = key.length === 1 ? key.toLowerCase() : key;\n\t\tif (key === ' ') {\n\t\t\tif (!this.spaceHeld) {\n\t\t\t\tthis.spaceHeld = true;\n\t\t\t\tthis.notify();\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tif (input.mod) {\n\t\t\tswitch (lower) {\n\t\t\t\tcase 'z':\n\t\t\t\t\tinput.shift ? this.redo() : this.undo();\n\t\t\t\t\treturn true;\n\t\t\t\tcase 'y':\n\t\t\t\t\tthis.redo();\n\t\t\t\t\treturn true;\n\t\t\t\tcase 'a':\n\t\t\t\t\tthis.selectAll();\n\t\t\t\t\treturn true;\n\t\t\t\tcase 'd':\n\t\t\t\t\tthis.duplicate();\n\t\t\t\t\treturn true;\n\t\t\t\tcase 'g':\n\t\t\t\t\tinput.shift ? this.ungroup() : this.group();\n\t\t\t\t\treturn true;\n\t\t\t\tcase 'j':\n\t\t\t\t\treturn input.alt ? this.averageAnchors('both').ok : this.joinPaths().ok;\n\t\t\t\tcase ']':\n\t\t\t\t\tthis.arrange(input.alt ? 'front' : 'forward');\n\t\t\t\t\treturn true;\n\t\t\t\tcase '[':\n\t\t\t\t\tthis.arrange(input.alt ? 'back' : 'backward');\n\t\t\t\t\treturn true;\n\t\t\t\tcase '=':\n\t\t\t\tcase '+':\n\t\t\t\t\tthis.setViewport({ zoom: this.viewport.zoom * 1.25 });\n\t\t\t\t\treturn true;\n\t\t\t\tcase '-':\n\t\t\t\t\tthis.setViewport({ zoom: this.viewport.zoom / 1.25 });\n\t\t\t\t\treturn true;\n\t\t\t\tcase '0':\n\t\t\t\t\tthis.setViewport({ zoom: 1 });\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\tswitch (key) {\n\t\t\tcase 'Escape':\n\t\t\t\tif (this.drag) this.cancelDrag();\n\t\t\t\telse if (this.tool === 'width' && this.widthPoint) {\n\t\t\t\t\tthis.widthPoint = null;\n\t\t\t\t\tthis.notify();\n\t\t\t\t}\n\t\t\t\telse if (this.pen) this.finishPath();\n\t\t\t\telse if (this.tool === 'direct' && this.anchors.length) {\n\t\t\t\t\tthis.anchors = [];\n\t\t\t\t\tthis.notify();\n\t\t\t\t} else if (this.tool !== 'select') this.setTool('select');\n\t\t\t\telse this.clearSelection();\n\t\t\t\treturn true;\n\t\t\tcase 'Enter':\n\t\t\t\tif (this.pen) {\n\t\t\t\t\tthis.finishPath();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (this.tool === 'select' && this.selection.length === 1 && this.getNode(this.selection[0])?.type === 'path') {\n\t\t\t\t\tthis.tool = 'direct';\n\t\t\t\t\tthis.editingId = this.selection[0];\n\t\t\t\t\tthis.notify();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\tcase 'Delete':\n\t\t\tcase 'Backspace':\n\t\t\t\tif (this.tool === 'width' && this.widthPoint) return this.removeWidthPoint(this.widthPoint).ok;\n\t\t\t\tif (this.pen) {\n\t\t\t\t\tconst node = this.getNode(this.pen.nodeId) as VectorPathNode;\n\t\t\t\t\tconst sp = node.subpaths[this.pen.subpath];\n\t\t\t\t\tif (sp.anchors.length > 2) this.deleteAnchors([{ nodeId: node.id, subpath: this.pen.subpath, index: sp.anchors.length - 1 }]);\n\t\t\t\t\telse {\n\t\t\t\t\t\tthis.removeNodes([node.id], { label: 'Delete Path' });\n\t\t\t\t\t\tthis.pen = null;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn this.deleteSelection().ok;\n\t\t\tcase 'ArrowLeft':\n\t\t\tcase 'ArrowRight':\n\t\t\tcase 'ArrowUp':\n\t\t\tcase 'ArrowDown': {\n\t\t\t\tconst step = input.shift ? 10 : 1;\n\t\t\t\tconst dx = key === 'ArrowLeft' ? -step : key === 'ArrowRight' ? step : 0;\n\t\t\t\tconst dy = key === 'ArrowUp' ? -step : key === 'ArrowDown' ? step : 0;\n\t\t\t\treturn this.translate(dx, dy).ok;\n\t\t\t}\n\t\t}\n\t\tif (key.length === 1 && !input.alt) {\n\t\t\tconst tool = TOOL_KEYS[lower];\n\t\t\tif (tool) {\n\t\t\t\tthis.setTool(tool);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tkeyUp(input: VectorKeyInput): void {\n\t\tif (input.key === ' ' && this.spaceHeld) {\n\t\t\tthis.spaceHeld = false;\n\t\t\tthis.notify();\n\t\t}\n\t}\n}\n\n/** \"Rectangle\", \"Square\", \"Ellipse\", \"Circle\", \"Line\", \"Triangle\" or \"Polygon\". */\nfunction inkShapeLabel(shape: VectorInkShape): string {\n\tconst name = vectorInkShapeName(shape);\n\treturn name[0].toUpperCase() + name.slice(1);\n}\n\n/** The subpath of a recognised pencil shape. */\nfunction inkShapeSubpath(shape: VectorInkShape): VectorSubpath {\n\tswitch (shape.kind) {\n\t\tcase 'line':\n\t\t\treturn lineSubpath({ x: shape.a[0], y: shape.a[1] }, { x: shape.b[0], y: shape.b[1] });\n\t\tcase 'rect':\n\t\t\treturn rectSubpath(shape);\n\t\tcase 'ellipse':\n\t\t\treturn ellipseSubpath(shape);\n\t\tcase 'polygon':\n\t\t\treturn { anchors: shape.points.map(([x, y]) => ({ x, y })), closed: true };\n\t}\n}\n\n/** Snaps `p` to the nearest 45° direction from `origin`, keeping its distance. */\nfunction constrain45(origin: Vec2, p: Vec2): Vec2 {\n\tconst dx = p.x - origin.x;\n\tconst dy = p.y - origin.y;\n\tconst len = Math.hypot(dx, dy);\n\tconst a = Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * (Math.PI / 4);\n\treturn { x: origin.x + Math.cos(a) * len, y: origin.y + Math.sin(a) * len };\n}\n\n/** Scale factors and origin for dragging a selection-box handle to `p`. */\nexport function scaleFor(handle: VectorTransformHandle, b: VectorBounds, p: Vec2, mods: VectorModifiers = {}): { sx: number; sy: number; origin: Vec2 } {\n\tconst west = handle.includes('w');\n\tconst east = handle.includes('e');\n\tconst north = handle.startsWith('n');\n\tconst south = handle.startsWith('s');\n\tconst center = { x: b.x + b.width / 2, y: b.y + b.height / 2 };\n\tconst origin = mods.alt ? center : { x: west ? b.x + b.width : east ? b.x : center.x, y: north ? b.y + b.height : south ? b.y : center.y };\n\tconst reachX = mods.alt ? b.width / 2 : b.width;\n\tconst reachY = mods.alt ? b.height / 2 : b.height;\n\tlet sx = west || east ? (reachX > 1e-9 ? ((p.x - origin.x) * (west ? -1 : 1)) / reachX : 1) : 1;\n\tlet sy = north || south ? (reachY > 1e-9 ? ((p.y - origin.y) * (north ? -1 : 1)) / reachY : 1) : 1;\n\tif (mods.shift) {\n\t\tif ((west || east) && (north || south)) {\n\t\t\tconst s = Math.max(Math.abs(sx), Math.abs(sy));\n\t\t\tsx = Math.sign(sx || 1) * s;\n\t\t\tsy = Math.sign(sy || 1) * s;\n\t\t} else if (west || east) sy = Math.abs(sx);\n\t\telse sx = Math.abs(sy);\n\t}\n\treturn { sx, sy, origin };\n}\n\n/** A style applied to a path; a `null` (or empty) width profile removes it. */\nfunction withStyle(node: VectorPathNode, style: VectorStyle & { opacity?: number }): VectorNode {\n\tconst next = { ...node, ...style } as VectorPathNode;\n\tif ('strokeWidthProfile' in style) {\n\t\tconst p = style.strokeWidthProfile ? sanitizeWidthProfile(style.strokeWidthProfile) : [];\n\t\tif (p.length) next.strokeWidthProfile = p;\n\t\telse delete next.strokeWidthProfile;\n\t}\n\treturn next;\n}\n\n/** True when node `id` or one of its ancestors is locked or hidden. */\nfunction hiddenOrLocked(nodes: readonly VectorNode[], id: string): boolean {\n\tconst loc = locateVectorNode(nodes as VectorNode[], id);\n\tif (!loc) return false;\n\tconst n = loc.list[loc.index];\n\tif (n.locked || n.visible === false) return true;\n\treturn loc.parent ? hiddenOrLocked(nodes, loc.parent.id) : false;\n}\n\n/** The width profile of pencil samples and their pressures (positions by length along the samples). */\nfunction pencilPressureProfile(points: readonly Point[], pressures: readonly number[]): VectorWidthPoint[] {\n\tconst n = Math.min(points.length, pressures.length);\n\tif (n < 2) return [];\n\tconst s = [0];\n\tfor (let i = 1; i < n; i++) s.push(s[i - 1] + Math.hypot(points[i][0] - points[i - 1][0], points[i][1] - points[i - 1][1]));\n\tconst total = s[n - 1];\n\tif (!(total > 0)) return [];\n\treturn pressureWidthProfile(s.map((d, i) => ({ t: d / total, pressure: pressures[i] })));\n}\n","/**\n * Framework-neutral render data for a vector editor: the scene (document-space SVG paths and\n * gradient defs) and the overlay (screen-space selection box, anchors, handles, marquee and\n * pen preview). React, Svelte or plain DOM code turns these into `<svg>` elements.\n */\nimport { bezierPathToSvg, transformBezierPath, type BezierPath } from '../canvas/pathops/bezier.js';\nimport { hatchPath } from '../canvas/pathops/hatch.js';\nimport type { SvgGradientDef } from '../canvas/gradient.js';\n\nexport type { SvgGradientDef };\nimport {\n\tgetAnchorWorld,\n\tgetVectorCornerWidgets,\n\tgetVectorSelectionBoxGeometry,\n\tgetVectorWidthHandles,\n\tgetVisibleAnchors,\n\tgetVisibleHandles,\n\ttype VectorEditorController,\n\ttype VectorEditorState,\n\ttype VectorSelectionBoxGeometry,\n\ttype VectorWidthPointRef\n} from './controller.js';\nimport { sanitizeWidthProfile, widthProfilePresetId, type VectorWidthPreset } from './width.js';\nimport {\n\tfindVectorNode,\n\tIDENTITY_MATRIX,\n\tinferAnchorType,\n\tmultiplyMatrices,\n\tnodeMatrix,\n\tvectorNodeBounds,\n\tvectorParentMatrix,\n\tvectorPathData,\n\tvectorPathWorldBezier,\n\ttype AffineMatrix\n} from './geometry.js';\nimport { vectorPaintToSvg, vectorStrokeSvgParts, type VectorRenderStrokeParts } from './svg.js';\nimport { vectorCorners } from './corners.js';\nimport type { VectorGuideKind, VectorSnapKind } from './snap.js';\nimport type {\n\tVectorAnchorRef,\n\tVectorAnchorType,\n\tVectorArrowAlign,\n\tVectorArrowhead,\n\tVectorBounds,\n\tVectorCornerKind,\n\tVectorHandleRef,\n\tVectorNode,\n\tVectorPaint,\n\tVectorPathfinderOperation,\n\tVectorPathNode,\n\tVectorStrokeAlign,\n\tVectorTransformHandle,\n\tVectorWidthPoint,\n\tVec2\n} from './types.js';\n\nexport interface VectorRenderPath {\n\tkind: 'path';\n\tid: string;\n\t/** SVG `transform` (`matrix(…)`) for a rotated node. */\n\ttransform?: string;\n\td: string;\n\t/** `none`, a colour, or `url(#id)` of a gradient in `defs`. */\n\tfill: string;\n\tstroke: string;\n\tstrokeWidth: number;\n\tstrokeLinecap?: string;\n\tstrokeLinejoin?: string;\n\tstrokeDasharray?: string;\n\tfillRule: 'nonzero' | 'evenodd';\n\topacity: number;\n\t/**\n\t * Set when the stroke takes more than one element: an inside / outside alignment or\n\t * arrowheads. Draw `d` with the fill only, then `stroke.d` with the stroke (at\n\t * `stroke.width`, clipped or masked as `stroke.clip` says), then each head filled with\n\t * `stroke`; group them under `id`, `transform` and `opacity`.\n\t */\n\tstrokeParts?: VectorRenderStrokeParts;\n}\n\nexport interface VectorRenderGroup {\n\tkind: 'group';\n\tid: string;\n\t/** SVG `transform` (`matrix(…)`) for a rotated group. */\n\ttransform?: string;\n\topacity: number;\n\tchildren: VectorRenderNode[];\n}\n\nexport type VectorRenderNode = VectorRenderPath | VectorRenderGroup;\n\nexport interface VectorSceneRenderData {\n\t/** SVG `transform` for the document layer: `translate(x y) scale(zoom)`. */\n\ttransform: string;\n\twidth: number;\n\theight: number;\n\tbackground?: string;\n\t/** Gradients referenced by `fill` / `stroke` values. */\n\tdefs: SvgGradientDef[];\n\t/** Visible nodes, bottom to top. */\n\tnodes: VectorRenderNode[];\n}\n\nexport interface VectorRenderAnchor {\n\tref: VectorAnchorRef;\n\t/** Screen position. */\n\tx: number;\n\ty: number;\n\ttype: VectorAnchorType;\n\tselected: boolean;\n\thovered: boolean;\n\t/** The pen tool closes the path when this anchor is clicked. */\n\tcloses: boolean;\n}\n\nexport interface VectorRenderHandle {\n\tref: VectorHandleRef;\n\tx: number;\n\ty: number;\n\t/** Screen position of the handle's anchor (draw a line to it). */\n\tanchorX: number;\n\tanchorY: number;\n\thovered: boolean;\n}\n\n/** A live corner widget in screen pixels. */\nexport interface VectorRenderCornerWidget {\n\tref: VectorAnchorRef;\n\tx: number;\n\ty: number;\n\tradius: number;\n\tkind: VectorCornerKind;\n\thovered: boolean;\n\t/** Its corners are being dragged. */\n\tactive: boolean;\n}\n\n/**\n * A width point of the width tool in screen pixels: a diamond at (`x`, `y`) on the path and a\n * line across the stroke from `left` to `right`, with a handle at each end.\n */\nexport interface VectorRenderWidthPoint {\n\tref: VectorWidthPointRef;\n\tx: number;\n\ty: number;\n\tleft: Vec2;\n\tright: Vec2;\n\tselected: boolean;\n\t/** The part under the pointer, if any. */\n\thovered: 'center' | 'left' | 'right' | null;\n\t/** Being dragged. */\n\tactive: boolean;\n}\n\n/** A smart guide line in screen pixels. */\nexport interface VectorRenderGuideLine {\n\tkind: VectorGuideKind;\n\tx1: number;\n\ty1: number;\n\tx2: number;\n\ty2: number;\n}\n\n/** A smart guide label (\"anchor\", \"intersect\", \"align\", \"centre\", a gap or a size) at a screen position. */\nexport interface VectorRenderGuideLabel {\n\tkind: VectorSnapKind;\n\tx: number;\n\ty: number;\n\ttext: string;\n}\n\nexport interface VectorOverlayRenderData {\n\t/** Outlines (screen-space path data) of hovered and selected nodes. */\n\toutlines: { id: string; d: string; selected: boolean }[];\n\t/**\n\t * Selection box with resize and rotate handles (select tool). `x / y / width / height` and\n\t * each handle's `x / y` are the unrotated box in screen pixels: draw them inside\n\t * `<g transform={transform}>`. `corners` and each handle's `screen` are true positions.\n\t */\n\tselectionBox:\n\t\t| (VectorBounds & { angle: number; transform: string; corners: Vec2[]; handles: VectorSelectionBoxGeometry['handles'] })\n\t\t| null;\n\tanchors: VectorRenderAnchor[];\n\thandles: VectorRenderHandle[];\n\t/** Marquee rectangle, screen space. */\n\tmarquee: VectorBounds | null;\n\t/** Rubber-band segment from the pen path's last anchor to the pointer, screen space. */\n\tpenPreview: string | null;\n\t/** Artboard rectangle, screen space. */\n\tartboard: VectorBounds;\n\t/** Smart guides of the snap in progress, screen space (empty when nothing snapped). */\n\tguides: { lines: VectorRenderGuideLine[]; labels: VectorRenderGuideLabel[] };\n\t/**\n\t * The knife or eraser stroke being drawn, screen space: `d` is an open polyline; draw the\n\t * eraser's with a round-capped stroke `width` pixels wide (0 for the knife: a thin line).\n\t */\n\ttoolStroke: { tool: 'knife' | 'eraser'; d: string; width: number } | null;\n\t/** The pencil's lazy-mouse string from the pen to the pointer, screen space. */\n\tpencilString: { x1: number; y1: number; x2: number; y2: number } | null;\n\t/** Where the scissors would cut (screen space). */\n\tcutPoint: Vec2 | null;\n\t/**\n\t * Live corner widgets of the direct tool (screen space): drag one to round its corners,\n\t * Alt-click to cycle round / inverted / chamfer, click to pick its corner alone.\n\t */\n\tcornerWidgets: VectorRenderCornerWidget[];\n\t/** Width points of the width tool (screen space). */\n\twidthPoints: VectorRenderWidthPoint[];\n\t/**\n\t * Where a width-tool drag would add a width point (screen space): draw a dashed line from\n\t * `left` to `right` and a hollow diamond at (`x`, `y`).\n\t */\n\twidthSpot: { x: number; y: number; left: Vec2; right: Vec2 } | null;\n\t/**\n\t * Shape Builder and paint bucket highlight (screen space): `faces` are filled paths (fill\n\t * them translucent and outline them), `hatches` the 45° hatch lines over each face\n\t * (`hatchPath`, a few pixels apart; merge and erase only, empty strings for the paint\n\t * bucket: stroke them over the translucent fill), `lines` are the line pieces and outline\n\t * edges an erase deletes, `trail` is the drag's polyline. `mode` is `merge`, `erase` (Alt)\n\t * or `fill` (paint bucket).\n\t */\n\tbuilder: { mode: 'merge' | 'erase' | 'fill'; faces: string[]; hatches: string[]; lines: string[]; trail: string | null } | null;\n\t/** A short status, e.g. \"W 120 × H 80\" or \"45°\". */\n\tstatus: string | null;\n}\n\nconst fmt = (n: number) => Math.round(n * 100) / 100;\nconst fmtMatrix = (m: AffineMatrix) => `matrix(${m.map((n) => Math.round(n * 1e6) / 1e6).join(' ')})`;\n/** Distance between the Shape Builder's hatch lines over a face (screen pixels). */\nexport const VECTOR_BUILDER_HATCH_GAP = 6;\n\nfunction renderNode(node: VectorNode, defs: SvgGradientDef[], idPrefix: string): VectorRenderNode | null {\n\tif (node.visible === false) return null;\n\tif (node.type === 'group') {\n\t\tconst children = node.children.map((c) => renderNode(c, defs, idPrefix)).filter((c): c is VectorRenderNode => !!c);\n\t\treturn { kind: 'group', id: node.id, ...(node.transform ? { transform: fmtMatrix(node.transform) } : {}), opacity: node.opacity ?? 1, children };\n\t}\n\tconst fill = vectorPaintToSvg(node.fill, `${idPrefix}fill-${node.id}`);\n\tconst stroke = vectorPaintToSvg(node.stroke, `${idPrefix}stroke-${node.id}`);\n\tif (fill.gradient) defs.push(fill.gradient);\n\tif (stroke.gradient) defs.push(stroke.gradient);\n\tconst strokeParts = stroke.value !== 'none' ? vectorStrokeSvgParts(node, `${idPrefix}clip-${node.id}`) : undefined;\n\treturn {\n\t\tkind: 'path',\n\t\tid: node.id,\n\t\t...(node.transform ? { transform: fmtMatrix(node.transform) } : {}),\n\t\t...(strokeParts ? { strokeParts } : {}),\n\t\td: vectorPathData(node),\n\t\tfill: fill.value,\n\t\tstroke: stroke.value,\n\t\tstrokeWidth: node.strokeWidth ?? 1,\n\t\t...(node.strokeLinecap ? { strokeLinecap: node.strokeLinecap } : {}),\n\t\t...(node.strokeLinejoin ? { strokeLinejoin: node.strokeLinejoin } : {}),\n\t\t...(node.strokeDasharray?.length ? { strokeDasharray: node.strokeDasharray.join(' ') } : {}),\n\t\tfillRule: node.fillRule ?? 'nonzero',\n\t\topacity: node.opacity ?? 1\n\t};\n}\n\n/**\n * The document layer. Render the nodes inside `<g transform={transform}>` and `defs` in a\n * `<defs>` block. Pass a unique `idPrefix` when several editors share a page.\n */\nexport function getVectorSceneRenderData(state: Pick<VectorEditorState, 'document' | 'viewport'>, options: { idPrefix?: string } = {}): VectorSceneRenderData {\n\tconst defs: SvgGradientDef[] = [];\n\tconst prefix = options.idPrefix ?? 've-';\n\tconst nodes = state.document.nodes.map((n) => renderNode(n, defs, prefix)).filter((n): n is VectorRenderNode => !!n);\n\tconst v = state.viewport;\n\treturn {\n\t\ttransform: `translate(${fmt(v.x)} ${fmt(v.y)}) scale(${v.zoom})`,\n\t\twidth: state.document.width,\n\t\theight: state.document.height,\n\t\t...(state.document.background ? { background: state.document.background } : {}),\n\t\tdefs,\n\t\tnodes\n\t};\n}\n\nconst toScreen = (state: Pick<VectorEditorState, 'viewport'>, p: Vec2) => ({ x: p.x * state.viewport.zoom + state.viewport.x, y: p.y * state.viewport.zoom + state.viewport.y });\n\nfunction screenOutline(state: VectorEditorState, node: VectorNode): string {\n\tconst v = state.viewport;\n\tconst view: AffineMatrix = [v.zoom, 0, 0, v.zoom, v.x, v.y];\n\tconst parent = vectorParentMatrix(state.document.nodes, node.id) ?? IDENTITY_MATRIX;\n\treturn collectWithMatrix(node, parent)\n\t\t.map(({ path, parent: m }) => bezierPathToSvg(transformBezierPath(vectorPathWorldBezier(path, m), view), { precision: 2 }))\n\t\t.join(' ');\n}\n\n/** Path nodes in a subtree with the matrix of their parent space → document. */\nfunction collectWithMatrix(node: VectorNode, parent: AffineMatrix): { path: VectorPathNode; parent: AffineMatrix }[] {\n\tif (node.type === 'path') return [{ path: node, parent }];\n\tconst m = multiplyMatrices(nodeMatrix(node), parent);\n\treturn node.children.flatMap((c) => collectWithMatrix(c, m));\n}\n\nfunction collect(node: VectorNode): VectorPathNode[] {\n\tif (node.type === 'path') return [node];\n\treturn node.children.flatMap(collect);\n}\n\n/** The editing overlay in screen pixels. Render it on top of the scene, untransformed. */\nexport function getVectorOverlayRenderData(state: VectorEditorState): VectorOverlayRenderData {\n\tconst doc = state.document;\n\tconst z = state.viewport.zoom;\n\tconst outlines: VectorOverlayRenderData['outlines'] = [];\n\tconst seen = new Set<string>();\n\tconst outline = (id: string, selected: boolean) => {\n\t\tif (seen.has(id)) return;\n\t\tconst node = findVectorNode(doc.nodes, id);\n\t\tif (!node || node.visible === false) return;\n\t\tseen.add(id);\n\t\toutlines.push({ id, d: screenOutline(state, node), selected });\n\t};\n\tfor (const id of state.selection) outline(id, true);\n\tif (state.editingId) outline(state.editingId, true);\n\tif (state.hover?.nodeId && !state.interaction) outline(state.hover.nodeId, false);\n\n\tlet selectionBox: VectorOverlayRenderData['selectionBox'] = null;\n\tif (state.tool === 'select' && state.selectionFrame && state.interaction?.type !== 'marquee') {\n\t\tconst g = getVectorSelectionBoxGeometry(state.selectionFrame, state.viewport);\n\t\tselectionBox = { ...g.box, angle: g.angle, transform: g.transform, corners: g.corners, handles: g.handles };\n\t}\n\n\tconst selected = (r: VectorAnchorRef) => state.selectedAnchors.some((a) => a.nodeId === r.nodeId && a.subpath === r.subpath && a.index === r.index);\n\tconst sameAnchor = (a: VectorAnchorRef | undefined, b: VectorAnchorRef) => !!a && a.nodeId === b.nodeId && a.subpath === b.subpath && a.index === b.index;\n\tconst anchors: VectorRenderAnchor[] = getVisibleAnchors(state).map((ref) => {\n\t\tconst a = getAnchorWorld(doc, ref)!;\n\t\tconst s = toScreen(state, a);\n\t\tconst closes = !!state.pen && state.pen.nodeId === ref.nodeId && state.pen.subpath === ref.subpath && ref.index === 0;\n\t\treturn { ref, x: s.x, y: s.y, type: a.type ?? inferAnchorType(a), selected: selected(ref), hovered: sameAnchor(state.hover?.anchor, ref), closes };\n\t});\n\tif (state.tool === 'pen' && !state.pen && state.hover?.anchor) {\n\t\tconst a = getAnchorWorld(doc, state.hover.anchor);\n\t\tif (a) {\n\t\t\tconst s = toScreen(state, a);\n\t\t\tanchors.push({ ref: state.hover.anchor, x: s.x, y: s.y, type: a.type ?? 'corner', selected: false, hovered: true, closes: false });\n\t\t}\n\t}\n\n\tconst handles: VectorRenderHandle[] = getVisibleHandles(state).flatMap((ref) => {\n\t\tconst a = getAnchorWorld(doc, ref);\n\t\tconst h = a?.[ref.handle];\n\t\tif (!a || !h) return [];\n\t\tconst s = toScreen(state, h);\n\t\tconst sa = toScreen(state, a);\n\t\tconst hovered = !!state.hover?.handle && sameAnchor(state.hover.handle, ref) && state.hover.handle.handle === ref.handle;\n\t\treturn [{ ref, x: s.x, y: s.y, anchorX: sa.x, anchorY: sa.y, hovered }];\n\t});\n\n\tlet marquee: VectorBounds | null = null;\n\tif (state.interaction?.type === 'marquee') {\n\t\tconst b = state.interaction.bounds;\n\t\tconst tl = toScreen(state, b);\n\t\tmarquee = { x: tl.x, y: tl.y, width: b.width * z, height: b.height * z };\n\t}\n\n\tlet penPreview: string | null = null;\n\tif (state.tool === 'pen' && state.pen && state.pointer && !state.interaction) {\n\t\tconst node = findVectorNode(doc.nodes, state.pen.nodeId);\n\t\tconst sp = node?.type === 'path' ? node.subpaths[state.pen.subpath] : undefined;\n\t\tconst last = sp ? getAnchorWorld(doc, { nodeId: state.pen.nodeId, subpath: state.pen.subpath, index: sp.anchors.length - 1 }) : undefined;\n\t\tif (last) {\n\t\t\tconst a = toScreen(state, last);\n\t\t\tconst p = toScreen(state, state.pointer);\n\t\t\tconst c = last.out ? toScreen(state, last.out) : null;\n\t\t\tpenPreview = c ? `M${fmt(a.x)} ${fmt(a.y)}Q${fmt(c.x)} ${fmt(c.y)} ${fmt(p.x)} ${fmt(p.y)}` : `M${fmt(a.x)} ${fmt(a.y)}L${fmt(p.x)} ${fmt(p.y)}`;\n\t\t}\n\t}\n\n\tconst origin = toScreen(state, { x: 0, y: 0 });\n\tconst artboard = { x: origin.x, y: origin.y, width: doc.width * z, height: doc.height * z };\n\n\tlet status: string | null = null;\n\tconst it = state.interaction;\n\tif (it?.type === 'rotate') status = `${Math.round(it.angle)}°`;\n\telse if (it?.type === 'move' || it?.type === 'anchors') status = `Δ ${fmt(it.dx)}, ${fmt(it.dy)}`;\n\telse if (it?.type === 'scale' || it?.type === 'draw') {\n\t\tconst b = it.type === 'draw' ? (findVectorNode(doc.nodes, it.nodeId) ? vectorNodeBounds(findVectorNode(doc.nodes, it.nodeId)!) : null) : state.selectionFrame;\n\t\tif (b) status = `W ${fmt(b.width)} × H ${fmt(b.height)}`;\n\t}\n\n\tconst guides: VectorOverlayRenderData['guides'] = { lines: [], labels: [] };\n\tif (state.guides) {\n\t\tfor (const l of state.guides.lines) {\n\t\t\tconst a = toScreen(state, { x: l.x1, y: l.y1 });\n\t\t\tconst b = toScreen(state, { x: l.x2, y: l.y2 });\n\t\t\tguides.lines.push({ kind: l.kind, x1: fmt(a.x), y1: fmt(a.y), x2: fmt(b.x), y2: fmt(b.y) });\n\t\t}\n\t\tfor (const l of state.guides.labels) {\n\t\t\tconst p = toScreen(state, l);\n\t\t\tguides.labels.push({ kind: l.kind, x: fmt(p.x), y: fmt(p.y), text: l.text });\n\t\t}\n\t}\n\n\tlet toolStroke: VectorOverlayRenderData['toolStroke'] = null;\n\tif (it?.type === 'stroke') {\n\t\tconst pts = it.points.map((q) => toScreen(state, q));\n\t\tconst d = pts.map((q, i) => `${i ? 'L' : 'M'}${fmt(q.x)} ${fmt(q.y)}`).join('') + (pts.length === 1 ? `L${fmt(pts[0].x)} ${fmt(pts[0].y)}` : '');\n\t\ttoolStroke = { tool: it.tool, d, width: fmt(it.width * z) };\n\t}\n\tlet pencilString: VectorOverlayRenderData['pencilString'] = null;\n\tif (it?.type === 'draw' && it.string) {\n\t\tconst a = toScreen(state, it.string[0]);\n\t\tconst b = toScreen(state, it.string[1]);\n\t\tpencilString = { x1: fmt(a.x), y1: fmt(a.y), x2: fmt(b.x), y2: fmt(b.y) };\n\t}\n\tconst dragged = it?.type === 'corner' ? it.ref : null;\n\tconst cornerWidgets: VectorRenderCornerWidget[] = getVectorCornerWidgets(state).map((w) => {\n\t\tconst s = toScreen(state, w);\n\t\treturn { ref: w.ref, x: fmt(s.x), y: fmt(s.y), radius: w.radius, kind: w.kind, hovered: sameAnchor(state.hover?.corner, w.ref), active: !!dragged };\n\t});\n\tif (it?.type === 'corner') status = `R ${fmt(it.radius)}`;\n\tconst cutPoint = state.tool === 'scissors' && state.hover?.segment && !it ? (({ x, y }) => ({ x: fmt(x), y: fmt(y) }))(toScreen(state, state.hover.segment.point)) : null;\n\n\tconst sc = (p: Vec2) => {\n\t\tconst q = toScreen(state, p);\n\t\treturn { x: fmt(q.x), y: fmt(q.y) };\n\t};\n\tconst sameWidth = (a: VectorWidthPointRef | null | undefined, b: VectorWidthPointRef) => !!a && a.nodeId === b.nodeId && a.index === b.index;\n\tconst widthPoints: VectorRenderWidthPoint[] = getVectorWidthHandles(state).map((h) => {\n\t\tconst c = sc(h);\n\t\tconst hw = state.hover?.widthPoint;\n\t\tconst hovered = hw && sameWidth(hw, h.ref) && hw.subpath === h.ref.subpath ? hw.part : null;\n\t\treturn { ref: h.ref, x: c.x, y: c.y, left: sc(h.left), right: sc(h.right), selected: h.selected, hovered, active: it?.type === 'width' && sameWidth(it.ref, h.ref) };\n\t});\n\tconst spot = state.tool === 'width' && !it ? state.hover?.strokeSpot : null;\n\tconst widthSpot = spot ? { ...sc(spot.point), left: sc(spot.left), right: sc(spot.right) } : null;\n\tif (it?.type === 'width') status = it.mode === 'move' ? 'Move width point' : `W ${fmt(it.width)}`;\n\n\tlet builder: VectorOverlayRenderData['builder'] = null;\n\tif (state.builder) {\n\t\tconst v = state.viewport;\n\t\tconst view: AffineMatrix = [v.zoom, 0, 0, v.zoom, v.x, v.y];\n\t\tconst svg = (path: BezierPath) => bezierPathToSvg(path, { precision: 2 });\n\t\tconst screen = state.builder.faces.map((f) => transformBezierPath(f, view));\n\t\tconst hatch = state.builder.mode !== 'fill';\n\t\tconst trail = state.builder.trail && state.builder.trail.length > 1 ? state.builder.trail.map((q, i) => `${i ? 'L' : 'M'}${sc(q).x} ${sc(q).y}`).join('') : null;\n\t\tbuilder = {\n\t\t\tmode: state.builder.mode,\n\t\t\tfaces: screen.map(svg),\n\t\t\thatches: screen.map((f) => (hatch ? svg(hatchPath(f, { gap: VECTOR_BUILDER_HATCH_GAP })) : '')),\n\t\t\tlines: state.builder.lines.map((l) => svg(transformBezierPath(l, view))),\n\t\t\ttrail\n\t\t};\n\t\tif (state.builder.mode !== 'fill' && it?.type === 'builder') {\n\t\t\tconst n = state.builder.faces.length;\n\t\t\tstatus = state.builder.mode === 'erase' ? `Delete ${n} ${n === 1 ? 'face' : 'faces'}` : `Merge ${n} ${n === 1 ? 'face' : 'faces'}`;\n\t\t}\n\t}\n\n\treturn { outlines, selectionBox, anchors, handles, marquee, penPreview, artboard, guides, status, toolStroke, pencilString, cutPoint, cornerWidgets, widthPoints, widthSpot, builder };\n}\n\n// ---------------------------------------------------------------------------\n// Event adapters (duck-typed, so they work with DOM, React and Svelte events)\n// ---------------------------------------------------------------------------\n\n/** Colours and sizes (screen pixels) the bundled canvases draw the overlay with. */\nexport const VECTOR_OVERLAY_THEME = {\n\taccent: '#0ea5e9',\n\t/** Smart guide lines and labels. */\n\tguide: '#ff3dfc',\n\thandleFill: '#ffffff',\n\tmarqueeFill: 'rgba(14, 165, 233, 0.08)',\n\t/** The eraser's swath while it is dragged. */\n\teraserFill: 'rgba(239, 68, 68, 0.25)',\n\ttransformHandleSize: 8,\n\tanchorSize: 7,\n\thandleRadius: 3.5,\n\t/** Radius of a live corner widget (a ring with a dot). */\n\tcornerWidgetRadius: 4,\n\t/** Half the diagonal of a width point's diamond. */\n\twidthPointSize: 5,\n\t/** Shape Builder faces to merge and paint bucket regions. */\n\tbuilderFill: 'rgba(14, 165, 233, 0.22)',\n\t/** Shape Builder faces and line pieces an Alt gesture deletes. */\n\tbuilderErase: '#ef4444',\n\tbuilderEraseFill: 'rgba(239, 68, 68, 0.22)',\n\t/** Opacity of the hatch lines over Shape Builder faces (drawn in the face's outline colour). */\n\tbuilderHatchOpacity: 0.6\n} as const;\n\n/** SVG path data of the diamond a width point is drawn with (screen pixels). */\nexport function vectorDiamondPath(x: number, y: number, r: number = VECTOR_OVERLAY_THEME.widthPointSize): string {\n\treturn `M${fmt(x)} ${fmt(y - r)}L${fmt(x + r)} ${fmt(y)}L${fmt(x)} ${fmt(y + r)}L${fmt(x - r)} ${fmt(y)}Z`;\n}\n\ninterface ModifierEventLike {\n\tshiftKey?: boolean;\n\taltKey?: boolean;\n\tmetaKey?: boolean;\n\tctrlKey?: boolean;\n}\n\n/** Modifiers of a mouse / pointer / key event (`mod` is Cmd or Ctrl). */\nexport function toVectorModifiers(event: ModifierEventLike): { shift: boolean; alt: boolean; mod: boolean } {\n\treturn { shift: !!event.shiftKey, alt: !!event.altKey, mod: !!(event.metaKey || event.ctrlKey) };\n}\n\n/**\n * A pointer event as `VectorEditorController.pointerDown/Move/Up` input: modifiers, button,\n * and the pressure and pointer type the pencil records as a width profile.\n */\nexport function toVectorPointerInput(event: ModifierEventLike & { button?: number; pressure?: number; pointerType?: string }) {\n\treturn {\n\t\t...toVectorModifiers(event),\n\t\tbutton: event.button,\n\t\t...(typeof event.pressure === 'number' ? { pressure: event.pressure } : {}),\n\t\t...(event.pointerType ? { pointerType: event.pointerType } : {})\n\t};\n}\n\n/** A key event as `VectorEditorController.keyDown/keyUp` input. */\nexport function toVectorKeyInput(event: ModifierEventLike & { key: string }) {\n\treturn { key: event.key, ...toVectorModifiers(event) };\n}\n\n/** True for targets that should keep their own keys (inputs, textareas, contenteditable). */\nexport function isVectorTextTarget(target: unknown): boolean {\n\tconst el = target as { tagName?: string; isContentEditable?: boolean; getAttribute?: (name: string) => string | null } | null;\n\tif (!el || typeof el !== 'object') return false;\n\tconst tag = (el.tagName ?? '').toUpperCase();\n\tif (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true;\n\treturn !!el.isContentEditable || el.getAttribute?.('contenteditable') === 'true';\n}\n\n// ---------------------------------------------------------------------------\n// Style panel helpers\n// ---------------------------------------------------------------------------\n\n/** Style shown in a style panel: the first selected path's, with `mixed` flags when paths differ. */\nexport interface VectorSelectionStyle {\n\tfill: VectorPaint;\n\tstroke: VectorPaint;\n\tstrokeWidth: number;\n\topacity: number;\n\tstrokeAlign: VectorStrokeAlign;\n\tstartArrow: VectorArrowhead | null;\n\tendArrow: VectorArrowhead | null;\n\tarrowAlign: VectorArrowAlign;\n\tstartArrowScale: number;\n\tendArrowScale: number;\n\t/** The first path's width profile (null when uniform) and the preset it matches. */\n\tstrokeWidthProfile: VectorWidthPoint[] | null;\n\twidthProfile: VectorWidthPreset | 'custom';\n\t/**\n\t * Live corners of the selected anchors (direct tool) or of every corner of the selected\n\t * paths: the first one's radius and kind, and how many corners there are (0: none to round).\n\t */\n\tcornerRadius: number;\n\tcornerKind: VectorCornerKind;\n\tcorners: number;\n\t/** Some selected path is open, so arrowheads apply. */\n\thasOpenPath: boolean;\n\tmixed: {\n\t\tfill: boolean;\n\t\tstroke: boolean;\n\t\tstrokeWidth: boolean;\n\t\topacity: boolean;\n\t\tstrokeAlign: boolean;\n\t\tstartArrow: boolean;\n\t\tendArrow: boolean;\n\t\tarrowAlign: boolean;\n\t\tstartArrowScale: boolean;\n\t\tendArrowScale: boolean;\n\t\twidthProfile: boolean;\n\t\tcornerRadius: boolean;\n\t\tcornerKind: boolean;\n\t};\n\t/** Ids of the paths the style applies to. */\n\tpathIds: string[];\n}\n\nexport function getVectorSelectionStyle(\n\tstate: Pick<VectorEditorState, 'document' | 'selection'> & Partial<Pick<VectorEditorState, 'selectedAnchors' | 'tool'>>\n): VectorSelectionStyle | null {\n\tconst paths: VectorPathNode[] = [];\n\tfor (const id of state.selection) {\n\t\tconst node = findVectorNode(state.document.nodes, id);\n\t\tif (node) paths.push(...collect(node));\n\t}\n\tconst anchorMode = state.tool === 'direct' && !!state.selectedAnchors?.length;\n\tif (anchorMode) {\n\t\tfor (const r of state.selectedAnchors!) {\n\t\t\tif (paths.some((p) => p.id === r.nodeId)) continue;\n\t\t\tconst node = findVectorNode(state.document.nodes, r.nodeId);\n\t\t\tif (node?.type === 'path') paths.push(node);\n\t\t}\n\t}\n\tif (!paths.length) return null;\n\tconst first = paths[0];\n\tconst same = (get: (p: VectorPathNode) => unknown) => paths.every((p) => JSON.stringify(get(p) ?? null) === JSON.stringify(get(first) ?? null));\n\t// Corners: those of the selected anchors in the direct tool, else every corner of the paths.\n\tconst corners: { radius: number; kind: VectorCornerKind }[] = [];\n\tfor (const p of paths) {\n\t\tfor (const c of vectorCorners(p.subpaths)) {\n\t\t\tif (anchorMode && !state.selectedAnchors!.some((r) => r.nodeId === p.id && r.subpath === c.subpath && r.index === c.index)) continue;\n\t\t\tconst corner = p.subpaths[c.subpath].anchors[c.index].corner;\n\t\t\tcorners.push({ radius: corner?.radius ?? 0, kind: corner?.kind ?? 'round' });\n\t\t}\n\t}\n\tconst c0 = corners[0] ?? { radius: 0, kind: 'round' as const };\n\treturn {\n\t\tfill: first.fill ?? null,\n\t\tstroke: first.stroke ?? null,\n\t\tstrokeWidth: first.strokeWidth ?? 1,\n\t\topacity: first.opacity ?? 1,\n\t\tstrokeAlign: first.strokeAlign ?? 'center',\n\t\tstartArrow: first.startArrow ?? null,\n\t\tendArrow: first.endArrow ?? null,\n\t\tarrowAlign: first.arrowAlign ?? 'extend',\n\t\tstartArrowScale: first.startArrowScale ?? 1,\n\t\tendArrowScale: first.endArrowScale ?? 1,\n\t\tstrokeWidthProfile: profileOf(first),\n\t\twidthProfile: widthProfilePresetId(profileOf(first)),\n\t\tcornerRadius: c0.radius,\n\t\tcornerKind: c0.kind,\n\t\tcorners: corners.length,\n\t\thasOpenPath: paths.some((p) => p.subpaths.some((sp) => !sp.closed && sp.anchors.length > 1)),\n\t\tmixed: {\n\t\t\tfill: !same((p) => p.fill),\n\t\t\tstroke: !same((p) => p.stroke),\n\t\t\tstrokeWidth: !same((p) => p.strokeWidth ?? 1),\n\t\t\topacity: !same((p) => p.opacity ?? 1),\n\t\t\tstrokeAlign: !same((p) => p.strokeAlign ?? 'center'),\n\t\t\tstartArrow: !same((p) => p.startArrow ?? null),\n\t\t\tendArrow: !same((p) => p.endArrow ?? null),\n\t\t\tarrowAlign: !same((p) => p.arrowAlign ?? 'extend'),\n\t\t\tstartArrowScale: !same((p) => p.startArrowScale ?? 1),\n\t\t\tendArrowScale: !same((p) => p.endArrowScale ?? 1),\n\t\t\twidthProfile: !same(profileOf),\n\t\t\tcornerRadius: corners.some((c) => c.radius !== c0.radius),\n\t\t\tcornerKind: corners.some((c) => c.kind !== c0.kind)\n\t\t},\n\t\tpathIds: paths.map((p) => p.id)\n\t};\n}\n\nfunction profileOf(p: VectorPathNode): VectorWidthPoint[] | null {\n\tconst points = sanitizeWidthProfile(p.strokeWidthProfile);\n\treturn points.length && widthProfilePresetId(points) !== 'uniform' ? points : null;\n}\n\n/** Labels of the stroke alignments, corner kinds and arrowheads, for style panels. */\nexport const VECTOR_STROKE_ALIGN_LABELS: Readonly<Record<VectorStrokeAlign, string>> = { center: 'Center', inside: 'Inside', outside: 'Outside' };\nexport const VECTOR_CORNER_KIND_LABELS: Readonly<Record<VectorCornerKind, string>> = { round: 'Round', inverted: 'Inverted', chamfer: 'Chamfer' };\nexport const VECTOR_ARROWHEAD_LABELS: Readonly<Record<VectorArrowhead, string>> = {\n\ttriangle: 'Triangle',\n\tarrow: 'Arrow',\n\topen: 'Open arrow',\n\tcircle: 'Circle',\n\tsquare: 'Square',\n\tbar: 'Bar'\n};\n\n/** A paint as `#rrggbb` for `<input type=\"color\">`, or null for none, gradients and other CSS colours. */\nexport function vectorPaintToHex(paint: VectorPaint | undefined): string | null {\n\tif (typeof paint !== 'string') return null;\n\tconst m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(paint.trim());\n\tif (!m) return null;\n\tconst hex = m[1].length === 3 ? m[1].replace(/./g, (c) => c + c) : m[1];\n\treturn `#${hex.toLowerCase()}`;\n}\n\n// ---------------------------------------------------------------------------\n// Toolbar helpers\n// ---------------------------------------------------------------------------\n\n/** A path-editing button of the bundled toolbars. */\nexport interface VectorPathAction {\n\tid: 'join' | 'average' | 'cut' | 'clean' | 'smooth' | 'outline';\n\tlabel: string;\n\ttitle: string;\n\t/** Shortcut after Cmd / Ctrl, if any. */\n\tshortcut?: string;\n\t/** Whether it can run with `selected` nodes and `points` selected anchors (direct tool). */\n\tenabled: (selected: number, points: number) => boolean;\n\trun: (controller: VectorEditorController) => unknown;\n}\n\n/** Join, Average, Cut at Points, Remove Redundant Points, Smooth and Outline Stroke, as the toolbars show them. */\nexport const VECTOR_PATH_ACTIONS: readonly VectorPathAction[] = [\n\t{ id: 'join', label: '⋈', title: 'Join', shortcut: 'J', enabled: (s, p) => s + p > 0, run: (c) => c.joinPaths() },\n\t{ id: 'average', label: '⊹', title: 'Average Points', shortcut: 'Alt+J', enabled: (_s, p) => p > 1, run: (c) => c.averageAnchors('both') },\n\t{ id: 'cut', label: '✂·', title: 'Cut at Points', enabled: (_s, p) => p > 0, run: (c) => c.cutAtAnchors() },\n\t{ id: 'clean', label: '⌁', title: 'Remove Redundant Points', enabled: (s, p) => s + p > 0, run: (c) => c.removeRedundantPoints() },\n\t{ id: 'smooth', label: '∿', title: 'Smooth', enabled: (s, p) => s + p > 0, run: (c) => c.smoothPaths() },\n\t{ id: 'outline', label: '⊡', title: 'Outline Stroke', enabled: (s) => s > 0, run: (c) => c.outlineStroke() }\n];\n\n/** A Pathfinder button of the bundled toolbars. */\nexport interface VectorPathfinderAction {\n\tid: VectorPathfinderOperation;\n\tlabel: string;\n\ttitle: string;\n\t/** Paths (or groups) it needs selected. */\n\tmin: number;\n}\n\n/** Divide, Trim, Merge, Crop, Outline and Minus Back, as the toolbars show them. */\nexport const VECTOR_PATHFINDER_ACTIONS: readonly VectorPathfinderAction[] = [\n\t{ id: 'divide', label: '⊞', title: 'Divide', min: 1 },\n\t{ id: 'trim', label: '⧉', title: 'Trim', min: 2 },\n\t{ id: 'merge', label: '⧈', title: 'Merge', min: 2 },\n\t{ id: 'crop', label: '⌗', title: 'Crop', min: 2 },\n\t{ id: 'outline', label: '⬚', title: 'Outline', min: 1 },\n\t{ id: 'minusBack', label: '⊖', title: 'Minus Back', min: 2 }\n];\n\n/** The on / off path-editing settings the toolbars toggle. */\nexport const VECTOR_EDIT_TOGGLES: readonly { key: 'keepShapeOnDelete' | 'curvatureMoves' | 'recognizeShapes'; label: string; title: string }[] = [\n\t{ key: 'keepShapeOnDelete', label: 'Keep', title: 'Keep shape when deleting points' },\n\t{ key: 'curvatureMoves', label: 'Curv', title: 'Curvature point moves (Alt flips while dragging)' },\n\t{ key: 'recognizeShapes', label: 'Shapes', title: 'Turn pencil scribbles into shapes' }\n];\n\n","import type { CommandSpec } from '../commands/registry.js';\nimport type { VectorEditorController, VectorShapeInput } from './controller.js';\nimport { vectorNodeBounds, vectorNodeRotation, vectorParentMatrix, vectorPathData, IDENTITY_MATRIX } from './geometry.js';\nimport type { VectorAlign, VectorAnchorRef, VectorArrange, VectorAverageAxis, VectorBooleanOperation, VectorCornerKind, VectorNode, VectorPathfinderOperation, VectorStyle, VectorTool } from './types.js';\nimport { VECTOR_ARROWHEADS, VECTOR_CORNER_KINDS, VECTOR_PATHFINDER_OPERATIONS, VECTOR_TOOLS, type VectorWidthPoint } from './types.js';\nimport { VECTOR_WIDTH_PRESET_IDS, type VectorTaperOptions, type VectorWaveOptions, type VectorWidthPreset } from './width.js';\n\nexport interface VectorCommandOptions {\n\t/** Id prefix (default `vector.`); use one per editor when several are registered. */\n\tprefix?: string;\n\t/** Palette group (default `Vector`). */\n\tgroup?: string;\n\t/** Command scope. Omit for global commands. */\n\tscope?: string;\n}\n\n/** A node as listed for agents. */\nexport interface VectorNodeListing {\n\tid: string;\n\ttype: 'path' | 'group';\n\tname?: string;\n\tdepth: number;\n\t/** Axis-aligned bounds in document units. */\n\tbounds: { x: number; y: number; width: number; height: number } | null;\n\t/** Rotation in degrees, clockwise (ancestors' rotations included). */\n\trotation: number;\n\tvisible: boolean;\n\tlocked: boolean;\n\tselected: boolean;\n\tfill?: unknown;\n\tstroke?: unknown;\n\tstrokeWidth?: number;\n\t/** SVG path data (paths only). */\n\td?: string;\n\tchildren?: number;\n}\n\nconst fail = (message: string): never => {\n\tthrow new Error(message);\n};\n\nconst IDS = { type: 'array', items: { type: 'string' }, description: 'Node ids (default: the selection).' } as const;\n\nconst ANCHORS = {\n\ttype: 'array',\n\titems: {\n\t\ttype: 'object',\n\t\tproperties: { nodeId: { type: 'string' }, subpath: { type: 'integer', minimum: 0 }, index: { type: 'integer', minimum: 0 } },\n\t\trequired: ['nodeId', 'subpath', 'index']\n\t},\n\tdescription: 'Anchors as { nodeId, subpath, index } (default: the selected points).'\n} as const;\n\nconst POINTS = {\n\ttype: 'array',\n\titems: { type: 'array', items: { type: 'number' }, minItems: 2, maxItems: 2 },\n\tminItems: 1,\n\tdescription: 'Polyline [[x, y], …] in document units.'\n} as const;\n\nconst WIDTH_POINTS = {\n\ttype: ['array', 'null'],\n\titems: {\n\t\ttype: 'object',\n\t\tproperties: {\n\t\t\tt: { type: 'number', minimum: 0, maximum: 1, description: 'Position along each subpath by length (0 start, 1 end).' },\n\t\t\tleft: { type: 'number', minimum: 0, description: 'Left side as a multiple of half the stroke width (1 = uniform).' },\n\t\t\tright: { type: 'number', minimum: 0, description: 'Right side (looking along the path, y down).' }\n\t\t},\n\t\trequired: ['t', 'left', 'right']\n\t},\n\tdescription: 'Variable-width profile points, interpolated smoothly (monotone cubic); two points at one `t` make a step. `null` or `[]` strokes at a uniform width.'\n} as const;\n\nconst PAINT = {\n\tdescription: 'A CSS colour, `null` for none, or a gradient `{ type: \"linear\", angle, stops: [{ offset, color }] }`.'\n} as const;\n\nconst STYLE_PROPS = {\n\tfill: PAINT,\n\tstroke: PAINT,\n\tstrokeWidth: { type: 'number', minimum: 0 },\n\tstrokeLinecap: { type: 'string', enum: ['butt', 'round', 'square'] },\n\tstrokeLinejoin: { type: 'string', enum: ['miter', 'round', 'bevel'] },\n\tstrokeDasharray: { type: 'array', items: { type: 'number' } },\n\tfillRule: { type: 'string', enum: ['nonzero', 'evenodd'] },\n\tstrokeAlign: { type: 'string', enum: ['center', 'inside', 'outside'], description: 'Where the stroke sits on the outline (closed shapes only; open paths stroke centred).' },\n\tstartArrow: { type: ['string', 'null'], enum: [...VECTOR_ARROWHEADS, null], description: 'Head at the start of an open path, or null for none.' },\n\tendArrow: { type: ['string', 'null'], enum: [...VECTOR_ARROWHEADS, null], description: 'Head at the end of an open path, or null for none.' },\n\tarrowAlign: { type: 'string', enum: ['extend', 'tip'], description: '`extend`: the tip sits past the end point; `tip`: on it, the stroke shortened under the head.' },\n\tstartArrowScale: { type: 'number', exclusiveMinimum: 0, description: 'Start head size as a multiple of the stroke width (default 1).' },\n\tendArrowScale: { type: 'number', exclusiveMinimum: 0, description: 'End head size as a multiple of the stroke width (default 1).' },\n\tstrokeWidthProfile: WIDTH_POINTS\n} as const;\n\nconst pickStyle = (params: Record<string, unknown>): VectorStyle => {\n\tconst out: Record<string, unknown> = {};\n\tfor (const key of Object.keys(STYLE_PROPS)) if (params[key] !== undefined) out[key] = params[key];\n\treturn out as VectorStyle;\n};\n\nconst check = (result: { ok: boolean; message?: string }) => {\n\tif (!result.ok) fail(result.message ?? 'The command failed.');\n};\n\n/**\n * Palette and agent commands for a vector editor: list, select, add shapes and paths, style,\n * transform, align, arrange, group, boolean operations and SVG import / export. Register them\n * in a `CommandRegistry` and agents get them through `createCommandToolProvider`. Failures\n * throw sentences, which the registry returns as `{ ok: false, code: 'failed', message }`.\n */\nexport function createVectorCommands(controller: VectorEditorController, options: VectorCommandOptions = {}): CommandSpec[] {\n\tconst prefix = options.prefix ?? 'vector.';\n\tconst group = options.group ?? 'Vector';\n\tconst base = { group, ...(options.scope ? { scope: options.scope } : {}) };\n\tconst hasSelection = () => (controller.getState().selection.length ? true : 'Nothing is selected.');\n\tconst ids = (params: { ids?: string[] } | undefined) => {\n\t\tconst list = params?.ids ?? controller.getState().selection;\n\t\tfor (const id of list) if (!controller.getNode(id)) fail(`There is no node \"${id}\".`);\n\t\tif (!list.length) fail('Nothing is selected; pass ids.');\n\t\treturn list;\n\t};\n\tconst enabledFor = (_: unknown, params: { ids?: string[] } | undefined) => (params?.ids?.length ? true : hasSelection());\n\tconst anchorsOf = (refs: VectorAnchorRef[] | undefined): VectorAnchorRef[] => {\n\t\tif (!refs) return [...controller.getState().selectedAnchors];\n\t\tfor (const r of refs) {\n\t\t\tconst node = controller.getNode(r.nodeId);\n\t\t\tif (node?.type !== 'path' || !node.subpaths[r.subpath]?.anchors[r.index]) fail(`There is no anchor ${r.index} on subpath ${r.subpath} of \"${r.nodeId}\".`);\n\t\t}\n\t\treturn refs;\n\t};\n\n\tconst list = (): { width: number; height: number; nodes: VectorNodeListing[]; selection: readonly string[]; tool: VectorTool } => {\n\t\tconst state = controller.getState();\n\t\tconst out: VectorNodeListing[] = [];\n\t\tconst visit = (nodes: readonly VectorNode[], depth: number) => {\n\t\t\tfor (const n of nodes) {\n\t\t\t\tconst parent = vectorParentMatrix(state.document.nodes, n.id) ?? IDENTITY_MATRIX;\n\t\t\t\tconst b = vectorNodeBounds(n, parent);\n\t\t\t\tout.push({\n\t\t\t\t\tid: n.id,\n\t\t\t\t\ttype: n.type,\n\t\t\t\t\t...(n.name ? { name: n.name } : {}),\n\t\t\t\t\tdepth,\n\t\t\t\t\trotation: Math.round(vectorNodeRotation(n, parent) * 100) / 100,\n\t\t\t\t\tbounds: b && { x: Math.round(b.x * 100) / 100, y: Math.round(b.y * 100) / 100, width: Math.round(b.width * 100) / 100, height: Math.round(b.height * 100) / 100 },\n\t\t\t\t\tvisible: n.visible !== false,\n\t\t\t\t\tlocked: !!n.locked,\n\t\t\t\t\tselected: state.selection.includes(n.id),\n\t\t\t\t\t...(n.type === 'path'\n\t\t\t\t\t\t? { fill: n.fill ?? null, stroke: n.stroke ?? null, strokeWidth: n.strokeWidth ?? 1, d: vectorPathData(n, 2) }\n\t\t\t\t\t\t: { children: n.children.length })\n\t\t\t\t});\n\t\t\t\tif (n.type === 'group') visit(n.children, depth + 1);\n\t\t\t}\n\t\t};\n\t\tvisit(state.document.nodes, 0);\n\t\treturn { width: state.document.width, height: state.document.height, nodes: out, selection: state.selection, tool: state.tool };\n\t};\n\n\treturn [\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}list`,\n\t\t\tlabel: 'List Vector Nodes',\n\t\t\treadOnly: true,\n\t\t\tkeywords: ['layers', 'shapes', 'document', 'outline'],\n\t\t\tdescription: 'Lists every node (paths and groups, depth first) with bounds, style, path data and selection.',\n\t\t\trun: list\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}select`,\n\t\t\tlabel: 'Select Nodes',\n\t\t\tkeywords: ['pick', 'choose'],\n\t\t\tdescription: 'Selects nodes by id (empty list clears the selection).',\n\t\t\tparams: { type: 'object', properties: { ids: { type: 'array', items: { type: 'string' } }, add: { type: 'boolean' } }, required: ['ids'] },\n\t\t\trun: (_ctx: unknown, params: { ids: string[]; add?: boolean }) => {\n\t\t\t\tfor (const id of params.ids) if (!controller.getNode(id)) fail(`There is no node \"${id}\".`);\n\t\t\t\tif (!params.ids.length && !params.add) controller.clearSelection();\n\t\t\t\telse controller.select(params.ids, { add: params.add });\n\t\t\t\treturn { selection: controller.getState().selection };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}addShape`,\n\t\t\tlabel: 'Add Shape…',\n\t\t\tkeywords: ['rectangle', 'ellipse', 'circle', 'polygon', 'star', 'line', 'draw'],\n\t\t\tdescription: 'Adds a rectangle, ellipse, polygon, star or line in document units, using the current default style unless overridden.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tkind: { type: 'string', enum: ['rect', 'ellipse', 'polygon', 'star', 'line'] },\n\t\t\t\t\tx: { type: 'number' },\n\t\t\t\t\ty: { type: 'number' },\n\t\t\t\t\twidth: { type: 'number', description: 'For a line: the x offset of its end.' },\n\t\t\t\t\theight: { type: 'number', description: 'For a line: the y offset of its end.' },\n\t\t\t\t\tcornerRadius: { type: 'number', minimum: 0, description: 'Live corner radius of a rect, polygon or star.' },\n\t\t\t\t\tcornerKind: { type: 'string', enum: VECTOR_CORNER_KINDS },\n\t\t\t\t\tsides: { type: 'integer', minimum: 3 },\n\t\t\t\t\tpoints: { type: 'integer', minimum: 3 },\n\t\t\t\t\tinnerRatio: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\tname: { type: 'string' },\n\t\t\t\t\t...STYLE_PROPS\n\t\t\t\t},\n\t\t\t\trequired: ['kind', 'x', 'y', 'width', 'height']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: VectorShapeInput) => ({ id: controller.addShape(params) })\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}addPath`,\n\t\t\tlabel: 'Add Path…',\n\t\t\tkeywords: ['svg', 'path data', 'bezier', 'curve'],\n\t\t\tdescription: 'Adds a path from SVG path data (`d`), in document units.',\n\t\t\tparams: { type: 'object', properties: { d: { type: 'string' }, name: { type: 'string' }, ...STYLE_PROPS }, required: ['d'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { d: string; name?: string } & Record<string, unknown>) => {\n\t\t\t\tconst id = controller.addPath(params.d, { ...pickStyle(params), ...(params.name ? { name: params.name } : {}) });\n\t\t\t\tconst node = controller.getNode(id);\n\t\t\t\tif (node?.type === 'path' && !node.subpaths.length) {\n\t\t\t\t\tcontroller.undo();\n\t\t\t\t\tfail('The path data has no points.');\n\t\t\t\t}\n\t\t\t\treturn { id };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setStyle`,\n\t\t\tlabel: 'Set Style…',\n\t\t\tkeywords: ['fill', 'stroke', 'colour', 'color', 'gradient', 'width'],\n\t\t\tdescription: 'Sets fill, stroke and stroke settings of nodes (groups apply to every path inside).',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, ...STYLE_PROPS } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } & Record<string, unknown>) => {\n\t\t\t\tconst style = pickStyle(params);\n\t\t\t\tif (!Object.keys(style).length) fail('Pass at least one style property.');\n\t\t\t\tcheck(controller.setStyle(style, ids(params)));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setCorners`,\n\t\t\tlabel: 'Corner Radius…',\n\t\t\tkeywords: ['round', 'rounded', 'corners', 'radius', 'fillet', 'chamfer', 'live corners'],\n\t\t\tdescription:\n\t\t\t\t'Sets the live corner radius (and optionally `kind`: round, inverted or chamfer) of `anchors`, else the selected points (direct tool), else every corner of `ids` / the selection. Radius 0 makes corners sharp; radii shrink to fit short sides. The anchors stay editable.',\n\t\t\tparams: { type: 'object', properties: { radius: { type: 'number', minimum: 0 }, kind: { type: 'string', enum: VECTOR_CORNER_KINDS }, ids: IDS, anchors: ANCHORS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { radius?: number; kind?: VectorCornerKind; ids?: string[]; anchors?: VectorAnchorRef[] } | undefined) => {\n\t\t\t\tconst refs = params?.anchors ? anchorsOf(params.anchors) : undefined;\n\t\t\t\tconst target = { refs, ids: params?.ids ? ids(params) : undefined };\n\t\t\t\tif (params?.radius !== undefined) check(controller.setCornerRadius(params.radius, { ...target, kind: params.kind }));\n\t\t\t\telse if (params?.kind) check(controller.setCornerKind(params.kind, target));\n\t\t\t\telse fail('Pass `radius` and / or `kind`.');\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setWidthProfile`,\n\t\t\tlabel: 'Width Profile…',\n\t\t\tkeywords: ['variable width', 'taper', 'tapered', 'pressure', 'profile', 'brush', 'calligraphy', 'bulge', 'thick', 'thin'],\n\t\t\tdescription:\n\t\t\t\t'Gives the stroke of paths a variable width: a `preset` (`uniform` removes the profile), explicit `points` ({ t, left, right }: side scales along each subpath), or a parametric `taper` (startLength / endLength as fractions of the path, startWidth / endWidth 0–1, startEase / endEase 0–1) and / or `wave` (amount 0–1, cycles, phase in degrees). Profiled strokes draw as filled outlines; Outline Stroke bakes them.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tids: IDS,\n\t\t\t\t\tpreset: { type: 'string', enum: VECTOR_WIDTH_PRESET_IDS },\n\t\t\t\t\tpoints: WIDTH_POINTS,\n\t\t\t\t\ttaper: {\n\t\t\t\t\t\ttype: 'object',\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tstartLength: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\t\t\tendLength: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\t\t\tstartWidth: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\t\t\tendWidth: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\t\t\tstartEase: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\t\t\tendEase: { type: 'number', minimum: 0, maximum: 1 }\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\twave: { type: 'object', properties: { amount: { type: 'number', minimum: 0, maximum: 1 }, cycles: { type: 'number', exclusiveMinimum: 0 }, phase: { type: 'number' } } }\n\t\t\t\t}\n\t\t\t},\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (\n\t\t\t\t_ctx: unknown,\n\t\t\t\tparams: { ids?: string[]; preset?: VectorWidthPreset; points?: VectorWidthPoint[] | null; taper?: VectorTaperOptions; wave?: VectorWaveOptions } | undefined\n\t\t\t) => {\n\t\t\t\tconst target = { ids: ids(params) };\n\t\t\t\tif (params?.preset) check(controller.setWidthProfile(params.preset, target));\n\t\t\t\telse if (params?.points !== undefined) check(controller.setWidthProfile(params.points ?? null, target));\n\t\t\t\telse if (params?.taper || params?.wave) check(controller.setWidthProfile({ taper: params.taper, wave: params.wave }, target));\n\t\t\t\telse fail('Pass `preset`, `points`, `taper` or `wave`.');\n\t\t\t\tconst node = controller.getNode(target.ids[0]);\n\t\t\t\treturn { ok: true, points: node?.type === 'path' ? (node.strokeWidthProfile ?? []) : [] };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}outlineStroke`,\n\t\t\tlabel: 'Outline Stroke',\n\t\t\tkeywords: ['expand', 'stroke to path', 'outline', 'convert stroke'],\n\t\t\tdescription: 'Turns the stroke of paths into filled shapes of the area it paints (alignment, caps, joins, dashes and arrowheads included). Returns the new ids.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => {\n\t\t\t\tconst created = controller.outlineStroke({ ids: params?.ids ? ids(params) : undefined });\n\t\t\t\tif (!created.length) fail('No selected path has a stroke.');\n\t\t\t\treturn { ids: created };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}transform`,\n\t\t\tlabel: 'Transform…',\n\t\t\tkeywords: ['move', 'translate', 'scale', 'resize', 'rotate', 'flip'],\n\t\t\tdescription:\n\t\t\t\t'Moves (dx, dy), scales (sx, sy, along the selection box axes) and/or rotates (`rotate`: by degrees clockwise around the combined centre; `angle`: to an absolute rotation, each node around its own centre), in that order.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tids: IDS,\n\t\t\t\t\tdx: { type: 'number' },\n\t\t\t\t\tdy: { type: 'number' },\n\t\t\t\t\tsx: { type: 'number' },\n\t\t\t\t\tsy: { type: 'number' },\n\t\t\t\t\trotate: { type: 'number' },\n\t\t\t\t\tangle: { type: 'number' }\n\t\t\t\t}\n\t\t\t},\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; dx?: number; dy?: number; sx?: number; sy?: number; rotate?: number; angle?: number }) => {\n\t\t\t\tconst target = ids(params);\n\t\t\t\tif (params.dx || params.dy) check(controller.translate(params.dx ?? 0, params.dy ?? 0, { ids: target }));\n\t\t\t\tif (params.sx !== undefined || params.sy !== undefined) check(controller.scale(params.sx ?? 1, params.sy ?? params.sx ?? 1, { ids: target }));\n\t\t\t\tif (params.rotate) check(controller.rotate(params.rotate, { ids: target }));\n\t\t\t\tif (params.angle !== undefined) check(controller.setRotation(params.angle, { ids: target }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}delete`,\n\t\t\tlabel: 'Delete',\n\t\t\tkeywords: ['remove'],\n\t\t\tdescription: 'Deletes nodes.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => {\n\t\t\t\tcheck(controller.removeNodes(ids(params)));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}boolean`,\n\t\t\tlabel: 'Boolean Operation…',\n\t\t\tkeywords: ['union', 'unite', 'subtract', 'intersect', 'exclude', 'combine', 'pathfinder'],\n\t\t\tdescription: 'Combines two or more paths with union, subtract (upper shapes from the lowest), intersect or exclude.',\n\t\t\tparams: { type: 'object', properties: { operation: { type: 'string', enum: ['union', 'subtract', 'intersect', 'exclude'] }, ids: IDS }, required: ['operation'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { operation: VectorBooleanOperation; ids?: string[] }) => {\n\t\t\t\tconst id = controller.booleanOp(params.operation, { ids: ids(params) });\n\t\t\t\tif (!id) fail('Select at least two overlapping paths (the result was empty).');\n\t\t\t\treturn { id };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}pathfinder`,\n\t\t\tlabel: 'Pathfinder…',\n\t\t\tkeywords: ['divide', 'trim', 'merge', 'crop', 'outline', 'minus back', 'split', 'faces'],\n\t\t\tdescription:\n\t\t\t\t'Pathfinder over the given paths (bottom to top): divide (every face its own shape, painted like the top-most shape over it; open unfilled paths cut), trim (hidden parts removed), merge (trim, then touching parts of one fill joined), crop (the top shape crops the others), outline (outlines cut into open strokes where they meet) or minusBack (the top shape minus everything below). Results replace the paths, grouped when there are several.',\n\t\t\tparams: { type: 'object', properties: { operation: { type: 'string', enum: [...VECTOR_PATHFINDER_OPERATIONS] }, ids: IDS }, required: ['operation'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { operation: VectorPathfinderOperation; ids?: string[] }) => {\n\t\t\t\tif (!VECTOR_PATHFINDER_OPERATIONS.includes(params.operation)) fail(`Unknown Pathfinder operation \"${params.operation}\".`);\n\t\t\t\tconst created = controller.pathfinder(params.operation, { ids: ids(params) });\n\t\t\t\tif (!created.length) fail('Nothing came out: select paths that overlap (two or more, except for divide and outline).');\n\t\t\t\treturn { ids: created, selection: [...controller.getState().selection] };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}shapeBuilderFaces`,\n\t\t\tlabel: 'List Shape Builder Faces',\n\t\t\tkeywords: ['shape builder', 'regions', 'faces', 'planar'],\n\t\t\tdescription: 'Lists the faces the given paths divide the plane into: path data, area, a point inside and the ids of the paths filling each (empty when only outlines enclose it).',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => ({ faces: controller.getShapeBuilderFaces({ ids: ids(params) }) })\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}shapeBuilder`,\n\t\t\tlabel: 'Shape Builder',\n\t\t\tkeywords: ['merge faces', 'build shape', 'combine regions', 'delete region'],\n\t\t\tdescription:\n\t\t\t\t'Shape Builder gesture over the faces of the given paths: `points` is the pointer path in document units (one point is a click; [[x, y], …]; use the points from shapeBuilderFaces). Merges the faces it touches into one shape, or with `erase: true` deletes them, the pieces of unfilled open paths and the edges of other outlines (cut where paths meet) within `tolerance`; a deleted edge opens its path there, and edges bounding a deleted face go with it. Shapes covering those faces lose that area. Returns the counts of faces, line pieces and edges.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: { points: POINTS, erase: { type: 'boolean' }, tolerance: { type: 'number', minimum: 0 }, ids: IDS },\n\t\t\t\trequired: ['points']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { points: [number, number][]; erase?: boolean; tolerance?: number; ids?: string[] }) => {\n\t\t\t\tconst result = controller.shapeBuilder(params.points.map(([x, y]) => ({ x, y })), { ids: ids(params), erase: params.erase, tolerance: params.tolerance });\n\t\t\t\tcheck(result);\n\t\t\t\treturn { merged: result.merged, faces: result.faces, lines: result.lines, edges: result.edges };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}fillRegion`,\n\t\t\tlabel: 'Fill Region',\n\t\t\tkeywords: ['paint bucket', 'live paint', 'fill area', 'enclosed'],\n\t\t\tdescription:\n\t\t\t\t'Paint bucket: fills the area the visible outlines enclose around `point` (crossings split, nested shapes left as holes) with a new path in the current fill, below the selection or on top. `gap` closes gaps up to that size between loose ends.',\n\t\t\tparams: { type: 'object', properties: { point: { type: 'array', items: { type: 'number' }, minItems: 2, maxItems: 2, description: '[x, y] in document units.' }, gap: { type: 'number', minimum: 0 } }, required: ['point'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { point: [number, number]; gap?: number }) => {\n\t\t\t\tconst id = controller.fillRegion({ x: params.point[0], y: params.point[1] }, { gap: params.gap });\n\t\t\t\tif (!id) fail('No closed region surrounds that point.');\n\t\t\t\treturn { id };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}align`,\n\t\t\tlabel: 'Align…',\n\t\t\tkeywords: ['left', 'right', 'center', 'top', 'bottom', 'middle'],\n\t\t\tdescription: 'Aligns nodes to their combined bounds, or to the artboard (`to: \"artboard\"`, or when only one node is given).',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: { edge: { type: 'string', enum: ['left', 'center', 'right', 'top', 'middle', 'bottom'] }, to: { type: 'string', enum: ['selection', 'artboard'] }, ids: IDS },\n\t\t\t\trequired: ['edge']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { edge: VectorAlign; to?: 'selection' | 'artboard'; ids?: string[] }) => {\n\t\t\t\tcheck(controller.align(params.edge, { ids: ids(params), to: params.to }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}distribute`,\n\t\t\tlabel: 'Distribute…',\n\t\t\tkeywords: ['space', 'evenly', 'gaps'],\n\t\t\tdescription: 'Spaces three or more nodes with equal gaps.',\n\t\t\tparams: { type: 'object', properties: { direction: { type: 'string', enum: ['horizontal', 'vertical'] }, ids: IDS }, required: ['direction'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { direction: 'horizontal' | 'vertical'; ids?: string[] }) => {\n\t\t\t\tcheck(controller.distribute(params.direction, { ids: ids(params) }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}arrange`,\n\t\t\tlabel: 'Arrange…',\n\t\t\tkeywords: ['order', 'front', 'back', 'forward', 'backward', 'z-index', 'stack'],\n\t\t\tdescription: 'Changes stacking order within each node’s parent.',\n\t\t\tparams: { type: 'object', properties: { order: { type: 'string', enum: ['front', 'forward', 'backward', 'back'] }, ids: IDS }, required: ['order'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { order: VectorArrange; ids?: string[] }) => {\n\t\t\t\tcheck(controller.arrange(params.order, { ids: ids(params) }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}group`,\n\t\t\tlabel: 'Group',\n\t\t\tshortcut: 'Mod+G',\n\t\t\tdescription: 'Groups nodes that share a parent.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, name: { type: 'string' } } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; name?: string } | undefined) => {\n\t\t\t\tconst id = controller.group({ ids: ids(params), name: params?.name });\n\t\t\t\tif (!id) fail('Only nodes that share a parent can be grouped.');\n\t\t\t\treturn { id };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}ungroup`,\n\t\t\tlabel: 'Ungroup',\n\t\t\tshortcut: 'Mod+Shift+G',\n\t\t\tdescription: 'Replaces groups with their children.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[] } | undefined) => {\n\t\t\t\tcheck(controller.ungroup({ ids: ids(params) }));\n\t\t\t\treturn { selection: controller.getState().selection };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}deleteAnchors`,\n\t\t\tlabel: 'Delete Points',\n\t\t\tkeywords: ['remove', 'anchor', 'point', 'node'],\n\t\t\tdescription:\n\t\t\t\t'Deletes anchors. With `keepShape` (default: the editor setting, on) the neighbouring handles are refitted so the outline keeps its shape; off, the neighbours are joined as they are.',\n\t\t\tparams: { type: 'object', properties: { anchors: ANCHORS, keepShape: { type: 'boolean' } } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { anchors?: VectorAnchorRef[]; keepShape?: boolean } | undefined) => {\n\t\t\t\tcheck(controller.deleteAnchors(anchorsOf(params?.anchors), { keepShape: params?.keepShape }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}moveAnchor`,\n\t\t\tlabel: 'Move Point…',\n\t\t\tkeywords: ['anchor', 'drag', 'curvature'],\n\t\t\tdescription: 'Moves one anchor to (x, y) in document units. `curvature: true` bends its two segments like the Curvature tool instead of carrying its handles along.',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: { nodeId: { type: 'string' }, subpath: { type: 'integer', minimum: 0 }, index: { type: 'integer', minimum: 0 }, x: { type: 'number' }, y: { type: 'number' }, curvature: { type: 'boolean' } },\n\t\t\t\trequired: ['nodeId', 'subpath', 'index', 'x', 'y']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: VectorAnchorRef & { x: number; y: number; curvature?: boolean }) => {\n\t\t\t\tcheck(controller.moveAnchor({ nodeId: params.nodeId, subpath: params.subpath, index: params.index }, { x: params.x, y: params.y }, { curvature: params.curvature }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}bendSegment`,\n\t\t\tlabel: 'Bend Segment…',\n\t\t\tkeywords: ['curve', 'segment', 'drag'],\n\t\t\tdescription: 'Bends segment `segment` (from anchor `segment` to the next) so the curve passes through (x, y) at parameter `t` (default 0.5).',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tnodeId: { type: 'string' },\n\t\t\t\t\tsubpath: { type: 'integer', minimum: 0 },\n\t\t\t\t\tsegment: { type: 'integer', minimum: 0 },\n\t\t\t\t\tx: { type: 'number' },\n\t\t\t\t\ty: { type: 'number' },\n\t\t\t\t\tt: { type: 'number', minimum: 0, maximum: 1 }\n\t\t\t\t},\n\t\t\t\trequired: ['nodeId', 'subpath', 'segment', 'x', 'y']\n\t\t\t},\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { nodeId: string; subpath: number; segment: number; x: number; y: number; t?: number }) => {\n\t\t\t\tcheck(controller.bendSegment({ nodeId: params.nodeId, subpath: params.subpath, segment: params.segment }, { x: params.x, y: params.y }, params.t));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}join`,\n\t\t\tlabel: 'Join',\n\t\t\tshortcut: 'Mod+J',\n\t\t\tkeywords: ['connect', 'close', 'merge', 'endpoints'],\n\t\t\tdescription: 'Joins the open subpaths of paths nearest endpoints first (ends within `tolerance` merge); a single open path is closed.',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, tolerance: { type: 'number', minimum: 0 } } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; tolerance?: number } | undefined) => {\n\t\t\t\tcheck(controller.joinPaths({ ids: params?.ids ? ids(params) : undefined, tolerance: params?.tolerance }));\n\t\t\t\treturn { selection: controller.getState().selection };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}average`,\n\t\t\tlabel: 'Average Points…',\n\t\t\tshortcut: 'Mod+Alt+J',\n\t\t\tkeywords: ['align', 'points', 'anchors', 'collapse'],\n\t\t\tdescription: 'Moves anchors onto their average position: the same y (`horizontal`), the same x (`vertical`) or the same point (`both`, default).',\n\t\t\tparams: { type: 'object', properties: { axis: { type: 'string', enum: ['horizontal', 'vertical', 'both'] }, anchors: ANCHORS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { axis?: VectorAverageAxis; anchors?: VectorAnchorRef[] } | undefined) => {\n\t\t\t\tcheck(controller.averageAnchors(params?.axis ?? 'both', anchorsOf(params?.anchors)));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}removeRedundantPoints`,\n\t\t\tlabel: 'Remove Redundant Points',\n\t\t\tkeywords: ['simplify', 'clean up', 'anchors', 'collinear'],\n\t\t\tdescription: 'Drops anchors that can go without moving the outline more than `tolerance` document units (default 0.5).',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, tolerance: { type: 'number', minimum: 0 } } },\n\t\t\tenabled: enabledFor,\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; tolerance?: number } | undefined) => {\n\t\t\t\tcheck(controller.removeRedundantPoints({ ids: params?.ids ? ids(params) : undefined, tolerance: params?.tolerance }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}smooth`,\n\t\t\tlabel: 'Smooth Path',\n\t\t\tkeywords: ['round', 'soften', 'handles', 'curves'],\n\t\t\tdescription: 'Pulls the handles of paths (or of the selected points) towards smooth tangents by `amount` (0–1, default 1).',\n\t\t\tparams: { type: 'object', properties: { ids: IDS, amount: { type: 'number', minimum: 0, maximum: 1 }, anchors: ANCHORS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { ids?: string[]; amount?: number; anchors?: VectorAnchorRef[] } | undefined) => {\n\t\t\t\tcheck(controller.smoothPaths({ ids: params?.ids ? ids(params) : undefined, amount: params?.amount, refs: params?.anchors }));\n\t\t\t\treturn { ok: true };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}cut`,\n\t\t\tlabel: 'Cut Path (Scissors)…',\n\t\t\tkeywords: ['scissors', 'split', 'open', 'break'],\n\t\t\tdescription: 'Scissors: cuts path `nodeId` at the outline point nearest (x, y), or cuts at `anchors`. A closed path opens; an open one splits in two.',\n\t\t\tparams: { type: 'object', properties: { nodeId: { type: 'string' }, x: { type: 'number' }, y: { type: 'number' }, anchors: ANCHORS } },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { nodeId?: string; x?: number; y?: number; anchors?: VectorAnchorRef[] } | undefined) => {\n\t\t\t\tif (params?.nodeId !== undefined) {\n\t\t\t\t\tif (!controller.getNode(params.nodeId)) fail(`There is no node \"${params.nodeId}\".`);\n\t\t\t\t\tif (params.x === undefined || params.y === undefined) fail('Pass x and y with nodeId.');\n\t\t\t\t\tconst created = controller.cutPathAt(params.nodeId, { x: params.x!, y: params.y! });\n\t\t\t\t\tif (!created) fail('Nothing to cut there (the end of an open path, or a locked path).');\n\t\t\t\t\treturn { ids: created };\n\t\t\t\t}\n\t\t\t\tcheck(controller.cutAtAnchors(anchorsOf(params?.anchors)));\n\t\t\t\treturn { ids: controller.getState().selection };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}knife`,\n\t\t\tlabel: 'Knife…',\n\t\t\tkeywords: ['slice', 'cut', 'split', 'divide'],\n\t\t\tdescription: 'Cuts closed paths along a polyline wherever it crosses them edge to edge (no gap between pieces). Cuts `ids`, else the selection, else every path the line crosses.',\n\t\t\tparams: { type: 'object', properties: { points: { ...POINTS, minItems: 2 }, ids: IDS }, required: ['points'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { points: [number, number][]; ids?: string[] }) => {\n\t\t\t\tconst created = controller.knife(params.points.map(([x, y]) => ({ x, y })), { ids: params.ids ? ids(params) : undefined });\n\t\t\t\tif (!created.length) fail('The knife did not cross any closed path from edge to edge.');\n\t\t\t\treturn { ids: created };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}erase`,\n\t\t\tlabel: 'Erase…',\n\t\t\tkeywords: ['eraser', 'rub out', 'remove'],\n\t\t\tdescription:\n\t\t\t\t'Erases a round stroke of diameter `size` (default: the eraser size setting) along a polyline: filled shapes lose the area, outlines are cut under it. Erases from `ids`, else the selection, else every path it reaches.',\n\t\t\tparams: { type: 'object', properties: { points: POINTS, size: { type: 'number', exclusiveMinimum: 0 }, ids: IDS }, required: ['points'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { points: [number, number][]; size?: number; ids?: string[] }) => {\n\t\t\t\tconst changed = controller.erase(params.points.map(([x, y]) => ({ x, y })), { size: params.size, ids: params.ids ? ids(params) : undefined });\n\t\t\t\tif (!changed.length) fail('The eraser did not touch any path.');\n\t\t\t\treturn { ids: changed.filter((id) => controller.getNode(id)) };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setEditing`,\n\t\t\tlabel: 'Path Editing Options…',\n\t\t\tkeywords: ['settings', 'curvature', 'pencil', 'smoothing', 'lazy mouse', 'shapes', 'eraser'],\n\t\t\tdescription:\n\t\t\t\t'Sets how editing behaves: `keepShapeOnDelete`, `curvatureMoves` (anchor drags bend like the Curvature tool), `pencilSmoothing` (lazy mouse, 0–1), `recognizeShapes` (pencil scribbles become lines, rectangles, ellipses, polygons), `eraserSize` and `pencilPressure` (`pen`: record pen pressure on pencil strokes as a width profile, `all`: any pointer reporting pressure, `off`).',\n\t\t\tparams: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tkeepShapeOnDelete: { type: 'boolean' },\n\t\t\t\t\tcurvatureMoves: { type: 'boolean' },\n\t\t\t\t\tpencilSmoothing: { type: 'number', minimum: 0, maximum: 1 },\n\t\t\t\t\trecognizeShapes: { type: 'boolean' },\n\t\t\t\t\teraserSize: { type: 'number', exclusiveMinimum: 0 },\n\t\t\t\t\tpencilPressure: { type: 'string', enum: ['pen', 'all', 'off'] }\n\t\t\t\t}\n\t\t\t},\n\t\t\trun: (_ctx: unknown, params: Record<string, unknown> | undefined) => {\n\t\t\t\tconst patch: Record<string, unknown> = {};\n\t\t\t\tfor (const key of ['keepShapeOnDelete', 'curvatureMoves', 'pencilSmoothing', 'recognizeShapes', 'eraserSize', 'pencilPressure']) if (params?.[key] !== undefined) patch[key] = params[key];\n\t\t\t\tcontroller.setEditing(patch);\n\t\t\t\treturn { editing: controller.getState().editing };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}setTool`,\n\t\t\tlabel: 'Choose Tool…',\n\t\t\tkeywords: ['pen', 'pencil', 'select', 'rectangle', 'ellipse'],\n\t\t\tdescription: 'Switches the canvas tool.',\n\t\t\tparams: { type: 'object', properties: { tool: { type: 'string', enum: [...VECTOR_TOOLS] } }, required: ['tool'] },\n\t\t\trun: (_ctx: unknown, params: { tool: VectorTool }) => {\n\t\t\t\tcontroller.setTool(params.tool);\n\t\t\t\treturn { tool: params.tool };\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}exportSvg`,\n\t\t\tlabel: 'Export SVG',\n\t\t\treadOnly: true,\n\t\t\tkeywords: ['download', 'save', 'markup'],\n\t\t\tdescription: 'Returns the document as SVG markup.',\n\t\t\tparams: { type: 'object', properties: { precision: { type: 'integer', minimum: 0, maximum: 8 } } },\n\t\t\trun: (_ctx: unknown, params: { precision?: number } | undefined) => ({ svg: controller.toSvg({ precision: params?.precision }) })\n\t\t},\n\t\t{\n\t\t\t...base,\n\t\t\tid: `${prefix}importSvg`,\n\t\t\tlabel: 'Import SVG…',\n\t\t\tkeywords: ['open', 'load', 'paste', 'markup'],\n\t\t\tdescription: 'Adds the shapes of SVG markup on top of the document (or replaces it with `replace: true`).',\n\t\t\tparams: { type: 'object', properties: { svg: { type: 'string' }, replace: { type: 'boolean' } }, required: ['svg'] },\n\t\t\tundoable: true,\n\t\t\trun: (_ctx: unknown, params: { svg: string; replace?: boolean }) => {\n\t\t\t\tcheck(params.replace ? controller.loadSvg(params.svg) : controller.importSvg(params.svg));\n\t\t\t\treturn { nodes: controller.getState().document.nodes.length, selection: controller.getState().selection };\n\t\t\t}\n\t\t}\n\t];\n}\n"]}