svelteplot 0.8.1-pr-298.0 → 0.8.1-pr-298.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/Mark.svelte +1 -1
  2. package/dist/Mark.svelte.d.ts +1 -0
  3. package/dist/constants.d.ts +2 -0
  4. package/dist/constants.js +2 -0
  5. package/dist/helpers/projection.js +7 -2
  6. package/dist/marks/Area.svelte.d.ts +1 -0
  7. package/dist/marks/AreaX.svelte.d.ts +1 -0
  8. package/dist/marks/Arrow.svelte.d.ts +1 -0
  9. package/dist/marks/AxisX.svelte.d.ts +1 -0
  10. package/dist/marks/AxisY.svelte +1 -1
  11. package/dist/marks/AxisY.svelte.d.ts +1 -0
  12. package/dist/marks/BarX.svelte.d.ts +1 -0
  13. package/dist/marks/BarY.svelte.d.ts +1 -0
  14. package/dist/marks/BoxX.svelte +1 -0
  15. package/dist/marks/BoxY.svelte +1 -0
  16. package/dist/marks/Cell.svelte.d.ts +1 -0
  17. package/dist/marks/Dot.svelte.d.ts +1 -0
  18. package/dist/marks/DotX.svelte.d.ts +1 -0
  19. package/dist/marks/DotY.svelte.d.ts +1 -0
  20. package/dist/marks/Frame.svelte.d.ts +1 -0
  21. package/dist/marks/Geo.svelte +2 -0
  22. package/dist/marks/Geo.svelte.d.ts +2 -0
  23. package/dist/marks/GridX.svelte.d.ts +1 -0
  24. package/dist/marks/GridY.svelte.d.ts +1 -0
  25. package/dist/marks/Line.svelte +5 -2
  26. package/dist/marks/Line.svelte.d.ts +1 -0
  27. package/dist/marks/LineX.svelte.d.ts +1 -0
  28. package/dist/marks/LineY.svelte.d.ts +1 -0
  29. package/dist/marks/Link.svelte.d.ts +1 -0
  30. package/dist/marks/Rect.svelte.d.ts +1 -0
  31. package/dist/marks/RuleX.svelte.d.ts +1 -0
  32. package/dist/marks/RuleY.svelte.d.ts +1 -0
  33. package/dist/marks/Spike.svelte.d.ts +1 -0
  34. package/dist/marks/Text.svelte.d.ts +1 -0
  35. package/dist/marks/TickX.svelte.d.ts +1 -0
  36. package/dist/marks/TickY.svelte.d.ts +1 -0
  37. package/dist/marks/Trail.svelte +163 -0
  38. package/dist/marks/Trail.svelte.d.ts +44 -0
  39. package/dist/marks/Vector.svelte.d.ts +1 -0
  40. package/dist/marks/helpers/Box.svelte +42 -39
  41. package/dist/marks/helpers/TrailCanvas.svelte +140 -0
  42. package/dist/marks/helpers/TrailCanvas.svelte.d.ts +40 -0
  43. package/dist/marks/helpers/trail.d.ts +23 -0
  44. package/dist/marks/helpers/trail.js +372 -0
  45. package/dist/marks/index.d.ts +1 -0
  46. package/dist/marks/index.js +1 -0
  47. package/dist/types/mark.d.ts +2 -1
  48. package/dist/types/plot.d.ts +5 -1
  49. package/package.json +16 -15
@@ -43,6 +43,7 @@
43
43
  import { resolveChannel } from '../../helpers/resolve.js';
44
44
  import type { BaseMarkProps, ChannelAccessor, DataRecord, RawValue } from '../../types';
45
45
  import { IS_SORTED } from '../../transforms/sort';
46
+ import Up from '../../../theme/components/icons/Up.svelte';
46
47
 
47
48
  let markProps: BoxMarkProps = $props();
48
49
 
