@open-pencil/scene-graph 0.17.0-beta.5 → 0.17.0-beta.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/comments/schema.d.ts.map +1 -1
- package/dist/comments/schema.js +1 -0
- package/dist/comments/schema.js.map +1 -1
- package/dist/comments/threads.d.ts +2 -0
- package/dist/comments/threads.d.ts.map +1 -1
- package/dist/comments/threads.js +11 -5
- package/dist/comments/threads.js.map +1 -1
- package/dist/components/properties.d.ts.map +1 -1
- package/dist/components/properties.js +1 -1
- package/dist/components/properties.js.map +1 -1
- package/dist/constants.d.ts +12 -2
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +42 -1
- package/dist/constants.js.map +1 -1
- package/dist/copy.d.ts.map +1 -1
- package/dist/copy.js +3 -0
- package/dist/copy.js.map +1 -1
- package/dist/css/grid.d.ts.map +1 -1
- package/dist/css/grid.js +27 -3
- package/dist/css/grid.js.map +1 -1
- package/dist/css/index.d.ts +3 -3
- package/dist/css/index.js +3 -3
- package/dist/css/layout.d.ts +13 -1
- package/dist/css/layout.d.ts.map +1 -1
- package/dist/css/layout.js +26 -1
- package/dist/css/layout.js.map +1 -1
- package/dist/css/values.d.ts +18 -1
- package/dist/css/values.d.ts.map +1 -1
- package/dist/css/values.js +39 -1
- package/dist/css/values.js.map +1 -1
- package/dist/geometry.d.ts +6 -6
- package/dist/geometry.d.ts.map +1 -1
- package/dist/geometry.js +4 -20
- package/dist/geometry.js.map +1 -1
- package/dist/graph.d.ts +5 -2
- package/dist/graph.d.ts.map +1 -1
- package/dist/graph.js +16 -6
- package/dist/graph.js.map +1 -1
- package/dist/icons/glyph.d.ts.map +1 -1
- package/dist/icons/glyph.js +1 -1
- package/dist/icons/glyph.js.map +1 -1
- package/dist/ids.js +1 -1
- package/dist/ids.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/instances/index.d.ts +6 -1
- package/dist/instances/index.d.ts.map +1 -1
- package/dist/instances/index.js +20 -8
- package/dist/instances/index.js.map +1 -1
- package/dist/instances/swap.js +1 -1
- package/dist/instances/swap.js.map +1 -1
- package/dist/instances/sync.js +25 -1
- package/dist/instances/sync.js.map +1 -1
- package/dist/layout/index.d.ts +2 -1
- package/dist/layout/index.js +2 -1
- package/dist/layout/strokes.d.ts +10 -0
- package/dist/layout/strokes.d.ts.map +1 -0
- package/dist/layout/strokes.js +30 -0
- package/dist/layout/strokes.js.map +1 -0
- package/dist/node-defaults.d.ts.map +1 -1
- package/dist/node-defaults.js +49 -37
- package/dist/node-defaults.js.map +1 -1
- package/dist/outline/flatten.d.ts.map +1 -1
- package/dist/outline/flatten.js +2 -2
- package/dist/outline/flatten.js.map +1 -1
- package/dist/parse-path.d.ts +4 -1
- package/dist/parse-path.d.ts.map +1 -1
- package/dist/parse-path.js +15 -1
- package/dist/parse-path.js.map +1 -1
- package/dist/paths/index.d.ts +2 -2
- package/dist/paths/index.js +2 -2
- package/dist/paths/network.d.ts +26 -6
- package/dist/paths/network.d.ts.map +1 -1
- package/dist/paths/network.js +79 -13
- package/dist/paths/network.js.map +1 -1
- package/dist/paths/smooth-corners.d.ts.map +1 -1
- package/dist/paths/smooth-corners.js +1 -1
- package/dist/paths/smooth-corners.js.map +1 -1
- package/dist/primitives/index.d.ts +1 -7
- package/dist/primitives/index.d.ts.map +1 -1
- package/dist/shaders/model.d.ts.map +1 -1
- package/dist/shaders/model.js +1 -1
- package/dist/shaders/model.js.map +1 -1
- package/dist/shared-styles.d.ts.map +1 -1
- package/dist/shared-styles.js +2 -9
- package/dist/shared-styles.js.map +1 -1
- package/dist/strokes.d.ts +39 -0
- package/dist/strokes.d.ts.map +1 -0
- package/dist/strokes.js +104 -0
- package/dist/strokes.js.map +1 -0
- package/dist/text/index.d.ts +2 -1
- package/dist/text/index.js +2 -1
- package/dist/text/runs.d.ts +29 -0
- package/dist/text/runs.d.ts.map +1 -0
- package/dist/text/runs.js +72 -0
- package/dist/text/runs.js.map +1 -0
- package/dist/transfer/dependencies.d.ts.map +1 -1
- package/dist/transfer/dependencies.js +1 -1
- package/dist/transfer/dependencies.js.map +1 -1
- package/dist/types.d.ts +47 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/variables/resolution.d.ts.map +1 -1
- package/dist/variables/resolution.js +1 -1
- package/dist/variables/resolution.js.map +1 -1
- package/dist/vector-network.d.ts.map +1 -1
- package/dist/vector-network.js +2 -4
- package/dist/vector-network.js.map +1 -1
- package/package.json +10 -13
- package/src/comments/schema.ts +1 -0
- package/src/comments/threads.ts +13 -5
- package/src/components/properties.ts +2 -1
- package/src/constants.ts +25 -1
- package/src/copy.ts +3 -0
- package/src/css/grid.ts +31 -3
- package/src/css/index.ts +13 -2
- package/src/css/layout.ts +36 -0
- package/src/css/values.ts +49 -0
- package/src/geometry.ts +9 -27
- package/src/graph.ts +13 -6
- package/src/icons/glyph.ts +2 -1
- package/src/ids.ts +1 -1
- package/src/instances/index.ts +24 -9
- package/src/instances/swap.ts +2 -1
- package/src/instances/sync.ts +41 -0
- package/src/layout/index.ts +1 -0
- package/src/layout/strokes.ts +23 -0
- package/src/node-defaults.ts +48 -33
- package/src/outline/flatten.ts +2 -1
- package/src/parse-path.ts +14 -0
- package/src/paths/network.ts +90 -13
- package/src/paths/smooth-corners.ts +2 -1
- package/src/primitives/index.ts +0 -5
- package/src/shaders/model.ts +2 -1
- package/src/shared-styles.ts +3 -4
- package/src/strokes.ts +121 -0
- package/src/text/index.ts +1 -0
- package/src/text/runs.ts +80 -0
- package/src/transfer/dependencies.ts +2 -1
- package/src/types.ts +50 -0
- package/src/variables/resolution.ts +2 -1
- package/src/vector-network.ts +2 -4
- package/dist/arrays.d.ts +0 -17
- package/dist/arrays.d.ts.map +0 -1
- package/dist/arrays.js +0 -38
- package/dist/arrays.js.map +0 -1
- package/dist/random.d.ts +0 -7
- package/dist/random.d.ts.map +0 -1
- package/dist/random.js +0 -25
- package/dist/random.js.map +0 -1
- package/src/arrays.ts +0 -37
- package/src/random.ts +0 -28
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flatten.js","names":[],"sources":["../../src/outline/flatten.ts"],"sourcesContent":["import { appendAll } from '../arrays'\nimport { cubicPoint } from '../cubic'\nimport { GeometryCommand, readGeometryBlob } from '../geometry'\nimport { buildChains } from '../paths/network'\nimport type { PolygonOutlineCommand } from '../polygon'\nimport type { Vector } from '../primitives'\nimport type { VectorNetwork } from '../types'\n\n/**\n * Keeps a huge curve at a tiny tolerance from flattening into an unbounded number of points, while\n * leaving room for the largest arcs at the maximum zoom: a 100,000-unit circle at 25,600% needs\n * about 12,000 steps to stay within the click pad.\n */\nconst MAX_CURVE_STEPS = 65_536\n\n/**\n * Steps that keep a cubic's polyline within `tolerance` of it: equal steps in t stray at most\n * M / (8n²) from a curve whose second derivative is at most M, and for a cubic\n * M ≤ 6 · max(|p0 − 2p1 + p2|, |p1 − 2p2 + p3|).\n */\nfunction curveSteps(p0: Vector, p1: Vector, p2: Vector, p3: Vector, tolerance: number): number {\n const bend = Math.max(\n Math.hypot(p0.x - 2 * p1.x + p2.x, p0.y - 2 * p1.y + p2.y),\n Math.hypot(p1.x - 2 * p2.x + p3.x, p1.y - 2 * p2.y + p3.y)\n )\n const steps = Math.ceil(Math.sqrt((6 * bend) / (8 * tolerance)))\n return Math.min(MAX_CURVE_STEPS, Math.max(1, steps))\n}\n\n/** Points along a cubic after its start, within `tolerance` of it, ending on `p3`. */\nfunction cubicPoints(p0: Vector, p1: Vector, p2: Vector, p3: Vector, tolerance: number): Vector[] {\n const steps = curveSteps(p0, p1, p2, p3, tolerance)\n const points: Vector[] = []\n for (let step = 1; step <= steps; step++) points.push(cubicPoint(p0, p1, p2, p3, step / steps))\n return points\n}\n\n/** Points along a vector network segment, from its start to its end, in network coordinates. */\nexport function segmentPoints(\n network: VectorNetwork,\n index: number,\n tolerance: number\n): Vector[] | null {\n // `at` counts a negative index from the end and truncates a fraction; a loop naming either\n // refers to no segment.\n if (!Number.isInteger(index) || index < 0) return null\n const segment = network.segments.at(index)\n if (!segment || segment.start < 0 || segment.end < 0) return null\n const p0 = network.vertices.at(segment.start)\n const p3 = network.vertices.at(segment.end)\n if (!p0 || !p3) return null\n const { tangentStart: a, tangentEnd: b } = segment\n if (a.x === 0 && a.y === 0 && b.x === 0 && b.y === 0) return [p0, p3]\n const p1 = { x: p0.x + a.x, y: p0.y + a.y }\n const p2 = { x: p3.x + b.x, y: p3.y + b.y }\n return [p0, ...cubicPoints(p0, p1, p2, p3, tolerance)]\n}\n\n/**\n * A loop's points in the order it is walked. Segments in a loop can be stored either way round,\n * so each is followed from the vertex the previous one ended on.\n */\nexport function loopPoints(network: VectorNetwork, loop: number[], tolerance: number): Vector[] {\n const { segments } = network\n const first = segments.at(loop[0] ?? -1)\n const second = segments.at(loop[1] ?? -1)\n if (!first) return []\n // Walk the first segment toward the vertex it shares with the next one.\n const firstForward = !second || first.end === second.start || first.end === second.end\n let current = firstForward ? first.start : first.end\n const points: Vector[] = []\n for (const index of loop) {\n const segment = segments.at(index)\n const along = segmentPoints(network, index, tolerance)\n if (!segment || !along) continue\n const forward = segment.start === current\n appendAll(points, forward ? along : along.toReversed())\n current = forward ? segment.end : segment.start\n }\n return points\n}\n\n/**\n * The network's segments joined into runs, chained through the vertices they share as the canvas\n * draws an open network (`buildChains`), each run walked from its open end.\n */\nexport function segmentRuns(network: VectorNetwork, tolerance: number): Vector[][] {\n const runs: Vector[][] = []\n for (const chain of buildChains(network.segments)) {\n let current = chain.start\n let run: Vector[] = []\n for (const index of chain.segments) {\n const segment = network.segments[index]\n const forward = segment.start === current\n current = forward ? segment.end : segment.start\n const along = segmentPoints(network, index, tolerance)\n // A segment naming a missing vertex breaks the run: what follows starts a run of its own.\n if (!along) {\n if (run.length > 1) runs.push(run)\n run = []\n continue\n }\n const points = forward ? along : along.toReversed()\n appendAll(run, run.length > 0 ? points.slice(1) : points)\n }\n if (run.length > 1) runs.push(run)\n }\n return runs\n}\n\n/** The contours of a Figma geometry blob, curves flattened to within `tolerance`. */\nexport function blobContours(blob: Uint8Array, tolerance: number): Vector[][] {\n const contours: Vector[][] = []\n let contour: Vector[] = []\n const flush = () => {\n if (contour.length > 1) contours.push(contour)\n contour = []\n }\n readGeometryBlob(blob, (command, c) => {\n if (command === GeometryCommand.CLOSE) return flush()\n if (command === GeometryCommand.MOVE) {\n flush()\n contour.push({ x: c[0], y: c[1] })\n return\n }\n const end = { x: c[c.length - 2], y: c[c.length - 1] }\n const last = contour.at(-1)\n if (!last || command === GeometryCommand.LINE) {\n contour.push(end)\n } else if (command === GeometryCommand.QUAD) {\n // A quadratic as the cubic with the same curve.\n const q = { x: c[0], y: c[1] }\n const c1 = { x: last.x + (2 / 3) * (q.x - last.x), y: last.y + (2 / 3) * (q.y - last.y) }\n const c2 = { x: end.x + (2 / 3) * (q.x - end.x), y: end.y + (2 / 3) * (q.y - end.y) }\n appendAll(contour, cubicPoints(last, c1, c2, end, tolerance))\n } else {\n appendAll(\n contour,\n cubicPoints(last, { x: c[0], y: c[1] }, { x: c[2], y: c[3] }, end, tolerance)\n )\n }\n })\n flush()\n return contours\n}\n\n/** The contours of polygon outline commands, curves flattened to within `tolerance`. */\nexport function commandContours(\n commands: readonly PolygonOutlineCommand[],\n tolerance: number\n): Vector[][] {\n const contours: Vector[][] = []\n let contour: Vector[] = []\n for (const command of commands) {\n if (command.type === 'Z' || command.type === 'M') {\n if (contour.length > 1) contours.push(contour)\n contour = command.type === 'M' ? [{ x: command.x, y: command.y }] : []\n continue\n }\n const last = contour.at(-1) ?? { x: 0, y: 0 }\n if (command.type !== 'C') contour.push({ x: command.x, y: command.y })\n else\n appendAll(\n contour,\n cubicPoints(\n last,\n { x: command.x1, y: command.y1 },\n { x: command.x2, y: command.y2 },\n { x: command.x, y: command.y },\n tolerance\n )\n )\n }\n if (contour.length > 1) contours.push(contour)\n return contours\n}\n\n/** Points around an ellipse arc from `start` to `end` radians, at most `tolerance` off it. */\nexport function arcPoints(\n cx: number,\n cy: number,\n rx: number,\n ry: number,\n start: number,\n end: number,\n tolerance: number\n): Vector[] {\n const radius = Math.max(rx, ry)\n // A chord over angle θ strays r(1 − cos(θ/2)) from the arc.\n const step =\n radius > tolerance ? 2 * Math.acos(Math.max(-1, 1 - tolerance / radius)) : Math.PI / 2\n const steps = Math.min(\n MAX_CURVE_STEPS,\n Math.max(1, Math.ceil(Math.abs(end - start) / Math.max(step, 1e-3)))\n )\n const points: Vector[] = []\n for (let i = 0; i <= steps; i++) {\n const angle = start + ((end - start) * i) / steps\n points.push({ x: cx + rx * Math.cos(angle), y: cy + ry * Math.sin(angle) })\n }\n return points\n}\n"],"mappings":";;;;;;;;;;AAaA,MAAM,kBAAkB;;;;;;AAOxB,SAAS,WAAW,IAAY,IAAY,IAAY,IAAY,WAA2B;CAC7F,MAAM,OAAO,KAAK,IAChB,KAAK,MAAM,GAAG,IAAI,IAAI,GAAG,IAAI,GAAG,GAAG,GAAG,IAAI,IAAI,GAAG,IAAI,GAAG,CAAC,GACzD,KAAK,MAAM,GAAG,IAAI,IAAI,GAAG,IAAI,GAAG,GAAG,GAAG,IAAI,IAAI,GAAG,IAAI,GAAG,CAAC,CAC3D;CACA,MAAM,QAAQ,KAAK,KAAK,KAAK,KAAM,IAAI,QAAS,IAAI,UAAU,CAAC;CAC/D,OAAO,KAAK,IAAI,iBAAiB,KAAK,IAAI,GAAG,KAAK,CAAC;AACrD;;AAGA,SAAS,YAAY,IAAY,IAAY,IAAY,IAAY,WAA6B;CAChG,MAAM,QAAQ,WAAW,IAAI,IAAI,IAAI,IAAI,SAAS;CAClD,MAAM,SAAmB,CAAC;CAC1B,KAAK,IAAI,OAAO,GAAG,QAAQ,OAAO,QAAQ,OAAO,KAAK,WAAW,IAAI,IAAI,IAAI,IAAI,OAAO,KAAK,CAAC;CAC9F,OAAO;AACT;;AAGA,SAAgB,cACd,SACA,OACA,WACiB;CAGjB,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,G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;GAAG,GAAG,QAAQ;EAAE,GAC7B,SACF,CACF;CACJ;CACA,IAAI,QAAQ,SAAS,GAAG,SAAS,KAAK,OAAO;CAC7C,OAAO;AACT;;AAGA,SAAgB,UACd,IACA,IACA,IACA,IACA,OACA,KACA,WACU;CACV,MAAM,SAAS,KAAK,IAAI,IAAI,EAAE;CAE9B,MAAM,OACJ,SAAS,YAAY,IAAI,KAAK,KAAK,KAAK,IAAI,IAAI,IAAI,YAAY,MAAM,CAAC,IAAI,KAAK,KAAK;CACvF,MAAM,QAAQ,KAAK,IACjB,iBACA,KAAK,IAAI,GAAG,KAAK,KAAK,KAAK,IAAI,MAAM,KAAK,IAAI,KAAK,IAAI,MAAM,IAAI,CAAC,CAAC,CACrE;CACA,MAAM,SAAmB,CAAC;CAC1B,KAAK,IAAI,IAAI,GAAG,KAAK,OAAO,KAAK;EAC/B,MAAM,QAAQ,SAAU,MAAM,SAAS,IAAK;EAC5C,OAAO,KAAK;GAAE,GAAG,KAAK,KAAK,KAAK,IAAI,KAAK;GAAG,GAAG,KAAK,KAAK,KAAK,IAAI,KAAK;EAAE,CAAC;CAC5E;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"flatten.js","names":[],"sources":["../../src/outline/flatten.ts"],"sourcesContent":["import { appendAll } from '@open-pencil/std/arrays'\n\nimport { cubicPoint } from '../cubic'\nimport { GeometryCommand, readGeometryBlob } from '../geometry'\nimport { buildChains } from '../paths/network'\nimport type { PolygonOutlineCommand } from '../polygon'\nimport type { Vector } from '../primitives'\nimport type { VectorNetwork } from '../types'\n\n/**\n * Keeps a huge curve at a tiny tolerance from flattening into an unbounded number of points, while\n * leaving room for the largest arcs at the maximum zoom: a 100,000-unit circle at 25,600% needs\n * about 12,000 steps to stay within the click pad.\n */\nconst MAX_CURVE_STEPS = 65_536\n\n/**\n * Steps that keep a cubic's polyline within `tolerance` of it: equal steps in t stray at most\n * M / (8n²) from a curve whose second derivative is at most M, and for a cubic\n * M ≤ 6 · max(|p0 − 2p1 + p2|, |p1 − 2p2 + p3|).\n */\nfunction curveSteps(p0: Vector, p1: Vector, p2: Vector, p3: Vector, tolerance: number): number {\n const bend = Math.max(\n Math.hypot(p0.x - 2 * p1.x + p2.x, p0.y - 2 * p1.y + p2.y),\n Math.hypot(p1.x - 2 * p2.x + p3.x, p1.y - 2 * p2.y + p3.y)\n )\n const steps = Math.ceil(Math.sqrt((6 * bend) / (8 * tolerance)))\n return Math.min(MAX_CURVE_STEPS, Math.max(1, steps))\n}\n\n/** Points along a cubic after its start, within `tolerance` of it, ending on `p3`. */\nfunction cubicPoints(p0: Vector, p1: Vector, p2: Vector, p3: Vector, tolerance: number): Vector[] {\n const steps = curveSteps(p0, p1, p2, p3, tolerance)\n const points: Vector[] = []\n for (let step = 1; step <= steps; step++) points.push(cubicPoint(p0, p1, p2, p3, step / steps))\n return points\n}\n\n/** Points along a vector network segment, from its start to its end, in network coordinates. */\nexport function segmentPoints(\n network: VectorNetwork,\n index: number,\n tolerance: number\n): Vector[] | null {\n // `at` counts a negative index from the end and truncates a fraction; a loop naming either\n // refers to no segment.\n if (!Number.isInteger(index) || index < 0) return null\n const segment = network.segments.at(index)\n if (!segment || segment.start < 0 || segment.end < 0) return null\n const p0 = network.vertices.at(segment.start)\n const p3 = network.vertices.at(segment.end)\n if (!p0 || !p3) return null\n const { tangentStart: a, tangentEnd: b } = segment\n if (a.x === 0 && a.y === 0 && b.x === 0 && b.y === 0) return [p0, p3]\n const p1 = { x: p0.x + a.x, y: p0.y + a.y }\n const p2 = { x: p3.x + b.x, y: p3.y + b.y }\n return [p0, ...cubicPoints(p0, p1, p2, p3, tolerance)]\n}\n\n/**\n * A loop's points in the order it is walked. Segments in a loop can be stored either way round,\n * so each is followed from the vertex the previous one ended on.\n */\nexport function loopPoints(network: VectorNetwork, loop: number[], tolerance: number): Vector[] {\n const { segments } = network\n const first = segments.at(loop[0] ?? -1)\n const second = segments.at(loop[1] ?? -1)\n if (!first) return []\n // Walk the first segment toward the vertex it shares with the next one.\n const firstForward = !second || first.end === second.start || first.end === second.end\n let current = firstForward ? first.start : first.end\n const points: Vector[] = []\n for (const index of loop) {\n const segment = segments.at(index)\n const along = segmentPoints(network, index, tolerance)\n if (!segment || !along) continue\n const forward = segment.start === current\n appendAll(points, forward ? along : along.toReversed())\n current = forward ? segment.end : segment.start\n }\n return points\n}\n\n/**\n * The network's segments joined into runs, chained through the vertices they share as the canvas\n * draws an open network (`buildChains`), each run walked from its open end.\n */\nexport function segmentRuns(network: VectorNetwork, tolerance: number): Vector[][] {\n const runs: Vector[][] = []\n for (const chain of buildChains(network.segments)) {\n let current = chain.start\n let run: Vector[] = []\n for (const index of chain.segments) {\n const segment = network.segments[index]\n const forward = segment.start === current\n current = forward ? segment.end : segment.start\n const along = segmentPoints(network, index, tolerance)\n // A segment naming a missing vertex breaks the run: what follows starts a run of its own.\n if (!along) {\n if (run.length > 1) runs.push(run)\n run = []\n continue\n }\n const points = forward ? along : along.toReversed()\n appendAll(run, run.length > 0 ? points.slice(1) : points)\n }\n if (run.length > 1) runs.push(run)\n }\n return runs\n}\n\n/** The contours of a Figma geometry blob, curves flattened to within `tolerance`. */\nexport function blobContours(blob: Uint8Array, tolerance: number): Vector[][] {\n const contours: Vector[][] = []\n let contour: Vector[] = []\n const flush = () => {\n if (contour.length > 1) contours.push(contour)\n contour = []\n }\n readGeometryBlob(blob, (command, c) => {\n if (command === GeometryCommand.CLOSE) return flush()\n if (command === GeometryCommand.MOVE) {\n flush()\n contour.push({ x: c[0], y: c[1] })\n return\n }\n const end = { x: c[c.length - 2], y: c[c.length - 1] }\n const last = contour.at(-1)\n if (!last || command === GeometryCommand.LINE) {\n contour.push(end)\n } else if (command === GeometryCommand.QUAD) {\n // A quadratic as the cubic with the same curve.\n const q = { x: c[0], y: c[1] }\n const c1 = { x: last.x + (2 / 3) * (q.x - last.x), y: last.y + (2 / 3) * (q.y - last.y) }\n const c2 = { x: end.x + (2 / 3) * (q.x - end.x), y: end.y + (2 / 3) * (q.y - end.y) }\n appendAll(contour, cubicPoints(last, c1, c2, end, tolerance))\n } else {\n appendAll(\n contour,\n cubicPoints(last, { x: c[0], y: c[1] }, { x: c[2], y: c[3] }, end, tolerance)\n )\n }\n })\n flush()\n return contours\n}\n\n/** The contours of polygon outline commands, curves flattened to within `tolerance`. */\nexport function commandContours(\n commands: readonly PolygonOutlineCommand[],\n tolerance: number\n): Vector[][] {\n const contours: Vector[][] = []\n let contour: Vector[] = []\n for (const command of commands) {\n if (command.type === 'Z' || command.type === 'M') {\n if (contour.length > 1) contours.push(contour)\n contour = command.type === 'M' ? [{ x: command.x, y: command.y }] : []\n continue\n }\n const last = contour.at(-1) ?? { x: 0, y: 0 }\n if (command.type !== 'C') contour.push({ x: command.x, y: command.y })\n else\n appendAll(\n contour,\n cubicPoints(\n last,\n { x: command.x1, y: command.y1 },\n { x: command.x2, y: command.y2 },\n { x: command.x, y: command.y },\n tolerance\n )\n )\n }\n if (contour.length > 1) contours.push(contour)\n return contours\n}\n\n/** Points around an ellipse arc from `start` to `end` radians, at most `tolerance` off it. */\nexport function arcPoints(\n cx: number,\n cy: number,\n rx: number,\n ry: number,\n start: number,\n end: number,\n tolerance: number\n): Vector[] {\n const radius = Math.max(rx, ry)\n // A chord over angle θ strays r(1 − cos(θ/2)) from the arc.\n const step =\n radius > tolerance ? 2 * Math.acos(Math.max(-1, 1 - tolerance / radius)) : Math.PI / 2\n const steps = Math.min(\n MAX_CURVE_STEPS,\n Math.max(1, Math.ceil(Math.abs(end - start) / Math.max(step, 1e-3)))\n )\n const points: Vector[] = []\n for (let i = 0; i <= steps; i++) {\n const angle = start + ((end - start) * i) / steps\n points.push({ x: cx + rx * Math.cos(angle), y: cy + ry * Math.sin(angle) })\n }\n return points\n}\n"],"mappings":";;;;;;;;;;AAcA,MAAM,kBAAkB;;;;;;AAOxB,SAAS,WAAW,IAAY,IAAY,IAAY,IAAY,WAA2B;CAC7F,MAAM,OAAO,KAAK,IAChB,KAAK,MAAM,GAAG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AAU,MAAM,SAAS,IAAK;EAC5C,OAAO,KAAK;GAAE,GAAG,KAAK,KAAK,KAAK,IAAI,KAAK;GAAG,GAAG,KAAK,KAAK,KAAK,IAAI,KAAK;EAAE,CAAC;CAC5E;CACA,OAAO;AACT"}
|
package/dist/parse-path.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Rect } from "./primitives/index.js";
|
|
1
2
|
import { VectorNetwork, WindingRule } from "./types.js";
|
|
2
3
|
//#region src/parse-path.d.ts
|
|
3
4
|
type VectorPathWindingRule = WindingRule | 'NONE';
|
|
@@ -31,6 +32,8 @@ declare function parseSVGPathData(d: string, windingRule: WindingRule, options:
|
|
|
31
32
|
}): SVGPathParseResult;
|
|
32
33
|
/** Parse the strict absolute command subset accepted by Figma's VectorPath API. */
|
|
33
34
|
declare function parsePluginVectorPath(d: string, windingRule: VectorPathWindingRule): SVGPathParseResult;
|
|
35
|
+
/** A `viewBox` value as a rect, or null when it is malformed or does not establish a viewport. */
|
|
36
|
+
declare function parseSVGViewBoxValue(value: string | null | undefined): Rect | null;
|
|
34
37
|
//#endregion
|
|
35
|
-
export { SVGPathParseResult, VectorPathWindingRule, parsePluginVectorPath, parseSVGPath, parseSVGPathData };
|
|
38
|
+
export { SVGPathParseResult, VectorPathWindingRule, parsePluginVectorPath, parseSVGPath, parseSVGPathData, parseSVGViewBoxValue };
|
|
36
39
|
//# sourceMappingURL=parse-path.d.ts.map
|
package/dist/parse-path.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parse-path.d.ts","names":[],"sources":["../src/parse-path.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"parse-path.d.ts","names":[],"sources":["../src/parse-path.ts"],"mappings":";;;KAWY,wBAAwB;KAIxB;EAAuB;EAAU,SAAS;;EAAoB;EAAW;;;;;;;;;;;;iBAiBrE,aACd,WACA,cAAa,aACb;EAAW;IACV;;;;;;iBAaa,iBACd,WACA,aAAa,aACb;EAAW;IACV;;iBAKa,sBACd,WACA,aAAa,wBACZ;;iBA0La,qBAAqB,mCAAmC"}
|
package/dist/parse-path.js
CHANGED
|
@@ -194,7 +194,21 @@ function parsePath(d, windingRule, options) {
|
|
|
194
194
|
}
|
|
195
195
|
};
|
|
196
196
|
}
|
|
197
|
+
/** A `viewBox` value as a rect, or null when it is malformed or does not establish a viewport. */
|
|
198
|
+
function parseSVGViewBoxValue(value) {
|
|
199
|
+
if (!value) return null;
|
|
200
|
+
const values = value.trim().split(/[\s,]+/).map(Number);
|
|
201
|
+
if (values.length !== 4 || values.some((entry) => !Number.isFinite(entry))) return null;
|
|
202
|
+
const [x = 0, y = 0, width = 0, height = 0] = values;
|
|
203
|
+
if (width <= 0 || height <= 0) return null;
|
|
204
|
+
return {
|
|
205
|
+
x,
|
|
206
|
+
y,
|
|
207
|
+
width,
|
|
208
|
+
height
|
|
209
|
+
};
|
|
210
|
+
}
|
|
197
211
|
//#endregion
|
|
198
|
-
export { parsePluginVectorPath, parseSVGPath, parseSVGPathData };
|
|
212
|
+
export { parsePluginVectorPath, parseSVGPath, parseSVGPathData, parseSVGViewBoxValue };
|
|
199
213
|
|
|
200
214
|
//# sourceMappingURL=parse-path.js.map
|
package/dist/parse-path.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parse-path.js","names":[],"sources":["../src/parse-path.ts"],"sourcesContent":["import svgpath from 'svgpath'\n\nimport type { VectorNetwork, VectorVertex, VectorSegment, VectorRegion, WindingRule } from './types'\n\ninterface SubPath {\n startVertexIndex: number\n segmentIndices: number[]\n closed: boolean\n}\n\nexport type VectorPathWindingRule = WindingRule | 'NONE'\n\n/** How far apart an end and its subpath's start can be from rounding alone. */\nconst CLOSING_ROUNDING = 1e-6\nexport type SVGPathParseResult = { ok: true; network: VectorNetwork } | { ok: false; error: string }\n\ninterface ParseOptions {\n includeOpenRegions: boolean\n strictCommands: boolean\n}\n\n/**\n * Parse an SVG path `d` attribute into a VectorNetwork.\n *\n * Uses `svgpath` to normalize all commands to absolute M/L/C/Z\n * (arcs → cubics via `.unarc()`, smooth curves → explicit via `.unshort()`).\n *\n * Only closed subpaths form the fill region unless `includeOpenRegions` is set. SVG fills every\n * subpath as if it were closed, so set it for a filled path to keep holes that an open subpath and\n * a closed one cut together under the path's fill rule.\n */\nexport function parseSVGPath(\n d: string,\n windingRule: WindingRule = 'NONZERO',\n options: { includeOpenRegions?: boolean } = {}\n): VectorNetwork {\n const parsed = parsePath(d, windingRule, {\n includeOpenRegions: options.includeOpenRegions ?? false,\n strictCommands: false\n })\n return parsed.ok ? parsed.network : { vertices: [], segments: [], regions: [] }\n}\n\n/**\n * Parse a `d` with any command SVG has, its closed subpaths filled under `windingRule` and, with\n * `includeOpenRegions`, its open ones too, as SVG fills them. Unlike `parseSVGPath`, a path that\n * does not parse says why.\n */\nexport function parseSVGPathData(\n d: string,\n windingRule: WindingRule,\n options: { includeOpenRegions: boolean }\n): SVGPathParseResult {\n return parsePath(d, windingRule, { ...options, strictCommands: false })\n}\n\n/** Parse the strict absolute command subset accepted by Figma's VectorPath API. */\nexport function parsePluginVectorPath(\n d: string,\n windingRule: VectorPathWindingRule\n): SVGPathParseResult {\n return parsePath(d, windingRule, {\n includeOpenRegions: windingRule !== 'NONE',\n strictCommands: true\n })\n}\n\nfunction parsePath(\n d: string,\n windingRule: VectorPathWindingRule,\n options: ParseOptions\n): SVGPathParseResult {\n const vertices: VectorVertex[] = []\n const segments: VectorSegment[] = []\n const subPaths: SubPath[] = []\n\n let currentSubPath: SubPath | null = null\n let cx = 0\n let cy = 0\n\n const vertexMap = new Map<string, number>()\n /** How many segment ends sit on each vertex. */\n const uses: number[] = []\n\n function getOrCreateVertex(x: number, y: number): number {\n const key = `${x},${y}`\n const existing = vertexMap.get(key)\n if (existing !== undefined) return existing\n const idx = vertices.length\n vertices.push({ x, y })\n vertexMap.set(key, idx)\n return idx\n }\n\n function addSegment(\n x1: number,\n y1: number,\n x2: number,\n y2: number,\n tx1: number,\n ty1: number,\n tx2: number,\n ty2: number\n ): void {\n const startIdx = getOrCreateVertex(x1, y1)\n const endIdx = getOrCreateVertex(x2, y2)\n uses[startIdx] = (uses[startIdx] ?? 0) + 1\n uses[endIdx] = (uses[endIdx] ?? 0) + 1\n const segIdx = segments.length\n segments.push({\n start: startIdx,\n end: endIdx,\n tangentStart: { x: tx1 - x1, y: ty1 - y1 },\n tangentEnd: { x: tx2 - x2, y: ty2 - y2 }\n })\n if (currentSubPath) {\n currentSubPath.segmentIndices.push(segIdx)\n }\n }\n\n function addLine(x1: number, y1: number, x2: number, y2: number): void {\n addSegment(x1, y1, x2, y2, x1, y1, x2, y2)\n }\n\n function addCubic(\n x1: number,\n y1: number,\n cp1x: number,\n cp1y: number,\n cp2x: number,\n cp2y: number,\n x2: number,\n y2: number\n ): void {\n addSegment(x1, y1, x2, y2, cp1x, cp1y, cp2x, cp2y)\n }\n\n /**\n * A subpath that ends a hair off its start, as an arc turned into curves does, ends on the start\n * vertex, as Figma merges them; the point it ended on goes when no other segment uses it.\n */\n function closeOnStart(subPath: SubPath): void {\n const lastIndex = subPath.segmentIndices.at(-1)\n if (lastIndex === undefined) return\n const last = segments[lastIndex]\n if (last.end === subPath.startVertexIndex) return\n const stray = last.end\n last.end = subPath.startVertexIndex\n uses[subPath.startVertexIndex] += 1\n uses[stray] -= 1\n // Only the newest vertex can go without renumbering the others.\n if (uses[stray] > 0 || stray !== vertices.length - 1) return\n const point = vertices[stray]\n vertices.pop()\n uses.pop()\n vertexMap.delete(`${point.x},${point.y}`)\n }\n\n const parsed = svgpath(d)\n const parseError = 'err' in parsed && typeof parsed.err === 'string' ? parsed.err : null\n if (parseError) return { ok: false, error: parseError }\n if (options.strictCommands) {\n const unsupportedCommands = new Set<string>()\n parsed.iterate((segment) => {\n if (!['M', 'L', 'Q', 'C', 'Z'].includes(segment[0])) unsupportedCommands.add(segment[0])\n })\n const unsupportedCommand = unsupportedCommands.values().next().value\n if (unsupportedCommand !== undefined) {\n return { ok: false, error: `Unsupported path command ${unsupportedCommand}` }\n }\n }\n const normalized = parsed.abs().unshort().unarc()\n\n normalized.iterate((seg) => {\n const cmd = seg[0]\n\n if (cmd === 'M') {\n cx = seg[1]\n cy = seg[2]\n currentSubPath = {\n startVertexIndex: getOrCreateVertex(cx, cy),\n segmentIndices: [],\n closed: false\n }\n subPaths.push(currentSubPath)\n } else if (cmd === 'L') {\n addLine(cx, cy, seg[1], seg[2])\n cx = seg[1]\n cy = seg[2]\n } else if (cmd === 'H') {\n addLine(cx, cy, seg[1], cy)\n cx = seg[1]\n } else if (cmd === 'V') {\n addLine(cx, cy, cx, seg[1])\n cy = seg[1]\n } else if (cmd === 'C') {\n addCubic(cx, cy, seg[1], seg[2], seg[3], seg[4], seg[5], seg[6])\n cx = seg[5]\n cy = seg[6]\n } else if (cmd === 'Q') {\n const qx = seg[1]\n const qy = seg[2]\n const ex = seg[3]\n const ey = seg[4]\n const cp1x = cx + (2 / 3) * (qx - cx)\n const cp1y = cy + (2 / 3) * (qy - cy)\n const cp2x = ex + (2 / 3) * (qx - ex)\n const cp2y = ey + (2 / 3) * (qy - ey)\n addCubic(cx, cy, cp1x, cp1y, cp2x, cp2y, ex, ey)\n cx = ex\n cy = ey\n } else if (cmd === 'Z' || cmd === 'z') {\n if (currentSubPath) {\n const startVert = vertices[currentSubPath.startVertexIndex]\n // Only rounding, such as an arc turned into curves leaves, merges an end into the start;\n // a point the path drew, however close, keeps its own closing segment.\n const rounding =\n Math.abs(cx - startVert.x) <= CLOSING_ROUNDING &&\n Math.abs(cy - startVert.y) <= CLOSING_ROUNDING\n if (rounding) closeOnStart(currentSubPath)\n else addLine(cx, cy, startVert.x, startVert.y)\n currentSubPath.closed = true\n cx = startVert.x\n cy = startVert.y\n }\n }\n })\n\n const regions: VectorRegion[] = []\n const regionPaths = subPaths.filter(\n (subPath) =>\n windingRule !== 'NONE' &&\n subPath.segmentIndices.length > 0 &&\n (subPath.closed || options.includeOpenRegions)\n )\n if (regionPaths.length > 0 && windingRule !== 'NONE') {\n regions.push({\n windingRule,\n loops: regionPaths.map((subPath) => subPath.segmentIndices)\n })\n }\n\n return { ok: true, network: { vertices, segments, regions } }\n}\n"],"mappings":";;;AAaA,MAAM,mBAAmB;;;;;;;;;;;AAkBzB,SAAgB,aACd,GACA,cAA2B,WAC3B,UAA4C,CAAC,GAC9B;CACf,MAAM,SAAS,UAAU,GAAG,aAAa;EACvC,oBAAoB,QAAQ,sBAAsB;EAClD,gBAAgB;CAClB,CAAC;CACD,OAAO,OAAO,KAAK,OAAO,UAAU;EAAE,UAAU,CAAC;EAAG,UAAU,CAAC;EAAG,SAAS,CAAC;CAAE;AAChF;;;;;;AAOA,SAAgB,iBACd,GACA,aACA,SACoB;CACpB,OAAO,UAAU,GAAG,aAAa;EAAE,GAAG;EAAS,gBAAgB;CAAM,CAAC;AACxE;;AAGA,SAAgB,sBACd,GACA,aACoB;CACpB,OAAO,UAAU,GAAG,aAAa;EAC/B,oBAAoB,gBAAgB;EACpC,gBAAgB;CAClB,CAAC;AACH;AAEA,SAAS,UACP,GACA,aACA,SACoB;CACpB,MAAM,WAA2B,CAAC;CAClC,MAAM,WAA4B,CAAC;CACnC,MAAM,WAAsB,CAAC;CAE7B,IAAI,iBAAiC;CACrC,IAAI,KAAK;CACT,IAAI,KAAK;CAET,MAAM,4BAAY,IAAI,IAAoB;;CAE1C,MAAM,OAAiB,CAAC;CAExB,SAAS,kBAAkB,GAAW,GAAmB;EACvD,MAAM,MAAM,GAAG,EAAE,GAAG;EACpB,MAAM,WAAW,UAAU,IAAI,GAAG;EAClC,IAAI,aAAa,KAAA,GAAW,OAAO;EACnC,MAAM,MAAM,SAAS;EACrB,SAAS,KAAK;GAAE;GAAG;EAAE,CAAC;EACtB,UAAU,IAAI,KAAK,GAAG;EACtB,OAAO;CACT;CAEA,SAAS,WACP,IACA,IACA,IACA,IACA,KACA,KACA,KACA,KACM;EACN,MAAM,WAAW,kBAAkB,IAAI,EAAE;EACz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AAM,IAAI,KAAM,KAAK;GAClC,MAAM,OAAO,KAAM,IAAI,KAAM,KAAK;GAClC,MAAM,OAAO,KAAM,IAAI,KAAM,KAAK;GAClC,SAAS,IAAI,IAAI,MAAM,MAAM,MAAM,MAAM,IAAI,EAAE;GAC/C,KAAK;GACL,KAAK;EACP,OAAO,IAAI,QAAQ,OAAO,QAAQ,KAC5B;OAAA,gBAAgB;IAClB,MAAM,YAAY,SAAS,eAAe;IAM1C,IAFE,KAAK,IAAI,KAAK,UAAU,CAAC,KAAK,oBAC9B,KAAK,IAAI,KAAK,UAAU,CAAC,KAAK,kBAClB,aAAa,cAAc;SACpC,QAAQ,IAAI,IAAI,UAAU,GAAG,UAAU,CAAC;IAC7C,eAAe,SAAS;IACxB,KAAK,UAAU;IACf,KAAK,UAAU;GACjB;;CAEJ,CAAC;CAED,MAAM,UAA0B,CAAC;CACjC,MAAM,cAAc,SAAS,QAC1B,YACC,gBAAgB,UAChB,QAAQ,eAAe,SAAS,MAC/B,QAAQ,UAAU,QAAQ,mBAC/B;CACA,IAAI,YAAY,SAAS,KAAK,gBAAgB,QAC5C,QAAQ,KAAK;EACX;EACA,OAAO,YAAY,KAAK,YAAY,QAAQ,cAAc;CAC5D,CAAC;CAGH,OAAO;EAAE,IAAI;EAAM,SAAS;GAAE;GAAU;GAAU;EAAQ;CAAE;AAC9D"}
|
|
1
|
+
{"version":3,"file":"parse-path.js","names":[],"sources":["../src/parse-path.ts"],"sourcesContent":["import svgpath from 'svgpath'\n\nimport type { Rect } from './primitives'\nimport type { VectorNetwork, VectorVertex, VectorSegment, VectorRegion, WindingRule } from './types'\n\ninterface SubPath {\n startVertexIndex: number\n segmentIndices: number[]\n closed: boolean\n}\n\nexport type VectorPathWindingRule = WindingRule | 'NONE'\n\n/** How far apart an end and its subpath's start can be from rounding alone. */\nconst CLOSING_ROUNDING = 1e-6\nexport type SVGPathParseResult = { ok: true; network: VectorNetwork } | { ok: false; error: string }\n\ninterface ParseOptions {\n includeOpenRegions: boolean\n strictCommands: boolean\n}\n\n/**\n * Parse an SVG path `d` attribute into a VectorNetwork.\n *\n * Uses `svgpath` to normalize all commands to absolute M/L/C/Z\n * (arcs → cubics via `.unarc()`, smooth curves → explicit via `.unshort()`).\n *\n * Only closed subpaths form the fill region unless `includeOpenRegions` is set. SVG fills every\n * subpath as if it were closed, so set it for a filled path to keep holes that an open subpath and\n * a closed one cut together under the path's fill rule.\n */\nexport function parseSVGPath(\n d: string,\n windingRule: WindingRule = 'NONZERO',\n options: { includeOpenRegions?: boolean } = {}\n): VectorNetwork {\n const parsed = parsePath(d, windingRule, {\n includeOpenRegions: options.includeOpenRegions ?? false,\n strictCommands: false\n })\n return parsed.ok ? parsed.network : { vertices: [], segments: [], regions: [] }\n}\n\n/**\n * Parse a `d` with any command SVG has, its closed subpaths filled under `windingRule` and, with\n * `includeOpenRegions`, its open ones too, as SVG fills them. Unlike `parseSVGPath`, a path that\n * does not parse says why.\n */\nexport function parseSVGPathData(\n d: string,\n windingRule: WindingRule,\n options: { includeOpenRegions: boolean }\n): SVGPathParseResult {\n return parsePath(d, windingRule, { ...options, strictCommands: false })\n}\n\n/** Parse the strict absolute command subset accepted by Figma's VectorPath API. */\nexport function parsePluginVectorPath(\n d: string,\n windingRule: VectorPathWindingRule\n): SVGPathParseResult {\n return parsePath(d, windingRule, {\n includeOpenRegions: windingRule !== 'NONE',\n strictCommands: true\n })\n}\n\nfunction parsePath(\n d: string,\n windingRule: VectorPathWindingRule,\n options: ParseOptions\n): SVGPathParseResult {\n const vertices: VectorVertex[] = []\n const segments: VectorSegment[] = []\n const subPaths: SubPath[] = []\n\n let currentSubPath: SubPath | null = null\n let cx = 0\n let cy = 0\n\n const vertexMap = new Map<string, number>()\n /** How many segment ends sit on each vertex. */\n const uses: number[] = []\n\n function getOrCreateVertex(x: number, y: number): number {\n const key = `${x},${y}`\n const existing = vertexMap.get(key)\n if (existing !== undefined) return existing\n const idx = vertices.length\n vertices.push({ x, y })\n vertexMap.set(key, idx)\n return idx\n }\n\n function addSegment(\n x1: number,\n y1: number,\n x2: number,\n y2: number,\n tx1: number,\n ty1: number,\n tx2: number,\n ty2: number\n ): void {\n const startIdx = getOrCreateVertex(x1, y1)\n const endIdx = getOrCreateVertex(x2, y2)\n uses[startIdx] = (uses[startIdx] ?? 0) + 1\n uses[endIdx] = (uses[endIdx] ?? 0) + 1\n const segIdx = segments.length\n segments.push({\n start: startIdx,\n end: endIdx,\n tangentStart: { x: tx1 - x1, y: ty1 - y1 },\n tangentEnd: { x: tx2 - x2, y: ty2 - y2 }\n })\n if (currentSubPath) {\n currentSubPath.segmentIndices.push(segIdx)\n }\n }\n\n function addLine(x1: number, y1: number, x2: number, y2: number): void {\n addSegment(x1, y1, x2, y2, x1, y1, x2, y2)\n }\n\n function addCubic(\n x1: number,\n y1: number,\n cp1x: number,\n cp1y: number,\n cp2x: number,\n cp2y: number,\n x2: number,\n y2: number\n ): void {\n addSegment(x1, y1, x2, y2, cp1x, cp1y, cp2x, cp2y)\n }\n\n /**\n * A subpath that ends a hair off its start, as an arc turned into curves does, ends on the start\n * vertex, as Figma merges them; the point it ended on goes when no other segment uses it.\n */\n function closeOnStart(subPath: SubPath): void {\n const lastIndex = subPath.segmentIndices.at(-1)\n if (lastIndex === undefined) return\n const last = segments[lastIndex]\n if (last.end === subPath.startVertexIndex) return\n const stray = last.end\n last.end = subPath.startVertexIndex\n uses[subPath.startVertexIndex] += 1\n uses[stray] -= 1\n // Only the newest vertex can go without renumbering the others.\n if (uses[stray] > 0 || stray !== vertices.length - 1) return\n const point = vertices[stray]\n vertices.pop()\n uses.pop()\n vertexMap.delete(`${point.x},${point.y}`)\n }\n\n const parsed = svgpath(d)\n const parseError = 'err' in parsed && typeof parsed.err === 'string' ? parsed.err : null\n if (parseError) return { ok: false, error: parseError }\n if (options.strictCommands) {\n const unsupportedCommands = new Set<string>()\n parsed.iterate((segment) => {\n if (!['M', 'L', 'Q', 'C', 'Z'].includes(segment[0])) unsupportedCommands.add(segment[0])\n })\n const unsupportedCommand = unsupportedCommands.values().next().value\n if (unsupportedCommand !== undefined) {\n return { ok: false, error: `Unsupported path command ${unsupportedCommand}` }\n }\n }\n const normalized = parsed.abs().unshort().unarc()\n\n normalized.iterate((seg) => {\n const cmd = seg[0]\n\n if (cmd === 'M') {\n cx = seg[1]\n cy = seg[2]\n currentSubPath = {\n startVertexIndex: getOrCreateVertex(cx, cy),\n segmentIndices: [],\n closed: false\n }\n subPaths.push(currentSubPath)\n } else if (cmd === 'L') {\n addLine(cx, cy, seg[1], seg[2])\n cx = seg[1]\n cy = seg[2]\n } else if (cmd === 'H') {\n addLine(cx, cy, seg[1], cy)\n cx = seg[1]\n } else if (cmd === 'V') {\n addLine(cx, cy, cx, seg[1])\n cy = seg[1]\n } else if (cmd === 'C') {\n addCubic(cx, cy, seg[1], seg[2], seg[3], seg[4], seg[5], seg[6])\n cx = seg[5]\n cy = seg[6]\n } else if (cmd === 'Q') {\n const qx = seg[1]\n const qy = seg[2]\n const ex = seg[3]\n const ey = seg[4]\n const cp1x = cx + (2 / 3) * (qx - cx)\n const cp1y = cy + (2 / 3) * (qy - cy)\n const cp2x = ex + (2 / 3) * (qx - ex)\n const cp2y = ey + (2 / 3) * (qy - ey)\n addCubic(cx, cy, cp1x, cp1y, cp2x, cp2y, ex, ey)\n cx = ex\n cy = ey\n } else if (cmd === 'Z' || cmd === 'z') {\n if (currentSubPath) {\n const startVert = vertices[currentSubPath.startVertexIndex]\n // Only rounding, such as an arc turned into curves leaves, merges an end into the start;\n // a point the path drew, however close, keeps its own closing segment.\n const rounding =\n Math.abs(cx - startVert.x) <= CLOSING_ROUNDING &&\n Math.abs(cy - startVert.y) <= CLOSING_ROUNDING\n if (rounding) closeOnStart(currentSubPath)\n else addLine(cx, cy, startVert.x, startVert.y)\n currentSubPath.closed = true\n cx = startVert.x\n cy = startVert.y\n }\n }\n })\n\n const regions: VectorRegion[] = []\n const regionPaths = subPaths.filter(\n (subPath) =>\n windingRule !== 'NONE' &&\n subPath.segmentIndices.length > 0 &&\n (subPath.closed || options.includeOpenRegions)\n )\n if (regionPaths.length > 0 && windingRule !== 'NONE') {\n regions.push({\n windingRule,\n loops: regionPaths.map((subPath) => subPath.segmentIndices)\n })\n }\n\n return { ok: true, network: { vertices, segments, regions } }\n}\n\n/** A `viewBox` value as a rect, or null when it is malformed or does not establish a viewport. */\nexport function parseSVGViewBoxValue(value: string | null | undefined): Rect | null {\n if (!value) return null\n const values = value\n .trim()\n .split(/[\\s,]+/)\n .map(Number)\n if (values.length !== 4 || values.some((entry) => !Number.isFinite(entry))) return null\n const [x = 0, y = 0, width = 0, height = 0] = values\n if (width <= 0 || height <= 0) return null\n return { x, y, width, height }\n}\n"],"mappings":";;;AAcA,MAAM,mBAAmB;;;;;;;;;;;AAkBzB,SAAgB,aACd,GACA,cAA2B,WAC3B,UAA4C,CAAC,GAC9B;CACf,MAAM,SAAS,UAAU,GAAG,aAAa;EACvC,oBAAoB,QAAQ,sBAAsB;EAClD,gBAAgB;CAClB,CAAC;CACD,OAAO,OAAO,KAAK,OAAO,UAAU;EAAE,UAAU,CAAC;EAAG,UAAU,CAAC;EAAG,SAAS,CAAC;CAAE;AAChF;;;;;;AAOA,SAAgB,iBACd,GACA,aACA,SACoB;CACpB,OAAO,UAAU,GAAG,aAAa;EAAE,GAAG;EAAS,gBAAgB;CAAM,CAAC;AACxE;;AAGA,SAAgB,sBACd,GACA,aACoB;CACpB,OAAO,UAAU,GAAG,aAAa;EAC/B,oBAAoB,gBAAgB;EACpC,gBAAgB;CAClB,CAAC;AACH;AAEA,SAAS,UACP,GACA,aACA,SACoB;CACpB,MAAM,WAA2B,CAAC;CAClC,MAAM,WAA4B,CAAC;CACnC,MAAM,WAAsB,CAAC;CAE7B,IAAI,iBAAiC;CACrC,IAAI,KAAK;CACT,IAAI,KAAK;CAET,MAAM,4BAAY,IAAI,IAAoB;;CAE1C,MAAM,OAAiB,CAAC;CAExB,SAAS,kBAAkB,GAAW,GAAmB;EACv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MACZ,KAAK,CAAC,CACN,MAAM,QAAQ,CAAC,CACf,IAAI,MAAM;CACb,IAAI,OAAO,WAAW,KAAK,OAAO,MAAM,UAAU,CAAC,OAAO,SAAS,KAAK,CAAC,GAAG,OAAO;CACnF,MAAM,CAAC,IAAI,GAAG,IAAI,GAAG,QAAQ,GAAG,SAAS,KAAK;CAC9C,IAAI,SAAS,KAAK,UAAU,GAAG,OAAO;CACtC,OAAO;EAAE;EAAG;EAAG;EAAO;CAAO;AAC/B"}
|
package/dist/paths/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ArcCentre, ArcOutline, ArcStep, ArcSweep, arcOutline, sweepsWholeEllipse } from "./arc.js";
|
|
2
2
|
import { PathSink, outlineSVGPath, replayOutline, roundCoordinate, svgPathSink } from "./sink.js";
|
|
3
|
-
import { Chain, StrokeRun, addLoopToPath, addOpenSegmentsToPath, addRegionToPath, addSegmentDirected, addStrokeRunToPath, buildChains, strokeRuns } from "./network.js";
|
|
3
|
+
import { Chain, RunContinuation, StrokeRun, addLoopToPath, addOpenSegmentsToPath, addRegionToPath, addSegmentDirected, addStrokeRunToPath, buildChains, joinedSegmentPairs, leavingDirection, segmentsByVertex, strokeRuns } from "./network.js";
|
|
4
4
|
import { SmoothCornerSink, SmoothRectNode, traceSmoothRect } from "./smooth-corners.js";
|
|
5
|
-
export { ArcCentre, ArcOutline, ArcStep, ArcSweep, Chain, PathSink, SmoothCornerSink, SmoothRectNode, StrokeRun, addLoopToPath, addOpenSegmentsToPath, addRegionToPath, addSegmentDirected, addStrokeRunToPath, arcOutline, buildChains, outlineSVGPath, replayOutline, roundCoordinate, strokeRuns, svgPathSink, sweepsWholeEllipse, traceSmoothRect };
|
|
5
|
+
export { ArcCentre, ArcOutline, ArcStep, ArcSweep, Chain, PathSink, RunContinuation, SmoothCornerSink, SmoothRectNode, StrokeRun, addLoopToPath, addOpenSegmentsToPath, addRegionToPath, addSegmentDirected, addStrokeRunToPath, arcOutline, buildChains, joinedSegmentPairs, leavingDirection, outlineSVGPath, replayOutline, roundCoordinate, segmentsByVertex, strokeRuns, svgPathSink, sweepsWholeEllipse, traceSmoothRect };
|
package/dist/paths/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import { addLoopToPath, addOpenSegmentsToPath, addRegionToPath, addSegmentDirected, addStrokeRunToPath, buildChains, joinedSegmentPairs, leavingDirection, segmentsByVertex, strokeRuns } from "./network.js";
|
|
1
2
|
import { arcOutline, sweepsWholeEllipse } from "./arc.js";
|
|
2
|
-
import { addLoopToPath, addOpenSegmentsToPath, addRegionToPath, addSegmentDirected, addStrokeRunToPath, buildChains, strokeRuns } from "./network.js";
|
|
3
3
|
import { outlineSVGPath, replayOutline, roundCoordinate, svgPathSink } from "./sink.js";
|
|
4
4
|
import { traceSmoothRect } from "./smooth-corners.js";
|
|
5
|
-
export { addLoopToPath, addOpenSegmentsToPath, addRegionToPath, addSegmentDirected, addStrokeRunToPath, arcOutline, buildChains, outlineSVGPath, replayOutline, roundCoordinate, strokeRuns, svgPathSink, sweepsWholeEllipse, traceSmoothRect };
|
|
5
|
+
export { addLoopToPath, addOpenSegmentsToPath, addRegionToPath, addSegmentDirected, addStrokeRunToPath, arcOutline, buildChains, joinedSegmentPairs, leavingDirection, outlineSVGPath, replayOutline, roundCoordinate, segmentsByVertex, strokeRuns, svgPathSink, sweepsWholeEllipse, traceSmoothRect };
|
package/dist/paths/network.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Vector } from "../primitives/index.js";
|
|
2
|
+
import { VectorNetwork, VectorRegion, VectorSegment, VectorVertex } from "../types.js";
|
|
2
3
|
import { PathSink } from "./sink.js";
|
|
3
4
|
//#region src/paths/network.d.ts
|
|
4
5
|
declare function addSegmentDirected(path: PathSink, seg: VectorSegment, vertices: VectorVertex[], forward: boolean): void;
|
|
@@ -30,14 +31,33 @@ interface StrokeRun {
|
|
|
30
31
|
/** Whether the run comes back to its start, joining there instead of taking caps. */
|
|
31
32
|
closed: boolean;
|
|
32
33
|
}
|
|
34
|
+
type RunContinuation = (vertex: number, from: number) => number | undefined;
|
|
33
35
|
/**
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
* caps. Runs stop at open ends and at junctions where three or more segments meet.
|
|
36
|
+
* The indices of the segments meeting at each vertex, in segment order; a segment from a vertex to
|
|
37
|
+
* itself is listed there once. `include` leaves out the segments it returns false for.
|
|
37
38
|
*/
|
|
38
|
-
declare function
|
|
39
|
+
declare function segmentsByVertex(segments: readonly VectorSegment[], include?: (index: number) => boolean): Map<number, number[]>;
|
|
40
|
+
/**
|
|
41
|
+
* The direction segment `index` leaves `vertex` in: along its handle there, or with that handle
|
|
42
|
+
* collapsed, toward the far end's control point, as a cubic leaves toward its next distinct
|
|
43
|
+
* control point; a straight segment leaves along its chord.
|
|
44
|
+
*/
|
|
45
|
+
declare function leavingDirection(network: Pick<VectorNetwork, 'vertices' | 'segments'>, index: number, vertex: number): Vector;
|
|
46
|
+
/**
|
|
47
|
+
* The pairs of segments a stroke may join at each vertex: the two at a vertex exactly two meet at,
|
|
48
|
+
* and with several regions, also each two region edges next to each other around a vertex,
|
|
49
|
+
* which region strokes join where the gap between them is unfilled, open segments aside.
|
|
50
|
+
*/
|
|
51
|
+
declare function joinedSegmentPairs(network: VectorNetwork): [vertex: number, a: number, b: number][];
|
|
52
|
+
/**
|
|
53
|
+
* Segments chained into runs as Figma strokes a network: by default a run passes through every
|
|
54
|
+
* vertex exactly two segments meet at, so its corners take the stroke's join and only its open
|
|
55
|
+
* ends take caps. Runs stop at open ends and at junctions where three or more segments meet, unless
|
|
56
|
+
* `continuation` names a segment to go on with there.
|
|
57
|
+
*/
|
|
58
|
+
declare function strokeRuns(segments: VectorSegment[], continuation?: RunContinuation): StrokeRun[];
|
|
39
59
|
/** Emits a stroke run as one contour, closed when the run comes back to its start. */
|
|
40
60
|
declare function addStrokeRunToPath(path: PathSink, run: StrokeRun, segments: VectorSegment[], vertices: VectorVertex[]): void;
|
|
41
61
|
//#endregion
|
|
42
|
-
export { Chain, StrokeRun, addLoopToPath, addOpenSegmentsToPath, addRegionToPath, addSegmentDirected, addStrokeRunToPath, buildChains, strokeRuns };
|
|
62
|
+
export { Chain, RunContinuation, StrokeRun, addLoopToPath, addOpenSegmentsToPath, addRegionToPath, addSegmentDirected, addStrokeRunToPath, buildChains, joinedSegmentPairs, leavingDirection, segmentsByVertex, strokeRuns };
|
|
43
63
|
//# sourceMappingURL=network.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network.d.ts","names":[],"sources":["../../src/paths/network.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"network.d.ts","names":[],"sources":["../../src/paths/network.ts"],"mappings":";;;;iBAIgB,mBACd,MAAM,UACN,KAAK,eACL,UAAU,gBACV;;;;;;iBAsBc,cACd,MAAM,UACN,gBACA,UAAU,iBACV,UAAU;;iBA2BI,gBACd,MAAM,UACN,QAAQ,KAAK,wBACb,UAAU,iBACV,UAAU;iBA+GI,sBACd,MAAM,UACN,UAAU,iBACV,UAAU,gBACV;;;;;;UAuBe;EACf;EACA;;iBAGc,YAAY,UAAU,kBAAkB;;UAiDvC;;EAEf;;EAEA;;EAEA;;KAGU,mBAAmB,gBAAgB;;;;;iBAM/B,iBACd,mBAAmB,iBACnB,WAAW,4BACV;;;;;;iBAoBa,iBACd,SAAS,KAAK,yCACd,eACA,iBACC;;;;;;iBAkBa,mBACd,SAAS,iBACP,gBAAgB,WAAW;;;;;;;iBA+Bf,WAAW,UAAU,iBAAiB,eAAe,kBAAkB;;iBA6CvE,mBACd,MAAM,UACN,KAAK,WACL,UAAU,iBACV,UAAU"}
|
package/dist/paths/network.js
CHANGED
|
@@ -178,30 +178,96 @@ function buildChains(segments) {
|
|
|
178
178
|
return chains;
|
|
179
179
|
}
|
|
180
180
|
/**
|
|
181
|
-
*
|
|
182
|
-
*
|
|
183
|
-
* caps. Runs stop at open ends and at junctions where three or more segments meet.
|
|
181
|
+
* The indices of the segments meeting at each vertex, in segment order; a segment from a vertex to
|
|
182
|
+
* itself is listed there once. `include` leaves out the segments it returns false for.
|
|
184
183
|
*/
|
|
185
|
-
function
|
|
186
|
-
const
|
|
184
|
+
function segmentsByVertex(segments, include) {
|
|
185
|
+
const byVertex = /* @__PURE__ */ new Map();
|
|
187
186
|
const meet = (vertex, index) => {
|
|
188
|
-
const list =
|
|
187
|
+
const list = byVertex.get(vertex);
|
|
189
188
|
if (list) list.push(index);
|
|
190
|
-
else
|
|
189
|
+
else byVertex.set(vertex, [index]);
|
|
191
190
|
};
|
|
192
191
|
for (const [index, segment] of segments.entries()) {
|
|
192
|
+
if (include && !include(index)) continue;
|
|
193
193
|
meet(segment.start, index);
|
|
194
194
|
if (segment.end !== segment.start) meet(segment.end, index);
|
|
195
195
|
}
|
|
196
|
+
return byVertex;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* The direction segment `index` leaves `vertex` in: along its handle there, or with that handle
|
|
200
|
+
* collapsed, toward the far end's control point, as a cubic leaves toward its next distinct
|
|
201
|
+
* control point; a straight segment leaves along its chord.
|
|
202
|
+
*/
|
|
203
|
+
function leavingDirection(network, index, vertex) {
|
|
204
|
+
const segment = network.segments[index];
|
|
205
|
+
const atStart = segment.start === vertex;
|
|
206
|
+
const handle = atStart ? segment.tangentStart : segment.tangentEnd;
|
|
207
|
+
if (handle.x !== 0 || handle.y !== 0) return handle;
|
|
208
|
+
const from = network.vertices[vertex];
|
|
209
|
+
const to = network.vertices[atStart ? segment.end : segment.start];
|
|
210
|
+
const farHandle = atStart ? segment.tangentEnd : segment.tangentStart;
|
|
211
|
+
const control = {
|
|
212
|
+
x: to.x + farHandle.x - from.x,
|
|
213
|
+
y: to.y + farHandle.y - from.y
|
|
214
|
+
};
|
|
215
|
+
if (control.x !== 0 || control.y !== 0) return control;
|
|
216
|
+
return {
|
|
217
|
+
x: to.x - from.x,
|
|
218
|
+
y: to.y - from.y
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* The pairs of segments a stroke may join at each vertex: the two at a vertex exactly two meet at,
|
|
223
|
+
* and with several regions, also each two region edges next to each other around a vertex,
|
|
224
|
+
* which region strokes join where the gap between them is unfilled, open segments aside.
|
|
225
|
+
*/
|
|
226
|
+
function joinedSegmentPairs(network) {
|
|
227
|
+
const pairs = [];
|
|
228
|
+
for (const [vertex, indices] of segmentsByVertex(network.segments)) if (indices.length === 2) pairs.push([
|
|
229
|
+
vertex,
|
|
230
|
+
indices[0],
|
|
231
|
+
indices[1]
|
|
232
|
+
]);
|
|
233
|
+
if (network.regions.length < 2) return pairs;
|
|
234
|
+
const bounding = new Set(network.regions.flatMap((region) => region.loops.flat()));
|
|
235
|
+
const edges = segmentsByVertex(network.segments, (index) => bounding.has(index) && network.segments[index].start !== network.segments[index].end);
|
|
236
|
+
for (const [vertex, indices] of edges) {
|
|
237
|
+
if (indices.length < 2) continue;
|
|
238
|
+
const angle = (index) => {
|
|
239
|
+
const direction = leavingDirection(network, index, vertex);
|
|
240
|
+
return Math.atan2(direction.y, direction.x);
|
|
241
|
+
};
|
|
242
|
+
const around = indices.toSorted((a, b) => angle(a) - angle(b));
|
|
243
|
+
for (const [position, index] of around.entries()) pairs.push([
|
|
244
|
+
vertex,
|
|
245
|
+
index,
|
|
246
|
+
around[(position + 1) % around.length]
|
|
247
|
+
]);
|
|
248
|
+
}
|
|
249
|
+
return pairs;
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Segments chained into runs as Figma strokes a network: by default a run passes through every
|
|
253
|
+
* vertex exactly two segments meet at, so its corners take the stroke's join and only its open
|
|
254
|
+
* ends take caps. Runs stop at open ends and at junctions where three or more segments meet, unless
|
|
255
|
+
* `continuation` names a segment to go on with there.
|
|
256
|
+
*/
|
|
257
|
+
function strokeRuns(segments, continuation) {
|
|
258
|
+
const incident = segmentsByVertex(segments);
|
|
196
259
|
const used = /* @__PURE__ */ new Set();
|
|
197
260
|
const across = (index, vertex) => segments[index].start === vertex ? segments[index].end : segments[index].start;
|
|
198
|
-
|
|
261
|
+
const throughPairs = (vertex, from) => {
|
|
262
|
+
const meeting = incident.get(vertex);
|
|
263
|
+
if (meeting?.length !== 2) return;
|
|
264
|
+
return meeting[0] === from ? meeting[1] : meeting[0];
|
|
265
|
+
};
|
|
266
|
+
const continueAt = continuation ?? throughPairs;
|
|
199
267
|
const extend = (vertex, from, add) => {
|
|
200
268
|
for (;;) {
|
|
201
|
-
const
|
|
202
|
-
if (
|
|
203
|
-
const next = meeting[0] === from ? meeting[1] : meeting[0];
|
|
204
|
-
if (used.has(next)) return vertex;
|
|
269
|
+
const next = continueAt(vertex, from);
|
|
270
|
+
if (next === void 0 || used.has(next)) return vertex;
|
|
205
271
|
used.add(next);
|
|
206
272
|
add(next);
|
|
207
273
|
vertex = across(next, vertex);
|
|
@@ -244,6 +310,6 @@ function addStrokeRunToPath(path, run, segments, vertices) {
|
|
|
244
310
|
if (run.closed) path.close();
|
|
245
311
|
}
|
|
246
312
|
//#endregion
|
|
247
|
-
export { addLoopToPath, addOpenSegmentsToPath, addRegionToPath, addSegmentDirected, addStrokeRunToPath, buildChains, strokeRuns };
|
|
313
|
+
export { addLoopToPath, addOpenSegmentsToPath, addRegionToPath, addSegmentDirected, addStrokeRunToPath, buildChains, joinedSegmentPairs, leavingDirection, segmentsByVertex, strokeRuns };
|
|
248
314
|
|
|
249
315
|
//# sourceMappingURL=network.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network.js","names":[],"sources":["../../src/paths/network.ts"],"sourcesContent":["import type { Vector } from '../primitives'\nimport type { VectorRegion, VectorSegment, VectorVertex } from '../types'\nimport type { PathSink } from './sink'\n\nexport function addSegmentDirected(\n path: PathSink,\n seg: VectorSegment,\n vertices: VectorVertex[],\n forward: boolean\n): void {\n const p0 = forward ? vertices[seg.start] : vertices[seg.end]\n const p3 = forward ? vertices[seg.end] : vertices[seg.start]\n const ts = seg.tangentStart\n const te = seg.tangentEnd\n\n const isLine = ts.x === 0 && ts.y === 0 && te.x === 0 && te.y === 0\n if (isLine) {\n path.lineTo(p3.x, p3.y)\n } else if (forward) {\n path.cubicTo(p0.x + ts.x, p0.y + ts.y, p3.x + te.x, p3.y + te.y, p3.x, p3.y)\n } else {\n path.cubicTo(p0.x + te.x, p0.y + te.y, p3.x + ts.x, p3.y + ts.y, p3.x, p3.y)\n }\n}\n\n/**\n * Draws one region loop. It starts at the end of its first segment away from the second, as a\n * loop's stored order runs; a segment that does not continue from the last starts a new subpath,\n * and the loop closes only when it runs unbroken back to where it started.\n */\nexport function addLoopToPath(\n path: PathSink,\n loop: number[],\n segments: VectorSegment[],\n vertices: VectorVertex[]\n): void {\n if (loop.length === 0) return\n const first = segments[loop[0]]\n const second = loop.length > 1 ? segments[loop[1]] : null\n const secondMeetsStart = second?.start === first.start || second?.end === first.start\n const secondMeetsEnd = second?.start === first.end || second?.end === first.end\n const start = !second || secondMeetsEnd || !secondMeetsStart ? first.start : first.end\n let current = start\n let broken = false\n path.moveTo(vertices[start].x, vertices[start].y)\n for (const index of loop) {\n const segment = segments[index]\n const connected = segment.start === current || segment.end === current\n const forward = segment.start === current || !connected\n if (!connected) {\n broken = true\n const from = vertices[segment.start]\n path.moveTo(from.x, from.y)\n }\n addSegmentDirected(path, segment, vertices, forward)\n current = forward ? segment.end : segment.start\n }\n if (!broken && current === start) path.close()\n}\n\n/** A region's loops, one after another: the outline its fill rule fills. */\nexport function addRegionToPath(\n path: PathSink,\n region: Pick<VectorRegion, 'loops'>,\n segments: VectorSegment[],\n vertices: VectorVertex[]\n): void {\n for (const loop of region.loops) addLoopToPath(path, loop, segments, vertices)\n}\n\nfunction isStraight(seg: VectorSegment): boolean {\n const { tangentStart: ts, tangentEnd: te } = seg\n return ts.x === 0 && ts.y === 0 && te.x === 0 && te.y === 0\n}\n\n/** Cubic handle length, as a fraction of the radius, of a circular arc turning by `angle`. */\nfunction arcHandle(angle: number): number {\n return (4 / 3) * Math.tan(angle / 4)\n}\n\ninterface RoundedCorner {\n /** Where the arc leaves the incoming segment and joins the outgoing one. */\n start: Vector\n end: Vector\n handleIn: Vector\n handleOut: Vector\n}\n\n/**\n * The arc rounding `corner` between straight runs from `from` and to `after`, or null when the\n * runs do not turn or have no length. A radius never takes more than half of either run.\n */\nfunction roundedCorner(\n from: Vector,\n corner: Vector,\n after: Vector,\n radius: number\n): RoundedCorner | null {\n const inLength = Math.hypot(corner.x - from.x, corner.y - from.y)\n const outLength = Math.hypot(after.x - corner.x, after.y - corner.y)\n if (radius <= 0 || inLength === 0 || outLength === 0) return null\n const inDir = { x: (corner.x - from.x) / inLength, y: (corner.y - from.y) / inLength }\n const outDir = { x: (after.x - corner.x) / outLength, y: (after.y - corner.y) / outLength }\n const turn = Math.acos(Math.max(-1, Math.min(1, inDir.x * outDir.x + inDir.y * outDir.y)))\n if (turn <= 1e-6) return null\n const reach = Math.min(radius * Math.tan(turn / 2), inLength / 2, outLength / 2)\n const handle = arcHandle(turn) * (reach / Math.tan(turn / 2))\n const start = { x: corner.x - inDir.x * reach, y: corner.y - inDir.y * reach }\n const end = { x: corner.x + outDir.x * reach, y: corner.y + outDir.y * reach }\n return {\n start,\n end,\n handleIn: { x: start.x + inDir.x * handle, y: start.y + inDir.y * handle },\n handleOut: { x: end.x - outDir.x * handle, y: end.y - outDir.y * handle }\n }\n}\n\nfunction drawCorner(path: PathSink, corner: RoundedCorner) {\n path.lineTo(corner.start.x, corner.start.y)\n path.cubicTo(\n corner.handleIn.x,\n corner.handleIn.y,\n corner.handleOut.x,\n corner.handleOut.y,\n corner.end.x,\n corner.end.y\n )\n}\n\n/**\n * Draws one chain, rounding each vertex where two straight segments meet by its corner radius, or\n * `cornerRadius` when it has none, as Figma rounds a vector's corners. A chain that comes back to\n * where it started is closed, its last corner rounded too.\n */\nfunction addChainToPath(\n path: PathSink,\n { start: first, segments: chain }: Chain,\n segments: VectorSegment[],\n vertices: VectorVertex[],\n cornerRadius: number\n): void {\n // The chain's vertices in drawing order; a closed chain ends where it started.\n const order = [first]\n for (const segIdx of chain) {\n const seg = segments[segIdx]\n order.push(seg.start === order[order.length - 1] ? seg.end : seg.start)\n }\n const closed = chain.length > 2 && order[order.length - 1] === first\n const cornerAt = (index: number): RoundedCorner | null => {\n const incoming = segments[chain[index - 1]]\n const outgoing = segments[chain[index % chain.length]]\n if (!isStraight(incoming) || !isStraight(outgoing)) return null\n const corner = vertices[order[index]]\n return roundedCorner(\n vertices[order[index - 1]],\n corner,\n vertices[order[(index % chain.length) + 1]],\n corner.cornerRadius ?? cornerRadius\n )\n }\n const wrap = closed ? cornerAt(chain.length) : null\n const begin = wrap?.end ?? vertices[first]\n path.moveTo(begin.x, begin.y)\n for (let index = 0; index < chain.length; index++) {\n const last = index === chain.length - 1\n const corner = last ? wrap : cornerAt(index + 1)\n if (corner) {\n drawCorner(path, corner)\n continue\n }\n const seg = segments[chain[index]]\n addSegmentDirected(path, seg, vertices, seg.start === order[index])\n }\n if (closed) path.close()\n}\n\nexport function addOpenSegmentsToPath(\n path: PathSink,\n segments: VectorSegment[],\n vertices: VectorVertex[],\n cornerRadius = 0\n): void {\n const visited = new Set<number>()\n const chains = buildChains(segments)\n\n for (const chain of chains) {\n for (const segIdx of chain.segments) visited.add(segIdx)\n addChainToPath(path, chain, segments, vertices, cornerRadius)\n }\n\n for (let i = 0; i < segments.length; i++) {\n if (visited.has(i)) continue\n const seg = segments[i]\n path.moveTo(vertices[seg.start].x, vertices[seg.start].y)\n addSegmentDirected(path, seg, vertices, true)\n }\n}\n\n/**\n * A run of connected segments in the order a walk took them, from the vertex it started at, or a\n * lone segment's own start. The start is kept rather than worked out again from the first two\n * segments, which two segments between the same vertices leave ambiguous.\n */\nexport interface Chain {\n start: number\n segments: number[]\n}\n\nexport function buildChains(segments: VectorSegment[]): Chain[] {\n if (segments.length === 0) return []\n\n const adj = new Map<number, number[]>()\n for (let i = 0; i < segments.length; i++) {\n const s = segments[i]\n const startList = adj.get(s.start) ?? []\n startList.push(i)\n adj.set(s.start, startList)\n\n const endList = adj.get(s.end) ?? []\n endList.push(i)\n adj.set(s.end, endList)\n }\n\n const visited = new Set<number>()\n const chains: Chain[] = []\n // Open runs start at their ends; closed loops left over start wherever their first segment does,\n // so every loop is one contour, not one per segment.\n const degree1 = [...adj.entries()].filter(([, segs]) => segs.length === 1).map(([v]) => v)\n const startVertices = [...degree1, ...segments.map((segment) => segment.start)]\n\n for (const startVertex of startVertices) {\n let current = startVertex\n const chain: number[] = []\n\n for (;;) {\n const segs = adj.get(current)\n if (!segs) break\n\n const nextSeg = segs.find((s) => !visited.has(s))\n if (nextSeg === undefined) break\n\n visited.add(nextSeg)\n chain.push(nextSeg)\n\n const seg = segments[nextSeg]\n current = seg.start === current ? seg.end : seg.start\n }\n\n // A lone segment keeps its stored direction, as a dash pattern runs from its start.\n const start = chain.length === 1 ? segments[chain[0]].start : startVertex\n if (chain.length > 0) chains.push({ start, segments: chain })\n }\n\n return chains\n}\n\n/** A stretch of a network's segments stroked as one contour, so its corners join. */\nexport interface StrokeRun {\n /** The vertex the run starts at. */\n start: number\n /** Segment indices in drawing order. */\n segments: number[]\n /** Whether the run comes back to its start, joining there instead of taking caps. */\n closed: boolean\n}\n\n/**\n * Segments chained into runs as Figma strokes a network: a run passes through every vertex\n * exactly two segments meet at, so its corners take the stroke's join and only its open ends take\n * caps. Runs stop at open ends and at junctions where three or more segments meet.\n */\nexport function strokeRuns(segments: VectorSegment[]): StrokeRun[] {\n const incident = new Map<number, number[]>()\n const meet = (vertex: number, index: number) => {\n const list = incident.get(vertex)\n if (list) list.push(index)\n else incident.set(vertex, [index])\n }\n for (const [index, segment] of segments.entries()) {\n meet(segment.start, index)\n if (segment.end !== segment.start) meet(segment.end, index)\n }\n const used = new Set<number>()\n const across = (index: number, vertex: number) =>\n segments[index].start === vertex ? segments[index].end : segments[index].start\n /** Extends a run through `vertex` for as long as two segments meet at each vertex reached. */\n const extend = (vertex: number, from: number, add: (index: number) => void) => {\n for (;;) {\n const meeting = incident.get(vertex)\n if (meeting?.length !== 2) return vertex\n const next = meeting[0] === from ? meeting[1] : meeting[0]\n if (used.has(next)) return vertex\n used.add(next)\n add(next)\n vertex = across(next, vertex)\n from = next\n }\n }\n\n const runs: StrokeRun[] = []\n for (const [first, segment] of segments.entries()) {\n if (used.has(first)) continue\n used.add(first)\n const run = [first]\n const end = extend(segment.end, first, (index) => run.push(index))\n if (end === segment.start) {\n runs.push({ start: segment.start, segments: run, closed: true })\n continue\n }\n const start = extend(segment.start, first, (index) => run.unshift(index))\n // A loop through a junction stops at it from both sides; it still closes there, whichever\n // of its segments is stored first.\n runs.push({ start, segments: run, closed: start === end })\n }\n return runs\n}\n\n/** Emits a stroke run as one contour, closed when the run comes back to its start. */\nexport function addStrokeRunToPath(\n path: PathSink,\n run: StrokeRun,\n segments: VectorSegment[],\n vertices: VectorVertex[]\n): void {\n let current = run.start\n path.moveTo(vertices[current].x, vertices[current].y)\n for (const index of run.segments) {\n const segment = segments[index]\n const forward = segment.start === current\n addSegmentDirected(path, segment, vertices, forward)\n current = forward ? segment.end : segment.start\n }\n if (run.closed) path.close()\n}\n"],"mappings":";AAIA,SAAgB,mBACd,MACA,KACA,UACA,SACM;CACN,MAAM,KAAK,UAAU,SAAS,IAAI,SAAS,SAAS,IAAI;CACxD,MAAM,KAAK,UAAU,SAAS,IAAI,OAAO,SAAS,IAAI;CACtD,MAAM,KAAK,IAAI;CACf,MAAM,KAAK,IAAI;CAGf,IADe,GAAG,MAAM,KAAK,GAAG,MAAM,KAAK,GAAG,MAAM,KAAK,GAAG,MAAM,GAEhE,KAAK,OAAO,GAAG,GAAG,GAAG,CAAC;MACjB,IAAI,SACT,KAAK,QAAQ,GAAG,IAAI,GAAG,GAAG,GAAG,IAAI,GAAG,GAAG,GAAG,IAAI,GAAG,GAAG,GAAG,IAAI,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC;MAE3E,KAAK,QAA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M,OAAO,QAAQ,OAAO,OAAO,QAAQ,KAAK,QAAQ;GACxD,IAAI,KAAK,IAAI,IAAI,GAAG,OAAO;GAC3B,KAAK,IAAI,IAAI;GACb,IAAI,IAAI;GACR,SAAS,OAAO,MAAM,MAAM;GAC5B,OAAO;EACT;CACF;CAEA,MAAM,OAAoB,CAAC;CAC3B,KAAK,MAAM,CAAC,OAAO,YAAY,SAAS,QAAQ,GAAG;EACjD,IAAI,KAAK,IAAI,KAAK,GAAG;EACrB,KAAK,IAAI,KAAK;EACd,MAAM,MAAM,CAAC,KAAK;EAClB,MAAM,MAAM,OAAO,QAAQ,KAAK,QAAQ,UAAU,IAAI,KAAK,KAAK,CAAC;EACjE,IAAI,QAAQ,QAAQ,OAAO;GACzB,KAAK,KAAK;IAAE,OAAO,QAAQ;IAAO,UAAU;IAAK,QAAQ;GAAK,CAAC;GAC/D;EACF;EACA,MAAM,QAAQ,OAAO,QAAQ,OAAO,QAAQ,UAAU,IAAI,QAAQ,KAAK,CAAC;EAGxE,KAAK,KAAK;GAAE;GAAO,UAAU;GAAK,QAAQ,UAAU;EAAI,CAAC;CAC3D;CACA,OAAO;AACT;;AAGA,SAAgB,mBACd,MACA,KACA,UACA,UACM;CACN,IAAI,UAAU,IAAI;CAClB,KAAK,OAAO,SAAS,QAAQ,CAAC,GAAG,SAAS,QAAQ,CAAC,CAAC;CACpD,KAAK,MAAM,SAAS,IAAI,UAAU;EAChC,MAAM,UAAU,SAAS;EACzB,MAAM,UAAU,QAAQ,UAAU;EAClC,mBAAmB,MAAM,SAAS,UAAU,OAAO;EACnD,UAAU,UAAU,QAAQ,MAAM,QAAQ;CAC5C;CACA,IAAI,IAAI,QAAQ,KAAK,MAAM;AAC7B"}
|
|
1
|
+
{"version":3,"file":"network.js","names":[],"sources":["../../src/paths/network.ts"],"sourcesContent":["import type { Vector } from '../primitives'\nimport type { VectorNetwork, VectorRegion, VectorSegment, VectorVertex } from '../types'\nimport type { PathSink } from './sink'\n\nexport function addSegmentDirected(\n path: PathSink,\n seg: VectorSegment,\n vertices: VectorVertex[],\n forward: boolean\n): void {\n const p0 = forward ? vertices[seg.start] : vertices[seg.end]\n const p3 = forward ? vertices[seg.end] : vertices[seg.start]\n const ts = seg.tangentStart\n const te = seg.tangentEnd\n\n const isLine = ts.x === 0 && ts.y === 0 && te.x === 0 && te.y === 0\n if (isLine) {\n path.lineTo(p3.x, p3.y)\n } else if (forward) {\n path.cubicTo(p0.x + ts.x, p0.y + ts.y, p3.x + te.x, p3.y + te.y, p3.x, p3.y)\n } else {\n path.cubicTo(p0.x + te.x, p0.y + te.y, p3.x + ts.x, p3.y + ts.y, p3.x, p3.y)\n }\n}\n\n/**\n * Draws one region loop. It starts at the end of its first segment away from the second, as a\n * loop's stored order runs; a segment that does not continue from the last starts a new subpath,\n * and the loop closes only when it runs unbroken back to where it started.\n */\nexport function addLoopToPath(\n path: PathSink,\n loop: number[],\n segments: VectorSegment[],\n vertices: VectorVertex[]\n): void {\n if (loop.length === 0) return\n const first = segments[loop[0]]\n const second = loop.length > 1 ? segments[loop[1]] : null\n const secondMeetsStart = second?.start === first.start || second?.end === first.start\n const secondMeetsEnd = second?.start === first.end || second?.end === first.end\n const start = !second || secondMeetsEnd || !secondMeetsStart ? first.start : first.end\n let current = start\n let broken = false\n path.moveTo(vertices[start].x, vertices[start].y)\n for (const index of loop) {\n const segment = segments[index]\n const connected = segment.start === current || segment.end === current\n const forward = segment.start === current || !connected\n if (!connected) {\n broken = true\n const from = vertices[segment.start]\n path.moveTo(from.x, from.y)\n }\n addSegmentDirected(path, segment, vertices, forward)\n current = forward ? segment.end : segment.start\n }\n if (!broken && current === start) path.close()\n}\n\n/** A region's loops, one after another: the outline its fill rule fills. */\nexport function addRegionToPath(\n path: PathSink,\n region: Pick<VectorRegion, 'loops'>,\n segments: VectorSegment[],\n vertices: VectorVertex[]\n): void {\n for (const loop of region.loops) addLoopToPath(path, loop, segments, vertices)\n}\n\nfunction isStraight(seg: VectorSegment): boolean {\n const { tangentStart: ts, tangentEnd: te } = seg\n return ts.x === 0 && ts.y === 0 && te.x === 0 && te.y === 0\n}\n\n/** Cubic handle length, as a fraction of the radius, of a circular arc turning by `angle`. */\nfunction arcHandle(angle: number): number {\n return (4 / 3) * Math.tan(angle / 4)\n}\n\ninterface RoundedCorner {\n /** Where the arc leaves the incoming segment and joins the outgoing one. */\n start: Vector\n end: Vector\n handleIn: Vector\n handleOut: Vector\n}\n\n/**\n * The arc rounding `corner` between straight runs from `from` and to `after`, or null when the\n * runs do not turn or have no length. A radius never takes more than half of either run.\n */\nfunction roundedCorner(\n from: Vector,\n corner: Vector,\n after: Vector,\n radius: number\n): RoundedCorner | null {\n const inLength = Math.hypot(corner.x - from.x, corner.y - from.y)\n const outLength = Math.hypot(after.x - corner.x, after.y - corner.y)\n if (radius <= 0 || inLength === 0 || outLength === 0) return null\n const inDir = { x: (corner.x - from.x) / inLength, y: (corner.y - from.y) / inLength }\n const outDir = { x: (after.x - corner.x) / outLength, y: (after.y - corner.y) / outLength }\n const turn = Math.acos(Math.max(-1, Math.min(1, inDir.x * outDir.x + inDir.y * outDir.y)))\n if (turn <= 1e-6) return null\n const reach = Math.min(radius * Math.tan(turn / 2), inLength / 2, outLength / 2)\n const handle = arcHandle(turn) * (reach / Math.tan(turn / 2))\n const start = { x: corner.x - inDir.x * reach, y: corner.y - inDir.y * reach }\n const end = { x: corner.x + outDir.x * reach, y: corner.y + outDir.y * reach }\n return {\n start,\n end,\n handleIn: { x: start.x + inDir.x * handle, y: start.y + inDir.y * handle },\n handleOut: { x: end.x - outDir.x * handle, y: end.y - outDir.y * handle }\n }\n}\n\nfunction drawCorner(path: PathSink, corner: RoundedCorner) {\n path.lineTo(corner.start.x, corner.start.y)\n path.cubicTo(\n corner.handleIn.x,\n corner.handleIn.y,\n corner.handleOut.x,\n corner.handleOut.y,\n corner.end.x,\n corner.end.y\n )\n}\n\n/**\n * Draws one chain, rounding each vertex where two straight segments meet by its corner radius, or\n * `cornerRadius` when it has none, as Figma rounds a vector's corners. A chain that comes back to\n * where it started is closed, its last corner rounded too.\n */\nfunction addChainToPath(\n path: PathSink,\n { start: first, segments: chain }: Chain,\n segments: VectorSegment[],\n vertices: VectorVertex[],\n cornerRadius: number\n): void {\n // The chain's vertices in drawing order; a closed chain ends where it started.\n const order = [first]\n for (const segIdx of chain) {\n const seg = segments[segIdx]\n order.push(seg.start === order[order.length - 1] ? seg.end : seg.start)\n }\n const closed = chain.length > 2 && order[order.length - 1] === first\n const cornerAt = (index: number): RoundedCorner | null => {\n const incoming = segments[chain[index - 1]]\n const outgoing = segments[chain[index % chain.length]]\n if (!isStraight(incoming) || !isStraight(outgoing)) return null\n const corner = vertices[order[index]]\n return roundedCorner(\n vertices[order[index - 1]],\n corner,\n vertices[order[(index % chain.length) + 1]],\n corner.cornerRadius ?? cornerRadius\n )\n }\n const wrap = closed ? cornerAt(chain.length) : null\n const begin = wrap?.end ?? vertices[first]\n path.moveTo(begin.x, begin.y)\n for (let index = 0; index < chain.length; index++) {\n const last = index === chain.length - 1\n const corner = last ? wrap : cornerAt(index + 1)\n if (corner) {\n drawCorner(path, corner)\n continue\n }\n const seg = segments[chain[index]]\n addSegmentDirected(path, seg, vertices, seg.start === order[index])\n }\n if (closed) path.close()\n}\n\nexport function addOpenSegmentsToPath(\n path: PathSink,\n segments: VectorSegment[],\n vertices: VectorVertex[],\n cornerRadius = 0\n): void {\n const visited = new Set<number>()\n const chains = buildChains(segments)\n\n for (const chain of chains) {\n for (const segIdx of chain.segments) visited.add(segIdx)\n addChainToPath(path, chain, segments, vertices, cornerRadius)\n }\n\n for (let i = 0; i < segments.length; i++) {\n if (visited.has(i)) continue\n const seg = segments[i]\n path.moveTo(vertices[seg.start].x, vertices[seg.start].y)\n addSegmentDirected(path, seg, vertices, true)\n }\n}\n\n/**\n * A run of connected segments in the order a walk took them, from the vertex it started at, or a\n * lone segment's own start. The start is kept rather than worked out again from the first two\n * segments, which two segments between the same vertices leave ambiguous.\n */\nexport interface Chain {\n start: number\n segments: number[]\n}\n\nexport function buildChains(segments: VectorSegment[]): Chain[] {\n if (segments.length === 0) return []\n\n const adj = new Map<number, number[]>()\n for (let i = 0; i < segments.length; i++) {\n const s = segments[i]\n const startList = adj.get(s.start) ?? []\n startList.push(i)\n adj.set(s.start, startList)\n\n const endList = adj.get(s.end) ?? []\n endList.push(i)\n adj.set(s.end, endList)\n }\n\n const visited = new Set<number>()\n const chains: Chain[] = []\n // Open runs start at their ends; closed loops left over start wherever their first segment does,\n // so every loop is one contour, not one per segment.\n const degree1 = [...adj.entries()].filter(([, segs]) => segs.length === 1).map(([v]) => v)\n const startVertices = [...degree1, ...segments.map((segment) => segment.start)]\n\n for (const startVertex of startVertices) {\n let current = startVertex\n const chain: number[] = []\n\n for (;;) {\n const segs = adj.get(current)\n if (!segs) break\n\n const nextSeg = segs.find((s) => !visited.has(s))\n if (nextSeg === undefined) break\n\n visited.add(nextSeg)\n chain.push(nextSeg)\n\n const seg = segments[nextSeg]\n current = seg.start === current ? seg.end : seg.start\n }\n\n // A lone segment keeps its stored direction, as a dash pattern runs from its start.\n const start = chain.length === 1 ? segments[chain[0]].start : startVertex\n if (chain.length > 0) chains.push({ start, segments: chain })\n }\n\n return chains\n}\n\n/** A stretch of a network's segments stroked as one contour, so its corners join. */\nexport interface StrokeRun {\n /** The vertex the run starts at. */\n start: number\n /** Segment indices in drawing order. */\n segments: number[]\n /** Whether the run comes back to its start, joining there instead of taking caps. */\n closed: boolean\n}\n\nexport type RunContinuation = (vertex: number, from: number) => number | undefined\n\n/**\n * The indices of the segments meeting at each vertex, in segment order; a segment from a vertex to\n * itself is listed there once. `include` leaves out the segments it returns false for.\n */\nexport function segmentsByVertex(\n segments: readonly VectorSegment[],\n include?: (index: number) => boolean\n): Map<number, number[]> {\n const byVertex = new Map<number, number[]>()\n const meet = (vertex: number, index: number) => {\n const list = byVertex.get(vertex)\n if (list) list.push(index)\n else byVertex.set(vertex, [index])\n }\n for (const [index, segment] of segments.entries()) {\n if (include && !include(index)) continue\n meet(segment.start, index)\n if (segment.end !== segment.start) meet(segment.end, index)\n }\n return byVertex\n}\n\n/**\n * The direction segment `index` leaves `vertex` in: along its handle there, or with that handle\n * collapsed, toward the far end's control point, as a cubic leaves toward its next distinct\n * control point; a straight segment leaves along its chord.\n */\nexport function leavingDirection(\n network: Pick<VectorNetwork, 'vertices' | 'segments'>,\n index: number,\n vertex: number\n): Vector {\n const segment = network.segments[index]\n const atStart = segment.start === vertex\n const handle = atStart ? segment.tangentStart : segment.tangentEnd\n if (handle.x !== 0 || handle.y !== 0) return handle\n const from = network.vertices[vertex]\n const to = network.vertices[atStart ? segment.end : segment.start]\n const farHandle = atStart ? segment.tangentEnd : segment.tangentStart\n const control = { x: to.x + farHandle.x - from.x, y: to.y + farHandle.y - from.y }\n if (control.x !== 0 || control.y !== 0) return control\n return { x: to.x - from.x, y: to.y - from.y }\n}\n\n/**\n * The pairs of segments a stroke may join at each vertex: the two at a vertex exactly two meet at,\n * and with several regions, also each two region edges next to each other around a vertex,\n * which region strokes join where the gap between them is unfilled, open segments aside.\n */\nexport function joinedSegmentPairs(\n network: VectorNetwork\n): [vertex: number, a: number, b: number][] {\n const pairs: [number, number, number][] = []\n for (const [vertex, indices] of segmentsByVertex(network.segments)) {\n if (indices.length === 2) pairs.push([vertex, indices[0], indices[1]])\n }\n if (network.regions.length < 2) return pairs\n const bounding = new Set(network.regions.flatMap((region) => region.loops.flat()))\n const edges = segmentsByVertex(\n network.segments,\n (index) => bounding.has(index) && network.segments[index].start !== network.segments[index].end\n )\n for (const [vertex, indices] of edges) {\n if (indices.length < 2) continue\n const angle = (index: number) => {\n const direction = leavingDirection(network, index, vertex)\n return Math.atan2(direction.y, direction.x)\n }\n const around = indices.toSorted((a, b) => angle(a) - angle(b))\n for (const [position, index] of around.entries()) {\n pairs.push([vertex, index, around[(position + 1) % around.length]])\n }\n }\n return pairs\n}\n\n/**\n * Segments chained into runs as Figma strokes a network: by default a run passes through every\n * vertex exactly two segments meet at, so its corners take the stroke's join and only its open\n * ends take caps. Runs stop at open ends and at junctions where three or more segments meet, unless\n * `continuation` names a segment to go on with there.\n */\nexport function strokeRuns(segments: VectorSegment[], continuation?: RunContinuation): StrokeRun[] {\n const incident = segmentsByVertex(segments)\n const used = new Set<number>()\n const across = (index: number, vertex: number) =>\n segments[index].start === vertex ? segments[index].end : segments[index].start\n const throughPairs: RunContinuation = (vertex, from) => {\n const meeting = incident.get(vertex)\n if (meeting?.length !== 2) {\n return undefined\n }\n return meeting[0] === from ? meeting[1] : meeting[0]\n }\n const continueAt = continuation ?? throughPairs\n const extend = (vertex: number, from: number, add: (index: number) => void) => {\n for (;;) {\n const next = continueAt(vertex, from)\n if (next === undefined || used.has(next)) {\n return vertex\n }\n used.add(next)\n add(next)\n vertex = across(next, vertex)\n from = next\n }\n }\n\n const runs: StrokeRun[] = []\n for (const [first, segment] of segments.entries()) {\n if (used.has(first)) continue\n used.add(first)\n const run = [first]\n const end = extend(segment.end, first, (index) => run.push(index))\n if (end === segment.start) {\n runs.push({ start: segment.start, segments: run, closed: true })\n continue\n }\n const start = extend(segment.start, first, (index) => run.unshift(index))\n // A loop through a junction stops at it from both sides; it still closes there, whichever\n // of its segments is stored first.\n runs.push({ start, segments: run, closed: start === end })\n }\n return runs\n}\n\n/** Emits a stroke run as one contour, closed when the run comes back to its start. */\nexport function addStrokeRunToPath(\n path: PathSink,\n run: StrokeRun,\n segments: VectorSegment[],\n vertices: VectorVertex[]\n): void {\n let current = run.start\n path.moveTo(vertices[current].x, vertices[current].y)\n for (const index of run.segments) {\n const segment = segments[index]\n const forward = segment.start === current\n addSegmentDirected(path, segment, vertices, forward)\n current = forward ? segment.end : segment.start\n }\n if (run.closed) path.close()\n}\n"],"mappings":";AAIA,SAAgB,mBACd,MACA,KACA,UACA,SACM;CACN,MAAM,KAAK,UAAU,SAAS,IAAI,SAAS,SAAS,IAAI;CACxD,MAAM,KAAK,UAAU,SAAS,IAAI,OAAO,SAAS,IAAI;C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Q,UAAU,IAAI,KAAK,KAAK,CAAC;EACjE,IAAI,QAAQ,QAAQ,OAAO;GACzB,KAAK,KAAK;IAAE,OAAO,QAAQ;IAAO,UAAU;IAAK,QAAQ;GAAK,CAAC;GAC/D;EACF;EACA,MAAM,QAAQ,OAAO,QAAQ,OAAO,QAAQ,UAAU,IAAI,QAAQ,KAAK,CAAC;EAGxE,KAAK,KAAK;GAAE;GAAO,UAAU;GAAK,QAAQ,UAAU;EAAI,CAAC;CAC3D;CACA,OAAO;AACT;;AAGA,SAAgB,mBACd,MACA,KACA,UACA,UACM;CACN,IAAI,UAAU,IAAI;CAClB,KAAK,OAAO,SAAS,QAAQ,CAAC,GAAG,SAAS,QAAQ,CAAC,CAAC;CACpD,KAAK,MAAM,SAAS,IAAI,UAAU;EAChC,MAAM,UAAU,SAAS;EACzB,MAAM,UAAU,QAAQ,UAAU;EAClC,mBAAmB,MAAM,SAAS,UAAU,OAAO;EACnD,UAAU,UAAU,QAAQ,MAAM,QAAQ;CAC5C;CACA,IAAI,IAAI,QAAQ,KAAK,MAAM;AAC7B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"smooth-corners.d.ts","names":[],"sources":["../../src/paths/smooth-corners.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"smooth-corners.d.ts","names":[],"sources":["../../src/paths/smooth-corners.ts"],"mappings":";;;;KAMY,iBAAiB,KAC3B;;;;;UAce,yBAAyB;EACxC,aACE,YACA,YACA,qBACA,sBACA,gBACA,WACA;;;;;;iBAsSY,gBACd,MAAM,kBACN,MAAM,gBACN;EAAO;EAAc;EAAa;EAAe;GACjD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"smooth-corners.js","names":[],"sources":["../../src/paths/smooth-corners.ts"],"sourcesContent":["import { minOf } from '../arrays'\nimport type { SceneNode } from '../types'\nimport type { PathSink } from './sink'\n\n/** What a rectangle's smoothed corners are drawn from. */\nexport type SmoothRectNode = Pick<\n SceneNode,\n | 'cornerRadius'\n | 'cornerSmoothing'\n | 'independentCorners'\n | 'topLeftRadius'\n | 'topRightRadius'\n | 'bottomRightRadius'\n | 'bottomLeftRadius'\n>\n\n/**\n * Where a smoothed rectangle is traced: a CanvasKit `PathBuilder`, or a writer of SVG path data.\n * `arcToRotated` takes CanvasKit's arguments, which match an SVG arc's.\n */\nexport interface SmoothCornerSink extends PathSink {\n arcToRotated(\n rx: number,\n ry: number,\n xAxisRotate: number,\n useSmallArc: boolean,\n isCCW: boolean,\n x: number,\n y: number\n ): unknown\n}\n\ntype SmoothCornerKey = 'topLeft' | 'topRight' | 'bottomRight' | 'bottomLeft'\n\ntype SmoothCorner = {\n radius: number\n budget: number\n}\n\ntype SmoothCornerPathParams = {\n a: number\n b: number\n c: number\n d: number\n p: number\n radius: number\n arcSectionLength: number\n}\n\nfunction smoothCornerRadii(\n node: SmoothRectNode,\n width: number,\n height: number,\n spread: number\n): Record<SmoothCornerKey, SmoothCorner> {\n const radius = (value: number) => Math.max(0, value + spread)\n const radii: Record<SmoothCornerKey, number> = node.independentCorners\n ? {\n topLeft: radius(node.topLeftRadius),\n topRight: radius(node.topRightRadius),\n bottomRight: radius(node.bottomRightRadius),\n bottomLeft: radius(node.bottomLeftRadius)\n }\n : {\n topLeft: radius(node.cornerRadius),\n topRight: radius(node.cornerRadius),\n bottomRight: radius(node.cornerRadius),\n bottomLeft: radius(node.cornerRadius)\n }\n\n if (\n radii.topLeft === radii.topRight &&\n radii.topRight === radii.bottomRight &&\n radii.bottomRight === radii.bottomLeft\n ) {\n const budget = Math.min(width, height) / 2\n const clampedRadius = Math.min(radii.topLeft, budget)\n return {\n topLeft: { radius: clampedRadius, budget },\n topRight: { radius: clampedRadius, budget },\n bottomRight: { radius: clampedRadius, budget },\n bottomLeft: { radius: clampedRadius, budget }\n }\n }\n\n const budgets: Record<SmoothCornerKey, number> = {\n topLeft: -1,\n topRight: -1,\n bottomRight: -1,\n bottomLeft: -1\n }\n const adjacentByCorner: Record<\n SmoothCornerKey,\n Array<{ corner: SmoothCornerKey; sideLength: number }>\n > = {\n topLeft: [\n { corner: 'topRight', sideLength: width },\n { corner: 'bottomLeft', sideLength: height }\n ],\n topRight: [\n { corner: 'topLeft', sideLength: width },\n { corner: 'bottomRight', sideLength: height }\n ],\n bottomRight: [\n { corner: 'bottomLeft', sideLength: width },\n { corner: 'topRight', sideLength: height }\n ],\n bottomLeft: [\n { corner: 'bottomRight', sideLength: width },\n { corner: 'topLeft', sideLength: height }\n ]\n }\n\n for (const corner of (Object.keys(radii) as SmoothCornerKey[]).sort(\n (a, b) => radii[b] - radii[a]\n )) {\n const cornerRadius = radii[corner]\n const budget = minOf(\n adjacentByCorner[corner].map((adjacent) => {\n const adjacentRadius = radii[adjacent.corner]\n if (cornerRadius === 0 && adjacentRadius === 0) return 0\n if (budgets[adjacent.corner] >= 0) return adjacent.sideLength - budgets[adjacent.corner]\n return (cornerRadius / (cornerRadius + adjacentRadius)) * adjacent.sideLength\n })\n )\n budgets[corner] = budget\n radii[corner] = Math.min(cornerRadius, budget)\n }\n\n return {\n topLeft: { radius: radii.topLeft, budget: budgets.topLeft },\n topRight: { radius: radii.topRight, budget: budgets.topRight },\n bottomRight: { radius: radii.bottomRight, budget: budgets.bottomRight },\n bottomLeft: { radius: radii.bottomLeft, budget: budgets.bottomLeft }\n }\n}\n\nfunction degreesToRadians(degrees: number): number {\n return (degrees * Math.PI) / 180\n}\n\nfunction smoothCornerPathParams(corner: SmoothCorner, smoothing: number): SmoothCornerPathParams {\n let cornerSmoothing = smoothing\n let p = (1 + cornerSmoothing) * corner.radius\n if (corner.radius > 0) {\n const maxSmoothing = corner.budget / corner.radius - 1\n cornerSmoothing = Math.min(cornerSmoothing, maxSmoothing)\n p = Math.min(p, corner.budget)\n }\n\n const arcMeasure = 90 * (1 - cornerSmoothing)\n const arcSectionLength = Math.sin(degreesToRadians(arcMeasure / 2)) * corner.radius * Math.sqrt(2)\n const angleAlpha = (90 - arcMeasure) / 2\n const p3ToP4Distance = corner.radius * Math.tan(degreesToRadians(angleAlpha / 2))\n const angleBeta = 45 * cornerSmoothing\n const c = p3ToP4Distance * Math.cos(degreesToRadians(angleBeta))\n const d = c * Math.tan(degreesToRadians(angleBeta))\n const b = (p - arcSectionLength - c - d) / 3\n\n return {\n a: 2 * b,\n b,\n c,\n d,\n p,\n radius: corner.radius,\n arcSectionLength\n }\n}\n\nfunction drawTopRightSmoothCorner(\n path: SmoothCornerSink,\n corner: SmoothCornerPathParams,\n x: number,\n y: number\n) {\n if (corner.radius === 0) {\n path.lineTo(x + corner.p, y)\n return\n }\n path.cubicTo(\n x + corner.a,\n y,\n x + corner.a + corner.b,\n y,\n x + corner.a + corner.b + corner.c,\n y + corner.d\n )\n path.arcToRotated(\n corner.radius,\n corner.radius,\n 0,\n true,\n false,\n x + corner.p - corner.d,\n y + corner.p - corner.a - corner.b - corner.c\n )\n path.cubicTo(\n x + corner.p,\n y + corner.p - corner.a - corner.b,\n x + corner.p,\n y + corner.p - corner.a,\n x + corner.p,\n y + corner.p\n )\n}\n\nfunction drawBottomRightSmoothCorner(\n path: SmoothCornerSink,\n corner: SmoothCornerPathParams,\n x: number,\n y: number\n) {\n if (corner.radius === 0) {\n path.lineTo(x, y + corner.p)\n return\n }\n path.cubicTo(\n x,\n y + corner.a,\n x,\n y + corner.a + corner.b,\n x - corner.d,\n y + corner.a + corner.b + corner.c\n )\n path.arcToRotated(\n corner.radius,\n corner.radius,\n 0,\n true,\n false,\n x - corner.p + corner.a + corner.b + corner.c,\n y + corner.p - corner.d\n )\n path.cubicTo(\n x - corner.p + corner.a + corner.b,\n y + corner.p,\n x - corner.p + corner.a,\n y + corner.p,\n x - corner.p,\n y + corner.p\n )\n}\n\nfunction drawBottomLeftSmoothCorner(\n path: SmoothCornerSink,\n corner: SmoothCornerPathParams,\n x: number,\n y: number\n) {\n if (corner.radius === 0) {\n path.lineTo(x - corner.p, y)\n return\n }\n path.cubicTo(\n x - corner.a,\n y,\n x - corner.a - corner.b,\n y,\n x - corner.a - corner.b - corner.c,\n y - corner.d\n )\n path.arcToRotated(\n corner.radius,\n corner.radius,\n 0,\n true,\n false,\n x - corner.p + corner.d,\n y - corner.p + corner.a + corner.b + corner.c\n )\n path.cubicTo(\n x - corner.p,\n y - corner.p + corner.a + corner.b,\n x - corner.p,\n y - corner.p + corner.a,\n x - corner.p,\n y - corner.p\n )\n}\n\nfunction drawTopLeftSmoothCorner(\n path: SmoothCornerSink,\n corner: SmoothCornerPathParams,\n x: number,\n y: number\n) {\n if (corner.radius === 0) {\n path.lineTo(x, y - corner.p)\n return\n }\n path.cubicTo(\n x,\n y - corner.a,\n x,\n y - corner.a - corner.b,\n x + corner.d,\n y - corner.a - corner.b - corner.c\n )\n path.arcToRotated(\n corner.radius,\n corner.radius,\n 0,\n true,\n false,\n x + corner.p - corner.a - corner.b - corner.c,\n y - corner.p + corner.d\n )\n path.cubicTo(\n x + corner.p - corner.a - corner.b,\n y - corner.p,\n x + corner.p - corner.a,\n y - corner.p,\n x + corner.p,\n y - corner.p\n )\n}\n\n/**\n * Trace a rectangle with smoothed corners into `path`, as Figma rounds them. False, with nothing\n * traced, when no corner is rounded, so the caller can draw a plain rectangle.\n */\nexport function traceSmoothRect(\n path: SmoothCornerSink,\n node: SmoothRectNode,\n box: { left: number; top: number; right: number; bottom: number },\n spread = 0\n): boolean {\n const { left, top, right, bottom } = box\n const smoothing = Math.max(0, Math.min(node.cornerSmoothing, 1))\n const corners = smoothCornerRadii(node, right - left, bottom - top, spread)\n const topLeftCorner = smoothCornerPathParams(corners.topLeft, smoothing)\n const topRightCorner = smoothCornerPathParams(corners.topRight, smoothing)\n const bottomRightCorner = smoothCornerPathParams(corners.bottomRight, smoothing)\n const bottomLeftCorner = smoothCornerPathParams(corners.bottomLeft, smoothing)\n\n if (\n topLeftCorner.radius === 0 &&\n topRightCorner.radius === 0 &&\n bottomRightCorner.radius === 0 &&\n bottomLeftCorner.radius === 0\n ) {\n return false\n }\n\n path.moveTo(right - topRightCorner.p, top)\n drawTopRightSmoothCorner(path, topRightCorner, right - topRightCorner.p, top)\n path.lineTo(right, bottom - bottomRightCorner.p)\n drawBottomRightSmoothCorner(path, bottomRightCorner, right, bottom - bottomRightCorner.p)\n path.lineTo(left + bottomLeftCorner.p, bottom)\n drawBottomLeftSmoothCorner(path, bottomLeftCorner, left + bottomLeftCorner.p, bottom)\n path.lineTo(left, top + topLeftCorner.p)\n drawTopLeftSmoothCorner(path, topLeftCorner, left, top + topLeftCorner.p)\n path.close()\n return true\n}\n"],"mappings":";;AAiDA,SAAS,kBACP,MACA,OACA,QACA,QACuC;CACvC,MAAM,UAAU,UAAkB,KAAK,IAAI,GAAG,QAAQ,MAAM;CAC5D,MAAM,QAAyC,KAAK,qBAChD;EACE,SAAS,OAAO,KAAK,aAAa;EAClC,UAAU,OAAO,KAAK,cAAc;EACpC,aAAa,OAAO,KAAK,iBAAiB;EAC1C,YAAY,OAAO,KAAK,gBAAgB;CAC1C,IACA;EACE,SAAS,OAAO,KAAK,YAAY;EACjC,UAAU,OAAO,KAAK,YAAY;EAClC,aAAa,OAAO,KAAK,YAAY;EACrC,YAAY,OAAO,KAAK,YAAY;CACtC;CAEJ,IACE,MAAM,YAAY,MAAM,YACxB,MAAM,aAAa,MAAM,eACzB,MAAM,gBAAgB,MAAM,YAC5B;EACA,MAAM,SAAS,KAAK,IAAI,OAAO,MAAM,IAAI;EACzC,MAAM,gBAAgB,KAAK,IAAI,MAAM,SAAS,MAAM;EACpD,OAAO;GACL,SAAS;IAAE,QAAQ;IAAe;GAAO;GACzC,UAAU;IAAE,QAAQ;IAAe;GAAO;GAC1C,aAAa;IAAE,QAAQ;IAAe;GAAO;GAC7C,YAAY;IAAE,QAAQ;IAAe;GAAO;EAC9C;CACF;CAEA,MAAM,UAA2C;EAC/C,SAAS;EACT,UAAU;EACV,aAAa;EACb,YAAY;CACd;CACA,MAAM,mBAGF;EACF,SAAS,CACP;GAAE,QAAQ;GAAY,YAAY;EAAM,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BAAwB,MAAM,eAAe,MAAM,MAAM,cAAc,CAAC;CACxE,KAAK,MAAM;CACX,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"smooth-corners.js","names":[],"sources":["../../src/paths/smooth-corners.ts"],"sourcesContent":["import { minOf } from '@open-pencil/std/arrays'\n\nimport type { SceneNode } from '../types'\nimport type { PathSink } from './sink'\n\n/** What a rectangle's smoothed corners are drawn from. */\nexport type SmoothRectNode = Pick<\n SceneNode,\n | 'cornerRadius'\n | 'cornerSmoothing'\n | 'independentCorners'\n | 'topLeftRadius'\n | 'topRightRadius'\n | 'bottomRightRadius'\n | 'bottomLeftRadius'\n>\n\n/**\n * Where a smoothed rectangle is traced: a CanvasKit `PathBuilder`, or a writer of SVG path data.\n * `arcToRotated` takes CanvasKit's arguments, which match an SVG arc's.\n */\nexport interface SmoothCornerSink extends PathSink {\n arcToRotated(\n rx: number,\n ry: number,\n xAxisRotate: number,\n useSmallArc: boolean,\n isCCW: boolean,\n x: number,\n y: number\n ): unknown\n}\n\ntype SmoothCornerKey = 'topLeft' | 'topRight' | 'bottomRight' | 'bottomLeft'\n\ntype SmoothCorner = {\n radius: number\n budget: number\n}\n\ntype SmoothCornerPathParams = {\n a: number\n b: number\n c: number\n d: number\n p: number\n radius: number\n arcSectionLength: number\n}\n\nfunction smoothCornerRadii(\n node: SmoothRectNode,\n width: number,\n height: number,\n spread: number\n): Record<SmoothCornerKey, SmoothCorner> {\n const radius = (value: number) => Math.max(0, value + spread)\n const radii: Record<SmoothCornerKey, number> = node.independentCorners\n ? {\n topLeft: radius(node.topLeftRadius),\n topRight: radius(node.topRightRadius),\n bottomRight: radius(node.bottomRightRadius),\n bottomLeft: radius(node.bottomLeftRadius)\n }\n : {\n topLeft: radius(node.cornerRadius),\n topRight: radius(node.cornerRadius),\n bottomRight: radius(node.cornerRadius),\n bottomLeft: radius(node.cornerRadius)\n }\n\n if (\n radii.topLeft === radii.topRight &&\n radii.topRight === radii.bottomRight &&\n radii.bottomRight === radii.bottomLeft\n ) {\n const budget = Math.min(width, height) / 2\n const clampedRadius = Math.min(radii.topLeft, budget)\n return {\n topLeft: { radius: clampedRadius, budget },\n topRight: { radius: clampedRadius, budget },\n bottomRight: { radius: clampedRadius, budget },\n bottomLeft: { radius: clampedRadius, budget }\n }\n }\n\n const budgets: Record<SmoothCornerKey, number> = {\n topLeft: -1,\n topRight: -1,\n bottomRight: -1,\n bottomLeft: -1\n }\n const adjacentByCorner: Record<\n SmoothCornerKey,\n Array<{ corner: SmoothCornerKey; sideLength: number }>\n > = {\n topLeft: [\n { corner: 'topRight', sideLength: width },\n { corner: 'bottomLeft', sideLength: height }\n ],\n topRight: [\n { corner: 'topLeft', sideLength: width },\n { corner: 'bottomRight', sideLength: height }\n ],\n bottomRight: [\n { corner: 'bottomLeft', sideLength: width },\n { corner: 'topRight', sideLength: height }\n ],\n bottomLeft: [\n { corner: 'bottomRight', sideLength: width },\n { corner: 'topLeft', sideLength: height }\n ]\n }\n\n for (const corner of (Object.keys(radii) as SmoothCornerKey[]).sort(\n (a, b) => radii[b] - radii[a]\n )) {\n const cornerRadius = radii[corner]\n const budget = minOf(\n adjacentByCorner[corner].map((adjacent) => {\n const adjacentRadius = radii[adjacent.corner]\n if (cornerRadius === 0 && adjacentRadius === 0) return 0\n if (budgets[adjacent.corner] >= 0) return adjacent.sideLength - budgets[adjacent.corner]\n return (cornerRadius / (cornerRadius + adjacentRadius)) * adjacent.sideLength\n })\n )\n budgets[corner] = budget\n radii[corner] = Math.min(cornerRadius, budget)\n }\n\n return {\n topLeft: { radius: radii.topLeft, budget: budgets.topLeft },\n topRight: { radius: radii.topRight, budget: budgets.topRight },\n bottomRight: { radius: radii.bottomRight, budget: budgets.bottomRight },\n bottomLeft: { radius: radii.bottomLeft, budget: budgets.bottomLeft }\n }\n}\n\nfunction degreesToRadians(degrees: number): number {\n return (degrees * Math.PI) / 180\n}\n\nfunction smoothCornerPathParams(corner: SmoothCorner, smoothing: number): SmoothCornerPathParams {\n let cornerSmoothing = smoothing\n let p = (1 + cornerSmoothing) * corner.radius\n if (corner.radius > 0) {\n const maxSmoothing = corner.budget / corner.radius - 1\n cornerSmoothing = Math.min(cornerSmoothing, maxSmoothing)\n p = Math.min(p, corner.budget)\n }\n\n const arcMeasure = 90 * (1 - cornerSmoothing)\n const arcSectionLength = Math.sin(degreesToRadians(arcMeasure / 2)) * corner.radius * Math.sqrt(2)\n const angleAlpha = (90 - arcMeasure) / 2\n const p3ToP4Distance = corner.radius * Math.tan(degreesToRadians(angleAlpha / 2))\n const angleBeta = 45 * cornerSmoothing\n const c = p3ToP4Distance * Math.cos(degreesToRadians(angleBeta))\n const d = c * Math.tan(degreesToRadians(angleBeta))\n const b = (p - arcSectionLength - c - d) / 3\n\n return {\n a: 2 * b,\n b,\n c,\n d,\n p,\n radius: corner.radius,\n arcSectionLength\n }\n}\n\nfunction drawTopRightSmoothCorner(\n path: SmoothCornerSink,\n corner: SmoothCornerPathParams,\n x: number,\n y: number\n) {\n if (corner.radius === 0) {\n path.lineTo(x + corner.p, y)\n return\n }\n path.cubicTo(\n x + corner.a,\n y,\n x + corner.a + corner.b,\n y,\n x + corner.a + corner.b + corner.c,\n y + corner.d\n )\n path.arcToRotated(\n corner.radius,\n corner.radius,\n 0,\n true,\n false,\n x + corner.p - corner.d,\n y + corner.p - corner.a - corner.b - corner.c\n )\n path.cubicTo(\n x + corner.p,\n y + corner.p - corner.a - corner.b,\n x + corner.p,\n y + corner.p - corner.a,\n x + corner.p,\n y + corner.p\n )\n}\n\nfunction drawBottomRightSmoothCorner(\n path: SmoothCornerSink,\n corner: SmoothCornerPathParams,\n x: number,\n y: number\n) {\n if (corner.radius === 0) {\n path.lineTo(x, y + corner.p)\n return\n }\n path.cubicTo(\n x,\n y + corner.a,\n x,\n y + corner.a + corner.b,\n x - corner.d,\n y + corner.a + corner.b + corner.c\n )\n path.arcToRotated(\n corner.radius,\n corner.radius,\n 0,\n true,\n false,\n x - corner.p + corner.a + corner.b + corner.c,\n y + corner.p - corner.d\n )\n path.cubicTo(\n x - corner.p + corner.a + corner.b,\n y + corner.p,\n x - corner.p + corner.a,\n y + corner.p,\n x - corner.p,\n y + corner.p\n )\n}\n\nfunction drawBottomLeftSmoothCorner(\n path: SmoothCornerSink,\n corner: SmoothCornerPathParams,\n x: number,\n y: number\n) {\n if (corner.radius === 0) {\n path.lineTo(x - corner.p, y)\n return\n }\n path.cubicTo(\n x - corner.a,\n y,\n x - corner.a - corner.b,\n y,\n x - corner.a - corner.b - corner.c,\n y - corner.d\n )\n path.arcToRotated(\n corner.radius,\n corner.radius,\n 0,\n true,\n false,\n x - corner.p + corner.d,\n y - corner.p + corner.a + corner.b + corner.c\n )\n path.cubicTo(\n x - corner.p,\n y - corner.p + corner.a + corner.b,\n x - corner.p,\n y - corner.p + corner.a,\n x - corner.p,\n y - corner.p\n )\n}\n\nfunction drawTopLeftSmoothCorner(\n path: SmoothCornerSink,\n corner: SmoothCornerPathParams,\n x: number,\n y: number\n) {\n if (corner.radius === 0) {\n path.lineTo(x, y - corner.p)\n return\n }\n path.cubicTo(\n x,\n y - corner.a,\n x,\n y - corner.a - corner.b,\n x + corner.d,\n y - corner.a - corner.b - corner.c\n )\n path.arcToRotated(\n corner.radius,\n corner.radius,\n 0,\n true,\n false,\n x + corner.p - corner.a - corner.b - corner.c,\n y - corner.p + corner.d\n )\n path.cubicTo(\n x + corner.p - corner.a - corner.b,\n y - corner.p,\n x + corner.p - corner.a,\n y - corner.p,\n x + corner.p,\n y - corner.p\n )\n}\n\n/**\n * Trace a rectangle with smoothed corners into `path`, as Figma rounds them. False, with nothing\n * traced, when no corner is rounded, so the caller can draw a plain rectangle.\n */\nexport function traceSmoothRect(\n path: SmoothCornerSink,\n node: SmoothRectNode,\n box: { left: number; top: number; right: number; bottom: number },\n spread = 0\n): boolean {\n const { left, top, right, bottom } = box\n const smoothing = Math.max(0, Math.min(node.cornerSmoothing, 1))\n const corners = smoothCornerRadii(node, right - left, bottom - top, spread)\n const topLeftCorner = smoothCornerPathParams(corners.topLeft, smoothing)\n const topRightCorner = smoothCornerPathParams(corners.topRight, smoothing)\n const bottomRightCorner = smoothCornerPathParams(corners.bottomRight, smoothing)\n const bottomLeftCorner = smoothCornerPathParams(corners.bottomLeft, smoothing)\n\n if (\n topLeftCorner.radius === 0 &&\n topRightCorner.radius === 0 &&\n bottomRightCorner.radius === 0 &&\n bottomLeftCorner.radius === 0\n ) {\n return false\n }\n\n path.moveTo(right - topRightCorner.p, top)\n drawTopRightSmoothCorner(path, topRightCorner, right - topRightCorner.p, top)\n path.lineTo(right, bottom - bottomRightCorner.p)\n drawBottomRightSmoothCorner(path, bottomRightCorner, right, bottom - bottomRightCorner.p)\n path.lineTo(left + bottomLeftCorner.p, bottom)\n drawBottomLeftSmoothCorner(path, bottomLeftCorner, left + bottomLeftCorner.p, bottom)\n path.lineTo(left, top + topLeftCorner.p)\n drawTopLeftSmoothCorner(path, topLeftCorner, left, top + topLeftCorner.p)\n path.close()\n return true\n}\n"],"mappings":";;AAkDA,SAAS,kBACP,MACA,OACA,QACA,QACuC;CACvC,MAAM,UAAU,UAAkB,KAAK,IAAI,GAAG,QAAQ,MAAM;CAC5D,MAAM,QAAyC,KAAK,qBAChD;EACE,SAAS,OAAO,KAAK,aAAa;EAClC,UAAU,OAAO,KAAK,cAAc;EACpC,aAAa,OAAO,KAAK,iBAAiB;EAC1C,YAAY,OAAO,KAAK,gBAAgB;CAC1C,IACA;EACE,SAAS,OAAO,KAAK,YAAY;EACjC,UAAU,OAAO,KAAK,YAAY;EAClC,aAAa,OAAO,KAAK,YAAY;EACrC,YAAY,OAAO,KAAK,YAAY;CACtC;CAEJ,IACE,MAAM,YAAY,MAAM,YACxB,MAAM,aAAa,MAAM,eACzB,MAAM,gBAAgB,MAAM,YAC5B;EACA,MAAM,SAAS,KAAK,IAAI,OAAO,MAAM,IAAI;EACzC,MAAM,gBAAgB,KAAK,IAAI,MAAM,SAAS,MAAM;EACpD,OAAO;GACL,SAAS;IAA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AgB,QAAQ,eAAe,GAAG,GAAG;CAC5E,KAAK,OAAO,OAAO,SAAS,kBAAkB,CAAC;CAC/C,4BAA4B,MAAM,mBAAmB,OAAO,SAAS,kBAAkB,CAAC;CACxF,KAAK,OAAO,OAAO,iBAAiB,GAAG,MAAM;CAC7C,2BAA2B,MAAM,kBAAkB,OAAO,iBAAiB,GAAG,MAAM;CACpF,KAAK,OAAO,MAAM,MAAM,cAAc,CAAC;CACvC,wBAAwB,MAAM,eAAe,MAAM,MAAM,cAAc,CAAC;CACxE,KAAK,MAAM;CACX,OAAO;AACT"}
|
|
@@ -32,12 +32,6 @@ interface Rect {
|
|
|
32
32
|
width: number;
|
|
33
33
|
height: number;
|
|
34
34
|
}
|
|
35
|
-
type JSONPrimitive = string | number | boolean | null;
|
|
36
|
-
type JSONValue = JSONPrimitive | JSONObject | JSONArray;
|
|
37
|
-
type JSONObject = {
|
|
38
|
-
[key: string]: unknown;
|
|
39
|
-
};
|
|
40
|
-
type JSONArray = unknown[];
|
|
41
35
|
//#endregion
|
|
42
|
-
export { Color, GUID,
|
|
36
|
+
export { Color, GUID, Matrix, Rect, Size, Vector, finiteNumberSchema, matrixSchema, vectorSchema };
|
|
43
37
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/primitives/index.ts"],"mappings":";;UAAiB;EACf;EACA;;UAGe;EACf;EACA;EACA;EACA;;UAGe;EACf;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;;UAGe;EACf;EACA;EACA;EACA
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/primitives/index.ts"],"mappings":";;UAAiB;EACf;EACA;;UAGe;EACf;EACA;EACA;EACA;;UAGe;EACf;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;;UAGe;EACf;EACA;EACA;EACA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.d.ts","names":[],"sources":["../../src/shaders/model.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"model.d.ts","names":[],"sources":["../../src/shaders/model.ts"],"mappings":";;;;KAaK,aAAa,KAAK;;iBAGP,iBAAiB,MAAM,KAAK,2BAA2B;;;;;;iBASvD,cACd,MAAM,KAAK,0BACX,OAAO,OACN;;iBAMa,eAAe,MAAM;;;;;iBAQrB,iBACd,MAAM,KAAK,0BACX,iBAAiB,QACjB,mBAAkB,gBACjB;;;;;iBAea,kBAAkB,QAAQ;EACxC,OAAO;EACP,QAAQ;;;iBAiBM,gBAAgB,QAAQ;;;;;iBAQxB,qBACd,QAAQ,aACR;EAAQ;EAAe"}
|
package/dist/shaders/model.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { TRANSPARENT } from "../constants.js";
|
|
2
|
-
import { randomHex } from "../random.js";
|
|
3
2
|
import { readAllPluginData, withAllPluginData } from "../plugin-data/field.js";
|
|
4
3
|
import { OPEN_PENCIL_PLUGIN_DATA } from "../plugin-data/fields.js";
|
|
5
4
|
import { imagePaintHashes } from "../images.js";
|
|
5
|
+
import { randomHex } from "@open-pencil/std/random";
|
|
6
6
|
import { sha1 } from "@noble/hashes/legacy.js";
|
|
7
7
|
import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils.js";
|
|
8
8
|
//#region src/shaders/model.ts
|