@weasel-js/paint 1.5.0 → 1.5.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.
package/dist/index.d.ts CHANGED
@@ -9,6 +9,66 @@ interface TextureHandle {
9
9
  readonly id: string;
10
10
  }
11
11
 
12
+ /**
13
+ * Convert a 0..1 float sRGB triple to OKLab — the renderer's own color space,
14
+ * and what a caller holding a `resolveColor` result has. Rounds into the u8
15
+ * grid the way every other float→u8 crossing in this file does, rather than
16
+ * leaving each caller to pick a convention.
17
+ */
18
+ declare function srgbFloatToOklab(r: number, g: number, b: number): [number, number, number];
19
+ /** Convert an 8-bit sRGB triple to OKLab. Channels are indices into a 256-entry
20
+ * LUT: pass integers, or `srgbFloatToOklab` for 0..1 floats. */
21
+ declare function srgbU8ToOklab(r: number, g: number, b: number): [number, number, number];
22
+ /** Convert OKLab back to an 8-bit sRGB triple, clamped into gamut. */
23
+ declare function oklabToSrgbU8(L: number, A: number, B: number): [number, number, number];
24
+ /** Blend two 8-bit sRGB colors through OKLab. Perceptually even, and it does
25
+ * not pass through the muddy midpoints an sRGB blend produces between
26
+ * complementary hues. */
27
+ declare function lerpOklab(from: readonly [number, number, number], to: readonly [number, number, number], t: number): [number, number, number];
28
+ /** Convert OKLab (L, a, b) to OKLCh (L, C, h). h is in radians, range [-π, π]. */
29
+ declare function oklabToOklch(L: number, A: number, B: number): [number, number, number];
30
+ /** Convert OKLCh (L, C, h) to OKLab (L, a, b). h is in radians. */
31
+ declare function oklchToOklab(L: number, C: number, h: number): [number, number, number];
32
+ /** Lerp OKLCh values with shortest-arc hue interpolation. Lightness and
33
+ * chroma lerp linearly. When chroma is near zero on either endpoint, hue
34
+ * is taken from the other endpoint (avoids hue snap-from-undefined).
35
+ * h inputs are in radians. */
36
+ declare function lerpOklch(from: readonly [number, number, number], to: readonly [number, number, number], t: number): [number, number, number];
37
+ /** Which space a color blend is computed in. `'rgb'` is cheapest; `'oklab'`
38
+ * is perceptually even; `'oklch'` additionally travels around the hue wheel
39
+ * rather than through it. */
40
+ type ColorSpace = 'rgb' | 'oklab' | 'oklch';
41
+ /** Lerp a flat RGBA color array `from` toward `to`. Inputs are 0..1
42
+ * floats (the renderer's color space); outputs are 0..1 floats too.
43
+ * Alpha is always linearly lerped; RGB channels are lerped in the
44
+ * requested color space. OKLab / OKLCh paths bounce through u8 because
45
+ * the gamma-correction LUT and gamut-clip routines are byte-keyed —
46
+ * the round-trip is lossy at <1% per channel, well under the visible
47
+ * threshold for these animations. */
48
+ declare function lerpColorArray(from: readonly number[], to: readonly number[], t: number, space?: ColorSpace): number[];
49
+ /**
50
+ * OKLCh with the hue in **degrees**, and `#rrggbb` on the other side.
51
+ *
52
+ * The helpers above take radians, because that is what the math wants. Every
53
+ * consumer that authors colors — a theme ramp, a palette generator — wants
54
+ * degrees and a hex string, and two packages independently built the same
55
+ * wrapper before this existed.
56
+ */
57
+ interface OklchDeg {
58
+ readonly L: number;
59
+ readonly C: number;
60
+ /** 0..360. */
61
+ readonly H: number;
62
+ }
63
+ /**
64
+ * OKLCh (hue in degrees) to `#rrggbb`. Over-saturated requests come back at
65
+ * the gamut boundary: `oklabToSrgbU8` clips chroma at constant lightness, which
66
+ * is what lets a caller find a hue's ceiling by asking for far more than exists.
67
+ */
68
+ declare function oklchDegToHex(L: number, C: number, hueDeg: number): string;
69
+ /** `#rrggbb` to OKLCh with the hue wrapped into 0..360. */
70
+ declare function hexToOklchDeg(hex: string): OklchDeg;
71
+
12
72
  /**
13
73
  * FillStyle and Stroke types — the unified shape for "what color or texture
14
74
  * paints these pixels," modeled on SVG's paint-server concept.
@@ -39,6 +99,12 @@ interface TextureHandle {
39
99
  * `createTilePattern()`. A handle is a session-scoped registry key, so a
40
100
  * paint carrying one cannot be persisted or exported; prefer the spec.
41
101
  *
102
+ * `interpolate` on a gradient names the space its stops blend through, and
103
+ * defaults to `'rgb'` — the channel-wise sRGB lerp every other vector format
104
+ * means by a gradient. `'oklab'` spaces the blend perceptually; `'oklch'`
105
+ * additionally travels around the hue wheel, so red to blue stays saturated
106
+ * instead of passing through a muddy purple. Alpha is linear in every space.
107
+ *
42
108
  * `units` on a pattern names the space the tile's origin and scale live in,
43
109
  * not the space of any geometry (a pattern has none). Under `'bounds'` the
44
110
  * tile anchors to the painted node's box, so the pattern travels with the
@@ -71,6 +137,7 @@ type FillStyle = {
71
137
  };
72
138
  stops: GradStop[];
73
139
  units?: GradientUnits;
140
+ interpolate?: ColorSpace;
74
141
  opacity?: number;
75
142
  } | {
76
143
  fill: 'radial-gradient';
@@ -81,6 +148,7 @@ type FillStyle = {
81
148
  radius: number;
82
149
  stops: GradStop[];
83
150
  units?: GradientUnits;
151
+ interpolate?: ColorSpace;
84
152
  opacity?: number;
85
153
  } | {
86
154
  fill: 'conic-gradient';
@@ -91,6 +159,7 @@ type FillStyle = {
91
159
  angle: number;
92
160
  stops: GradStop[];
93
161
  units?: GradientUnits;
162
+ interpolate?: ColorSpace;
94
163
  opacity?: number;
95
164
  };
96
165
  /**
@@ -184,10 +253,23 @@ type MarkerKey = KitMarkerKey | (string & {});
184
253
  */
185
254
  type MarkerRef = MarkerKey | {
186
255
  key: MarkerKey;
187
- size?: number | {
188
- px: number;
189
- };
256
+ size?: ScreenLength;
190
257
  };
258
+ /**
259
+ * A length the author states either in world units (a plain number) or in
260
+ * screen pixels (`{ px }`), resolved against the accumulated transform scale
261
+ * wherever it is consumed — so a `{ px }` length holds its on-screen size as
262
+ * the view zooms, with no call-site arithmetic.
263
+ */
264
+ type ScreenLength = number | {
265
+ px: number;
266
+ };
267
+ /**
268
+ * Resolve a {@link ScreenLength} to world units. A non-finite or zero scale
269
+ * has no world to divide into, so the pixel count passes through unchanged
270
+ * rather than becoming `Infinity`.
271
+ */
272
+ declare function resolveScreenLength(value: ScreenLength, scale: number): number;
191
273
  /** Stroke style: a FillStyle plus structural line parameters. */