@@ -80,7 +81,7 @@
80
81
  const { data: grouped, ...groupChannels } = $derived(
81
82
  groupFn(
82
83
  {
83
- data: data.filter((d) => resolveChannel(yProp, d, { x, y }) != null),
84
+ data: data.filter((d) => resolveChannel(xProp, d, { x, y }) != null),
84
85
  x,
85
86
  y,
86
87
  [x1Prop]: xChannel,
@@ -121,44 +122,46 @@
121
122
  : 0) || 0;
122
123
 
123
124
  const boxData = $derived.by(() => {
124
- const boxes = grouped.map((row) => {
125
- const medianKey = groupChannels[xProp];
126
- const p25Key = groupChannels[x1Prop];
127
- const p75Key = groupChannels[x2Prop];
128
- const groupKey = groupChannels[yProp];
129
-
130
- const iqr = row[p75Key] - row[p25Key];
131
- const whisker = iqr * 1.5;
132
- const lower = row[p25Key] - whisker;
133
- const upper = row[p75Key] + whisker;
134
- const data = row[groupChannels.fill].map((d) => ({
135
- ...d,
136
- [orientation === 'y' ? Y : X]: resolveChannel(xProp, d, {
137
- x,
138
- y
139
- })
140
- }));
141
- const valueSym = orientation === 'y' ? Y : X;
142
- const groupSym = orientation === 'y' ? X : Y;
143
- const outliers = data.filter((d) => d[valueSym] < lower || d[valueSym] > upper);
144
- const inside = data
145
- .filter((d) => d[valueSym] >= lower && d[valueSym] <= upper)
146
- .sort((a, b) => a[valueSym] - b[valueSym]);
147
-
148
- return {
149
- ...data[0],
150
- [SORT_REF]: row[groupChannels.fill]?.[0],
151
- [groupSym]: row[groupKey],
152
- [P25]: row[p25Key],
153
- [MEDIAN]: row[medianKey],
154
- [P75]: row[p75Key],
155
- [MIN]: inside[0][valueSym],
156
- [MAX]: inside.at(-1)[valueSym],
157
- [FX]: resolveChannel('fx', data[0], { fx }, null),
158
- [FY]: resolveChannel('fy', data[0], { fy }, null),
159
- [OUTLIERS]: outliers
160
- };
161
- });
125
+ const boxes = grouped
126
+ .map((row) => {
127
+ const medianKey = groupChannels[xProp];
128
+ const p25Key = groupChannels[x1Prop];
129
+ const p75Key = groupChannels[x2Prop];
130
+ const groupKey = groupChannels[yProp];
131
+
132
+ const iqr = row[p75Key] - row[p25Key];
133
+ const whisker = iqr * 1.5;
134
+ const lower = row[p25Key] - whisker;
135
+ const upper = row[p75Key] + whisker;
136
+ const data = row[groupChannels.fill].map((d) => ({
137
+ ...d,
138
+ [orientation === 'y' ? Y : X]: resolveChannel(xProp, d, {
139
+ x,
140
+ y
141
+ })
142
+ }));
143
+ const valueSym = orientation === 'y' ? Y : X;
144
+ const groupSym = orientation === 'y' ? X : Y;
145
+ const outliers = data.filter((d) => d[valueSym] < lower || d[valueSym] > upper);
146
+ const inside = data
147
+ .filter((d) => d[valueSym] >= lower && d[valueSym] <= upper)
148
+ .sort((a, b) => a[valueSym] - b[valueSym]);
149
+
150
+ return {
151
+ ...data[0],
152
+ [SORT_REF]: row[groupChannels.fill]?.[0],
153
+ [groupSym]: row[groupKey],
154
+ [P25]: row[p25Key],
155
+ [MEDIAN]: row[medianKey],
156
+ [P75]: row[p75Key],
157
+ [MIN]: inside.length ? inside[0][valueSym] : null,
158
+ [MAX]: inside.length ? inside.at(-1)[valueSym] : null,
159
+ [FX]: resolveChannel('fx', data[0], { fx }, null),
160
+ [FY]: resolveChannel('fy', data[0], { fy }, null),
161
+ [OUTLIERS]: outliers
162
+ };
163
+ })
164
+ .filter(Boolean);
162
165
 
163
166
  const stripSortRef = ({ [SORT_REF]: _, ...rest }) => rest;
164
167
 
@@ -0,0 +1,140 @@
1
+ <script lang="ts" generics="Datum extends DataRecord">
2
+ import type {
3
+ Mark,
4
+ BaseMarkProps,
5
+ PlotContext,
6
+ ScaledDataRecord,
7
+ UsedScales,
8
+ CurveName,
9
+ ConstantAccessor
10
+ } from '../../types/index.js';
11
+ import CanvasLayer from './CanvasLayer.svelte';
12
+ import type { Attachment } from 'svelte/attachments';
13
+ import { devicePixelRatio } from 'svelte/reactivity/window';
14
+ import { resolveColor } from './canvas.js';
15
+ import { getContext } from 'svelte';
16
+ import type { CurveFactory } from 'd3-shape';
17
+ import { trailPath, type TrailSample } from './trail';
18
+ import { resolveProp, resolveScaledStyleProps } from '../../helpers/resolve';
19
+
20
+ interface TrailCanvasProps<Datum> {
21
+ curve?: CurveName | CurveFactory;
22
+ tension?: number;
23
+ cap?: 'butt' | 'round';
24
+ resolution?: number | 'auto';
25
+ data: ScaledDataRecord<Datum>[][];
26
+ usedScales: UsedScales;
27
+ options: {
28
+ fill?: ConstantAccessor<string, Datum>;
29
+ defined?: ConstantAccessor<boolean, Datum>;
30
+ opacity?: ConstantAccessor<number, Datum>;
31
+ 'fill-opacity'?: ConstantAccessor<number, Datum>;
32
+ };
33
+ }
34
+
35
+ let {
36
+ curve,
37
+ cap,
38
+ tension,
39
+ resolution,
40
+ usedScales,
41
+ data: groupedTrailData,
42
+ options
43
+ }: TrailCanvasProps<Datum> = $props();
44
+
45
+ function maybeOpacity(value: unknown) {
46
+ return value == null ? 1 : +value;
47
+ }
48
+
49
+ const { getPlotState } = getContext<PlotContext>('svelteplot');
50
+ const plot = $derived(getPlotState());
51
+
52
+ const render = ((canvas: HTMLCanvasElement) => {
53
+ const context = canvas.getContext('2d');
54
+
55
+ $effect(() => {
56
+ if (context) {
57
+ context.resetTransform();
58
+ context.scale(devicePixelRatio.current ?? 1, devicePixelRatio.current ?? 1);
59
+
60
+ for (const trailData of groupedTrailData) {
61
+ if (trailData.length < 2) continue;
62
+
63
+ // Get the first point to determine line styles
64
+ const firstPoint = trailData[0];
65
+ if (!firstPoint || !firstPoint.valid) continue;
66
+
67
+ const samples = trailData.map((d) => ({
68
+ x: Number(d.x),
69
+ y: Number(d.y),
70
+ r: Number(d.r ?? 0)
71
+ })) satisfies TrailSample[];
72
+
73
+ const defined = trailData.map(
74
+ (d) =>
75
+ d.valid &&
76
+ d.r >= 0 &&
77
+ (resolveProp(options.defined, d.datum, true) ?? true)
78
+ );
79
+
80
+ let { fill, ...restStyles } = resolveScaledStyleProps(
81
+ firstPoint.datum,
82
+ options,
83
+ usedScales,
84
+ plot,
85
+ 'fill'
86
+ );
87
+
88
+ const opacity = maybeOpacity(restStyles['opacity']);
89
+ const fillOpacity = maybeOpacity(restStyles['fill-opacity']);
90
+
91
+ fill = resolveColor(fill, canvas);
92
+
93
+ context.fillStyle = fill ? fill : 'currentColor';
94
+ context.beginPath();
95
+
96
+ trailPath(samples, defined, context, {
97
+ curve,
98
+ cap,
99
+ tension,
100
+ ...(typeof resolution === 'number' ? { samplesPerSegment: resolution } : {})
101
+ });
102
+
103
+ context.globalAlpha = opacity * fillOpacity;
104
+ context.fill();
105
+
106
+ // {#each groupedTrailData as trailData, i (i)}
107
+ // {@const samples = trailData.map((d) => ({
108
+ // x: Number(d.x),
109
+ // y: Number(d.y),
110
+ // r: Number(d.r ?? 0)
111
+ // })) satisfies TrailSample[]}
112
+ // {@const defined = trailData.map(
113
+ // (d) =>
114
+ // d.valid &&
115
+ // d.r >= 0 &&
116
+ // (resolveProp(options.defined, d.datum, true) ?? true)
117
+ // )}
118
+ // {@const pathString = trailPath(samples, defined, d3Path(), {
119
+ // curve,
120
+ // cap,
121
+ // tension,
122
+ // ...(typeof resolution === 'number'
123
+ // ? { samplesPerSegment: resolution }
124
+ // : {})
125
+ }
126
+ }
127
+
128
+ return () => {
129
+ context?.clearRect(
130
+ 0,
131
+ 0,
132
+ plot.width * (devicePixelRatio.current ?? 1),
133
+ plot.height * (devicePixelRatio.current ?? 1)
134
+ );
135
+ };
136
+ });
137
+ }) as Attachment;
138
+ </script>
139
+
140
+ <CanvasLayer {@attach render} />
@@ -0,0 +1,40 @@
1
+ import type { ScaledDataRecord, UsedScales, CurveName, ConstantAccessor } from '../../types/index.js';
2
+ import type { CurveFactory } from 'd3-shape';
3
+ interface TrailCanvasProps<Datum> {
4
+ curve?: CurveName | CurveFactory;
5
+ tension?: number;
6
+ cap?: 'butt' | 'round';
7
+ resolution?: number | 'auto';
8
+ data: ScaledDataRecord<Datum>[][];
9
+ usedScales: UsedScales;
10
+ options: {
11
+ fill?: ConstantAccessor<string, Datum>;
12
+ defined?: ConstantAccessor<boolean, Datum>;
13
+ opacity?: ConstantAccessor<number, Datum>;
14
+ 'fill-opacity'?: ConstantAccessor<number, Datum>;
15
+ };
16
+ }
17
+ declare function $$render<Datum extends DataRecord>(): {
18
+ props: TrailCanvasProps<Datum>;
19
+ exports: {};
20
+ bindings: "";
21
+ slots: {};
22
+ events: {};
23
+ };
24
+ declare class __sveltets_Render<Datum extends DataRecord> {
25
+ props(): ReturnType<typeof $$render<Datum>>['props'];
26
+ events(): ReturnType<typeof $$render<Datum>>['events'];
27
+ slots(): ReturnType<typeof $$render<Datum>>['slots'];
28
+ bindings(): "";
29
+ exports(): {};
30
+ }
31
+ interface $$IsomorphicComponent {
32
+ new <Datum extends DataRecord>(options: import('svelte').ComponentConstructorOptions<ReturnType<__sveltets_Render<Datum>['props']>>): import('svelte').SvelteComponent<ReturnType<__sveltets_Render<Datum>['props']>, ReturnType<__sveltets_Render<Datum>['events']>, ReturnType<__sveltets_Render<Datum>['slots']>> & {
33
+ $$bindings?: ReturnType<__sveltets_Render<Datum>['bindings']>;
34
+ } & ReturnType<__sveltets_Render<Datum>['exports']>;
35
+ <Datum extends DataRecord>(internal: unknown, props: ReturnType<__sveltets_Render<Datum>['props']> & {}): ReturnType<__sveltets_Render<Datum>['exports']>;
36
+ z_$$bindings?: ReturnType<__sveltets_Render<any>['bindings']>;
37
+ }
38
+ declare const TrailCanvas: $$IsomorphicComponent;
39
+ type TrailCanvas<Datum extends DataRecord> = InstanceType<typeof TrailCanvas<Datum>>;
40
+ export default TrailCanvas;
@@ -0,0 +1,23 @@
1
+ import type { Path } from 'd3-path';
2
+ import type { CurveName } from '../../types/index.js';
3
+ import type { CurveFactory } from 'd3-shape';
4
+ export type TrailContext = CanvasRenderingContext2D | Path;
5
+ export type TrailCurve = CurveName | CurveFactory;
6
+ export type TrailCap = 'round' | 'butt';
7
+ export type TrailOptions = {
8
+ curve?: TrailCurve;
9
+ samplesPerSegment?: number;
10
+ cap?: TrailCap;
11
+ tension?: number;
12
+ };
13
+ export type TrailSample = {
14
+ x: number;
15
+ y: number;
16
+ r: number;
17
+ };
18
+ /**
19
+ * Draw a stroked capsule trail along successive points with varying widths.
20
+ * Adapted from Vega's trail mark implementation.
21
+ */
22
+ export declare function trailPath(samples: TrailSample[], defined: boolean[], context: TrailContext, options?: TrailOptions): string | void;
23
+ export default trailPath;
@@ -0,0 +1,372 @@
1
+ import { TAU } from '../../constants.js';
2
+ import { maybeCurve } from '../../helpers/curves.js';
3
+ /**
4
+ * Draw a stroked capsule trail along successive points with varying widths.
5
+ * Adapted from Vega's trail mark implementation.
6
+ */
7
+ export function trailPath(samples, defined, context, options = {}) {
8
+ const { curve = 'linear', cap = 'round', tension = 0.5 } = options;
9
+ const samplesPerSegment = options.samplesPerSegment ?? estimateSamplesPerSegment(samples, defined);
10
+ const curveFactory = maybeCurve(curve, tension);
11
+ let drawSamples = samples;
12
+ let drawDefined = defined;
13
+ if (curve !== 'linear' || tension !== 0) {
14
+ const smoothedSamples = [];
15
+ const smoothedDefined = [];
16
+ const len = Math.min(samples.length, defined.length);
17
+ let i = 0;
18
+ while (i < len) {
19
+ if (!defined[i]) {
20
+ smoothedSamples.push(samples[i]);
21
+ smoothedDefined.push(false);
22
+ i += 1;
23
+ continue;
24
+ }
25
+ const segment = [];
26
+ while (i < len && defined[i]) {
27
+ segment.push(samples[i]);
28
+ i += 1;
29
+ }
30
+ const resampled = resampleCurve(segment, curveFactory, Math.max(1, samplesPerSegment));
31
+ smoothedSamples.push(...resampled);
32
+ smoothedDefined.push(...new Array(resampled.length).fill(true));
33
+ // preserve a gap between defined segments
34
+ if (i < len) {
35
+ smoothedSamples.push(samples[i]);
36
+ smoothedDefined.push(false);
37
+ }
38
+ }
39
+ drawSamples = smoothedSamples;
40
+ drawDefined = smoothedDefined;
41
+ }
42
+ const len = Math.min(drawSamples.length, drawDefined.length);
43
+ if (len === 0)
44
+ return;
45
+ // Butt caps: build joined polygon offsets using angle bisectors to avoid gaps.
46
+ if (cap === 'butt') {
47
+ const normalizeVec = (x, y) => {
48
+ const lenVec = Math.hypot(x, y);
49
+ return lenVec === 0 ? [0, 0] : [x / lenVec, y / lenVec];
50
+ };
51
+ let i = 0;
52
+ while (i < len) {
53
+ if (!drawDefined[i]) {
54
+ i += 1;
55
+ continue;
56
+ }
57
+ const runStart = i;
58
+ while (i < len && drawDefined[i])
59
+ i += 1;
60
+ const runEnd = i - 1;
61
+ const left = [];
62
+ const right = [];
63
+ for (let j = runStart; j <= runEnd; j += 1) {
64
+ const curr = drawSamples[j];
65
+ const r = curr.r;
66
+ const hasPrev = j > runStart;
67
+ const hasNext = j < runEnd;
68
+ const prev = hasPrev ? drawSamples[j - 1] : curr;
69
+ const next = hasNext ? drawSamples[j + 1] : curr;
70
+ const dirPrev = hasPrev
71
+ ? normalizeVec(curr.x - prev.x, curr.y - prev.y)
72
+ : normalizeVec(next.x - curr.x, next.y - curr.y);
73
+ const dirNext = hasNext ? normalizeVec(next.x - curr.x, next.y - curr.y) : dirPrev;
74
+ const normPrev = [-dirPrev[1], dirPrev[0]];
75
+ const normNext = [-dirNext[1], dirNext[0]];
76
+ let nx = normPrev[0] + normNext[0];
77
+ let ny = normPrev[1] + normNext[1];
78
+ const nLen = Math.hypot(nx, ny);
79
+ if (nLen < 1e-6) {
80
+ // Straight/180-deg turn: fall back to current normal.
81
+ nx = normPrev[0];
82
+ ny = normPrev[1];
83
+ }
84
+ else {
85
+ nx /= nLen;
86
+ ny /= nLen;
87
+ }
88
+ // Scale to preserve half-width along the miter direction.
89
+ const dot = nx * normPrev[0] + ny * normPrev[1];
90
+ const safeDot = Math.abs(dot) < 1e-6 ? 1 : dot;
91
+ const scale = r / safeDot;
92
+ const ox = nx * scale;
93
+ const oy = ny * scale;
94
+ left.push([curr.x + ox, curr.y + oy]);
95
+ right.push([curr.x - ox, curr.y - oy]);
96
+ }
97
+ if (left.length > 0) {
98
+ context.moveTo(left[0][0], left[0][1]);
99
+ for (let j = 1; j < left.length; j += 1) {
100
+ context.lineTo(left[j][0], left[j][1]);
101
+ }
102
+ for (let j = right.length - 1; j >= 0; j -= 1) {
103
+ context.lineTo(right[j][0], right[j][1]);
104
+ }
105
+ context.closePath();
106
+ }
107
+ }
108
+ return typeof context.toString === 'function' ? context.toString() : undefined;
109
+ }
110
+ // Round caps: original capsule behavior.
111
+ let ready = false;
112
+ let x1 = 0;
113
+ let y1 = 0;
114
+ let r1 = 0;
115
+ function point(x2, y2, r2, isStartOfRun, isEndOfRun) {
116
+ if (ready) {
117
+ let ux = y1 - y2;
118
+ let uy = x2 - x1;
119
+ if (ux || uy) {
120
+ // compute normal vector scaled by radius
121
+ const ud = Math.hypot(ux, uy);
122
+ const rx = (ux /= ud) * r1;
123
+ const ry = (uy /= ud) * r1;
124
+ const t = Math.atan2(uy, ux);
125
+ // keep rounded joins for interior segments even when using butt caps
126
+ const drawStartCap = !isStartOfRun || cap === 'round';
127
+ const drawEndCap = !isEndOfRun || cap === 'round';
128
+ context.moveTo(x1 - rx, y1 - ry);
129
+ context.lineTo(x2 - ux * r2, y2 - uy * r2);
130
+ if (drawEndCap) {
131
+ context.arc(x2, y2, r2, t - Math.PI, t);
132
+ }
133
+ else {
134
+ context.lineTo(x2 + ux * r2, y2 + uy * r2);
135
+ }
136
+ context.lineTo(x1 + rx, y1 + ry);
137
+ if (drawStartCap) {
138
+ context.arc(x1, y1, r1, t, t + Math.PI);
139
+ }
140
+ }
141
+ else {
142
+ if (cap === 'round' || (!isStartOfRun && !isEndOfRun)) {
143
+ context.arc(x2, y2, r2, 0, TAU);
144
+ }
145
+ }
146
+ context.closePath();
147
+ }
148
+ else {
149
+ ready = true;
150
+ }
151
+ x1 = x2;
152
+ y1 = y2;
153
+ r1 = r2;
154
+ }
155
+ let i = 0;
156
+ while (i < len) {
157
+ // Skip gaps
158
+ if (!drawDefined[i]) {
159
+ i += 1;
160
+ ready = false;
161
+ continue;
162
+ }
163
+ const runStart = i;
164
+ while (i < len && drawDefined[i])
165
+ i += 1;
166
+ const runEnd = i - 1;
167
+ // Prime the first point of the run
168
+ const first = drawSamples[runStart];
169
+ ready = false;
170
+ x1 = first.x;
171
+ y1 = first.y;
172
+ r1 = first.r;
173
+ ready = true;
174
+ for (let j = runStart + 1; j <= runEnd; j += 1) {
175
+ const { x: x2, y: y2, r } = drawSamples[j];
176
+ const isStart = j - 1 === runStart;
177
+ const isEnd = j === runEnd;
178
+ point(Number(x2), Number(y2), Number(r), isStart, isEnd);
179
+ }
180
+ ready = false;
181
+ }
182
+ return typeof context.toString === 'function' ? context.toString() : undefined;
183
+ }
184
+ function resampleCurve(points, curveFactory, samplesPerSegment) {
185
+ if (points.length === 0)
186
+ return [];
187
+ const commands = [];
188
+ let pendingRadius = points[0].r;
189
+ let currentRadius = points[0].r;
190
+ let currentPoint = null;
191
+ const ctx = {
192
+ beginPath() { },
193
+ closePath() { },
194
+ moveTo(x, y) {
195
+ currentPoint = [x, y];
196
+ currentRadius = pendingRadius;
197
+ commands.push({ type: 'move', to: [x, y], r: currentRadius });
198
+ },
199
+ lineTo(x, y) {
200
+ const from = currentPoint ?? [x, y];
201
+ commands.push({
202
+ type: 'line',
203
+ from: [from[0], from[1], currentRadius],
204
+ to: [x, y, pendingRadius]
205
+ });
206
+ currentPoint = [x, y];
207
+ currentRadius = pendingRadius;
208
+ },
209
+ bezierCurveTo(x1, y1, x2, y2, x, y) {
210
+ const from = currentPoint ?? [x, y];
211
+ commands.push({
212
+ type: 'cubic',
213
+ from: [from[0], from[1], currentRadius],
214
+ cp1: [x1, y1],
215
+ cp2: [x2, y2],
216
+ to: [x, y, pendingRadius]
217
+ });
218
+ currentPoint = [x, y];
219
+ currentRadius = pendingRadius;
220
+ },
221
+ quadraticCurveTo(x1, y1, x, y) {
222
+ const from = currentPoint ?? [x, y];
223
+ commands.push({
224
+ type: 'quad',
225
+ from: [from[0], from[1], currentRadius],
226
+ cp: [x1, y1],
227
+ to: [x, y, pendingRadius]
228
+ });
229
+ currentPoint = [x, y];
230
+ currentRadius = pendingRadius;
231
+ },
232
+ arc() { },
233
+ rect() { }
234
+ };
235
+ const curve = curveFactory(ctx);
236
+ curve.lineStart();
237
+ for (let idx = 0; idx < points.length; idx += 1) {
238
+ const pt = points[idx];
239
+ pendingRadius = pt.r;
240
+ curve.point(pt.x, pt.y);
241
+ }
242
+ curve.lineEnd();
243
+ const geom = flattenCommands(commands, samplesPerSegment);
244
+ if (geom.length === 0)
245
+ return geom;
246
+ // Re-map radii along the resampled path using the original cumulative
247
+ // length as the parameter to avoid curve-specific radius drift.
248
+ const origCum = [0];
249
+ for (let i = 1; i < points.length; i += 1) {
250
+ const dx = points[i].x - points[i - 1].x;
251
+ const dy = points[i].y - points[i - 1].y;
252
+ origCum.push(origCum[i - 1] + Math.hypot(dx, dy));
253
+ }
254
+ const origTotal = origCum[origCum.length - 1] || 1;
255
+ const resCum = [0];
256
+ for (let i = 1; i < geom.length; i += 1) {
257
+ const dx = geom[i].x - geom[i - 1].x;
258
+ const dy = geom[i].y - geom[i - 1].y;
259
+ resCum.push(resCum[i - 1] + Math.hypot(dx, dy));
260
+ }
261
+ const resTotal = resCum[resCum.length - 1] || 1;
262
+ const radiusAt = (target) => {
263
+ let idx = 1;
264
+ while (idx < origCum.length && origCum[idx] < target)
265
+ idx += 1;
266
+ if (idx === origCum.length)
267
+ return points[points.length - 1].r;
268
+ const t0 = origCum[idx - 1];
269
+ const t1 = origCum[idx];
270
+ const r0 = points[idx - 1].r;
271
+ const r1 = points[idx].r;
272
+ const t = t1 === t0 ? 0 : (target - t0) / (t1 - t0);
273
+ return lerp(r0, r1, t);
274
+ };
275
+ for (let i = 0; i < geom.length; i += 1) {
276
+ const frac = resCum[i] / resTotal;
277
+ geom[i].r = Number(radiusAt(frac * origTotal).toFixed(2));
278
+ }
279
+ return geom;
280
+ }
281
+ function flattenCommands(commands, samplesPerSegment, precision = 2) {
282
+ const result = [];
283
+ let last = null;
284
+ const round = (v) => {
285
+ const m = 10 ** precision;
286
+ return Math.round(v * m) / m;
287
+ };
288
+ const pushPoint = (x, y, r) => {
289
+ x = round(x);
290
+ y = round(y);
291
+ r = round(r);
292
+ if (!last || last[0] !== x || last[1] !== y || last[2] !== r) {
293
+ result.push({ x, y, r });
294
+ last = [x, y, r];
295
+ }
296
+ };
297
+ for (const cmd of commands) {
298
+ if (cmd.type === 'move') {
299
+ pushPoint(cmd.to[0], cmd.to[1], cmd.r);
300
+ continue;
301
+ }
302
+ if (cmd.type === 'line') {
303
+ const [x1, y1, r1] = cmd.from;
304
+ const [x2, y2, r2] = cmd.to;
305
+ for (let step = 1; step <= samplesPerSegment; step += 1) {
306
+ const t = step / samplesPerSegment;
307
+ pushPoint(lerp(x1, x2, t), lerp(y1, y2, t), lerp(r1, r2, t));
308
+ }
309
+ continue;
310
+ }
311
+ if (cmd.type === 'cubic') {
312
+ const [x0, y0, r0] = cmd.from;
313
+ const [x1, y1] = cmd.cp1;
314
+ const [x2, y2] = cmd.cp2;
315
+ const [x3, y3, r3] = cmd.to;
316
+ for (let step = 1; step <= samplesPerSegment; step += 1) {
317
+ const t = step / samplesPerSegment;
318
+ pushPoint(cubic(x0, x1, x2, x3, t), cubic(y0, y1, y2, y3, t), lerp(r0, r3, t));
319
+ }
320
+ continue;
321
+ }
322
+ if (cmd.type === 'quad') {
323
+ const [x0, y0, r0] = cmd.from;
324
+ const [cx, cy] = cmd.cp;
325
+ const [x1, y1, r1] = cmd.to;
326
+ for (let step = 1; step <= samplesPerSegment; step += 1) {
327
+ const t = step / samplesPerSegment;
328
+ pushPoint(quad(x0, cx, x1, t), quad(y0, cy, y1, t), lerp(r0, r1, t));
329
+ }
330
+ }
331
+ }
332
+ return result;
333
+ }
334
+ function cubic(p0, p1, p2, p3, t) {
335
+ const it = 1 - t;
336
+ return it * it * it * p0 + 3 * it * it * t * p1 + 3 * it * t * t * p2 + t * t * t * p3;
337
+ }
338
+ function quad(p0, p1, p2, t) {
339
+ const it = 1 - t;
340
+ return it * it * p0 + 2 * it * t * p1 + t * t * p2;
341
+ }
342
+ function lerp(a, b, t) {
343
+ return a + (b - a) * t;
344
+ }
345
+ function estimateSamplesPerSegment(samples, defined) {
346
+ const n = Math.min(samples.length, defined.length);
347
+ let distSum = 0;
348
+ let distCount = 0;
349
+ let rSum = 0;
350
+ let rCount = 0;
351
+ for (let i = 0; i < n; i++) {
352
+ if (defined[i]) {
353
+ rSum += samples[i].r;
354
+ rCount += 1;
355
+ }
356
+ if (i === 0 || !defined[i] || !defined[i - 1])
357
+ continue;
358
+ const dx = samples[i].x - samples[i - 1].x;
359
+ const dy = samples[i].y - samples[i - 1].y;
360
+ const d = Math.hypot(dx, dy);
361
+ if (isFinite(d) && d > 0) {
362
+ distSum += d;
363
+ distCount += 1;
364
+ }
365
+ }
366
+ const meanDist = distCount ? distSum / distCount : 0;
367
+ const meanRadius = rCount ? rSum / rCount : 0;
368
+ const base = meanRadius > 0 ? meanDist / meanRadius : meanDist;
369
+ // Keep within a reasonable range to avoid excessive subdivision.
370
+ return Math.max(1, Math.min(32, Math.round(base || 1)));
371
+ }
372
+ export default trailPath;