192
274
  interface Stroke {
193
275
  /**
@@ -200,9 +282,7 @@ interface Stroke {
200
282
  /** World units, or `{ px }` for screen pixels — resolved against the
201
283
  * accumulated transform scale at draw time, so it holds its on-screen
202
284
  * thickness as the view zooms. */
203
- width?: number | {
204
- px: number;
205
- };
285
+ width?: ScreenLength;
206
286
  /** Per `CanvasRenderingContext2D.setLineDash` — empty/omitted = solid. */
207
287
  dash?: number[];
208
288
  /** Marker at the first vertex of each open subpath, rotated to point back
@@ -319,4 +399,4 @@ interface Region {
319
399
  shape: 'rectangle' | 'circle';
320
400
  }
321
401
 
322
- export { type FillStyle, type GradStop, type GradientFill, type GradientKind, type GradientUnits, type KitMarkerKey, type MarkerKey, type MarkerRef, type Region, STROKE_DASH_RATIOS, type Stroke, type StrokeAlign, type StrokeDashStyle, type TextureHandle, type TilePatternSpec, alignedStrokeRect, dashForStrokeStyle, strokeDashStyleOf };
402
+ export { type ColorSpace, type FillStyle, type GradStop, type GradientFill, type GradientKind, type GradientUnits, type KitMarkerKey, type MarkerKey, type MarkerRef, type OklchDeg, type Region, STROKE_DASH_RATIOS, type ScreenLength, type Stroke, type StrokeAlign, type StrokeDashStyle, type TextureHandle, type TilePatternSpec, alignedStrokeRect, dashForStrokeStyle, hexToOklchDeg, lerpColorArray, lerpOklab, lerpOklch, oklabToOklch, oklabToSrgbU8, oklchDegToHex, oklchToOklab, resolveScreenLength, srgbFloatToOklab, srgbU8ToOklab, strokeDashStyleOf };
package/dist/index.js CHANGED
@@ -1,4 +1,9 @@
1
1
  // src/paint.ts
2
+ function resolveScreenLength(value, scale) {
3
+ if (typeof value === "number") return value;
4
+ if (!Number.isFinite(scale) || scale === 0) return value.px;
5
+ return value.px / scale;
6
+ }
2
7
  function alignedStrokeRect(rect, align, width = 1) {
3
8
  if (align === "center") return rect;
4
9
  const sign = align === "inner" ? -1 : 1;
@@ -35,6 +40,166 @@ function strokeDashStyleOf(dash, width) {
35
40
  return "custom";
36
41
  }
37
42
 
38
- export { STROKE_DASH_RATIOS, alignedStrokeRect, dashForStrokeStyle, strokeDashStyleOf };
43
+ // src/colorSpaces.ts
44
+ var SRGB_TO_LINEAR = (() => {
45
+ const lut = new Float64Array(256);
46
+ for (let i = 0; i < 256; i++) {
47
+ const c = i / 255;
48
+ lut[i] = c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
49
+ }
50
+ return lut;
51
+ })();
52
+ function linearToSrgbByte(c) {
53
+ if (c <= 0) return 0;
54
+ if (c >= 1) return 255;
55
+ const v = c <= 31308e-7 ? c * 12.92 : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
56
+ return Math.round(v * 255);
57
+ }
58
+ var f2u = (v) => Math.max(0, Math.min(255, Math.round(v * 255)));
59
+ function srgbFloatToOklab(r, g, b) {
60
+ return srgbU8ToOklab(f2u(r), f2u(g), f2u(b));
61
+ }
62
+ function srgbU8ToOklab(r, g, b) {
63
+ const rl = SRGB_TO_LINEAR[r & 255];
64
+ const gl = SRGB_TO_LINEAR[g & 255];
65
+ const bl = SRGB_TO_LINEAR[b & 255];
66
+ const l = 0.4122214708 * rl + 0.5363325363 * gl + 0.0514459929 * bl;
67
+ const m = 0.2119034982 * rl + 0.6806995451 * gl + 0.1073969566 * bl;
68
+ const s = 0.0883024619 * rl + 0.2817188376 * gl + 0.6299787005 * bl;
69
+ const lp = Math.cbrt(l);
70
+ const mp = Math.cbrt(m);
71
+ const sp = Math.cbrt(s);
72
+ return [
73
+ 0.2104542553 * lp + 0.793617785 * mp - 0.0040720468 * sp,
74
+ 1.9779984951 * lp - 2.428592205 * mp + 0.4505937099 * sp,
75
+ 0.0259040371 * lp + 0.7827717662 * mp - 0.808675766 * sp
76
+ ];
77
+ }
78
+ function oklabToLinearSrgb(L, A, B) {
79
+ const lp = L + 0.3963377774 * A + 0.2158037573 * B;
80
+ const mp = L - 0.1055613458 * A - 0.0638541728 * B;
81
+ const sp = L - 0.0894841775 * A - 1.291485548 * B;
82
+ const l = lp * lp * lp;
83
+ const m = mp * mp * mp;
84
+ const s = sp * sp * sp;
85
+ return [
86
+ 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
87
+ -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
88
+ -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s
89
+ ];
90
+ }
91
+ function inGamut(rl, gl, bl) {
92
+ const eps = 1e-6;
93
+ return rl >= -eps && rl <= 1 + eps && gl >= -eps && gl <= 1 + eps && bl >= -eps && bl <= 1 + eps;
94
+ }
95
+ function clipToGamut(L, A, B) {
96
+ let [rl, gl, bl] = oklabToLinearSrgb(L, A, B);
97
+ if (inGamut(rl, gl, bl)) return [rl, gl, bl];
98
+ let lo = 0;
99
+ let hi = 1;
100
+ for (let i = 0; i < 5; i++) {
101
+ const t = (lo + hi) / 2;
102
+ [rl, gl, bl] = oklabToLinearSrgb(L, A * t, B * t);
103
+ if (inGamut(rl, gl, bl)) lo = t;
104
+ else hi = t;
105
+ }
106
+ [rl, gl, bl] = oklabToLinearSrgb(L, A * lo, B * lo);
107
+ return [rl, gl, bl];
108
+ }
109
+ function oklabToSrgbU8(L, A, B) {
110
+ const [rl, gl, bl] = clipToGamut(L, A, B);
111
+ return [linearToSrgbByte(rl), linearToSrgbByte(gl), linearToSrgbByte(bl)];
112
+ }
113
+ function lerpOklab(from, to, t) {
114
+ return [
115
+ from[0] + (to[0] - from[0]) * t,
116
+ from[1] + (to[1] - from[1]) * t,
117
+ from[2] + (to[2] - from[2]) * t
118
+ ];
119
+ }
120
+ function oklabToOklch(L, A, B) {
121
+ const C = Math.hypot(A, B);
122
+ const h = Math.atan2(B, A);
123
+ return [L, C, h];
124
+ }
125
+ function oklchToOklab(L, C, h) {
126
+ return [L, C * Math.cos(h), C * Math.sin(h)];
127
+ }
128
+ function lerpOklch(from, to, t) {
129
+ const [L1, C1, h1Raw] = from;
130
+ const [L2, C2, h2Raw] = to;
131
+ const C_EPS = 1e-4;
132
+ const h1 = C1 < C_EPS ? h2Raw : h1Raw;
133
+ const h2 = C2 < C_EPS ? h1Raw : h2Raw;
134
+ const TWO_PI = Math.PI * 2;
135
+ let dh = h2 - h1;
136
+ while (dh > Math.PI) dh -= TWO_PI;
137
+ while (dh < -Math.PI) dh += TWO_PI;
138
+ return [
139
+ L1 + (L2 - L1) * t,
140
+ C1 + (C2 - C1) * t,
141
+ h1 + dh * t
142
+ ];
143
+ }
144
+ var u2f = (v) => v / 255;
145
+ function lerpColorArray(from, to, t, space = "rgb") {
146
+ if (from.length !== to.length) {
147
+ throw new Error(`lerpColorArray: length mismatch (from=${from.length}, to=${to.length})`);
148
+ }
149
+ if (from.length % 4 !== 0) {
150
+ throw new Error(`lerpColorArray: length ${from.length} not divisible by 4`);
151
+ }
152
+ const out = new Array(from.length);
153
+ const n = from.length / 4;
154
+ if (space === "rgb") {
155
+ for (let i = 0; i < from.length; i++) {
156
+ out[i] = from[i] + (to[i] - from[i]) * t;
157
+ }
158
+ return out;
159
+ }
160
+ if (space === "oklch") {
161
+ for (let i = 0; i < n; i++) {
162
+ const k = i * 4;
163
+ const fLab = srgbU8ToOklab(f2u(from[k]), f2u(from[k + 1]), f2u(from[k + 2]));
164
+ const tLab = srgbU8ToOklab(f2u(to[k]), f2u(to[k + 1]), f2u(to[k + 2]));
165
+ const fLch = oklabToOklch(fLab[0], fLab[1], fLab[2]);
166
+ const tLch = oklabToOklch(tLab[0], tLab[1], tLab[2]);
167
+ const midLch = lerpOklch(fLch, tLch, t);
168
+ const midLab = oklchToOklab(midLch[0], midLch[1], midLch[2]);
169
+ const [r, g, b] = oklabToSrgbU8(midLab[0], midLab[1], midLab[2]);
170
+ out[k] = u2f(r);
171
+ out[k + 1] = u2f(g);
172
+ out[k + 2] = u2f(b);
173
+ out[k + 3] = from[k + 3] + (to[k + 3] - from[k + 3]) * t;
174
+ }
175
+ return out;
176
+ }
177
+ for (let i = 0; i < n; i++) {
178
+ const k = i * 4;
179
+ const fLab = srgbU8ToOklab(f2u(from[k]), f2u(from[k + 1]), f2u(from[k + 2]));
180
+ const tLab = srgbU8ToOklab(f2u(to[k]), f2u(to[k + 1]), f2u(to[k + 2]));
181
+ const mid = lerpOklab(fLab, tLab, t);
182
+ const [r, g, b] = oklabToSrgbU8(mid[0], mid[1], mid[2]);
183
+ out[k] = u2f(r);
184
+ out[k + 1] = u2f(g);
185
+ out[k + 2] = u2f(b);
186
+ out[k + 3] = from[k + 3] + (to[k + 3] - from[k + 3]) * t;
187
+ }
188
+ return out;
189
+ }
190
+ var hex2 = (v) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, "0");
191
+ function oklchDegToHex(L, C, hueDeg) {
192
+ const [l, a, b] = oklchToOklab(L, C, hueDeg * Math.PI / 180);
193
+ const [r, g, bl] = oklabToSrgbU8(l, a, b);
194
+ return `#${hex2(r)}${hex2(g)}${hex2(bl)}`;
195
+ }
196
+ function hexToOklchDeg(hex) {
197
+ const n = Number.parseInt(hex.slice(1), 16);
198
+ const [L, A, B] = srgbU8ToOklab(n >> 16 & 255, n >> 8 & 255, n & 255);
199
+ const [l, c, h] = oklabToOklch(L, A, B);
200
+ return { L: l, C: c, H: (h * 180 / Math.PI % 360 + 360) % 360 };
201
+ }
202
+
203
+ export { STROKE_DASH_RATIOS, alignedStrokeRect, dashForStrokeStyle, hexToOklchDeg, lerpColorArray, lerpOklab, lerpOklch, oklabToOklch, oklabToSrgbU8, oklchDegToHex, oklchToOklab, resolveScreenLength, srgbFloatToOklab, srgbU8ToOklab, strokeDashStyleOf };
39
204
  //# sourceMappingURL=index.js.map
40
205
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/paint.ts"],"names":[],"mappings":";AA+NO,SAAS,iBAAA,CACd,IAAA,EACA,KAAA,EACA,KAAA,GAAQ,CAAA,EACiD;AACzD,EAAA,IAAI,KAAA,KAAU,UAAU,OAAO,IAAA;AAG/B,EAAA,MAAM,IAAA,GAAO,KAAA,KAAU,OAAA,GAAU,EAAA,GAAK,CAAA;AACtC,EAAA,MAAM,CAAA,GAAK,OAAO,KA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M,MAAA,GAAS,mBAAmB,KAAK,CAAA;AAGvC,IAAA,IAAI,KAAK,MAAA,KAAW,MAAA,CAAO,UAAU,MAAA,CAAO,KAAA,CAAM,CAAC,CAAA,EAAG,CAAA,KAAM,KAAK,GAAA,CAAI,IAAA,CAAK,CAAC,CAAA,GAAI,CAAA,GAAI,CAAC,CAAA,IAAK,CAAA,GAAI,IAAI,CAAA,EAAG;AAClG,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,EACF;AACA,EAAA,OAAO,QAAA;AACT","file":"index.js","sourcesContent":["/**\n * FillStyle and Stroke types — the unified shape for \"what color or texture\n * paints these pixels,\" modeled on SVG's paint-server concept.\n *\n * - `FillStyle` is a tagged union: solid color, pattern, or gradient. Used\n * wherever a kit option previously took `fillStyle: string`.\n * - `Stroke` pairs a `FillStyle` with structural stroke parameters (width, dash,\n * line cap/join, alignment).\n * - These types are consumed by the GL renderer's DrawCommand path fills\n * and strokes.\n *\n * The 2D `applyPaint` / `applyStroke` / `renderFilledRegion` helpers that\n * formerly lived alongside these types were deleted with the 2D backend in\n * Step 10. `alignedStrokeRect` survives as a pure geometry helper used by\n * path tessellation and the selection overlay.\n */\n\nimport type { TextureHandle } from './texture';\n\n/**\n * Color/texture strategy for fills (and, via `Stroke.paint`, strokes).\n *\n * `fill` is optional and defaults to `'solid'` — `{ color: '#abc' }` is\n * equivalent to `{ fill: 'solid', color: '#abc' }`. Pattern paints must set\n * `fill: 'pattern'` explicitly.\n *\n * The `'pattern'` variant's payload is either a `TilePatternSpec` — plain\n * data naming one of the built-in tiles, which survives serialization — or a\n * `TextureHandle` for a tile the consumer built itself via\n * `createTilePattern()`. A handle is a session-scoped registry key, so a\n * paint carrying one cannot be persisted or exported; prefer the spec.\n *\n * `units` on a pattern names the space the tile's origin and scale live in,\n * not the space of any geometry (a pattern has none). Under `'bounds'` the\n * tile anchors to the painted node's box, so the pattern travels with the\n * node and a resize reveals more tiles rather than stretching them;\n * `fillInPoseFrame` resolves that to a `'local'` paint with an explicit\n * `origin` before the renderer sees it.\n */\nexport type FillStyle =\n | { fill?: 'solid'; color: string; opacity?: number }\n | { fill: 'pattern'; pattern: TextureHandle | TilePatternSpec; units?: GradientUnits; origin?: { x: number; y: number }; opacity?: number }\n | { fill: 'linear-gradient'; from: { x: number; y: number }; to: { x: number; y: number }; stops: GradStop[]; units?: GradientUnits; opacity?: number }\n | { fill: 'radial-gradient'; center: { x: number; y: number }; radius: number; stops: GradStop[]; units?: GradientUnits; opacity?: number }\n | { fill: 'conic-gradient'; center: { x: number; y: number }; angle: number; stops: GradStop[]; units?: GradientUnits; opacity?: number };\n\n/**\n * Which coordinate space a gradient's geometry (`from`/`to`, `center`,\n * `radius`) is expressed in. SVG's `gradientUnits`, plus an option for\n * paints that are themselves viewport furniture.\n *\n * - `'bounds'`: fractions of the painted node's bounding box, `0..1` on each\n * axis — SVG `objectBoundingBox`. Resolved by the node painter, before the\n * renderer sees it, so the paint follows the node through moves, resizes\n * and rotation. What a gradient on a scene node wants.\n * - `'local'`: the coordinate space the geometry was handed to the renderer\n * in — the enclosing group's frame. For draw commands a consumer builds\n * itself, where \"the coordinates I just wrote\" is the useful frame.\n * - `'world'`: scene coordinates. The paint stays put under pan and zoom\n * while the geometry moves through it. SVG `userSpaceOnUse`. Requires the\n * renderer to have been handed a view matrix; falls back to `'screen'`\n * when it has not.\n * - `'screen'`: CSS pixels of the drawing surface. For overlays and\n * viewport-fixed washes that should not move with the content at all.\n *\n * Defaults to `'screen'`, which is the behavior every gradient had before\n * this field existed.\n */\nexport type GradientUnits = 'bounds' | 'local' | 'world' | 'screen';\n\n/**\n * A built-in tile, described as plain data. The serializable half of the\n * pattern paint: `resolvePatternSpec()` turns one into a `TextureHandle`\n * at paint time, memoized so identical specs share a texture.\n *\n * `size` is the tile's edge length, and doubles as its extent in paint\n * space — a bigger `size` rasterizes a bigger tile rather than magnifying\n * a small one, which is why there is no separate scale field.\n */\nexport interface TilePatternSpec {\n tile: 'hatch' | 'crosshatch' | 'dots' | 'chunks';\n color: string;\n /** `chunks` only — omit for a transparent tile background. */\n bg?: string;\n size?: number;\n /** `hatch` / `crosshatch`. */\n lineWidth?: number;\n /** `dots`. */\n radius?: number;\n /** `chunks`. */\n density?: number;\n chunkSize?: number;\n seed?: number;\n}\n\n/** A single color stop within a gradient. `offset` is in 0..1. */\nexport interface GradStop {\n offset: number;\n color: string;\n}\n\n/** The gradient members of `FillStyle`, as one type. What a gradient editor\n * edits, and what the gradient-specific helpers accept. */\nexport type GradientFill = Extract<\n FillStyle,\n { fill: 'linear-gradient' | 'radial-gradient' | 'conic-gradient' }\n>;\n\n/** `GradientFill['fill']` — the three gradient discriminants on their own. */\nexport type GradientKind = GradientFill['fill'];\n\n/**\n * Where a stroke sits relative to the geometric edge it strokes.\n *\n * - `'center'` (default): canvas-native — half the stroke width sits inside\n * the geometry, half outside.\n * - `'inner'`: the entire stroke lies inside the geometry. The outer edge of\n * the stroke coincides with the geometric edge.\n * - `'outer'`: the entire stroke lies outside the geometry. The inner edge\n * of the stroke coincides with the geometric edge.\n *\n * Mirrors the (proposed) SVG `stroke-alignment` property. Honoring `inner`\n * or `outer` is the renderer's responsibility — for axis-aligned rects, the\n * kit shifts coordinates by `width / 2`. For arbitrary paths, renderers\n * typically use a stencil mask of the stroked path against the geometry.\n */\nexport type StrokeAlign = 'center' | 'inner' | 'outer';\n\n/**\n * The kit's built-in marker vocabulary, open on the string the way\n * `PaintKind` is so a consumer's registered key typechecks.\n */\nexport type KitMarkerKey =\n | 'arrow' | 'arrow-open' | 'arrow-concave'\n | 'diamond' | 'diamond-hollow'\n | 'circle' | 'square' | 'bar';\nexport type MarkerKey = KitMarkerKey | (string & {});\n\n/**\n * A marker on one end (or every interior vertex) of a stroke.\n *\n * `size` reuses `Stroke.width`'s unit system: a bare number scales with the\n * resolved stroke width, `{ px }` pins screen pixels. That is SVG's\n * `markerUnits` in the idiom this codebase already resolves at draw time.\n * Omitted, the marker is one stroke width per unit.\n */\nexport type MarkerRef = MarkerKey | { key: MarkerKey; size?: number | { px: number } };\n\n/** Stroke style: a FillStyle plus structural line parameters. */\nexport interface Stroke {\n /**\n * Omitted, the stroke paints nothing — the same \"no paint\" a `fill: null`\n * says for a node's fill. Documents written before mid-2026 can hold a\n * stroke whose other fields were seeded without one, and the type is\n * optional so every reader has to answer for that rather than throw on it.\n */\n paint?: FillStyle;\n /** World units, or `{ px }` for screen pixels — resolved against the\n * accumulated transform scale at draw time, so it holds its on-screen\n * thickness as the view zooms. */\n width?: number | { px: number };\n /** Per `CanvasRenderingContext2D.setLineDash` — empty/omitted = solid. */\n dash?: number[];\n /** Marker at the first vertex of each open subpath, rotated to point back\n * along the line (SVG's `auto-start-reverse`, as the only behavior). */\n markerStart?: MarkerRef;\n /** Marker at every interior authored vertex, on the bisector of the\n * incoming and outgoing directions. Never insets the stroke. */\n markerMid?: MarkerRef;\n /** Marker at the last vertex of each open subpath. */\n markerEnd?: MarkerRef;\n cap?: 'butt' | 'round' | 'square';\n join?: 'miter' | 'round' | 'bevel';\n /**\n * Miter join fallback threshold. When the miter length exceeds\n * `miterLimit * width / 2`, the join falls back to a bevel. Default 4,\n * matching SVG — which is also what the kit's own serializer implies when\n * it omits the attribute for an unset field. Canvas2D's 10 lets an acute\n * corner throw a spike four times the half-width.\n */\n miterLimit?: number;\n /** Where the stroke sits relative to the geometric edge. Default `'center'`. */\n align?: StrokeAlign;\n /**\n * Per-anchor RGBA, flat (length = 4 × countPathAnchors(path)). Each\n * value in 0..1. Arc-length interpolated across the tessellated ribbon\n * between consecutive anchors. When set, `paint` is still required —\n * its `opacity` (and color, as a placeholder) flow through the shader.\n */\n vertexColors?: number[];\n /**\n * Per-anchor stroke width (length = `countPathAnchors(path)`). When set,\n * the tessellator interpolates half-widths along each segment to produce\n * a tapered ribbon. `width` is used as the fallback for any anchor whose\n * entry is missing or non-finite. Pressure-driven pencil strokes use\n * this; pair with `pressureToWidth` to derive widths from stylus input.\n *\n * Joins between adjacent segments whose widths differ by more than\n * `varyingWidthJoinThreshold` (default 1.5×) are forced to bevel\n * regardless of the `join` setting — miter math is unstable when widths\n * vary across the corner; smooth round joins with mismatched widths\n * are a future enhancement.\n */\n vertexWidths?: number[];\n /**\n * Max width ratio (greater / lesser) at which a non-bevel join is\n * preserved when `vertexWidths` causes adjacent segments to differ.\n * Beyond this ratio the join falls back to bevel. Default 1.5. Ignored\n * when `vertexWidths` is absent.\n */\n varyingWidthJoinThreshold?: number;\n}\n\n/**\n * Inflate (positive) or deflate (negative) a rect to honor `align` when\n * stroking it. Returns the rect to pass to a stroked-rect renderer. `width`\n * is the stroke width (defaults to 1 to match canvas).\n *\n * Pure geometry helper — no rendering side effects. Used by path\n * tessellation and the selection overlay to produce a rect whose\n * center-aligned stroke visually coincides with the requested\n * inner/outer-aligned stroke of the original rect.\n */\nexport function alignedStrokeRect(\n rect: { x: number; y: number; width: number; height: number },\n align: StrokeAlign,\n width = 1,\n): { x: number; y: number; width: number; height: number } {\n if (align === 'center') return rect;\n // For 'inner', shift inward by width/2 so the stroke's outer edge coincides\n // with the geometric edge. For 'outer', shift outward.\n const sign = align === 'inner' ? -1 : 1;\n const d = (sign * width) / 2;\n return {\n x: rect.x - d,\n y: rect.y - d,\n width: rect.width + 2 * d,\n height: rect.height + 2 * d,\n };\n}\n\n/**\n * The named line styles a `Stroke.dash` array reads as.\n *\n * `custom` is what an imported array that matches no preset reads as — it is\n * reportable, not authorable: there is no array it maps back to.\n */\nexport type StrokeDashStyle = 'solid' | 'dashed' | 'dotted' | 'custom';\n\n/**\n * Dash and gap lengths of the presets, **as multiples of the stroke width**.\n *\n * SVG dash lengths are absolute, so a fixed pattern is a different style at\n * every width: `[6, 3]` is dots on a hairline and a railroad on a 20px\n * stroke. Scaling by the width is what makes \"dashed\" one style.\n */\nexport const STROKE_DASH_RATIOS = {\n dashed: [3, 2],\n dotted: [1, 2],\n} as const satisfies Record<'dashed' | 'dotted', readonly [number, number]>;\n\n/** `width` as a plain number — a `{ px }` width is read at scale 1, matching\n * what an unresolved stroke reaching the tessellator gets. */\nfunction dashWidth(width: number | { px: number } | undefined): number {\n const w = typeof width === 'object' ? width.px : (width ?? 1);\n return Number.isFinite(w) && w > 0 ? w : 1;\n}\n\n/**\n * The `Stroke.dash` array for a named style at `width`, or `undefined` for\n * `solid` — which is stored as no dash at all, not as an empty pattern.\n *\n * `custom` has no array of its own and returns `undefined`; a caller that\n * offers it as a choice should refuse the choice rather than call this.\n */\nexport function dashForStrokeStyle(\n style: StrokeDashStyle,\n width: number | { px: number } | undefined,\n): number[] | undefined {\n if (style !== 'dashed' && style !== 'dotted') return undefined;\n const w = dashWidth(width);\n return STROKE_DASH_RATIOS[style].map((r) => r * w);\n}\n\n/**\n * The style a stored `dash` reads as at `width`. Absent or empty is `solid`;\n * an array matching neither preset is `custom`.\n */\nexport function strokeDashStyleOf(\n dash: readonly number[] | undefined,\n width: number | { px: number } | undefined,\n): StrokeDashStyle {\n if (dash === undefined || dash.length === 0 || dash.every((v) => v === 0)) return 'solid';\n const w = dashWidth(width);\n for (const style of ['dashed', 'dotted'] as const) {\n const preset = STROKE_DASH_RATIOS[style];\n // Tolerance is relative to the width: the presets are multiples of it, and\n // a round-tripped array carries the serializer's decimal trimming.\n if (dash.length === preset.length && preset.every((r, i) => Math.abs(dash[i] - r * w) <= w * 1e-3)) {\n return style;\n }\n }\n return 'custom';\n}\n\n/** Region a fill is clipped to. */\nexport interface Region {\n x: number;\n y: number;\n w: number;\n h: number;\n shape: 'rectangle' | 'circle';\n}\n"]}
1
+ {"version":3,"sources":["../src/paint.ts","../src/colorSpaces.ts"],"names":[],"mappings":";AAwKO,SAAS,mBAAA,CAAoB,OAAqB,KAAA,EAAuB;AAC9E,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,EAAU,OAAO,KAAA;AACtC,EAAA,IAAI,CAAC,OAAO,QAAA,CAAS,KAAK,KAAK,KAAA,KAAU,CAAA,SAAU,KAAA,CAAM,EAAA;AACzD,EAAA,OAAO,MAAM,EAAA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AA,EAAG,IAAA,CAAK,CAAC,CAAC,CAAA,EAAG,IAAA,CAAK,EAAE,CAAC,CAAA,CAAA;AACzC;AAGO,SAAS,cAAc,GAAA,EAAuB;AACnD,EAAA,MAAM,IAAI,MAAA,CAAO,QAAA,CAAS,IAAI,KAAA,CAAM,CAAC,GAAG,EAAE,CAAA;AAC1C,EAAA,MAAM,CAAC,CAAA,EAAG,CAAA,EAAG,CAAC,CAAA,GAAI,aAAA,CAAe,CAAA,IAAK,EAAA,GAAM,GAAA,EAAM,CAAA,IAAK,CAAA,GAAK,GAAA,EAAK,IAAI,GAAG,CAAA;AACxE,EAAA,MAAM,CAAC,GAAG,CAAA,EAAG,CAAC,IAAI,YAAA,CAAa,CAAA,EAAG,GAAG,CAAC,CAAA;AACtC,EAAA,OAAO,EAAE,CAAA,EAAG,CAAA,EAAG,CAAA,EAAG,CAAA,EAAG,CAAA,EAAA,CAAO,CAAA,GAAI,GAAA,GAAO,IAAA,CAAK,EAAA,GAAM,GAAA,GAAO,GAAA,IAAO,GAAA,EAAI;AACtE","file":"index.js","sourcesContent":["/**\n * FillStyle and Stroke types — the unified shape for \"what color or texture\n * paints these pixels,\" modeled on SVG's paint-server concept.\n *\n * - `FillStyle` is a tagged union: solid color, pattern, or gradient. Used\n * wherever a kit option previously took `fillStyle: string`.\n * - `Stroke` pairs a `FillStyle` with structural stroke parameters (width, dash,\n * line cap/join, alignment).\n * - These types are consumed by the GL renderer's DrawCommand path fills\n * and strokes.\n *\n * The 2D `applyPaint` / `applyStroke` / `renderFilledRegion` helpers that\n * formerly lived alongside these types were deleted with the 2D backend in\n * Step 10. `alignedStrokeRect` survives as a pure geometry helper used by\n * path tessellation and the selection overlay.\n */\n\nimport type { TextureHandle } from './texture';\nimport type { ColorSpace } from './colorSpaces';\n\n/**\n * Color/texture strategy for fills (and, via `Stroke.paint`, strokes).\n *\n * `fill` is optional and defaults to `'solid'` — `{ color: '#abc' }` is\n * equivalent to `{ fill: 'solid', color: '#abc' }`. Pattern paints must set\n * `fill: 'pattern'` explicitly.\n *\n * The `'pattern'` variant's payload is either a `TilePatternSpec` — plain\n * data naming one of the built-in tiles, which survives serialization — or a\n * `TextureHandle` for a tile the consumer built itself via\n * `createTilePattern()`. A handle is a session-scoped registry key, so a\n * paint carrying one cannot be persisted or exported; prefer the spec.\n *\n * `interpolate` on a gradient names the space its stops blend through, and\n * defaults to `'rgb'` — the channel-wise sRGB lerp every other vector format\n * means by a gradient. `'oklab'` spaces the blend perceptually; `'oklch'`\n * additionally travels around the hue wheel, so red to blue stays saturated\n * instead of passing through a muddy purple. Alpha is linear in every space.\n *\n * `units` on a pattern names the space the tile's origin and scale live in,\n * not the space of any geometry (a pattern has none). Under `'bounds'` the\n * tile anchors to the painted node's box, so the pattern travels with the\n * node and a resize reveals more tiles rather than stretching them;\n * `fillInPoseFrame` resolves that to a `'local'` paint with an explicit\n * `origin` before the renderer sees it.\n */\nexport type FillStyle =\n | { fill?: 'solid'; color: string; opacity?: number }\n | { fill: 'pattern'; pattern: TextureHandle | TilePatternSpec; units?: GradientUnits; origin?: { x: number; y: number }; opacity?: number }\n | { fill: 'linear-gradient'; from: { x: number; y: number }; to: { x: number; y: number }; stops: GradStop[]; units?: GradientUnits; interpolate?: ColorSpace; opacity?: number }\n | { fill: 'radial-gradient'; center: { x: number; y: number }; radius: number; stops: GradStop[]; units?: GradientUnits; interpolate?: ColorSpace; opacity?: number }\n | { fill: 'conic-gradient'; center: { x: number; y: number }; angle: number; stops: GradStop[]; units?: GradientUnits; interpolate?: ColorSpace; opacity?: number };\n\n/**\n * Which coordinate space a gradient's geometry (`from`/`to`, `center`,\n * `radius`) is expressed in. SVG's `gradientUnits`, plus an option for\n * paints that are themselves viewport furniture.\n *\n * - `'bounds'`: fractions of the painted node's bounding box, `0..1` on each\n * axis — SVG `objectBoundingBox`. Resolved by the node painter, before the\n * renderer sees it, so the paint follows the node through moves, resizes\n * and rotation. What a gradient on a scene node wants.\n * - `'local'`: the coordinate space the geometry was handed to the renderer\n * in — the enclosing group's frame. For draw commands a consumer builds\n * itself, where \"the coordinates I just wrote\" is the useful frame.\n * - `'world'`: scene coordinates. The paint stays put under pan and zoom\n * while the geometry moves through it. SVG `userSpaceOnUse`. Requires the\n * renderer to have been handed a view matrix; falls back to `'screen'`\n * when it has not.\n * - `'screen'`: CSS pixels of the drawing surface. For overlays and\n * viewport-fixed washes that should not move with the content at all.\n *\n * Defaults to `'screen'`, which is the behavior every gradient had before\n * this field existed.\n */\nexport type GradientUnits = 'bounds' | 'local' | 'world' | 'screen';\n\n/**\n * A built-in tile, described as plain data. The serializable half of the\n * pattern paint: `resolvePatternSpec()` turns one into a `TextureHandle`\n * at paint time, memoized so identical specs share a texture.\n *\n * `size` is the tile's edge length, and doubles as its extent in paint\n * space — a bigger `size` rasterizes a bigger tile rather than magnifying\n * a small one, which is why there is no separate scale field.\n */\nexport interface TilePatternSpec {\n tile: 'hatch' | 'crosshatch' | 'dots' | 'chunks';\n color: string;\n /** `chunks` only — omit for a transparent tile background. */\n bg?: string;\n size?: number;\n /** `hatch` / `crosshatch`. */\n lineWidth?: number;\n /** `dots`. */\n radius?: number;\n /** `chunks`. */\n density?: number;\n chunkSize?: number;\n seed?: number;\n}\n\n/** A single color stop within a gradient. `offset` is in 0..1. */\nexport interface GradStop {\n offset: number;\n color: string;\n}\n\n/** The gradient members of `FillStyle`, as one type. What a gradient editor\n * edits, and what the gradient-specific helpers accept. */\nexport type GradientFill = Extract<\n FillStyle,\n { fill: 'linear-gradient' | 'radial-gradient' | 'conic-gradient' }\n>;\n\n/** `GradientFill['fill']` — the three gradient discriminants on their own. */\nexport type GradientKind = GradientFill['fill'];\n\n/**\n * Where a stroke sits relative to the geometric edge it strokes.\n *\n * - `'center'` (default): canvas-native — half the stroke width sits inside\n * the geometry, half outside.\n * - `'inner'`: the entire stroke lies inside the geometry. The outer edge of\n * the stroke coincides with the geometric edge.\n * - `'outer'`: the entire stroke lies outside the geometry. The inner edge\n * of the stroke coincides with the geometric edge.\n *\n * Mirrors the (proposed) SVG `stroke-alignment` property. Honoring `inner`\n * or `outer` is the renderer's responsibility — for axis-aligned rects, the\n * kit shifts coordinates by `width / 2`. For arbitrary paths, renderers\n * typically use a stencil mask of the stroked path against the geometry.\n */\nexport type StrokeAlign = 'center' | 'inner' | 'outer';\n\n/**\n * The kit's built-in marker vocabulary, open on the string the way\n * `PaintKind` is so a consumer's registered key typechecks.\n */\nexport type KitMarkerKey =\n | 'arrow' | 'arrow-open' | 'arrow-concave'\n | 'diamond' | 'diamond-hollow'\n | 'circle' | 'square' | 'bar';\nexport type MarkerKey = KitMarkerKey | (string & {});\n\n/**\n * A marker on one end (or every interior vertex) of a stroke.\n *\n * `size` reuses `Stroke.width`'s unit system: a bare number scales with the\n * resolved stroke width, `{ px }` pins screen pixels. That is SVG's\n * `markerUnits` in the idiom this codebase already resolves at draw time.\n * Omitted, the marker is one stroke width per unit.\n */\nexport type MarkerRef = MarkerKey | { key: MarkerKey; size?: ScreenLength };\n\n/**\n * A length the author states either in world units (a plain number) or in\n * screen pixels (`{ px }`), resolved against the accumulated transform scale\n * wherever it is consumed — so a `{ px }` length holds its on-screen size as\n * the view zooms, with no call-site arithmetic.\n */\nexport type ScreenLength = number | { px: number };\n\n/**\n * Resolve a {@link ScreenLength} to world units. A non-finite or zero scale\n * has no world to divide into, so the pixel count passes through unchanged\n * rather than becoming `Infinity`.\n */\nexport function resolveScreenLength(value: ScreenLength, scale: number): number {\n if (typeof value === 'number') return value;\n if (!Number.isFinite(scale) || scale === 0) return value.px;\n return value.px / scale;\n}\n\n/** Stroke style: a FillStyle plus structural line parameters. */\nexport interface Stroke {\n /**\n * Omitted, the stroke paints nothing — the same \"no paint\" a `fill: null`\n * says for a node's fill. Documents written before mid-2026 can hold a\n * stroke whose other fields were seeded without one, and the type is\n * optional so every reader has to answer for that rather than throw on it.\n */\n paint?: FillStyle;\n /** World units, or `{ px }` for screen pixels — resolved against the\n * accumulated transform scale at draw time, so it holds its on-screen\n * thickness as the view zooms. */\n width?: ScreenLength;\n /** Per `CanvasRenderingContext2D.setLineDash` — empty/omitted = solid. */\n dash?: number[];\n /** Marker at the first vertex of each open subpath, rotated to point back\n * along the line (SVG's `auto-start-reverse`, as the only behavior). */\n markerStart?: MarkerRef;\n /** Marker at every interior authored vertex, on the bisector of the\n * incoming and outgoing directions. Never insets the stroke. */\n markerMid?: MarkerRef;\n /** Marker at the last vertex of each open subpath. */\n markerEnd?: MarkerRef;\n cap?: 'butt' | 'round' | 'square';\n join?: 'miter' | 'round' | 'bevel';\n /**\n * Miter join fallback threshold. When the miter length exceeds\n * `miterLimit * width / 2`, the join falls back to a bevel. Default 4,\n * matching SVG — which is also what the kit's own serializer implies when\n * it omits the attribute for an unset field. Canvas2D's 10 lets an acute\n * corner throw a spike four times the half-width.\n */\n miterLimit?: number;\n /** Where the stroke sits relative to the geometric edge. Default `'center'`. */\n align?: StrokeAlign;\n /**\n * Per-anchor RGBA, flat (length = 4 × countPathAnchors(path)). Each\n * value in 0..1. Arc-length interpolated across the tessellated ribbon\n * between consecutive anchors. When set, `paint` is still required —\n * its `opacity` (and color, as a placeholder) flow through the shader.\n */\n vertexColors?: number[];\n /**\n * Per-anchor stroke width (length = `countPathAnchors(path)`). When set,\n * the tessellator interpolates half-widths along each segment to produce\n * a tapered ribbon. `width` is used as the fallback for any anchor whose\n * entry is missing or non-finite. Pressure-driven pencil strokes use\n * this; pair with `pressureToWidth` to derive widths from stylus input.\n *\n * Joins between adjacent segments whose widths differ by more than\n * `varyingWidthJoinThreshold` (default 1.5×) are forced to bevel\n * regardless of the `join` setting — miter math is unstable when widths\n * vary across the corner; smooth round joins with mismatched widths\n * are a future enhancement.\n */\n vertexWidths?: number[];\n /**\n * Max width ratio (greater / lesser) at which a non-bevel join is\n * preserved when `vertexWidths` causes adjacent segments to differ.\n * Beyond this ratio the join falls back to bevel. Default 1.5. Ignored\n * when `vertexWidths` is absent.\n */\n varyingWidthJoinThreshold?: number;\n}\n\n/**\n * Inflate (positive) or deflate (negative) a rect to honor `align` when\n * stroking it. Returns the rect to pass to a stroked-rect renderer. `width`\n * is the stroke width (defaults to 1 to match canvas).\n *\n * Pure geometry helper — no rendering side effects. Used by path\n * tessellation and the selection overlay to produce a rect whose\n * center-aligned stroke visually coincides with the requested\n * inner/outer-aligned stroke of the original rect.\n */\nexport function alignedStrokeRect(\n rect: { x: number; y: number; width: number; height: number },\n align: StrokeAlign,\n width = 1,\n): { x: number; y: number; width: number; height: number } {\n if (align === 'center') return rect;\n // For 'inner', shift inward by width/2 so the stroke's outer edge coincides\n // with the geometric edge. For 'outer', shift outward.\n const sign = align === 'inner' ? -1 : 1;\n const d = (sign * width) / 2;\n return {\n x: rect.x - d,\n y: rect.y - d,\n width: rect.width + 2 * d,\n height: rect.height + 2 * d,\n };\n}\n\n/**\n * The named line styles a `Stroke.dash` array reads as.\n *\n * `custom` is what an imported array that matches no preset reads as — it is\n * reportable, not authorable: there is no array it maps back to.\n */\nexport type StrokeDashStyle = 'solid' | 'dashed' | 'dotted' | 'custom';\n\n/**\n * Dash and gap lengths of the presets, **as multiples of the stroke width**.\n *\n * SVG dash lengths are absolute, so a fixed pattern is a different style at\n * every width: `[6, 3]` is dots on a hairline and a railroad on a 20px\n * stroke. Scaling by the width is what makes \"dashed\" one style.\n */\nexport const STROKE_DASH_RATIOS = {\n dashed: [3, 2],\n dotted: [1, 2],\n} as const satisfies Record<'dashed' | 'dotted', readonly [number, number]>;\n\n/** `width` as a plain number — a `{ px }` width is read at scale 1, matching\n * what an unresolved stroke reaching the tessellator gets. */\nfunction dashWidth(width: number | { px: number } | undefined): number {\n const w = typeof width === 'object' ? width.px : (width ?? 1);\n return Number.isFinite(w) && w > 0 ? w : 1;\n}\n\n/**\n * The `Stroke.dash` array for a named style at `width`, or `undefined` for\n * `solid` — which is stored as no dash at all, not as an empty pattern.\n *\n * `custom` has no array of its own and returns `undefined`; a caller that\n * offers it as a choice should refuse the choice rather than call this.\n */\nexport function dashForStrokeStyle(\n style: StrokeDashStyle,\n width: number | { px: number } | undefined,\n): number[] | undefined {\n if (style !== 'dashed' && style !== 'dotted') return undefined;\n const w = dashWidth(width);\n return STROKE_DASH_RATIOS[style].map((r) => r * w);\n}\n\n/**\n * The style a stored `dash` reads as at `width`. Absent or empty is `solid`;\n * an array matching neither preset is `custom`.\n */\nexport function strokeDashStyleOf(\n dash: readonly number[] | undefined,\n width: number | { px: number } | undefined,\n): StrokeDashStyle {\n if (dash === undefined || dash.length === 0 || dash.every((v) => v === 0)) return 'solid';\n const w = dashWidth(width);\n for (const style of ['dashed', 'dotted'] as const) {\n const preset = STROKE_DASH_RATIOS[style];\n // Tolerance is relative to the width: the presets are multiples of it, and\n // a round-tripped array carries the serializer's decimal trimming.\n if (dash.length === preset.length && preset.every((r, i) => Math.abs(dash[i] - r * w) <= w * 1e-3)) {\n return style;\n }\n }\n return 'custom';\n}\n\n/** Region a fill is clipped to. */\nexport interface Region {\n x: number;\n y: number;\n w: number;\n h: number;\n shape: 'rectangle' | 'circle';\n}\n","// sRGB ↔ OKLab conversion. Reference: https://bottosson.github.io/posts/oklab/\n\nconst SRGB_TO_LINEAR: Float64Array = (() => {\n const lut = new Float64Array(256);\n for (let i = 0; i < 256; i++) {\n const c = i / 255;\n lut[i] = c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);\n }\n return lut;\n})();\n\nfunction linearToSrgbByte(c: number): number {\n if (c <= 0) return 0;\n if (c >= 1) return 255;\n const v = c <= 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;\n return Math.round(v * 255);\n}\n\n/** 0..1 float channel to the 8-bit index the LUTs are cut for. Rounds and\n * clamps; `& 0xff` would truncate, and wrap anything out of range. */\nconst f2u = (v: number): number => Math.max(0, Math.min(255, Math.round(v * 255)));\n\n/**\n * Convert a 0..1 float sRGB triple to OKLab — the renderer's own color space,\n * and what a caller holding a `resolveColor` result has. Rounds into the u8\n * grid the way every other float→u8 crossing in this file does, rather than\n * leaving each caller to pick a convention.\n */\nexport function srgbFloatToOklab(r: number, g: number, b: number): [number, number, number] {\n return srgbU8ToOklab(f2u(r), f2u(g), f2u(b));\n}\n\n/** Convert an 8-bit sRGB triple to OKLab. Channels are indices into a 256-entry\n * LUT: pass integers, or `srgbFloatToOklab` for 0..1 floats. */\nexport function srgbU8ToOklab(r: number, g: number, b: number): [number, number, number] {\n const rl = SRGB_TO_LINEAR[r & 0xff];\n const gl = SRGB_TO_LINEAR[g & 0xff];\n const bl = SRGB_TO_LINEAR[b & 0xff];\n const l = 0.4122214708 * rl + 0.5363325363 * gl + 0.0514459929 * bl;\n const m = 0.2119034982 * rl + 0.6806995451 * gl + 0.1073969566 * bl;\n const s = 0.0883024619 * rl + 0.2817188376 * gl + 0.6299787005 * bl;\n const lp = Math.cbrt(l);\n const mp = Math.cbrt(m);\n const sp = Math.cbrt(s);\n return [\n 0.2104542553 * lp + 0.7936177850 * mp - 0.0040720468 * sp,\n 1.9779984951 * lp - 2.4285922050 * mp + 0.4505937099 * sp,\n 0.0259040371 * lp + 0.7827717662 * mp - 0.8086757660 * sp,\n ];\n}\n\nfunction oklabToLinearSrgb(L: number, A: number, B: number): [number, number, number] {\n const lp = L + 0.3963377774 * A + 0.2158037573 * B;\n const mp = L - 0.1055613458 * A - 0.0638541728 * B;\n const sp = L - 0.0894841775 * A - 1.2914855480 * B;\n const l = lp * lp * lp;\n const m = mp * mp * mp;\n const s = sp * sp * sp;\n return [\n +4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,\n -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,\n -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s,\n ];\n}\n\nfunction inGamut(rl: number, gl: number, bl: number): boolean {\n // Small epsilon absorbs float-roundtrip noise on pure-primary colors.\n const eps = 1e-6;\n return (\n rl >= -eps && rl <= 1 + eps &&\n gl >= -eps && gl <= 1 + eps &&\n bl >= -eps && bl <= 1 + eps\n );\n}\n\nfunction clipToGamut(L: number, A: number, B: number): [number, number, number] {\n let [rl, gl, bl] = oklabToLinearSrgb(L, A, B);\n if (inGamut(rl, gl, bl)) return [rl, gl, bl];\n let lo = 0;\n let hi = 1;\n // 5 iterations → ~3% chroma precision; sufficient for u8 output.\n for (let i = 0; i < 5; i++) {\n const t = (lo + hi) / 2;\n [rl, gl, bl] = oklabToLinearSrgb(L, A * t, B * t);\n if (inGamut(rl, gl, bl)) lo = t; else hi = t;\n }\n [rl, gl, bl] = oklabToLinearSrgb(L, A * lo, B * lo);\n return [rl, gl, bl];\n}\n\n/** Convert OKLab back to an 8-bit sRGB triple, clamped into gamut. */\nexport function oklabToSrgbU8(L: number, A: number, B: number): [number, number, number] {\n const [rl, gl, bl] = clipToGamut(L, A, B);\n return [linearToSrgbByte(rl), linearToSrgbByte(gl), linearToSrgbByte(bl)];\n}\n\n/** Blend two 8-bit sRGB colors through OKLab. Perceptually even, and it does\n * not pass through the muddy midpoints an sRGB blend produces between\n * complementary hues. */\nexport function lerpOklab(\n from: readonly [number, number, number],\n to: readonly [number, number, number],\n t: number,\n): [number, number, number] {\n return [\n from[0] + (to[0] - from[0]) * t,\n from[1] + (to[1] - from[1]) * t,\n from[2] + (to[2] - from[2]) * t,\n ];\n}\n\n/** Convert OKLab (L, a, b) to OKLCh (L, C, h). h is in radians, range [-π, π]. */\nexport function oklabToOklch(L: number, A: number, B: number): [number, number, number] {\n const C = Math.hypot(A, B);\n const h = Math.atan2(B, A);\n return [L, C, h];\n}\n\n/** Convert OKLCh (L, C, h) to OKLab (L, a, b). h is in radians. */\nexport function oklchToOklab(L: number, C: number, h: number): [number, number, number] {\n return [L, C * Math.cos(h), C * Math.sin(h)];\n}\n\n/** Lerp OKLCh values with shortest-arc hue interpolation. Lightness and\n * chroma lerp linearly. When chroma is near zero on either endpoint, hue\n * is taken from the other endpoint (avoids hue snap-from-undefined).\n * h inputs are in radians. */\nexport function lerpOklch(\n from: readonly [number, number, number],\n to: readonly [number, number, number],\n t: number,\n): [number, number, number] {\n const [L1, C1, h1Raw] = from;\n const [L2, C2, h2Raw] = to;\n const C_EPS = 1e-4;\n // When one endpoint is near-achromatic, take hue from the other endpoint\n // to avoid spurious arc rotation through undefined hue space.\n const h1 = C1 < C_EPS ? h2Raw : h1Raw;\n const h2 = C2 < C_EPS ? h1Raw : h2Raw;\n const TWO_PI = Math.PI * 2;\n // Shortest-arc delta in [-π, π].\n let dh = h2 - h1;\n while (dh > Math.PI) dh -= TWO_PI;\n while (dh < -Math.PI) dh += TWO_PI;\n return [\n L1 + (L2 - L1) * t,\n C1 + (C2 - C1) * t,\n h1 + dh * t,\n ];\n}\n\n/** Which space a color blend is computed in. `'rgb'` is cheapest; `'oklab'`\n * is perceptually even; `'oklch'` additionally travels around the hue wheel\n * rather than through it. */\nexport type ColorSpace = 'rgb' | 'oklab' | 'oklch';\n\nconst u2f = (v: number): number => v / 255;\n\n/** Lerp a flat RGBA color array `from` toward `to`. Inputs are 0..1\n * floats (the renderer's color space); outputs are 0..1 floats too.\n * Alpha is always linearly lerped; RGB channels are lerped in the\n * requested color space. OKLab / OKLCh paths bounce through u8 because\n * the gamma-correction LUT and gamut-clip routines are byte-keyed —\n * the round-trip is lossy at <1% per channel, well under the visible\n * threshold for these animations. */\nexport function lerpColorArray(\n from: readonly number[],\n to: readonly number[],\n t: number,\n space: ColorSpace = 'rgb',\n): number[] {\n if (from.length !== to.length) {\n throw new Error(`lerpColorArray: length mismatch (from=${from.length}, to=${to.length})`);\n }\n if (from.length % 4 !== 0) {\n throw new Error(`lerpColorArray: length ${from.length} not divisible by 4`);\n }\n const out = new Array<number>(from.length);\n const n = from.length / 4;\n if (space === 'rgb') {\n // Pure float lerp — no rounding (which previously discretized 0..1\n // inputs to 0/1, giving the cycle its 'choppy 8-corner' look).\n for (let i = 0; i < from.length; i++) {\n out[i] = from[i] + (to[i] - from[i]) * t;\n }\n return out;\n }\n if (space === 'oklch') {\n for (let i = 0; i < n; i++) {\n const k = i * 4;\n const fLab = srgbU8ToOklab(f2u(from[k]), f2u(from[k + 1]), f2u(from[k + 2]));\n const tLab = srgbU8ToOklab(f2u(to[k]), f2u(to[k + 1]), f2u(to[k + 2]));\n const fLch = oklabToOklch(fLab[0], fLab[1], fLab[2]);\n const tLch = oklabToOklch(tLab[0], tLab[1], tLab[2]);\n const midLch = lerpOklch(fLch, tLch, t);\n const midLab = oklchToOklab(midLch[0], midLch[1], midLch[2]);\n const [r, g, b] = oklabToSrgbU8(midLab[0], midLab[1], midLab[2]);\n out[k] = u2f(r);\n out[k + 1] = u2f(g);\n out[k + 2] = u2f(b);\n out[k + 3] = from[k + 3] + (to[k + 3] - from[k + 3]) * t;\n }\n return out;\n }\n for (let i = 0; i < n; i++) {\n const k = i * 4;\n const fLab = srgbU8ToOklab(f2u(from[k]), f2u(from[k + 1]), f2u(from[k + 2]));\n const tLab = srgbU8ToOklab(f2u(to[k]), f2u(to[k + 1]), f2u(to[k + 2]));\n const mid = lerpOklab(fLab, tLab, t);\n const [r, g, b] = oklabToSrgbU8(mid[0], mid[1], mid[2]);\n out[k] = u2f(r);\n out[k + 1] = u2f(g);\n out[k + 2] = u2f(b);\n out[k + 3] = from[k + 3] + (to[k + 3] - from[k + 3]) * t;\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// OKLCh in degrees\n// ---------------------------------------------------------------------------\n\n/**\n * OKLCh with the hue in **degrees**, and `#rrggbb` on the other side.\n *\n * The helpers above take radians, because that is what the math wants. Every\n * consumer that authors colors — a theme ramp, a palette generator — wants\n * degrees and a hex string, and two packages independently built the same\n * wrapper before this existed.\n */\nexport interface OklchDeg {\n readonly L: number;\n readonly C: number;\n /** 0..360. */\n readonly H: number;\n}\n\nconst hex2 = (v: number): string => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0');\n\n/**\n * OKLCh (hue in degrees) to `#rrggbb`. Over-saturated requests come back at\n * the gamut boundary: `oklabToSrgbU8` clips chroma at constant lightness, which\n * is what lets a caller find a hue's ceiling by asking for far more than exists.\n */\nexport function oklchDegToHex(L: number, C: number, hueDeg: number): string {\n const [l, a, b] = oklchToOklab(L, C, (hueDeg * Math.PI) / 180);\n const [r, g, bl] = oklabToSrgbU8(l, a, b);\n return `#${hex2(r)}${hex2(g)}${hex2(bl)}`;\n}\n\n/** `#rrggbb` to OKLCh with the hue wrapped into 0..360. */\nexport function hexToOklchDeg(hex: string): OklchDeg {\n const n = Number.parseInt(hex.slice(1), 16);\n const [L, A, B] = srgbU8ToOklab((n >> 16) & 255, (n >> 8) & 255, n & 255);\n const [l, c, h] = oklabToOklch(L, A, B);\n return { L: l, C: c, H: ((((h * 180) / Math.PI) % 360) + 360) % 360 };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@weasel-js/paint",
3
- "version": "1.5.0",
3
+ "version": "1.5.2",
4
4
  "description": "Paint vocabulary for weasel: FillStyle, Stroke, gradients, dashes. Plain data, no renderer.",
5
5
  "license": "MIT",
6
6
  "type": "module",