@inditextech/weave-sdk 5.7.1 → 5.8.0-SNAPSHOT.613.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/sdk.js CHANGED
@@ -9579,7 +9579,7 @@ var WeaveRegisterManager = class {
9579
9579
  };
9580
9580
  //#endregion
9581
9581
  //#region package.json
9582
- var version = "5.7.1";
9582
+ var version = "5.8.0-SNAPSHOT.613.1";
9583
9583
  //#endregion
9584
9584
  //#region src/managers/setup.ts
9585
9585
  var WeaveSetupManager = class {
@@ -22088,6 +22088,27 @@ var WeaveFrameNode = class extends WeaveNode {
22088
22088
  //#endregion
22089
22089
  //#region src/nodes/stroke/constants.ts
22090
22090
  const WEAVE_STROKE_NODE_TYPE = "stroke";
22091
+ /**
22092
+ * The look equivalent to the rendering of strokes that have no look: the
22093
+ * default of every look setting.
22094
+ */
22095
+ const WEAVE_STROKE_LEGACY_LOOK = {
22096
+ version: 1,
22097
+ outline: "legacy",
22098
+ curve: "uniform",
22099
+ pressureInterp: "catmullRom",
22100
+ zoomAware: false,
22101
+ spacingPx: 2,
22102
+ edgePx: 1,
22103
+ caps: "separate",
22104
+ width: {
22105
+ min: 0,
22106
+ max: 1,
22107
+ gamma: 1,
22108
+ taperStart: 0,
22109
+ taperEnd: 0
22110
+ }
22111
+ };
22091
22112
  const WEAVE_STROKE_NODE_DEFAULT_CONFIG = {
22092
22113
  splineResolution: 8,
22093
22114
  splineTargetEdge: 1,
@@ -22096,9 +22117,380 @@ const WEAVE_STROKE_NODE_DEFAULT_CONFIG = {
22096
22117
  isEraser: false
22097
22118
  };
22098
22119
  //#endregion
22120
+ //#region src/nodes/stroke/render/curve.ts
22121
+ const lerp = (a, b, t) => a + (b - a) * t;
22122
+ /** Interval between two knots: the square root of the distance (alpha 0.5). */
22123
+ const knotStep = (a, b) => Math.max(Math.sqrt(Math.hypot(b.x - a.x, b.y - a.y)), 1e-6);
22124
+ /** Barry-Goldman evaluation of the centripetal Catmull-Rom curve at `u` in 0..1 of the middle span. */
22125
+ function evaluate(w, u) {
22126
+ const { p, t } = w;
22127
+ const at = lerp(t[1], t[2], u);
22128
+ const blend = (channel) => {
22129
+ const a1 = lerp(p[0][channel], p[1][channel], (at - t[0]) / (t[1] - t[0]));
22130
+ const a2 = lerp(p[1][channel], p[2][channel], (at - t[1]) / (t[2] - t[1]));
22131
+ const a3 = lerp(p[2][channel], p[3][channel], (at - t[2]) / (t[3] - t[2]));
22132
+ const b1 = lerp(a1, a2, (at - t[0]) / (t[2] - t[0]));
22133
+ const b2 = lerp(a2, a3, (at - t[1]) / (t[3] - t[1]));
22134
+ return lerp(b1, b2, (at - t[1]) / (t[2] - t[1]));
22135
+ };
22136
+ return {
22137
+ x: blend("x"),
22138
+ y: blend("y"),
22139
+ pressure: blend("pressure")
22140
+ };
22141
+ }
22142
+ function distanceToSegment(p, a, b) {
22143
+ const dx = b.x - a.x;
22144
+ const dy = b.y - a.y;
22145
+ const l = dx * dx + dy * dy;
22146
+ const t = l ? Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / l)) : 0;
22147
+ return Math.hypot(p.x - (a.x + dx * t), p.y - (a.y + dy * t));
22148
+ }
22149
+ /**
22150
+ * Samples a centripetal Catmull-Rom curve through `pts`.
22151
+ *
22152
+ * The knot intervals follow the distance between points, so the curve does not
22153
+ * overshoot or form cusps when the points are unevenly spaced, which the
22154
+ * uniform parametrization does. Pressure is interpolated linearly between the
22155
+ * two points of a span, or smoothly but never beyond them, so the width of the
22156
+ * stroke cannot exceed the widest of its neighbouring widths.
22157
+ */
22158
+ function getCentripetalPoints(pts, opts) {
22159
+ if (pts.length < 2) return [...pts];
22160
+ const out = [];
22161
+ for (let i = -1; i < pts.length - 2; i++) {
22162
+ const p0 = pts[Math.max(i, 0)];
22163
+ const p1 = pts[i + 1];
22164
+ const p2 = pts[i + 2];
22165
+ const p3 = pts[Math.min(i + 3, pts.length - 1)];
22166
+ const t1 = knotStep(p0, p1);
22167
+ const t2 = t1 + knotStep(p1, p2);
22168
+ const t3 = t2 + knotStep(p2, p3);
22169
+ const w = {
22170
+ p: [
22171
+ p0,
22172
+ p1,
22173
+ p2,
22174
+ p3
22175
+ ],
22176
+ t: [
22177
+ 0,
22178
+ t1,
22179
+ t2,
22180
+ t3
22181
+ ]
22182
+ };
22183
+ let deviation = 0;
22184
+ for (const probe of [
22185
+ .25,
22186
+ .5,
22187
+ .75
22188
+ ]) deviation = Math.max(deviation, distanceToSegment(evaluate(w, probe), p1, p2));
22189
+ const tolerance = Math.max(opts.edge * .1, 1e-6);
22190
+ const steps = deviation < opts.flatness ? 1 : Math.min(Math.max(Math.ceil(Math.sqrt(deviation / tolerance)), opts.minSteps), opts.maxSteps);
22191
+ const lo = Math.min(p1.pressure, p2.pressure);
22192
+ const hi = Math.max(p1.pressure, p2.pressure);
22193
+ for (let s = 0; s < steps; s++) {
22194
+ const u = s / steps;
22195
+ const q = evaluate(w, u);
22196
+ q.pressure = opts.pressure === "linear" ? lerp(p1.pressure, p2.pressure, u) : Math.min(hi, Math.max(lo, q.pressure));
22197
+ out.push(q);
22198
+ }
22199
+ }
22200
+ out.push(pts[pts.length - 1]);
22201
+ return out;
22202
+ }
22203
+ //#endregion
22204
+ //#region src/nodes/stroke/render/look.ts
22205
+ const OUTLINES = [
22206
+ "legacy",
22207
+ "round",
22208
+ "freehand"
22209
+ ];
22210
+ const CURVES = [
22211
+ "uniform",
22212
+ "centripetal",
22213
+ "none"
22214
+ ];
22215
+ const PRESSURE_INTERPS = ["catmullRom", "linear"];
22216
+ const CAPS = ["separate", "merged"];
22217
+ const isObject$2 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
22218
+ const pick = (v, allowed, fallback) => typeof v === "string" && allowed.includes(v) ? v : fallback;
22219
+ /** A finite number clamped to a range, or the fallback. */
22220
+ const num = (v, min, max, fallback) => typeof v === "number" && Number.isFinite(v) ? Math.min(max, Math.max(min, v)) : fallback;
22221
+ /**
22222
+ * Reads the look saved on a stroke. Returns `null` when the stroke has none or
22223
+ * its look is of a version this release does not understand, so the stroke is
22224
+ * drawn as in releases that did not know looks. Missing or invalid fields fall
22225
+ * back to the legacy values and out-of-range numbers are clamped, so a stored
22226
+ * look can never make the renderer misbehave.
22227
+ */
22228
+ function readStrokeLook(raw) {
22229
+ if (!isObject$2(raw) || raw["version"] !== WEAVE_STROKE_LEGACY_LOOK.version) return null;
22230
+ const base = WEAVE_STROKE_LEGACY_LOOK;
22231
+ const width = isObject$2(raw["width"]) ? raw["width"] : {};
22232
+ return {
22233
+ version: 1,
22234
+ outline: pick(raw["outline"], OUTLINES, base.outline),
22235
+ curve: pick(raw["curve"], CURVES, base.curve),
22236
+ pressureInterp: pick(raw["pressureInterp"], PRESSURE_INTERPS, base.pressureInterp),
22237
+ zoomAware: typeof raw["zoomAware"] === "boolean" ? raw["zoomAware"] : base.zoomAware,
22238
+ spacingPx: num(raw["spacingPx"], .5, 10, base.spacingPx),
22239
+ edgePx: num(raw["edgePx"], .25, 5, base.edgePx),
22240
+ caps: pick(raw["caps"], CAPS, base.caps),
22241
+ width: {
22242
+ min: num(width["min"], 0, 1, base.width.min),
22243
+ max: num(width["max"], 0, 1, base.width.max),
22244
+ gamma: num(width["gamma"], .2, 3, base.width.gamma),
22245
+ taperStart: num(width["taperStart"], 0, 200, base.width.taperStart),
22246
+ taperEnd: num(width["taperEnd"], 0, 200, base.width.taperEnd)
22247
+ }
22248
+ };
22249
+ }
22250
+ /** Quadratic ease-out: 0 at the tip, 1 once the taper distance is covered. */
22251
+ const easeOut = (t) => t * (2 - t);
22252
+ /** Lowest half-width drawn, in canvas units, so a stroke never vanishes. */
22253
+ const MIN_HALF_WIDTH = .5;
22254
+ /**
22255
+ * Half of the drawn width at a point, in canvas units.
22256
+ *
22257
+ * The width is the stroke width times `min + (max - min) * pressure^gamma`,
22258
+ * narrowed by the start and end tapers. With the default width rule this is
22259
+ * `strokeWidth * pressure / 2`, the legacy width. `distanceFromStart` and
22260
+ * `distanceToEnd` are along the stroke, in the unit of the tapers.
22261
+ */
22262
+ function halfWidthAt(look, strokeWidth, pressure, distanceFromStart, distanceToEnd) {
22263
+ const { min, max, gamma, taperStart, taperEnd } = look.width;
22264
+ const p = Math.min(1, Math.max(0, Number.isFinite(pressure) ? pressure : .5));
22265
+ let fraction = min + (max - min) * Math.pow(p, gamma);
22266
+ if (taperStart > 0 && distanceFromStart < taperStart) fraction *= easeOut(Math.max(0, distanceFromStart) / taperStart);
22267
+ if (taperEnd > 0 && distanceToEnd < taperEnd) fraction *= easeOut(Math.max(0, distanceToEnd) / taperEnd);
22268
+ return Math.max(strokeWidth * fraction / 2, MIN_HALF_WIDTH);
22269
+ }
22270
+ //#endregion
22271
+ //#region src/nodes/stroke/render/round-outline.ts
22272
+ /**
22273
+ * Drops points that the quads between their neighbours already cover. A point
22274
+ * is skipped only while every point skipped since the last kept one stays
22275
+ * within a hundredth of the radius of the chord that replaces them, in position
22276
+ * and in radius, so a vertex, a turn or a change of width is always kept. A gap
22277
+ * is also never wider than two radii. The first and last points are kept.
22278
+ */
22279
+ function thinRoundPoints(pts) {
22280
+ if (pts.length <= 2) return pts;
22281
+ const out = [pts[0]];
22282
+ let anchor = 0;
22283
+ for (let i = 2; i < pts.length; i++) {
22284
+ const a = pts[anchor];
22285
+ const b = pts[i];
22286
+ const dx = b.x - a.x;
22287
+ const dy = b.y - a.y;
22288
+ const chord = Math.hypot(dx, dy);
22289
+ let keepPrevious = chord > 2 * Math.min(a.r, b.r) || i - anchor > 24;
22290
+ for (let j = anchor + 1; j < i && !keepPrevious; j++) {
22291
+ const p = pts[j];
22292
+ const t = chord > 0 ? Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / (chord * chord))) : 0;
22293
+ const off = Math.hypot(p.x - (a.x + dx * t), p.y - (a.y + dy * t));
22294
+ const tolerance = .01 * Math.min(a.r, b.r, p.r);
22295
+ if (off > tolerance || Math.abs(p.r - (a.r + (b.r - a.r) * t)) > tolerance) keepPrevious = true;
22296
+ }
22297
+ if (keepPrevious) {
22298
+ out.push(pts[i - 1]);
22299
+ anchor = i - 1;
22300
+ }
22301
+ }
22302
+ out.push(pts[pts.length - 1]);
22303
+ return out;
22304
+ }
22305
+ /** Largest gap, in screen pixels, a skipped disc may leave on the outer side of a bend. */
22306
+ const MAX_WEDGE_PX = .1;
22307
+ const angleDiff = (a, b) => {
22308
+ let d = Math.abs(a - b);
22309
+ if (d > Math.PI) d = 2 * Math.PI - d;
22310
+ return d;
22311
+ };
22312
+ /**
22313
+ * Which points need their disc. Between two neighbours the tangent quad covers
22314
+ * the stroke exactly; a disc only matters where the outline turns, to fill the
22315
+ * wedge on the outside of the bend. Where the turn is so slight that the
22316
+ * wedge would be thinner than a tenth of a screen pixel the disc is skipped,
22317
+ * which removes most arcs of a smooth stroke and makes it far cheaper to fill.
22318
+ */
22319
+ function pointsNeedingDisc(pts, scale) {
22320
+ const need = new Array(pts.length).fill(false);
22321
+ if (pts.length === 0) return need;
22322
+ need[0] = true;
22323
+ need[pts.length - 1] = true;
22324
+ const dir = [0];
22325
+ const lean = [0];
22326
+ const valid = [false];
22327
+ for (let i = 1; i < pts.length; i++) {
22328
+ const p = pts[i];
22329
+ const q = pts[i - 1];
22330
+ const dx = p.x - q.x;
22331
+ const dy = p.y - q.y;
22332
+ const l = Math.hypot(dx, dy);
22333
+ const ok = l > Math.abs(p.r - q.r) && l >= 1e-9;
22334
+ valid.push(ok);
22335
+ dir.push(Math.atan2(dy, dx));
22336
+ lean.push(ok ? Math.asin(Math.max(-1, Math.min(1, (q.r - p.r) / l))) : 0);
22337
+ if (!ok) {
22338
+ need[i] = true;
22339
+ need[i - 1] = true;
22340
+ }
22341
+ }
22342
+ for (let i = 1; i < pts.length - 1; i++) {
22343
+ if (need[i]) continue;
22344
+ if (!valid[i] || !valid[i + 1]) {
22345
+ need[i] = true;
22346
+ continue;
22347
+ }
22348
+ const turn = angleDiff(dir[i], dir[i + 1]) + Math.abs(lean[i + 1] - lean[i]);
22349
+ const radiusPx = Math.max(pts[i].r * scale, 1e-6);
22350
+ if (turn > Math.sqrt(8 * MAX_WEDGE_PX / radiusPx)) need[i] = true;
22351
+ }
22352
+ return need;
22353
+ }
22354
+ /**
22355
+ * Appends the outline of a variable-width stroke to the current path: a disc at
22356
+ * every point and, between neighbours, the quad bounded by their two external
22357
+ * tangents. Every sub-path has the same winding, so a single non-zero fill is
22358
+ * the exact union: turns, reversals and ends are round by construction.
22359
+ */
22360
+ function appendRoundPath(ctx, points, scale = 1) {
22361
+ const pts = thinRoundPoints(points);
22362
+ const need = pointsNeedingDisc(pts, scale);
22363
+ const polygon = (v) => {
22364
+ let area = 0;
22365
+ for (let k = 0; k < v.length; k++) {
22366
+ const [x1, y1] = v[k];
22367
+ const [x2, y2] = v[(k + 1) % v.length];
22368
+ area += x1 * y2 - x2 * y1;
22369
+ }
22370
+ const w = area < 0 ? [...v].reverse() : v;
22371
+ ctx.moveTo(w[0][0], w[0][1]);
22372
+ for (let k = 1; k < w.length; k++) ctx.lineTo(w[k][0], w[k][1]);
22373
+ ctx.closePath();
22374
+ };
22375
+ const tangents = (i) => {
22376
+ const p = pts[i];
22377
+ const q = pts[i - 1];
22378
+ const dx = p.x - q.x;
22379
+ const dy = p.y - q.y;
22380
+ const l = Math.hypot(dx, dy);
22381
+ if (l <= Math.abs(p.r - q.r) || l < 1e-9) return null;
22382
+ const ux = dx / l;
22383
+ const uy = dy / l;
22384
+ const k = (q.r - p.r) / l;
22385
+ const s = Math.sqrt(Math.max(0, 1 - k * k));
22386
+ return {
22387
+ a: [k * ux - s * uy, k * uy + s * ux],
22388
+ b: [k * ux + s * uy, k * uy - s * ux]
22389
+ };
22390
+ };
22391
+ let left = [];
22392
+ let right = [];
22393
+ let prev = null;
22394
+ const flush = () => {
22395
+ if (left.length >= 2) polygon([...left, ...right.reverse()]);
22396
+ left = [];
22397
+ right = [];
22398
+ prev = null;
22399
+ };
22400
+ for (let i = 1; i < pts.length; i++) {
22401
+ const p = pts[i];
22402
+ const q = pts[i - 1];
22403
+ const t = tangents(i);
22404
+ if (!t) {
22405
+ flush();
22406
+ continue;
22407
+ }
22408
+ if (!prev) {
22409
+ left = [[q.x + q.r * t.a[0], q.y + q.r * t.a[1]]];
22410
+ right = [[q.x + q.r * t.b[0], q.y + q.r * t.b[1]]];
22411
+ } else {
22412
+ const mitre = (u, v) => {
22413
+ const sx = u[0] + v[0];
22414
+ const sy = u[1] + v[1];
22415
+ const d = (sx * sx + sy * sy) / 2;
22416
+ return [sx / d * q.r, sy / d * q.r];
22417
+ };
22418
+ const ml = mitre(prev.a, t.a);
22419
+ const mr = mitre(prev.b, t.b);
22420
+ left.push([q.x + ml[0], q.y + ml[1]]);
22421
+ right.push([q.x + mr[0], q.y + mr[1]]);
22422
+ }
22423
+ prev = t;
22424
+ const last = i === pts.length - 1;
22425
+ const next = last ? null : tangents(i + 1);
22426
+ if (last || need[i] || !next) {
22427
+ left.push([p.x + p.r * t.a[0], p.y + p.r * t.a[1]]);
22428
+ right.push([p.x + p.r * t.b[0], p.y + p.r * t.b[1]]);
22429
+ flush();
22430
+ }
22431
+ }
22432
+ flush();
22433
+ for (let i = 0; i < pts.length; i++) {
22434
+ if (!need[i]) continue;
22435
+ const p = pts[i];
22436
+ ctx.moveTo(p.x + p.r, p.y);
22437
+ ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2, false);
22438
+ }
22439
+ }
22440
+ /** Splits a centerline into the runs the dash pattern draws. */
22441
+ function splitRoundRuns(pts, dash) {
22442
+ if (!dash.length || dash.every((d) => !(d > 0))) return [pts];
22443
+ const runs = [];
22444
+ let index = 0;
22445
+ let on = true;
22446
+ let remaining = dash[0];
22447
+ let current = on ? [pts[0]] : [];
22448
+ for (let i = 1; i < pts.length; i++) {
22449
+ let a = pts[i - 1];
22450
+ const b = pts[i];
22451
+ let segment = Math.hypot(b.x - a.x, b.y - a.y);
22452
+ while (segment > remaining) {
22453
+ const t = remaining / segment;
22454
+ const cut = {
22455
+ x: a.x + (b.x - a.x) * t,
22456
+ y: a.y + (b.y - a.y) * t,
22457
+ r: a.r + (b.r - a.r) * t
22458
+ };
22459
+ if (on) {
22460
+ current.push(cut);
22461
+ runs.push(current);
22462
+ current = [];
22463
+ } else current = [cut];
22464
+ on = !on;
22465
+ index = (index + 1) % dash.length;
22466
+ segment -= remaining;
22467
+ remaining = dash[index];
22468
+ a = cut;
22469
+ if (!(remaining > 0)) remaining = Number.EPSILON;
22470
+ }
22471
+ remaining -= segment;
22472
+ if (on) current.push(b);
22473
+ }
22474
+ if (on && current.length > 0) runs.push(current);
22475
+ return runs.filter((r) => r.length > 0);
22476
+ }
22477
+ /**
22478
+ * Fills a round outline, once per dash run, so overlaps inside a run never
22479
+ * blend twice and a translucent colour stays uniform.
22480
+ */
22481
+ function drawRoundOutline(ctx, points, color, dash = [], scale = 1) {
22482
+ for (const run of splitRoundRuns(points, dash)) {
22483
+ ctx.beginPath();
22484
+ ctx.fillStyle = color;
22485
+ appendRoundPath(ctx, run, scale);
22486
+ ctx.fill();
22487
+ }
22488
+ }
22489
+ //#endregion
22099
22490
  //#region src/nodes/stroke/stroke.ts
22100
22491
  var WeaveStrokeNode = class WeaveStrokeNode extends WeaveNode {
22101
22492
  config;
22493
+ previewLook = null;
22102
22494
  nodeType = WEAVE_STROKE_NODE_TYPE;
22103
22495
  initialize = void 0;
22104
22496
  /**
@@ -22171,10 +22563,11 @@ var WeaveStrokeNode = class WeaveStrokeNode extends WeaveNode {
22171
22563
  * emitted as a single edge - subdividing a straight line adds vertices
22172
22564
  * without changing a pixel.
22173
22565
  */
22174
- getSplinePoints(pts, resolution = this.config.splineResolution) {
22566
+ getSplinePoints(pts, resolution = this.config.splineResolution, opts) {
22175
22567
  if (pts.length < 2) return [...pts];
22176
- const targetEdge = this.config.splineTargetEdge;
22177
- const maxSteps = this.config.splineMaxSteps;
22568
+ const targetEdge = opts?.targetEdge ?? this.config.splineTargetEdge;
22569
+ const maxSteps = opts?.maxSteps ?? this.config.splineMaxSteps;
22570
+ const flatness = opts?.flatness ?? WeaveStrokeNode.SPLINE_FLATNESS_EPSILON;
22178
22571
  const result = [];
22179
22572
  for (let i = -1; i < pts.length - 2; i++) {
22180
22573
  const p0 = pts[Math.max(i, 0)];
@@ -22191,8 +22584,12 @@ var WeaveStrokeNode = class WeaveStrokeNode extends WeaveNode {
22191
22584
  const at = this.catmullRomAt(p0, p1, p2, p3, probe);
22192
22585
  deviation = Math.max(deviation, this.distanceToSegment(at, p1, p2));
22193
22586
  }
22194
- const steps = deviation < WeaveStrokeNode.SPLINE_FLATNESS_EPSILON ? 1 : Math.min(Math.max(Math.ceil(chord / targetEdge), resolution), maxSteps);
22195
- for (let s = 0; s < steps; s++) result.push(this.catmullRomAt(p0, p1, p2, p3, s / steps));
22587
+ const steps = deviation < flatness ? 1 : Math.min(Math.max(Math.ceil(chord / targetEdge), resolution), maxSteps);
22588
+ for (let s = 0; s < steps; s++) {
22589
+ const q = this.catmullRomAt(p0, p1, p2, p3, s / steps);
22590
+ if (opts?.pressure === "linear") q.pressure = p1.pressure + (p2.pressure - p1.pressure) * (s / steps);
22591
+ result.push(q);
22592
+ }
22196
22593
  }
22197
22594
  result.push(pts[pts.length - 1]);
22198
22595
  return result;
@@ -22219,7 +22616,7 @@ var WeaveStrokeNode = class WeaveStrokeNode extends WeaveNode {
22219
22616
  * result by well under a pixel (95th-percentile outline edge 1.72px vs
22220
22617
  * 1.76px; byte-identical on long, gently-curved strokes).
22221
22618
  */
22222
- drawDashPolygon(ctx, leftSide, rightSide, color) {
22619
+ drawDashPolygon(ctx, leftSide, rightSide, color, mergeCaps = false) {
22223
22620
  const capStartL = leftSide[0];
22224
22621
  const capStartR = rightSide[0];
22225
22622
  const capEndL = leftSide.at(-1);
@@ -22231,6 +22628,24 @@ var WeaveStrokeNode = class WeaveStrokeNode extends WeaveNode {
22231
22628
  for (const p of leftSide) ctx.lineTo(p.x, p.y);
22232
22629
  for (const p of outlineRight) ctx.lineTo(p.x, p.y);
22233
22630
  ctx.closePath();
22631
+ if (mergeCaps) {
22632
+ const outline = [...leftSide, ...outlineRight];
22633
+ let area = 0;
22634
+ for (let i = 0; i < outline.length; i++) {
22635
+ const a = outline[i];
22636
+ const b = outline[(i + 1) % outline.length];
22637
+ area += a.x * b.y - b.x * a.y;
22638
+ }
22639
+ for (const [a, b] of [[capStartL, capStartR], [capEndL, capEndR]]) {
22640
+ const cx = (a.x + b.x) / 2;
22641
+ const cy = (a.y + b.y) / 2;
22642
+ const r = Math.hypot(a.x - b.x, a.y - b.y) / 2;
22643
+ ctx.moveTo(cx + r, cy);
22644
+ ctx.arc(cx, cy, r, 0, Math.PI * 2, area < 0);
22645
+ }
22646
+ ctx.fill();
22647
+ return;
22648
+ }
22234
22649
  ctx.fill();
22235
22650
  this.drawRoundCap(ctx, capStartL, capStartR, color);
22236
22651
  this.drawRoundCap(ctx, capEndL, capEndR, color);
@@ -22248,6 +22663,13 @@ var WeaveStrokeNode = class WeaveStrokeNode extends WeaveNode {
22248
22663
  }
22249
22664
  const filtered = this.resamplePoints(pts, this.config.resamplingSpacing);
22250
22665
  const centerline = this.getSplinePoints(filtered, this.config.splineResolution);
22666
+ this.drawCenterlineRibbon(ctx, centerline, (_i, p) => Math.max(baseW * p.pressure / 2, .5), color, dash, false);
22667
+ }
22668
+ /**
22669
+ * Draws the offset-outline ribbon along an already prepared centerline.
22670
+ * `halfWidth` gives the half-width at each centerline point.
22671
+ */
22672
+ drawCenterlineRibbon(ctx, centerline, halfWidth, color, dash, mergeCaps) {
22251
22673
  let dashIndex = 0;
22252
22674
  let dashOn = true;
22253
22675
  let dashRemaining = dash.length ? dash[0] : Infinity;
@@ -22261,7 +22683,7 @@ var WeaveStrokeNode = class WeaveStrokeNode extends WeaveNode {
22261
22683
  leftSide.push(pendingEndLeft);
22262
22684
  rightSide.push(pendingEndRight);
22263
22685
  }
22264
- this.drawDashPolygon(ctx, leftSide, rightSide, color);
22686
+ this.drawDashPolygon(ctx, leftSide, rightSide, color, mergeCaps);
22265
22687
  };
22266
22688
  for (let i = 0; i < centerline.length - 1; i++) {
22267
22689
  const p0 = centerline[i];
@@ -22271,8 +22693,8 @@ var WeaveStrokeNode = class WeaveStrokeNode extends WeaveNode {
22271
22693
  const segLen = Math.hypot(dx, dy) || 1;
22272
22694
  const nx = -dy / segLen;
22273
22695
  const ny = dx / segLen;
22274
- const w0 = Math.max(baseW * p0.pressure / 2, .5);
22275
- const w1 = Math.max(baseW * p1.pressure / 2, .5);
22696
+ const w0 = halfWidth(i, p0);
22697
+ const w1 = halfWidth(i + 1, p1);
22276
22698
  let traveled = 0;
22277
22699
  while (traveled < segLen) {
22278
22700
  const step = Math.min(dashRemaining, segLen - traveled);
@@ -22322,12 +22744,107 @@ var WeaveStrokeNode = class WeaveStrokeNode extends WeaveNode {
22322
22744
  }
22323
22745
  flushRun();
22324
22746
  }
22747
+ /**
22748
+ * The look a stroke is drawn with: the viewer-side preview if one is on,
22749
+ * otherwise the look saved with the stroke. `null` draws the legacy ribbon.
22750
+ */
22751
+ resolveLook(shape) {
22752
+ return this.previewLook ?? readStrokeLook(shape.getAttrs().look);
22753
+ }
22754
+ /**
22755
+ * Draws every stroke of this screen with `look`, without changing any saved
22756
+ * stroke and without other users seeing it. `null` turns the preview off.
22757
+ */
22758
+ setLookPreview(look) {
22759
+ this.previewLook = look === null ? null : readStrokeLook(look);
22760
+ this.redrawStrokes();
22761
+ }
22762
+ getLookPreview() {
22763
+ return this.previewLook;
22764
+ }
22765
+ redrawStrokes() {
22766
+ const stage = this.instance?.getStage?.();
22767
+ if (!stage || typeof stage.find !== "function") return;
22768
+ const layers = /* @__PURE__ */ new Set();
22769
+ for (const node of stage.find(".node")) if (node.getAttrs().nodeType === "stroke") layers.add(node.getLayer());
22770
+ for (const layer of layers) layer?.batchDraw();
22771
+ }
22772
+ /** Screen pixels per canvas unit at a shape. */
22773
+ screenScale(shape) {
22774
+ const scale = shape.getAbsoluteScale?.().x;
22775
+ return typeof scale === "number" && Number.isFinite(scale) && scale > 0 ? scale : 1;
22776
+ }
22777
+ /**
22778
+ * The centerline of a stroke with a look: the points resampled and joined by
22779
+ * the look's curve. Spacing and detail are in screen pixels when the look
22780
+ * follows the zoom, in canvas units otherwise; `scale` is screen pixels per
22781
+ * canvas unit.
22782
+ */
22783
+ buildLookCenterline(look, scale, pts) {
22784
+ const toCanvas = (px) => look.zoomAware ? px / scale : px;
22785
+ const edge = toCanvas(look.edgePx);
22786
+ const flatness = toCanvas(WeaveStrokeNode.SPLINE_FLATNESS_EPSILON);
22787
+ const maxSteps = look.zoomAware ? Math.max(this.config.splineMaxSteps, 256) : this.config.splineMaxSteps;
22788
+ const filtered = this.resamplePoints(pts, toCanvas(look.spacingPx));
22789
+ if (look.curve === "centripetal") return getCentripetalPoints(filtered, {
22790
+ edge,
22791
+ minSteps: 2,
22792
+ maxSteps,
22793
+ flatness,
22794
+ pressure: look.pressureInterp
22795
+ });
22796
+ if (look.curve === "none") return filtered;
22797
+ return this.getSplinePoints(filtered, this.config.splineResolution, {
22798
+ targetEdge: edge,
22799
+ maxSteps,
22800
+ flatness,
22801
+ pressure: look.pressureInterp
22802
+ });
22803
+ }
22804
+ /**
22805
+ * Draws a stroke that has a look: the centerline is built with the look's
22806
+ * curve, spacing and detail, widths follow its width rule, and the outline is
22807
+ * the legacy ribbon or the round one.
22808
+ */
22809
+ drawRibbonWithLook(ctx, shape, look, pts, baseW, color, dash) {
22810
+ if (!pts) return;
22811
+ if (pts.length < 2) {
22812
+ const pt = pts[0];
22813
+ const r = halfWidthAt(look, baseW, pt.pressure, Infinity, Infinity);
22814
+ ctx.beginPath();
22815
+ ctx.fillStyle = color;
22816
+ ctx.arc(pt.x, pt.y, r, 0, Math.PI * 2);
22817
+ ctx.fill();
22818
+ return;
22819
+ }
22820
+ const scale = this.screenScale(shape);
22821
+ const centerline = this.buildLookCenterline(look, scale, pts);
22822
+ const unit = look.zoomAware ? scale : 1;
22823
+ const along = [0];
22824
+ for (let i = 1; i < centerline.length; i++) along.push(along[i - 1] + Math.hypot(centerline[i].x - centerline[i - 1].x, centerline[i].y - centerline[i - 1].y) * unit);
22825
+ const total = along[along.length - 1];
22826
+ const halfWidth = (i, p) => halfWidthAt(look, baseW, p.pressure, along[i], total - along[i]);
22827
+ if (look.outline === "legacy") {
22828
+ this.drawCenterlineRibbon(ctx, centerline, halfWidth, color, dash, look.caps === "merged");
22829
+ return;
22830
+ }
22831
+ drawRoundOutline(ctx, centerline.map((p, i) => ({
22832
+ x: p.x,
22833
+ y: p.y,
22834
+ r: halfWidth(i, p)
22835
+ })), color, dash, scale);
22836
+ }
22325
22837
  drawShape(ctx, shape) {
22326
22838
  const strokeElements = shape.getAttrs().strokeElements;
22327
22839
  if (strokeElements?.length === 0) return;
22328
22840
  const color = shape.getAttrs().stroke ?? "black";
22329
22841
  const strokeWidth = shape.getAttrs().strokeWidth ?? 1;
22330
22842
  const dash = shape.getAttrs().dash ?? [];
22843
+ const look = this.resolveLook(shape);
22844
+ if (look) {
22845
+ this.drawRibbonWithLook(ctx, shape, look, strokeElements, strokeWidth, color, dash);
22846
+ return;
22847
+ }
22331
22848
  this.drawRibbonWithDash(ctx, strokeElements, strokeWidth, color, dash);
22332
22849
  }
22333
22850
  onRender(props) {
@@ -28381,6 +28898,8 @@ var WeaveLineToolAction = class extends WeaveAction {
28381
28898
  //#endregion
28382
28899
  //#region src/actions/brush-tool/constants.ts
28383
28900
  const BRUSH_TOOL_ACTION_NAME = "brushTool";
28901
+ /** Name under which the lab plugin registers itself. */
28902
+ const BRUSH_LAB_PLUGIN_NAME = "brushLab";
28384
28903
  const BRUSH_TOOL_STATE = {
28385
28904
  ["INACTIVE"]: "inactive",
28386
28905
  ["IDLE"]: "idle",
@@ -28398,207 +28917,2369 @@ const PREVIEW_ID_SUFFIX = "--preview";
28398
28917
  * Bounds the handover so a preview can never be orphaned on screen.
28399
28918
  */
28400
28919
  const PREVIEW_HANDOVER_MAX_FRAMES = 30;
28920
+ const BRUSH_INPUT_PROFILE_KEYS = [
28921
+ "mouse",
28922
+ "touch",
28923
+ "pen.applePencil",
28924
+ "pen.desktop"
28925
+ ];
28926
+ /**
28927
+ * The legacy input profile: reproduces, point for point, what the brush tool
28928
+ * recorded before profiles existed. Every profile starts from it.
28929
+ */
28930
+ const BRUSH_LEGACY_INPUT_PROFILE = {
28931
+ capture: {
28932
+ source: "legacy",
28933
+ clock: "now",
28934
+ minMovePx: 0,
28935
+ predicted: "tail",
28936
+ event: "pointermove"
28937
+ },
28938
+ pressure: {
28939
+ zero: "legacy",
28940
+ filter: "legacy",
28941
+ timeConstantMs: 40,
28942
+ oneEuro: {
28943
+ minCutoff: 1,
28944
+ beta: .01
28945
+ },
28946
+ floor: .15,
28947
+ start: "backfill",
28948
+ startSamples: 3,
28949
+ end: "backfill"
28950
+ },
28951
+ stabilizer: {
28952
+ type: "none",
28953
+ minCutoff: 3,
28954
+ beta: .01,
28955
+ radiusPx: 4,
28956
+ amount: .3,
28957
+ zoomAware: false,
28958
+ catchUpOnEnd: true
28959
+ },
28960
+ finalize: {
28961
+ mode: "dp",
28962
+ toleranceUnit: "canvas",
28963
+ pressureWeight: 20,
28964
+ resampleSpacingPx: 2
28965
+ },
28966
+ touchGuard: {
28967
+ waitMs: 0,
28968
+ movePx: 0,
28969
+ cancelOnSecondTouch: false,
28970
+ ignoreAfterPen: false
28971
+ }
28972
+ };
28401
28973
  const BRUSH_TOOL_DEFAULT_CONFIG = {
28974
+ input: {
28975
+ forceProfile: null,
28976
+ profiles: {
28977
+ mouse: BRUSH_LEGACY_INPUT_PROFILE,
28978
+ touch: BRUSH_LEGACY_INPUT_PROFILE,
28979
+ "pen.applePencil": BRUSH_LEGACY_INPUT_PROFILE,
28980
+ "pen.desktop": BRUSH_LEGACY_INPUT_PROFILE
28981
+ }
28982
+ },
28402
28983
  interpolationSteps: 10,
28403
28984
  simplifyTolerance: .5
28404
28985
  };
28405
28986
  //#endregion
28406
- //#region src/actions/brush-tool/brush-tool.ts
28407
- var WeaveBrushToolAction = class extends WeaveAction {
28408
- config;
28409
- initialized = false;
28410
- state;
28411
- clickPoint;
28412
- strokeId;
28413
- isSpacePressed = false;
28414
- isEraser;
28415
- container;
28416
- measureContainer;
28417
- cancelAction;
28418
- prevTouchAction;
28419
- penActive = false;
28420
- lastSmoothedPressure = .5;
28421
- hasPressureSample = false;
28422
- lastPointerPos = null;
28423
- lastPointerTime = 0;
28424
- predictedCount = 0;
28425
- onPropsChange = void 0;
28426
- onInit = void 0;
28427
- constructor(params) {
28428
- super();
28429
- this.config = mergeExceptArrays(BRUSH_TOOL_DEFAULT_CONFIG, params?.config ?? {});
28430
- this.initialize();
28987
+ //#region src/actions/brush-tool/stages/stabilizer.ts
28988
+ /** Time assumed between two samples whose times do not advance, in ms. */
28989
+ const NOMINAL_SAMPLE_INTERVAL_MS$1 = 5;
28990
+ const seconds = (now, last) => (now - last > 0 ? now - last : NOMINAL_SAMPLE_INTERVAL_MS$1) / 1e3;
28991
+ /**
28992
+ * Scale between canvas units and the units distances are configured in: screen
28993
+ * pixels when the stabilizer is zoom-aware, canvas units otherwise.
28994
+ */
28995
+ const unitScale = (cfg, ctx) => cfg.zoomAware && ctx.zoom > 0 && Number.isFinite(ctx.zoom) ? ctx.zoom : 1;
28996
+ var NoStabilizer = class {
28997
+ reset() {}
28998
+ seed() {}
28999
+ apply(point) {
29000
+ return point;
28431
29001
  }
28432
- initialize() {
28433
- this.initialized = false;
28434
- this.state = BRUSH_TOOL_STATE.INACTIVE;
28435
- this.strokeId = null;
28436
- this.clickPoint = null;
28437
- this.container = void 0;
28438
- this.isEraser = false;
28439
- this.measureContainer = void 0;
28440
- this.props = this.initProps();
28441
- this.isSpacePressed = false;
29002
+ };
29003
+ /** One Euro low-pass filter on one axis. */
29004
+ var OneEuroAxis = class {
29005
+ last = 0;
29006
+ derivative = 0;
29007
+ lastTime = 0;
29008
+ seeded = false;
29009
+ reset() {
29010
+ this.seeded = false;
29011
+ this.derivative = 0;
29012
+ }
29013
+ seed(value, time) {
29014
+ this.last = value;
29015
+ this.lastTime = time;
29016
+ this.derivative = 0;
29017
+ this.seeded = true;
29018
+ }
29019
+ filter(value, time, minCutoff, beta) {
29020
+ if (!this.seeded) {
29021
+ this.seed(value, time);
29022
+ return value;
29023
+ }
29024
+ const dt = seconds(time, this.lastTime);
29025
+ const factor = (cutoff) => {
29026
+ const r = 2 * Math.PI * cutoff * dt;
29027
+ return r / (r + 1);
29028
+ };
29029
+ const a = factor(1);
29030
+ this.derivative = a * ((value - this.last) / dt) + (1 - a) * this.derivative;
29031
+ const alpha = factor(minCutoff + beta * Math.abs(this.derivative));
29032
+ const filtered = alpha * value + (1 - alpha) * this.last;
29033
+ this.last = Number.isFinite(filtered) ? filtered : value;
29034
+ this.lastTime = time;
29035
+ return this.last;
28442
29036
  }
28443
- getName() {
28444
- return BRUSH_TOOL_ACTION_NAME;
29037
+ };
29038
+ /**
29039
+ * One Euro filter (Casiez, Roussel, Vogel 2012) on the pen position: slow
29040
+ * movement is smoothed, fast movement is followed closely.
29041
+ */
29042
+ var OneEuroStabilizer = class {
29043
+ cfg;
29044
+ x = new OneEuroAxis();
29045
+ y = new OneEuroAxis();
29046
+ constructor(cfg) {
29047
+ this.cfg = cfg;
28445
29048
  }
28446
- initProps() {
29049
+ reset() {
29050
+ this.x.reset();
29051
+ this.y.reset();
29052
+ }
29053
+ seed(point, ctx) {
29054
+ const s = unitScale(this.cfg, ctx);
29055
+ this.x.seed(point.x * s, ctx.now);
29056
+ this.y.seed(point.y * s, ctx.now);
29057
+ }
29058
+ apply(point, ctx) {
29059
+ const s = unitScale(this.cfg, ctx);
28447
29060
  return {
28448
- stroke: "#000000ff",
28449
- strokeWidth: 1,
28450
- opacity: 1
29061
+ x: this.x.filter(point.x * s, ctx.now, this.cfg.minCutoff, this.cfg.beta) / s,
29062
+ y: this.y.filter(point.y * s, ctx.now, this.cfg.minCutoff, this.cfg.beta) / s
28451
29063
  };
28452
29064
  }
28453
- /**
28454
- * Velocity-adaptive exponential smoothing of a single raw pressure sample.
28455
- *
28456
- * This is the one place pressure smoothing happens. Every sample that
28457
- * becomes a stroke point must go through it - including the
28458
- * high-frequency coalesced samples a stylus reports (see
28459
- * `handlePointerMove`), which previously bypassed it entirely and so
28460
- * landed in the stroke with their raw value, no pressure floor, and
28461
- * without advancing the smoothing state for later samples.
28462
- *
28463
- * Timing intentionally uses `performance.now()` (not the event's own
28464
- * `timeStamp`), matching the original behaviour: the two are not
28465
- * guaranteed to share a time origin, and mixing them corrupts the
28466
- * velocity term that drives `alpha`.
28467
- *
28468
- * The first sample of a stroke SEEDS the filter with its own value
28469
- * rather than being blended toward the neutral 0.5 baseline. Blending
28470
- * from a constant gives every stroke a warm-up transient: the filter
28471
- * starts at 0.5 and converges toward the pressure actually being
28472
- * applied, so a stroke drawn lighter than 0.5 renders visibly fatter at
28473
- * its start (and heavier than 0.5, thinner) until the filter catches
28474
- * up. Seeding removes that transient entirely - smoothing then only
28475
- * ever acts between real samples, which is its actual purpose.
28476
- */
28477
- smoothPressureSample(raw, clientX, clientY) {
28478
- const now = performance.now();
28479
- let velocity = 0;
28480
- const hasPosition = Number.isFinite(clientX) && Number.isFinite(clientY);
28481
- if (hasPosition && this.lastPointerPos && now - this.lastPointerTime > 0) {
28482
- const dx = clientX - this.lastPointerPos.x;
28483
- const dy = clientY - this.lastPointerPos.y;
28484
- velocity = Math.hypot(dx, dy) / (now - this.lastPointerTime) * 1e3;
28485
- }
28486
- if (hasPosition) this.lastPointerPos = {
28487
- x: clientX,
28488
- y: clientY
28489
- };
28490
- this.lastPointerTime = now;
28491
- const safeRaw = Number.isFinite(raw) ? raw : .5;
28492
- if (!this.hasPressureSample) {
28493
- this.hasPressureSample = true;
28494
- this.lastSmoothedPressure = safeRaw;
28495
- return Math.max(this.lastSmoothedPressure, .15);
29065
+ };
29066
+ /**
29067
+ * Pulled string: the recorded point is held back on a leash of fixed length
29068
+ * and only moves when the pen pulls it taut, so movement inside the leash
29069
+ * leaves no mark and tight curves are rounded.
29070
+ */
29071
+ var PulledStringStabilizer = class {
29072
+ cfg;
29073
+ tip = null;
29074
+ constructor(cfg) {
29075
+ this.cfg = cfg;
29076
+ }
29077
+ reset() {
29078
+ this.tip = null;
29079
+ }
29080
+ seed(point) {
29081
+ this.tip = { ...point };
29082
+ }
29083
+ apply(point, ctx) {
29084
+ if (!this.tip) {
29085
+ this.tip = { ...point };
29086
+ return point;
29087
+ }
29088
+ const leash = this.cfg.radiusPx / unitScale(this.cfg, ctx);
29089
+ const dx = point.x - this.tip.x;
29090
+ const dy = point.y - this.tip.y;
29091
+ const distance = Math.hypot(dx, dy);
29092
+ if (distance > leash && distance > 0) {
29093
+ const pull = (distance - leash) / distance;
29094
+ this.tip = {
29095
+ x: this.tip.x + dx * pull,
29096
+ y: this.tip.y + dy * pull
29097
+ };
28496
29098
  }
28497
- const alpha = Math.min(Math.max(velocity / 1500, .15), .6);
28498
- const smoothed = alpha * safeRaw + (1 - alpha) * this.lastSmoothedPressure;
28499
- this.lastSmoothedPressure = Number.isFinite(smoothed) ? smoothed : safeRaw;
28500
- return Math.max(this.lastSmoothedPressure, .15);
29099
+ return { ...this.tip };
28501
29100
  }
28502
- /**
28503
- * Raw pressure a pointer sample reports: the device's own reading for a
28504
- * pen, a neutral constant for devices that do not sense pressure.
28505
- */
28506
- getRawPressure(pointerType, pressure) {
28507
- if (pointerType === "pen") return (typeof pressure === "number" ? pressure : 0) || .5;
28508
- return .5;
29101
+ };
29102
+ /** Longest time constant of the streamline stabilizer, at amount 1, in ms. */
29103
+ const STREAMLINE_MAX_TAU_MS = 80;
29104
+ /**
29105
+ * Streamline: the recorded point eases towards the pen with a time constant
29106
+ * proportional to `amount`, so the result does not depend on how often samples
29107
+ * arrive. Amount 0 follows the pen exactly.
29108
+ */
29109
+ var StreamlineStabilizer = class {
29110
+ cfg;
29111
+ tip = null;
29112
+ lastTime = 0;
29113
+ constructor(cfg) {
29114
+ this.cfg = cfg;
28509
29115
  }
28510
- getEventPressure(e) {
28511
- return this.smoothPressureSample(this.getRawPressure(e.evt.pointerType, e.evt.pressure), e.evt.clientX, e.evt.clientY);
29116
+ reset() {
29117
+ this.tip = null;
28512
29118
  }
28513
- /**
28514
- * Resets the pressure-smoothing state (smoothed pressure, last known pointer
28515
- * position/time, and predicted-point bookkeeping) to a neutral baseline.
28516
- *
28517
- * This state is scoped to a single stroke: it must be reset before the
28518
- * first pressure sample of a new stroke is computed (in `handlePointerDown`,
28519
- * ahead of the `getEventPressure` call for point 0), not only afterwards -
28520
- * otherwise that first sample can inherit smoothing state left behind by
28521
- * the previous stroke (its ending pressure, pointer position and time),
28522
- * inflating the very first point's pressure.
28523
- */
28524
- resetPressureSmoothingState() {
28525
- this.lastSmoothedPressure = .5;
28526
- this.hasPressureSample = false;
28527
- this.lastPointerPos = null;
28528
- this.lastPointerTime = 0;
28529
- this.predictedCount = 0;
29119
+ seed(point, ctx) {
29120
+ this.tip = { ...point };
29121
+ this.lastTime = ctx.now;
28530
29122
  }
28531
- setupEvents() {
28532
- const stage = this.instance.getStage();
28533
- this.prevTouchAction = stage.container().style.touchAction;
28534
- stage.container().style.touchAction = "none";
28535
- window.addEventListener("keyup", (e) => {
28536
- if (e.code === "Space" && this.instance.getActiveAction() === "brushTool") this.isSpacePressed = false;
28537
- }, { signal: this.instance.getEventsController().signal });
28538
- window.addEventListener("keydown", (e) => {
28539
- if (e.code === "Enter" && this.instance.getActiveAction() === "brushTool") {
28540
- e.stopPropagation();
28541
- this.cancelAction();
28542
- return;
28543
- }
28544
- if (e.code === "Space" && this.instance.getActiveAction() === "brushTool") {
28545
- e.stopPropagation();
28546
- this.isSpacePressed = true;
28547
- return;
28548
- }
28549
- if (e.code === "Escape" && this.instance.getActiveAction() === "brushTool") {
28550
- e.stopPropagation();
28551
- this.cancelAction();
28552
- }
28553
- }, { signal: this.instance.getEventsController().signal });
28554
- const handlePointerDown = (e) => {
28555
- if (this.state === BRUSH_TOOL_STATE.INACTIVE) return;
28556
- if (this.state !== BRUSH_TOOL_STATE.IDLE) return;
28557
- if (this.getZoomPlugin()?.isPinching()) return;
28558
- if (this.isSpacePressed) return;
28559
- if (e?.evt?.button !== 0) return;
28560
- if (e.evt.pointerType === "touch" && this.penActive) return;
28561
- if (e.evt.pointerType === "pen") this.penActive = true;
28562
- this.resetPressureSmoothingState();
28563
- const pointPressure = this.getEventPressure(e);
28564
- this.handleStartStroke(pointPressure);
28565
- e.evt.stopPropagation();
28566
- };
28567
- stage.on("pointerdown", handlePointerDown);
28568
- const handlePointerMove = (e) => {
28569
- if (this.state === BRUSH_TOOL_STATE.INACTIVE) return;
28570
- this.setCursor();
28571
- if (this.state !== BRUSH_TOOL_STATE.DEFINE_STROKE) return;
28572
- if (this.getZoomPlugin()?.isPinching()) return;
28573
- const coalescedEvents = e.evt.getCoalescedEvents ? e.evt.getCoalescedEvents() : [];
28574
- if (coalescedEvents.length > 1) {
28575
- const samples = coalescedEvents.map((ce) => ({
28576
- pressure: this.smoothPressureSample(this.getRawPressure(ce.pointerType, ce.pressure), ce.clientX, ce.clientY),
28577
- isPredicted: false
28578
- }));
28579
- const predictedEvents = e.evt.getPredictedEvents ? e.evt.getPredictedEvents() : [];
28580
- if (predictedEvents.length > 0) {
28581
- const last = predictedEvents[predictedEvents.length - 1];
28582
- const predPressure = Math.max(.15 * this.getRawPressure(last.pointerType, last.pressure) + .85 * this.lastSmoothedPressure, .15);
28583
- samples.push({
28584
- pressure: predPressure,
28585
- sourceEvent: last,
28586
- isPredicted: true
28587
- });
28588
- }
28589
- this.applyMovementSamples(samples);
28590
- } else {
28591
- const pointPressure = this.getEventPressure(e);
28592
- this.handleMovement(pointPressure, void 0, false);
28593
- }
28594
- e.evt.stopPropagation();
29123
+ apply(point, ctx) {
29124
+ const tau = this.cfg.amount * STREAMLINE_MAX_TAU_MS;
29125
+ if (!this.tip || tau <= 0) {
29126
+ this.tip = { ...point };
29127
+ this.lastTime = ctx.now;
29128
+ return point;
29129
+ }
29130
+ const dt = seconds(ctx.now, this.lastTime) * 1e3;
29131
+ const alpha = 1 - Math.exp(-dt / tau);
29132
+ this.tip = {
29133
+ x: this.tip.x + (point.x - this.tip.x) * alpha,
29134
+ y: this.tip.y + (point.y - this.tip.y) * alpha
28595
29135
  };
28596
- stage.on("pointermove", handlePointerMove);
28597
- const handlePointerUp = (e) => {
28598
- this.penActive = false;
29136
+ this.lastTime = ctx.now;
29137
+ return { ...this.tip };
29138
+ }
29139
+ };
29140
+ /** Creates the stabilizer selected by a profile. */
29141
+ function createStabilizer(cfg) {
29142
+ switch (cfg.type) {
29143
+ case "oneEuro": return new OneEuroStabilizer(cfg);
29144
+ case "pulledString": return new PulledStringStabilizer(cfg);
29145
+ case "streamline": return new StreamlineStabilizer(cfg);
29146
+ default: return new NoStabilizer();
29147
+ }
29148
+ }
29149
+ //#endregion
29150
+ //#region src/actions/brush-tool/stages/pressure.ts
29151
+ /** Time assumed between two samples whose times do not advance, in ms. */
29152
+ const NOMINAL_SAMPLE_INTERVAL_MS = 5;
29153
+ function resetPressureState(state) {
29154
+ state.lastSmoothedPressure = .5;
29155
+ state.hasPressureSample = false;
29156
+ state.lastPointerPos = null;
29157
+ state.lastPointerTime = 0;
29158
+ state.predictedCount = 0;
29159
+ state.lastDerivative = 0;
29160
+ state.lastNonZeroPressure = null;
29161
+ }
29162
+ /**
29163
+ * Raw pressure a pointer sample reports: the device's own reading for a pen, a
29164
+ * neutral constant for devices that do not sense pressure.
29165
+ *
29166
+ * `zero` decides what a reported pressure of 0 means for a pen: `legacy`
29167
+ * replaces it with 0.5, `keep` records it (the pressure floor still applies),
29168
+ * `holdLast` repeats the last non-zero reading. `commit: false` reads without
29169
+ * remembering the value, for speculative samples.
29170
+ */
29171
+ function getRawPressure(pointerType, pressure, zero = "legacy", state, commit = true) {
29172
+ if (pointerType !== "pen") return .5;
29173
+ const value = typeof pressure === "number" && Number.isFinite(pressure) ? pressure : 0;
29174
+ switch (zero) {
29175
+ case "keep": return typeof pressure === "number" && Number.isFinite(pressure) ? pressure : .5;
29176
+ case "holdLast":
29177
+ if (value > 0) {
29178
+ if (commit && state) state.lastNonZeroPressure = value;
29179
+ return value;
29180
+ }
29181
+ return state?.lastNonZeroPressure ?? .5;
29182
+ default: return value || .5;
29183
+ }
29184
+ }
29185
+ /**
29186
+ * Legacy velocity-adaptive exponential smoothing of one raw pressure sample.
29187
+ *
29188
+ * The first sample of a stroke seeds the filter with its own value. Fast
29189
+ * movement gives a higher alpha (more responsive), slow movement a lower one.
29190
+ */
29191
+ function smoothLegacy(state, cfg, raw, clientX, clientY, now) {
29192
+ let velocity = 0;
29193
+ const hasPosition = Number.isFinite(clientX) && Number.isFinite(clientY);
29194
+ if (hasPosition && state.lastPointerPos && now - state.lastPointerTime > 0) {
29195
+ const dx = clientX - state.lastPointerPos.x;
29196
+ const dy = clientY - state.lastPointerPos.y;
29197
+ velocity = Math.hypot(dx, dy) / (now - state.lastPointerTime) * 1e3;
29198
+ }
29199
+ if (hasPosition) state.lastPointerPos = {
29200
+ x: clientX,
29201
+ y: clientY
29202
+ };
29203
+ state.lastPointerTime = now;
29204
+ const safeRaw = Number.isFinite(raw) ? raw : .5;
29205
+ if (!state.hasPressureSample) {
29206
+ state.hasPressureSample = true;
29207
+ state.lastSmoothedPressure = safeRaw;
29208
+ return Math.max(state.lastSmoothedPressure, cfg.floor);
29209
+ }
29210
+ const alpha = Math.min(Math.max(velocity / 1500, .15), .6);
29211
+ const smoothed = alpha * safeRaw + (1 - alpha) * state.lastSmoothedPressure;
29212
+ state.lastSmoothedPressure = Number.isFinite(smoothed) ? smoothed : safeRaw;
29213
+ return Math.max(state.lastSmoothedPressure, cfg.floor);
29214
+ }
29215
+ /** Seconds between two samples; a non-advancing clock assumes a nominal rate. */
29216
+ function elapsedSeconds(state, now) {
29217
+ const dt = now - state.lastPointerTime;
29218
+ return (dt > 0 ? dt : NOMINAL_SAMPLE_INTERVAL_MS) / 1e3;
29219
+ }
29220
+ /** Seeds a filter with its first sample. */
29221
+ function seed(state, value, now) {
29222
+ state.hasPressureSample = true;
29223
+ state.lastSmoothedPressure = value;
29224
+ state.lastPointerTime = now;
29225
+ state.lastDerivative = 0;
29226
+ }
29227
+ /** Exponential smoothing with a time constant, independent of the report rate. */
29228
+ function smoothTimeEma(state, cfg, safeRaw, now) {
29229
+ if (!state.hasPressureSample) {
29230
+ seed(state, safeRaw, now);
29231
+ return Math.max(safeRaw, cfg.floor);
29232
+ }
29233
+ const dt = elapsedSeconds(state, now) * 1e3;
29234
+ const alpha = 1 - Math.exp(-dt / Math.max(cfg.timeConstantMs, 1e-6));
29235
+ const smoothed = alpha * safeRaw + (1 - alpha) * state.lastSmoothedPressure;
29236
+ state.lastSmoothedPressure = Number.isFinite(smoothed) ? smoothed : safeRaw;
29237
+ state.lastPointerTime = now;
29238
+ return Math.max(state.lastSmoothedPressure, cfg.floor);
29239
+ }
29240
+ const smoothingFactor = (dt, cutoff) => {
29241
+ const r = 2 * Math.PI * cutoff * dt;
29242
+ return r / (r + 1);
29243
+ };
29244
+ /**
29245
+ * One Euro filter (Casiez, Roussel, Vogel 2012): a low-pass filter whose cutoff
29246
+ * rises with speed, so slow changes are smoothed and fast ones follow closely.
29247
+ */
29248
+ function smoothOneEuro(state, cfg, safeRaw, now) {
29249
+ if (!state.hasPressureSample) {
29250
+ seed(state, safeRaw, now);
29251
+ return Math.max(safeRaw, cfg.floor);
29252
+ }
29253
+ const dt = elapsedSeconds(state, now);
29254
+ const derivative = (safeRaw - state.lastSmoothedPressure) / dt;
29255
+ const a = smoothingFactor(dt, 1);
29256
+ state.lastDerivative = a * derivative + (1 - a) * state.lastDerivative;
29257
+ const cutoff = cfg.oneEuro.minCutoff + cfg.oneEuro.beta * Math.abs(state.lastDerivative);
29258
+ const alpha = smoothingFactor(dt, cutoff);
29259
+ const smoothed = alpha * safeRaw + (1 - alpha) * state.lastSmoothedPressure;
29260
+ state.lastSmoothedPressure = Number.isFinite(smoothed) ? smoothed : safeRaw;
29261
+ state.lastPointerTime = now;
29262
+ return Math.max(state.lastSmoothedPressure, cfg.floor);
29263
+ }
29264
+ /** Smooths one raw pressure sample with the filter selected by the profile. */
29265
+ function smoothPressure(state, cfg, raw, clientX, clientY, now) {
29266
+ const safeRaw = Number.isFinite(raw) ? raw : .5;
29267
+ switch (cfg.filter) {
29268
+ case "timeEma": return smoothTimeEma(state, cfg, safeRaw, now);
29269
+ case "oneEuro": return smoothOneEuro(state, cfg, safeRaw, now);
29270
+ case "none":
29271
+ state.hasPressureSample = true;
29272
+ state.lastSmoothedPressure = safeRaw;
29273
+ state.lastPointerTime = now;
29274
+ return Math.max(safeRaw, cfg.floor);
29275
+ default: return smoothLegacy(state, cfg, raw, clientX, clientY, now);
29276
+ }
29277
+ }
29278
+ /**
29279
+ * Pressure of a predicted (speculative) sample. It blends against the current
29280
+ * state read-only, because predicted samples are rolled back and must not
29281
+ * advance the state real samples depend on.
29282
+ */
29283
+ function peekPredictedPressure(state, cfg, raw) {
29284
+ return Math.max(.15 * raw + .85 * state.lastSmoothedPressure, cfg.floor);
29285
+ }
29286
+ /**
29287
+ * Start policy for the first point's pressure. A stroke's pointer-down reading
29288
+ * is frequently an unreliable contact spike.
29289
+ *
29290
+ * - `backfill`: the first real movement sample replaces it once it exists.
29291
+ * - `average`: it becomes the mean of the first `startSamples` real movement
29292
+ * readings, refined as each one arrives, so it never keeps the contact value.
29293
+ * - `none`: it is left as reported.
29294
+ *
29295
+ * Predicted samples never change it.
29296
+ */
29297
+ function applyStartPolicy(elements, incoming, isPredicted, cfg) {
29298
+ if (isPredicted || elements.length === 0) return;
29299
+ if (cfg.start === "backfill" && elements.length === 1) elements[0] = {
29300
+ ...elements[0],
29301
+ pressure: incoming.pressure
29302
+ };
29303
+ else if (cfg.start === "average" && elements.length <= cfg.startSamples) {
29304
+ const readings = [...elements.slice(1), incoming];
29305
+ elements[0] = {
29306
+ ...elements[0],
29307
+ pressure: readings.reduce((sum, p) => sum + p.pressure, 0) / readings.length
29308
+ };
29309
+ }
29310
+ }
29311
+ /**
29312
+ * End policy. A lift-off reading can be as unreliable as the contact spike;
29313
+ * under `backfill` the last point takes the second-to-last point's pressure.
29314
+ */
29315
+ function applyEndPolicy(elements, cfg) {
29316
+ if (cfg.end === "backfill" && elements.length >= 2) {
29317
+ const result = [...elements];
29318
+ const lastIndex = result.length - 1;
29319
+ result[lastIndex] = {
29320
+ ...result[lastIndex],
29321
+ pressure: result[lastIndex - 1].pressure
29322
+ };
29323
+ return result;
29324
+ }
29325
+ return elements;
29326
+ }
29327
+ //#endregion
29328
+ //#region src/actions/brush-tool/stages/capture.ts
29329
+ const createCaptureState = () => ({ lastClient: null });
29330
+ /**
29331
+ * Legacy capture of a pointer move that carries batched (coalesced) samples.
29332
+ *
29333
+ * Every real sample is smoothed through the same path as any other sample but
29334
+ * deliberately carries no `sourceEvent`: coalesced samples keep using the
29335
+ * event's already-resolved pointer position. The last predicted sample, if
29336
+ * any, is appended as a provisional point.
29337
+ *
29338
+ * Returns `null` when the event has at most one sample, so the caller takes
29339
+ * the single-event path.
29340
+ */
29341
+ function captureLegacySamples(evt, deps) {
29342
+ const coalescedEvents = evt.getCoalescedEvents ? evt.getCoalescedEvents() : [];
29343
+ if (coalescedEvents.length <= 1) return null;
29344
+ const samples = coalescedEvents.map((ce) => ({
29345
+ pressure: deps.smooth(deps.rawPressure(ce.pointerType, ce.pressure), ce.clientX, ce.clientY, ce.timeStamp),
29346
+ isPredicted: false
29347
+ }));
29348
+ const predictedEvents = evt.getPredictedEvents ? evt.getPredictedEvents() : [];
29349
+ if (predictedEvents.length > 0) {
29350
+ const last = predictedEvents[predictedEvents.length - 1];
29351
+ samples.push({
29352
+ pressure: deps.predictedPressure(deps.rawPressure(last.pointerType, last.pressure, false)),
29353
+ sourceEvent: last,
29354
+ isPredicted: true
29355
+ });
29356
+ }
29357
+ return samples;
29358
+ }
29359
+ /**
29360
+ * Captures every sample a pointer move carries: each batched (coalesced) sample
29361
+ * becomes a point at its own position, pressure and time, in the order the
29362
+ * browser reported them. An event without a batch is one sample.
29363
+ *
29364
+ * Positions are computed from each sample's client coordinates, so no shared
29365
+ * stage state is changed. Samples closer than `minMovePx` (screen px) to the
29366
+ * last recorded one are skipped. The browser's predicted tail is appended as a
29367
+ * provisional point when enabled and at least one real sample was kept.
29368
+ */
29369
+ function captureCoalescedSamples(evt, deps, cfg, state) {
29370
+ const batch = evt.getCoalescedEvents ? evt.getCoalescedEvents() : [];
29371
+ const source = batch.length > 0 ? batch : [evt];
29372
+ const samples = [];
29373
+ for (const ce of source) {
29374
+ if (cfg.minMovePx > 0 && state.lastClient && Math.hypot(ce.clientX - state.lastClient.x, ce.clientY - state.lastClient.y) < cfg.minMovePx) continue;
29375
+ state.lastClient = {
29376
+ x: ce.clientX,
29377
+ y: ce.clientY
29378
+ };
29379
+ samples.push({
29380
+ pressure: deps.smooth(deps.rawPressure(ce.pointerType, ce.pressure), ce.clientX, ce.clientY, ce.timeStamp),
29381
+ point: deps.toContainerPoint(ce.clientX, ce.clientY),
29382
+ time: ce.timeStamp,
29383
+ isPredicted: false
29384
+ });
29385
+ }
29386
+ if (samples.length > 0 && cfg.predicted === "tail") {
29387
+ const predictedEvents = evt.getPredictedEvents ? evt.getPredictedEvents() : [];
29388
+ if (predictedEvents.length > 0) {
29389
+ const last = predictedEvents[predictedEvents.length - 1];
29390
+ samples.push({
29391
+ pressure: deps.predictedPressure(deps.rawPressure(last.pointerType, last.pressure, false)),
29392
+ point: deps.toContainerPoint(last.clientX, last.clientY),
29393
+ time: last.timeStamp,
29394
+ isPredicted: true
29395
+ });
29396
+ }
29397
+ }
29398
+ return samples;
29399
+ }
29400
+ //#endregion
29401
+ //#region src/actions/brush-tool/stages/bezier-fit.ts
29402
+ const sub = (a, b) => ({
29403
+ x: a.x - b.x,
29404
+ y: a.y - b.y
29405
+ });
29406
+ const add = (a, b) => ({
29407
+ x: a.x + b.x,
29408
+ y: a.y + b.y
29409
+ });
29410
+ const scale = (a, s) => ({
29411
+ x: a.x * s,
29412
+ y: a.y * s
29413
+ });
29414
+ const dot = (a, b) => a.x * b.x + a.y * b.y;
29415
+ const length = (a) => Math.hypot(a.x, a.y);
29416
+ const normalize = (a) => {
29417
+ const l = length(a);
29418
+ return l > 0 ? {
29419
+ x: a.x / l,
29420
+ y: a.y / l
29421
+ } : {
29422
+ x: 0,
29423
+ y: 0
29424
+ };
29425
+ };
29426
+ const B0 = (u) => (1 - u) ** 3;
29427
+ const B1 = (u) => 3 * u * (1 - u) ** 2;
29428
+ const B2 = (u) => 3 * u * u * (1 - u);
29429
+ const B3 = (u) => u ** 3;
29430
+ /** Point on a cubic Bézier curve. */
29431
+ function bezierPoint(b, t) {
29432
+ return {
29433
+ x: B0(t) * b[0].x + B1(t) * b[1].x + B2(t) * b[2].x + B3(t) * b[3].x,
29434
+ y: B0(t) * b[0].y + B1(t) * b[1].y + B2(t) * b[2].y + B3(t) * b[3].y
29435
+ };
29436
+ }
29437
+ function derivative(b, t) {
29438
+ const q = [
29439
+ sub(b[1], b[0]),
29440
+ sub(b[2], b[1]),
29441
+ sub(b[3], b[2])
29442
+ ].map((v) => scale(v, 3));
29443
+ const s = 1 - t;
29444
+ return {
29445
+ x: s * s * q[0].x + 2 * s * t * q[1].x + t * t * q[2].x,
29446
+ y: s * s * q[0].y + 2 * s * t * q[1].y + t * t * q[2].y
29447
+ };
29448
+ }
29449
+ function secondDerivative(b, t) {
29450
+ const q = [add(sub(b[2], scale(b[1], 2)), b[0]), add(sub(b[3], scale(b[2], 2)), b[1])].map((v) => scale(v, 6));
29451
+ return {
29452
+ x: (1 - t) * q[0].x + t * q[1].x,
29453
+ y: (1 - t) * q[0].y + t * q[1].y
29454
+ };
29455
+ }
29456
+ /**
29457
+ * Direction of the curve at `index`, estimated over a window at least
29458
+ * `window` long on each side (but inside `first..last`), so that noise in the
29459
+ * nearest samples does not tilt it. With `before` false only the following
29460
+ * points are used (a start tangent); with `after` false only the preceding
29461
+ * ones (an end tangent). The vector points forward along the stroke.
29462
+ */
29463
+ function windowTangent(pts, index, first, last, window, before, after) {
29464
+ let back = index;
29465
+ if (before) while (back > first && length(sub(pts[index], pts[back])) < window) back--;
29466
+ let ahead = index;
29467
+ if (after) while (ahead < last && length(sub(pts[ahead], pts[index])) < window) ahead++;
29468
+ return normalize(sub(pts[ahead], pts[back]));
29469
+ }
29470
+ function chordLengthParameterize(pts, first, last) {
29471
+ const u = [0];
29472
+ for (let i = first + 1; i <= last; i++) u.push(u[u.length - 1] + length(sub(pts[i], pts[i - 1])));
29473
+ const total = u[u.length - 1] || 1;
29474
+ return u.map((v) => v / total);
29475
+ }
29476
+ function generateBezier(pts, first, last, u, tHat1, tHat2) {
29477
+ const p0 = pts[first];
29478
+ const p3 = pts[last];
29479
+ let c00 = 0, c01 = 0, c11 = 0, x0 = 0, x1 = 0;
29480
+ for (let i = 0; i < u.length; i++) {
29481
+ const a0 = scale(tHat1, B1(u[i]));
29482
+ const a1 = scale(tHat2, B2(u[i]));
29483
+ c00 += dot(a0, a0);
29484
+ c01 += dot(a0, a1);
29485
+ c11 += dot(a1, a1);
29486
+ const tmp = sub(pts[first + i], add(scale(p0, B0(u[i]) + B1(u[i])), scale(p3, B2(u[i]) + B3(u[i]))));
29487
+ x0 += dot(a0, tmp);
29488
+ x1 += dot(a1, tmp);
29489
+ }
29490
+ const det = c00 * c11 - c01 * c01;
29491
+ const alphaL = det === 0 ? 0 : (x0 * c11 - x1 * c01) / det;
29492
+ const alphaR = det === 0 ? 0 : (c00 * x1 - c01 * x0) / det;
29493
+ const segLength = length(sub(p3, p0));
29494
+ const epsilon = 1e-6 * segLength;
29495
+ if (alphaL < epsilon || alphaR < epsilon) {
29496
+ const d = segLength / 3;
29497
+ return [
29498
+ p0,
29499
+ add(p0, scale(tHat1, d)),
29500
+ add(p3, scale(tHat2, d)),
29501
+ p3
29502
+ ];
29503
+ }
29504
+ return [
29505
+ p0,
29506
+ add(p0, scale(tHat1, alphaL)),
29507
+ add(p3, scale(tHat2, alphaR)),
29508
+ p3
29509
+ ];
29510
+ }
29511
+ function newtonRaphson(b, p, u) {
29512
+ const d = sub(bezierPoint(b, u), p);
29513
+ const d1 = derivative(b, u);
29514
+ const d2 = secondDerivative(b, u);
29515
+ const numerator = dot(d, d1);
29516
+ const denominator = dot(d1, d1) + dot(d, d2);
29517
+ return denominator === 0 ? u : u - numerator / denominator;
29518
+ }
29519
+ function maxError(pts, first, last, b, u) {
29520
+ let split = Math.floor((last - first + 1) / 2) + first;
29521
+ let max = 0;
29522
+ for (let i = first + 1; i < last; i++) {
29523
+ const d = sub(bezierPoint(b, u[i - first]), pts[i]);
29524
+ const e = dot(d, d);
29525
+ if (e >= max) {
29526
+ max = e;
29527
+ split = i;
29528
+ }
29529
+ }
29530
+ return {
29531
+ error: max,
29532
+ split
29533
+ };
29534
+ }
29535
+ function fitCubic(pts, first, last, tHat1, tHat2, errorSq, window, out) {
29536
+ if (last - first === 1) {
29537
+ const d = length(sub(pts[last], pts[first])) / 3;
29538
+ out.push({
29539
+ bez: [
29540
+ pts[first],
29541
+ add(pts[first], scale(tHat1, d)),
29542
+ add(pts[last], scale(tHat2, d)),
29543
+ pts[last]
29544
+ ],
29545
+ first,
29546
+ last,
29547
+ u: [0, 1]
29548
+ });
29549
+ return;
29550
+ }
29551
+ let u = chordLengthParameterize(pts, first, last);
29552
+ let bez = generateBezier(pts, first, last, u, tHat1, tHat2);
29553
+ let { error, split } = maxError(pts, first, last, bez, u);
29554
+ if (error < errorSq) {
29555
+ out.push({
29556
+ bez,
29557
+ first,
29558
+ last,
29559
+ u
29560
+ });
29561
+ return;
29562
+ }
29563
+ if (error < errorSq * 4) for (let i = 0; i < 4; i++) {
29564
+ const prime = u.map((v, k) => {
29565
+ const p = newtonRaphson(bez, pts[first + k], v);
29566
+ return Number.isFinite(p) ? Math.min(Math.max(p, 0), 1) : v;
29567
+ });
29568
+ bez = generateBezier(pts, first, last, prime, tHat1, tHat2);
29569
+ ({error, split} = maxError(pts, first, last, bez, prime));
29570
+ u = prime;
29571
+ if (error < errorSq) {
29572
+ out.push({
29573
+ bez,
29574
+ first,
29575
+ last,
29576
+ u
29577
+ });
29578
+ return;
29579
+ }
29580
+ }
29581
+ const center = windowTangent(pts, split, first, last, window, true, true);
29582
+ const back = scale(center, -1);
29583
+ fitCubic(pts, first, split, tHat1, back, errorSq, window, out);
29584
+ fitCubic(pts, split, last, center, tHat2, errorSq, window, out);
29585
+ }
29586
+ /**
29587
+ * Fits cubic Bézier segments to a polyline so that no input point is farther
29588
+ * than `tolerance` from the curve. Needs at least two points, none repeated
29589
+ * consecutively.
29590
+ */
29591
+ function fitCurve(points, tolerance) {
29592
+ if (points.length < 2) return [];
29593
+ const out = [];
29594
+ const last = points.length - 1;
29595
+ const window = tolerance * 3;
29596
+ fitCubic(points, 0, last, windowTangent(points, 0, 0, last, window, false, true), scale(windowTangent(points, last, 0, last, window, true, false), -1), tolerance * tolerance, window, out);
29597
+ return out;
29598
+ }
29599
+ //#endregion
29600
+ //#region src/actions/brush-tool/stages/finalize.ts
29601
+ /** Size of one screen pixel in canvas units at a zoom level. */
29602
+ const pixelSize = (zoom) => zoom > 0 && Number.isFinite(zoom) ? 1 / zoom : 1;
29603
+ /**
29604
+ * Tolerance applied when a stroke is finished, in canvas units. The legacy
29605
+ * value is the tool-level tolerance in canvas units; with the `screen` unit the
29606
+ * configured pixels are converted with the zoom in force when the stroke ends,
29607
+ * so the same setting gives the same on-screen fidelity at any zoom.
29608
+ */
29609
+ function resolveFinalizeTolerance(cfg, toolTolerance, zoom = 1) {
29610
+ const tolerance = cfg.tolerance ?? toolTolerance;
29611
+ return cfg.toleranceUnit === "screen" ? tolerance * pixelSize(zoom) : tolerance;
29612
+ }
29613
+ /** Distance from `p` to the segment, and where along it the closest point is. */
29614
+ function toSegment(p, { a, b }) {
29615
+ const dx = b.x - a.x;
29616
+ const dy = b.y - a.y;
29617
+ const lengthSq = dx * dx + dy * dy;
29618
+ const t = lengthSq ? Math.min(1, Math.max(0, ((p.x - a.x) * dx + (p.y - a.y) * dy) / lengthSq)) : 0;
29619
+ return {
29620
+ distance: Math.hypot(p.x - (a.x + dx * t), p.y - (a.y + dy * t)),
29621
+ t
29622
+ };
29623
+ }
29624
+ /**
29625
+ * Douglas-Peucker simplification that also keeps pressure detail: a point is
29626
+ * kept when it is off the straight path by more than `tolerance`, or when its
29627
+ * pressure differs from the pressure interpolated along that path by more than
29628
+ * `tolerance / pressureWeight`.
29629
+ */
29630
+ function simplifyWithPressure(points, tolerance, pressureWeight) {
29631
+ if (points.length <= 2) return points;
29632
+ const keep = new Uint8Array(points.length);
29633
+ keep[0] = keep[points.length - 1] = 1;
29634
+ const stack = [[0, points.length - 1]];
29635
+ while (stack.length > 0) {
29636
+ const [first, last] = stack.pop();
29637
+ let worst = 0;
29638
+ let index = -1;
29639
+ for (let i = first + 1; i < last; i++) {
29640
+ const { distance, t } = toSegment(points[i], {
29641
+ a: points[first],
29642
+ b: points[last]
29643
+ });
29644
+ const expected = points[first].pressure + (points[last].pressure - points[first].pressure) * t;
29645
+ const error = Math.max(distance, Math.abs(points[i].pressure - expected) * pressureWeight);
29646
+ if (error > worst) {
29647
+ worst = error;
29648
+ index = i;
29649
+ }
29650
+ }
29651
+ if (worst > tolerance && index !== -1) {
29652
+ keep[index] = 1;
29653
+ stack.push([first, index], [index, last]);
29654
+ }
29655
+ }
29656
+ return points.filter((_, i) => keep[i] === 1);
29657
+ }
29658
+ /** Pressure at curve parameter `t` of a segment, interpolated between input points. */
29659
+ function pressureAt(seg, points, t) {
29660
+ let prev = seg.u[0];
29661
+ for (let k = 1; k < seg.u.length; k++) {
29662
+ const next = Math.max(seg.u[k], prev);
29663
+ if (t <= next || k === seg.u.length - 1) {
29664
+ const span = next - prev;
29665
+ const f = span > 0 ? Math.min(1, Math.max(0, (t - prev) / span)) : 0;
29666
+ const p0 = points[seg.first + k - 1].pressure;
29667
+ return p0 + (points[seg.first + k].pressure - p0) * f;
29668
+ }
29669
+ prev = next;
29670
+ }
29671
+ return points[seg.last].pressure;
29672
+ }
29673
+ /**
29674
+ * Fits a smooth curve through the stroke and samples it back to points, so the
29675
+ * saved format stays `{x, y, pressure}`. `tolerance` is the largest distance
29676
+ * between the curve and an input point; `spacing` is the distance between
29677
+ * sampled points. Both are in canvas units. The first and last points are kept
29678
+ * exactly.
29679
+ */
29680
+ function fitAndResample(points, tolerance, spacing) {
29681
+ if (points.length < 3 || !(tolerance > 0)) return points;
29682
+ const distinct = points.filter((p, i) => i === 0 || p.x !== points[i - 1].x || p.y !== points[i - 1].y);
29683
+ if (distinct.length < 3) return points;
29684
+ const segments = fitCurve(distinct, tolerance);
29685
+ if (segments.length === 0) return points;
29686
+ const out = [];
29687
+ for (const seg of segments) {
29688
+ let arc = 0;
29689
+ let prev = seg.bez[0];
29690
+ for (let k = 1; k <= 16; k++) {
29691
+ const q = bezierPoint(seg.bez, k / 16);
29692
+ arc += Math.hypot(q.x - prev.x, q.y - prev.y);
29693
+ prev = q;
29694
+ }
29695
+ const steps = Math.max(1, Math.ceil(arc / Math.max(spacing, 1e-6)));
29696
+ for (let k = 0; k < steps; k++) {
29697
+ const t = k / steps;
29698
+ const q = k === 0 ? seg.bez[0] : bezierPoint(seg.bez, t);
29699
+ out.push({
29700
+ x: q.x,
29701
+ y: q.y,
29702
+ pressure: pressureAt(seg, distinct, t)
29703
+ });
29704
+ }
29705
+ }
29706
+ const end = distinct[distinct.length - 1];
29707
+ out.push({
29708
+ x: end.x,
29709
+ y: end.y,
29710
+ pressure: end.pressure
29711
+ });
29712
+ return out;
29713
+ }
29714
+ /** Reduces a finished stroke's points as selected by the profile. */
29715
+ function finalizePoints(points, cfg, toolTolerance, zoom = 1) {
29716
+ const tolerance = resolveFinalizeTolerance(cfg, toolTolerance, zoom);
29717
+ switch (cfg.mode) {
29718
+ case "none": return points;
29719
+ case "dpPressure": return simplifyWithPressure(points, tolerance, cfg.toleranceUnit === "screen" ? cfg.pressureWeight * pixelSize(zoom) : cfg.pressureWeight);
29720
+ case "bezierFit": return fitAndResample(points, tolerance, cfg.resampleSpacingPx * pixelSize(zoom));
29721
+ default: return simplify(points, tolerance, true);
29722
+ }
29723
+ }
29724
+ //#endregion
29725
+ //#region src/actions/brush-tool/profiles.ts
29726
+ /**
29727
+ * Coarse platform of the running browser: `ipad`, `ios`, `mac`, `windows`,
29728
+ * `android`, `linux` or `unknown`. iPadOS reports a desktop Mac user agent, so
29729
+ * a Mac with multi-touch is an iPad.
29730
+ */
29731
+ function detectBrushPlatform(nav) {
29732
+ const source = nav === void 0 ? typeof navigator === "undefined" ? null : navigator : nav;
29733
+ if (!source) return "unknown";
29734
+ const ua = source.userAgent ?? "";
29735
+ const platform = source.platform ?? "";
29736
+ if (/iPad/i.test(ua)) return "ipad";
29737
+ if (/iPhone|iPod/i.test(ua)) return "ios";
29738
+ if (/Mac/i.test(platform) && (source.maxTouchPoints ?? 0) > 1) return "ipad";
29739
+ if (/Android/i.test(ua)) return "android";
29740
+ if (/Win/i.test(platform) || /Windows/i.test(ua)) return "windows";
29741
+ if (/Mac/i.test(platform) || /Macintosh/i.test(ua)) return "mac";
29742
+ if (/Linux|X11/i.test(platform) || /Linux|X11/i.test(ua)) return "linux";
29743
+ return "unknown";
29744
+ }
29745
+ const isProfileKey = (key) => BRUSH_INPUT_PROFILE_KEYS.includes(key);
29746
+ /**
29747
+ * Profile chosen from the pointer type and platform. A pen on an iPad is an
29748
+ * Apple Pencil; any other pen is a desktop pen. Unknown pointer types behave
29749
+ * like a mouse.
29750
+ */
29751
+ function automaticBrushProfileKey(info) {
29752
+ switch (info.pointerType) {
29753
+ case "pen": return info.platform === "ipad" ? "pen.applePencil" : "pen.desktop";
29754
+ case "touch": return "touch";
29755
+ default: return "mouse";
29756
+ }
29757
+ }
29758
+ /**
29759
+ * Resolves the input profile for a stroke. A forced profile wins, then the
29760
+ * application's resolver, then the automatic choice. A resolver that throws or
29761
+ * returns an unknown key is ignored.
29762
+ */
29763
+ function resolveBrushInputProfileKey(info, cfg) {
29764
+ if (isProfileKey(cfg.forceProfile)) return cfg.forceProfile;
29765
+ if (cfg.resolveProfile) try {
29766
+ const key = cfg.resolveProfile(info);
29767
+ if (isProfileKey(key)) return key;
29768
+ } catch {}
29769
+ return automaticBrushProfileKey(info);
29770
+ }
29771
+ //#endregion
29772
+ //#region src/actions/brush-tool/tunables/descriptors.ts
29773
+ const profile = (key, spec) => ({
29774
+ key,
29775
+ scope: "profile",
29776
+ path: key.split("."),
29777
+ ...spec
29778
+ });
29779
+ const look = (key, spec) => ({
29780
+ key,
29781
+ scope: "look",
29782
+ path: key.split("."),
29783
+ ...spec
29784
+ });
29785
+ /** Every setting accepted by an input profile. */
29786
+ const BRUSH_PROFILE_TUNABLES = [
29787
+ profile("capture.source", {
29788
+ stage: "capture",
29789
+ group: "Capture",
29790
+ kind: "capture",
29791
+ type: "enum",
29792
+ default: "legacy",
29793
+ options: ["legacy", "coalesced"],
29794
+ help: "legacy keeps one position per event; coalesced keeps every batched pen sample with its own position."
29795
+ }),
29796
+ profile("capture.clock", {
29797
+ stage: "capture",
29798
+ group: "Capture",
29799
+ kind: "capture",
29800
+ type: "enum",
29801
+ default: "now",
29802
+ options: ["now", "event"],
29803
+ help: "Time base of time-dependent filters: processing time or the time reported by each sample."
29804
+ }),
29805
+ profile("capture.minMovePx", {
29806
+ stage: "capture",
29807
+ group: "Capture",
29808
+ kind: "capture",
29809
+ type: "number",
29810
+ default: 0,
29811
+ min: 0,
29812
+ max: 3,
29813
+ step: .1,
29814
+ unit: "px",
29815
+ help: "Samples closer than this to the last recorded one are skipped."
29816
+ }),
29817
+ profile("capture.predicted", {
29818
+ stage: "capture",
29819
+ group: "Capture",
29820
+ kind: "capture",
29821
+ type: "enum",
29822
+ default: "tail",
29823
+ options: ["off", "tail"],
29824
+ help: "Draw the browser-predicted tail ahead of the pen to hide latency."
29825
+ }),
29826
+ profile("capture.event", {
29827
+ stage: "capture",
29828
+ group: "Capture",
29829
+ kind: "capture",
29830
+ type: "enum",
29831
+ default: "pointermove",
29832
+ options: ["pointermove", "pointerrawupdate"],
29833
+ help: "Event that delivers samples. pointerrawupdate lowers latency where supported.",
29834
+ advanced: true
29835
+ }),
29836
+ profile("pressure.zero", {
29837
+ stage: "pressure",
29838
+ group: "Pressure",
29839
+ kind: "capture",
29840
+ type: "enum",
29841
+ default: "legacy",
29842
+ options: [
29843
+ "legacy",
29844
+ "keep",
29845
+ "holdLast"
29846
+ ],
29847
+ help: "How a pen pressure of 0 is treated: legacy replaces it with 0.5, keep records it, holdLast repeats the last non-zero value."
29848
+ }),
29849
+ profile("pressure.filter", {
29850
+ stage: "pressure",
29851
+ group: "Pressure",
29852
+ kind: "capture",
29853
+ type: "enum",
29854
+ default: "legacy",
29855
+ options: [
29856
+ "legacy",
29857
+ "timeEma",
29858
+ "oneEuro",
29859
+ "none"
29860
+ ],
29861
+ help: "Pressure smoothing: the legacy velocity-adaptive filter, a time-based one, the One Euro filter, or none."
29862
+ }),
29863
+ profile("pressure.timeConstantMs", {
29864
+ stage: "pressure",
29865
+ group: "Pressure",
29866
+ kind: "capture",
29867
+ type: "number",
29868
+ default: 40,
29869
+ min: 1,
29870
+ max: 500,
29871
+ step: 1,
29872
+ unit: "ms",
29873
+ help: "Time constant of the timeEma filter; larger is smoother and slower."
29874
+ }),
29875
+ profile("pressure.oneEuro.minCutoff", {
29876
+ stage: "pressure",
29877
+ group: "Pressure",
29878
+ kind: "capture",
29879
+ type: "number",
29880
+ default: 1,
29881
+ min: .01,
29882
+ max: 10,
29883
+ step: .01,
29884
+ unit: "Hz",
29885
+ help: "One Euro minimum cutoff: lower removes more jitter at slow speed.",
29886
+ advanced: true
29887
+ }),
29888
+ profile("pressure.oneEuro.beta", {
29889
+ stage: "pressure",
29890
+ group: "Pressure",
29891
+ kind: "capture",
29892
+ type: "number",
29893
+ default: .01,
29894
+ min: 0,
29895
+ max: 1,
29896
+ step: .001,
29897
+ help: "One Euro speed coefficient: higher removes more lag at high speed.",
29898
+ advanced: true
29899
+ }),
29900
+ profile("pressure.floor", {
29901
+ stage: "pressure",
29902
+ group: "Pressure",
29903
+ kind: "capture",
29904
+ type: "number",
29905
+ default: .15,
29906
+ min: 0,
29907
+ max: .5,
29908
+ step: .01,
29909
+ unit: "fraction",
29910
+ help: "Lowest pressure that is recorded; prevents invisible strokes."
29911
+ }),
29912
+ profile("pressure.start", {
29913
+ stage: "pressure",
29914
+ group: "Pressure",
29915
+ kind: "capture",
29916
+ type: "enum",
29917
+ default: "backfill",
29918
+ options: [
29919
+ "backfill",
29920
+ "average",
29921
+ "none"
29922
+ ],
29923
+ help: "First point: backfill takes the next real sample, average takes the mean of the first movement readings, none keeps the contact reading."
29924
+ }),
29925
+ profile("pressure.startSamples", {
29926
+ stage: "pressure",
29927
+ group: "Pressure",
29928
+ kind: "capture",
29929
+ type: "number",
29930
+ default: 3,
29931
+ min: 1,
29932
+ max: 10,
29933
+ step: 1,
29934
+ integer: true,
29935
+ unit: "count",
29936
+ help: "Number of readings averaged by the average start policy.",
29937
+ advanced: true
29938
+ }),
29939
+ profile("pressure.end", {
29940
+ stage: "pressure",
29941
+ group: "Pressure",
29942
+ kind: "capture",
29943
+ type: "enum",
29944
+ default: "backfill",
29945
+ options: ["backfill", "none"],
29946
+ help: "Last point: backfill takes the second-to-last pressure, none keeps the lift-off reading."
29947
+ }),
29948
+ profile("stabilizer.type", {
29949
+ stage: "stabilizer",
29950
+ group: "Stabilizer",
29951
+ kind: "capture",
29952
+ type: "enum",
29953
+ default: "none",
29954
+ options: [
29955
+ "none",
29956
+ "oneEuro",
29957
+ "pulledString",
29958
+ "streamline"
29959
+ ],
29960
+ help: "Smooths the pen position while drawing."
29961
+ }),
29962
+ profile("stabilizer.minCutoff", {
29963
+ stage: "stabilizer",
29964
+ group: "Stabilizer",
29965
+ kind: "capture",
29966
+ type: "number",
29967
+ default: 3,
29968
+ min: .1,
29969
+ max: 20,
29970
+ step: .1,
29971
+ unit: "Hz",
29972
+ help: "One Euro minimum cutoff: lower removes more jitter at slow speed."
29973
+ }),
29974
+ profile("stabilizer.beta", {
29975
+ stage: "stabilizer",
29976
+ group: "Stabilizer",
29977
+ kind: "capture",
29978
+ type: "number",
29979
+ default: .01,
29980
+ min: 0,
29981
+ max: 1,
29982
+ step: .001,
29983
+ help: "One Euro speed coefficient: higher removes more lag at high speed."
29984
+ }),
29985
+ profile("stabilizer.radiusPx", {
29986
+ stage: "stabilizer",
29987
+ group: "Stabilizer",
29988
+ kind: "capture",
29989
+ type: "number",
29990
+ default: 4,
29991
+ min: 0,
29992
+ max: 40,
29993
+ step: .5,
29994
+ unit: "px",
29995
+ help: "Pulled string leash length: the pen must move this far before the line follows."
29996
+ }),
29997
+ profile("stabilizer.amount", {
29998
+ stage: "stabilizer",
29999
+ group: "Stabilizer",
30000
+ kind: "capture",
30001
+ type: "number",
30002
+ default: .3,
30003
+ min: 0,
30004
+ max: 1,
30005
+ step: .01,
30006
+ unit: "fraction",
30007
+ help: "Streamline strength: 0 follows the pen exactly, 1 is the strongest smoothing."
30008
+ }),
30009
+ profile("stabilizer.zoomAware", {
30010
+ stage: "stabilizer",
30011
+ group: "Stabilizer",
30012
+ kind: "capture",
30013
+ type: "boolean",
30014
+ default: false,
30015
+ help: "Interpret the distances in screen pixels, so the effect on screen is the same at every zoom level. Off: canvas units."
30016
+ }),
30017
+ profile("stabilizer.catchUpOnEnd", {
30018
+ stage: "stabilizer",
30019
+ group: "Stabilizer",
30020
+ kind: "capture",
30021
+ type: "boolean",
30022
+ default: true,
30023
+ help: "Complete the stroke at the position where the pen was lifted."
30024
+ }),
30025
+ profile("finalize.mode", {
30026
+ stage: "finalize",
30027
+ group: "Finish",
30028
+ kind: "capture",
30029
+ type: "enum",
30030
+ default: "dp",
30031
+ options: [
30032
+ "dp",
30033
+ "dpPressure",
30034
+ "bezierFit",
30035
+ "none"
30036
+ ],
30037
+ help: "How points are reduced when the stroke ends: simplification, simplification keeping pressure detail, curve fitting, or nothing."
30038
+ }),
30039
+ profile("finalize.tolerance", {
30040
+ stage: "finalize",
30041
+ group: "Finish",
30042
+ kind: "capture",
30043
+ type: "number",
30044
+ default: null,
30045
+ nullable: true,
30046
+ min: 0,
30047
+ max: 20,
30048
+ step: .05,
30049
+ help: "Tolerance of the finishing step. Empty uses the tool-level tolerance."
30050
+ }),
30051
+ profile("finalize.toleranceUnit", {
30052
+ stage: "finalize",
30053
+ group: "Finish",
30054
+ kind: "capture",
30055
+ type: "enum",
30056
+ default: "canvas",
30057
+ options: ["canvas", "screen"],
30058
+ help: "canvas: tolerance in canvas units. screen: in pixels, converted with the zoom when the stroke ends."
30059
+ }),
30060
+ profile("finalize.pressureWeight", {
30061
+ stage: "finalize",
30062
+ group: "Finish",
30063
+ kind: "capture",
30064
+ type: "number",
30065
+ default: 20,
30066
+ min: 0,
30067
+ max: 200,
30068
+ step: 1,
30069
+ help: "Distance units per pressure unit when simplification keeps pressure detail.",
30070
+ advanced: true
30071
+ }),
30072
+ profile("finalize.resampleSpacingPx", {
30073
+ stage: "finalize",
30074
+ group: "Finish",
30075
+ kind: "capture",
30076
+ type: "number",
30077
+ default: 2,
30078
+ min: .5,
30079
+ max: 20,
30080
+ step: .5,
30081
+ unit: "px",
30082
+ help: "Spacing of the points a fitted curve is resampled to.",
30083
+ advanced: true
30084
+ }),
30085
+ profile("touchGuard.waitMs", {
30086
+ stage: "touch",
30087
+ group: "Finger",
30088
+ kind: "capture",
30089
+ type: "number",
30090
+ default: 0,
30091
+ min: 0,
30092
+ max: 500,
30093
+ step: 10,
30094
+ unit: "ms",
30095
+ help: "Wait before a finger stroke is committed, so a second finger can cancel it."
30096
+ }),
30097
+ profile("touchGuard.movePx", {
30098
+ stage: "touch",
30099
+ group: "Finger",
30100
+ kind: "capture",
30101
+ type: "number",
30102
+ default: 0,
30103
+ min: 0,
30104
+ max: 40,
30105
+ step: 1,
30106
+ unit: "px",
30107
+ help: "Movement that commits the stroke before the wait ends."
30108
+ }),
30109
+ profile("touchGuard.cancelOnSecondTouch", {
30110
+ stage: "touch",
30111
+ group: "Finger",
30112
+ kind: "capture",
30113
+ type: "boolean",
30114
+ default: false,
30115
+ help: "Cancel the stroke when a second finger lands during the wait."
30116
+ }),
30117
+ profile("touchGuard.ignoreAfterPen", {
30118
+ stage: "touch",
30119
+ group: "Finger",
30120
+ kind: "capture",
30121
+ type: "boolean",
30122
+ default: false,
30123
+ help: "Finger input does not draw once a pen has been used."
30124
+ })
30125
+ ];
30126
+ /** Every setting accepted by a stroke look. */
30127
+ const BRUSH_LOOK_TUNABLES = [
30128
+ look("outline", {
30129
+ stage: "outline",
30130
+ group: "Outline",
30131
+ kind: "draw",
30132
+ type: "enum",
30133
+ default: "legacy",
30134
+ options: [
30135
+ "legacy",
30136
+ "round",
30137
+ "freehand"
30138
+ ],
30139
+ help: "Shape of the stroke: legacy ribbon, round (discs and segments, no spikes) or freehand."
30140
+ }),
30141
+ look("curve", {
30142
+ stage: "curve",
30143
+ group: "Curve",
30144
+ kind: "draw",
30145
+ type: "enum",
30146
+ default: "uniform",
30147
+ options: [
30148
+ "uniform",
30149
+ "centripetal",
30150
+ "none"
30151
+ ],
30152
+ help: "Curve through the points. centripetal does not overshoot when points are unevenly spaced."
30153
+ }),
30154
+ look("pressureInterp", {
30155
+ stage: "curve",
30156
+ group: "Curve",
30157
+ kind: "draw",
30158
+ type: "enum",
30159
+ default: "catmullRom",
30160
+ options: ["catmullRom", "linear"],
30161
+ help: "How pressure is interpolated between points. linear never bulges."
30162
+ }),
30163
+ look("zoomAware", {
30164
+ stage: "detail",
30165
+ group: "Detail",
30166
+ kind: "draw",
30167
+ type: "boolean",
30168
+ default: false,
30169
+ help: "Choose spacing and subdivision in screen pixels so smoothness does not depend on zoom."
30170
+ }),
30171
+ look("spacingPx", {
30172
+ stage: "detail",
30173
+ group: "Detail",
30174
+ kind: "draw",
30175
+ type: "number",
30176
+ default: 2,
30177
+ min: .5,
30178
+ max: 10,
30179
+ step: .5,
30180
+ unit: "px",
30181
+ help: "Minimum spacing between control points.",
30182
+ advanced: true
30183
+ }),
30184
+ look("edgePx", {
30185
+ stage: "detail",
30186
+ group: "Detail",
30187
+ kind: "draw",
30188
+ type: "number",
30189
+ default: 1,
30190
+ min: .25,
30191
+ max: 5,
30192
+ step: .25,
30193
+ unit: "px",
30194
+ help: "Detail of the curve. The centripetal curve keeps every edge within a tenth of this of the true curve; the uniform curve uses it as the target length of an edge.",
30195
+ advanced: true
30196
+ }),
30197
+ look("caps", {
30198
+ stage: "ends",
30199
+ group: "Ends",
30200
+ kind: "draw",
30201
+ type: "enum",
30202
+ default: "separate",
30203
+ options: ["separate", "merged"],
30204
+ help: "merged draws the round ends inside the same fill, so translucent colours stay uniform."
30205
+ }),
30206
+ look("width.min", {
30207
+ stage: "width",
30208
+ group: "Width",
30209
+ kind: "draw",
30210
+ type: "number",
30211
+ default: 0,
30212
+ min: 0,
30213
+ max: 1,
30214
+ step: .01,
30215
+ unit: "fraction",
30216
+ help: "Width at pressure 0, as a fraction of the stroke width."
30217
+ }),
30218
+ look("width.max", {
30219
+ stage: "width",
30220
+ group: "Width",
30221
+ kind: "draw",
30222
+ type: "number",
30223
+ default: 1,
30224
+ min: 0,
30225
+ max: 1,
30226
+ step: .01,
30227
+ unit: "fraction",
30228
+ help: "Width at pressure 1, as a fraction of the stroke width."
30229
+ }),
30230
+ look("width.gamma", {
30231
+ stage: "width",
30232
+ group: "Width",
30233
+ kind: "draw",
30234
+ type: "number",
30235
+ default: 1,
30236
+ min: .2,
30237
+ max: 3,
30238
+ step: .05,
30239
+ help: "Response curve: below 1 reacts faster to light pressure, above 1 needs a firmer press."
30240
+ }),
30241
+ look("width.taperStart", {
30242
+ stage: "width",
30243
+ group: "Width",
30244
+ kind: "draw",
30245
+ type: "number",
30246
+ default: 0,
30247
+ min: 0,
30248
+ max: 200,
30249
+ step: 1,
30250
+ unit: "px",
30251
+ help: "Distance over which the start narrows; 0 for none."
30252
+ }),
30253
+ look("width.taperEnd", {
30254
+ stage: "width",
30255
+ group: "Width",
30256
+ kind: "draw",
30257
+ type: "number",
30258
+ default: 0,
30259
+ min: 0,
30260
+ max: 200,
30261
+ step: 1,
30262
+ unit: "px",
30263
+ help: "Distance over which the end narrows; 0 for none."
30264
+ })
30265
+ ];
30266
+ /** Every tunable setting. */
30267
+ const BRUSH_TUNABLES = [...BRUSH_PROFILE_TUNABLES, ...BRUSH_LOOK_TUNABLES];
30268
+ /** Finds a tunable by scope and key. */
30269
+ function getBrushTunable(scope, key) {
30270
+ return BRUSH_TUNABLES.find((t) => t.scope === scope && t.key === key);
30271
+ }
30272
+ //#endregion
30273
+ //#region src/actions/brush-tool/tunables/validate.ts
30274
+ /**
30275
+ * Checks a value against a descriptor. Returns a message when the value is
30276
+ * invalid, or `null` when it is accepted.
30277
+ */
30278
+ function validateBrushTunableValue(tunable, value) {
30279
+ const name = `${tunable.scope} setting "${tunable.key}"`;
30280
+ if (value === null || value === void 0) return tunable.nullable ? null : `${name} cannot be empty`;
30281
+ switch (tunable.type) {
30282
+ case "boolean": return typeof value === "boolean" ? null : `${name} must be true or false`;
30283
+ case "enum": return typeof value === "string" && tunable.options?.includes(value) ? null : `${name} must be one of: ${tunable.options?.join(", ")}`;
30284
+ case "number":
30285
+ if (typeof value !== "number" || !Number.isFinite(value)) return `${name} must be a finite number`;
30286
+ if (tunable.integer && !Number.isInteger(value)) return `${name} must be a whole number`;
30287
+ if (tunable.min !== void 0 && value < tunable.min) return `${name} must be at least ${tunable.min}`;
30288
+ if (tunable.max !== void 0 && value > tunable.max) return `${name} must be at most ${tunable.max}`;
30289
+ return null;
30290
+ }
30291
+ }
30292
+ function collectLeaves(obj, prefix = []) {
30293
+ return Object.entries(obj).flatMap(([k, v]) => v !== null && typeof v === "object" && !Array.isArray(v) ? collectLeaves(v, [...prefix, k]) : [{
30294
+ key: [...prefix, k].join("."),
30295
+ value: v
30296
+ }]);
30297
+ }
30298
+ /**
30299
+ * Validates a partial profile or look against the descriptors. Every leaf must
30300
+ * name a known setting and hold an accepted value. Returns the messages of all
30301
+ * problems found; an empty list means the patch is valid.
30302
+ */
30303
+ function validateBrushTunablePatch(scope, patch) {
30304
+ if (patch === null || typeof patch !== "object" || Array.isArray(patch)) return [`A ${scope} change must be an object`];
30305
+ const errors = [];
30306
+ for (const { key, value } of collectLeaves(patch)) {
30307
+ const tunable = getBrushTunable(scope, key);
30308
+ if (!tunable) {
30309
+ errors.push(`Unknown ${scope} setting "${key}"`);
30310
+ continue;
30311
+ }
30312
+ const error = validateBrushTunableValue(tunable, value);
30313
+ if (error) errors.push(error);
30314
+ }
30315
+ return errors;
30316
+ }
30317
+ //#endregion
30318
+ //#region src/actions/brush-tool/tunables/merge.ts
30319
+ const isPlain = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
30320
+ /** Deep clone of plain data. */
30321
+ function cloneData(value) {
30322
+ if (Array.isArray(value)) return value.map(cloneData);
30323
+ if (isPlain(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, cloneData(v)]));
30324
+ return value;
30325
+ }
30326
+ /** Returns a new object: `base` with every defined value of `patch` merged in. */
30327
+ function mergeData(base, patch) {
30328
+ const result = cloneData(base);
30329
+ if (!isPlain(patch)) return result;
30330
+ for (const [k, v] of Object.entries(patch)) {
30331
+ if (v === void 0) continue;
30332
+ result[k] = isPlain(v) && isPlain(result[k]) ? mergeData(result[k], v) : cloneData(v);
30333
+ }
30334
+ return result;
30335
+ }
30336
+ /** Freezes plain data recursively. */
30337
+ function deepFreeze(value) {
30338
+ if (isPlain(value) || Array.isArray(value)) {
30339
+ for (const v of Object.values(value)) deepFreeze(v);
30340
+ Object.freeze(value);
30341
+ }
30342
+ return value;
30343
+ }
30344
+ //#endregion
30345
+ //#region src/actions/brush-tool/tunables/presets.ts
30346
+ const FIXES = {
30347
+ capture: {
30348
+ source: "coalesced",
30349
+ clock: "event"
30350
+ },
30351
+ pressure: { zero: "keep" }
30352
+ };
30353
+ const withFixes = (patch) => mergeData(FIXES, patch);
30354
+ const PEN_SMOOTH = withFixes({
30355
+ pressure: {
30356
+ filter: "oneEuro",
30357
+ oneEuro: {
30358
+ minCutoff: 1.5,
30359
+ beta: .02
30360
+ },
30361
+ start: "average"
30362
+ },
30363
+ stabilizer: {
30364
+ type: "oneEuro",
30365
+ minCutoff: 6,
30366
+ beta: .05,
30367
+ zoomAware: true
30368
+ },
30369
+ finalize: {
30370
+ mode: "bezierFit",
30371
+ toleranceUnit: "screen",
30372
+ tolerance: 2,
30373
+ resampleSpacingPx: 8
30374
+ }
30375
+ });
30376
+ const PEN_ILLUSTRATOR = withFixes({
30377
+ pressure: {
30378
+ filter: "timeEma",
30379
+ timeConstantMs: 30,
30380
+ start: "average"
30381
+ },
30382
+ stabilizer: {
30383
+ type: "streamline",
30384
+ amount: .25,
30385
+ zoomAware: true
30386
+ },
30387
+ finalize: {
30388
+ mode: "bezierFit",
30389
+ toleranceUnit: "screen",
30390
+ tolerance: 2,
30391
+ resampleSpacingPx: 8
30392
+ }
30393
+ });
30394
+ const TOUCH_GUARD = withFixes({ touchGuard: {
30395
+ waitMs: 100,
30396
+ movePx: 6,
30397
+ cancelOnSecondTouch: true
30398
+ } });
30399
+ const legacy = () => ({
30400
+ id: "legacy",
30401
+ label: "Legacy",
30402
+ description: "Behaviour of earlier releases, point for point.",
30403
+ patch: {}
30404
+ });
30405
+ const fixed = () => ({
30406
+ id: "fixed",
30407
+ label: "Fixed",
30408
+ description: "Keeps every pen sample, uses event time, keeps zero pressure.",
30409
+ patch: FIXES
30410
+ });
30411
+ const penPresets = () => [
30412
+ legacy(),
30413
+ fixed(),
30414
+ {
30415
+ id: "smooth",
30416
+ label: "Smooth",
30417
+ description: "Fixed, plus One Euro smoothing of pressure and position and a Bézier-fitted finish.",
30418
+ patch: PEN_SMOOTH
30419
+ },
30420
+ {
30421
+ id: "illustrator",
30422
+ label: "Illustrator-like",
30423
+ description: "Fixed, plus streamline stabilizing and a Bézier-fitted finish in screen pixels.",
30424
+ patch: PEN_ILLUSTRATOR
30425
+ }
30426
+ ];
30427
+ const RAW_PROFILE_PRESETS = {
30428
+ mouse: [
30429
+ legacy(),
30430
+ fixed(),
30431
+ {
30432
+ id: "stabilized",
30433
+ label: "Stabilized",
30434
+ description: "Fixed, plus One Euro position smoothing that follows the zoom and a Bézier-fitted finish.",
30435
+ patch: withFixes({
30436
+ stabilizer: {
30437
+ type: "oneEuro",
30438
+ minCutoff: 2,
30439
+ beta: .01,
30440
+ zoomAware: true
30441
+ },
30442
+ finalize: {
30443
+ mode: "bezierFit",
30444
+ toleranceUnit: "screen",
30445
+ tolerance: 2,
30446
+ resampleSpacingPx: 8
30447
+ }
30448
+ })
30449
+ },
30450
+ {
30451
+ id: "pulledString",
30452
+ label: "Pulled string",
30453
+ description: "Fixed, plus a pulled-string stabilizer.",
30454
+ patch: withFixes({ stabilizer: {
30455
+ type: "pulledString",
30456
+ radiusPx: 6,
30457
+ zoomAware: true
30458
+ } })
30459
+ }
30460
+ ],
30461
+ touch: [
30462
+ legacy(),
30463
+ fixed(),
30464
+ {
30465
+ id: "guarded",
30466
+ label: "Guarded",
30467
+ description: "Fixed, plus a short wait that a second finger can cancel.",
30468
+ patch: TOUCH_GUARD
30469
+ },
30470
+ {
30471
+ id: "smooth",
30472
+ label: "Smooth",
30473
+ description: "Guarded, plus One Euro position smoothing and a Bézier-fitted finish.",
30474
+ patch: mergeData(TOUCH_GUARD, {
30475
+ stabilizer: {
30476
+ type: "oneEuro",
30477
+ minCutoff: 3,
30478
+ beta: .02,
30479
+ zoomAware: true
30480
+ },
30481
+ finalize: {
30482
+ mode: "bezierFit",
30483
+ toleranceUnit: "screen",
30484
+ tolerance: 2,
30485
+ resampleSpacingPx: 8
30486
+ }
30487
+ })
30488
+ }
30489
+ ],
30490
+ "pen.applePencil": penPresets(),
30491
+ "pen.desktop": penPresets()
30492
+ };
30493
+ const WIDTH_CURVE = { width: {
30494
+ min: .2,
30495
+ gamma: .8
30496
+ } };
30497
+ const ROUND = {
30498
+ ...WIDTH_CURVE,
30499
+ outline: "round",
30500
+ caps: "merged",
30501
+ curve: "centripetal",
30502
+ pressureInterp: "linear",
30503
+ zoomAware: true
30504
+ };
30505
+ const RAW_LOOK_PRESETS = [
30506
+ {
30507
+ id: "legacy",
30508
+ label: "Legacy",
30509
+ description: "No look is stored: strokes are drawn as in earlier releases.",
30510
+ patch: null
30511
+ },
30512
+ {
30513
+ id: "widthCurve",
30514
+ label: "Width curve",
30515
+ description: "Legacy outline with a minimum width and a pressure curve.",
30516
+ patch: WIDTH_CURVE
30517
+ },
30518
+ {
30519
+ id: "round",
30520
+ label: "Round",
30521
+ description: "Round outline: no spikes at turns, uniform translucent colour.",
30522
+ patch: ROUND
30523
+ },
30524
+ {
30525
+ id: "freehand",
30526
+ label: "Freehand",
30527
+ description: "Freehand outline.",
30528
+ patch: {
30529
+ ...WIDTH_CURVE,
30530
+ outline: "freehand",
30531
+ caps: "merged",
30532
+ zoomAware: true
30533
+ }
30534
+ },
30535
+ {
30536
+ id: "illustrator",
30537
+ label: "Illustrator-like",
30538
+ description: "Round outline with a Size ± Variation style width range.",
30539
+ patch: {
30540
+ ...ROUND,
30541
+ width: {
30542
+ min: .4,
30543
+ max: 1,
30544
+ gamma: 1
30545
+ }
30546
+ }
30547
+ }
30548
+ ];
30549
+ const RAW_SCENARIOS = [
30550
+ {
30551
+ id: "A",
30552
+ label: "A: legacy",
30553
+ description: "Today's behaviour, identical point for point.",
30554
+ profiles: {
30555
+ mouse: "legacy",
30556
+ touch: "legacy",
30557
+ "pen.applePencil": "legacy",
30558
+ "pen.desktop": "legacy"
30559
+ },
30560
+ look: "legacy"
30561
+ },
30562
+ {
30563
+ id: "B",
30564
+ label: "B: fixes",
30565
+ description: "Every pen sample, event time and zero pressure kept.",
30566
+ profiles: {
30567
+ mouse: "fixed",
30568
+ touch: "fixed",
30569
+ "pen.applePencil": "fixed",
30570
+ "pen.desktop": "fixed"
30571
+ },
30572
+ look: "legacy"
30573
+ },
30574
+ {
30575
+ id: "C",
30576
+ label: "C: smooth",
30577
+ description: "B plus smoothing and a pressure curve.",
30578
+ profiles: {
30579
+ mouse: "stabilized",
30580
+ touch: "smooth",
30581
+ "pen.applePencil": "smooth",
30582
+ "pen.desktop": "smooth"
30583
+ },
30584
+ look: "widthCurve"
30585
+ },
30586
+ {
30587
+ id: "D",
30588
+ label: "D: round",
30589
+ description: "C plus the round outline.",
30590
+ profiles: {
30591
+ mouse: "stabilized",
30592
+ touch: "smooth",
30593
+ "pen.applePencil": "smooth",
30594
+ "pen.desktop": "smooth"
30595
+ },
30596
+ look: "round"
30597
+ },
30598
+ {
30599
+ id: "E",
30600
+ label: "E: freehand",
30601
+ description: "B plus the freehand outline.",
30602
+ profiles: {
30603
+ mouse: "fixed",
30604
+ touch: "fixed",
30605
+ "pen.applePencil": "fixed",
30606
+ "pen.desktop": "fixed"
30607
+ },
30608
+ look: "freehand"
30609
+ },
30610
+ {
30611
+ id: "F",
30612
+ label: "F: Illustrator-like",
30613
+ description: "Bézier-fitted finish, streamline stabilizing and a Size ± Variation width.",
30614
+ profiles: {
30615
+ mouse: "stabilized",
30616
+ touch: "smooth",
30617
+ "pen.applePencil": "illustrator",
30618
+ "pen.desktop": "illustrator"
30619
+ },
30620
+ look: "illustrator"
30621
+ }
30622
+ ];
30623
+ /** Factory profile presets per profile. Read-only. */
30624
+ const BRUSH_PROFILE_PRESETS = deepFreeze(RAW_PROFILE_PRESETS);
30625
+ /** Factory look presets. Read-only. */
30626
+ const BRUSH_LOOK_PRESETS = deepFreeze(RAW_LOOK_PRESETS);
30627
+ /** Factory scenarios. Read-only. */
30628
+ const BRUSH_SCENARIOS = deepFreeze(RAW_SCENARIOS);
30629
+ /** Full profile configuration of a preset: the legacy profile with its patch. */
30630
+ function resolveBrushProfilePatch(patch) {
30631
+ return mergeData(BRUSH_LEGACY_INPUT_PROFILE, patch);
30632
+ }
30633
+ /** Full look of a preset, or `null` when the preset stores no look. */
30634
+ function resolveBrushLookPatch(patch) {
30635
+ return patch === null ? null : mergeData(WEAVE_STROKE_LEGACY_LOOK, patch);
30636
+ }
30637
+ function getBrushScenario(id) {
30638
+ return BRUSH_SCENARIOS.find((s) => s.id === id);
30639
+ }
30640
+ /**
30641
+ * Registry of profile and look presets: the read-only factory presets plus
30642
+ * custom ones. Factory presets cannot be changed or removed; a copy under a
30643
+ * new name can be made and edited. Custom presets live in memory; the
30644
+ * application decides whether to keep them.
30645
+ */
30646
+ var WeaveBrushPresetRegistry = class WeaveBrushPresetRegistry {
30647
+ customProfiles = /* @__PURE__ */ new Map();
30648
+ customLooks = /* @__PURE__ */ new Map();
30649
+ static profileKey(key, id) {
30650
+ return `${key}/${id}`;
30651
+ }
30652
+ listProfilePresets(key) {
30653
+ const custom = [...this.customProfiles.entries()].filter(([k]) => k.startsWith(`${key}/`)).map(([, v]) => v);
30654
+ return [...BRUSH_PROFILE_PRESETS[key], ...custom];
30655
+ }
30656
+ getProfilePreset(key, id) {
30657
+ return this.listProfilePresets(key).find((p) => p.id === id);
30658
+ }
30659
+ isFactoryProfilePreset(key, id) {
30660
+ return BRUSH_PROFILE_PRESETS[key].some((p) => p.id === id);
30661
+ }
30662
+ /** Changes a custom profile preset; a factory preset is rejected. */
30663
+ setProfilePreset(key, id, patch) {
30664
+ if (this.isFactoryProfilePreset(key, id)) return {
30665
+ ok: false,
30666
+ error: `"${id}" is a factory preset and cannot be changed; copy it first`
30667
+ };
30668
+ const existing = this.customProfiles.get(WeaveBrushPresetRegistry.profileKey(key, id));
30669
+ if (!existing) return {
30670
+ ok: false,
30671
+ error: `Unknown preset "${id}"`
30672
+ };
30673
+ this.customProfiles.set(WeaveBrushPresetRegistry.profileKey(key, id), {
30674
+ ...existing,
30675
+ patch: mergeData(existing.patch, patch)
30676
+ });
30677
+ return { ok: true };
30678
+ }
30679
+ /** Copies a preset under a new id. */
30680
+ copyProfilePreset(key, fromId, newId, label = newId) {
30681
+ const from = this.getProfilePreset(key, fromId);
30682
+ if (!from) return {
30683
+ ok: false,
30684
+ error: `Unknown preset "${fromId}"`
30685
+ };
30686
+ if (this.getProfilePreset(key, newId)) return {
30687
+ ok: false,
30688
+ error: `A preset "${newId}" already exists`
30689
+ };
30690
+ this.customProfiles.set(WeaveBrushPresetRegistry.profileKey(key, newId), {
30691
+ id: newId,
30692
+ label,
30693
+ description: `Copy of ${from.label}`,
30694
+ patch: mergeData(from.patch, {})
30695
+ });
30696
+ return { ok: true };
30697
+ }
30698
+ removeProfilePreset(key, id) {
30699
+ if (this.isFactoryProfilePreset(key, id)) return {
30700
+ ok: false,
30701
+ error: `"${id}" is a factory preset and cannot be removed`
30702
+ };
30703
+ return this.customProfiles.delete(WeaveBrushPresetRegistry.profileKey(key, id)) ? { ok: true } : {
30704
+ ok: false,
30705
+ error: `Unknown preset "${id}"`
30706
+ };
30707
+ }
30708
+ listLookPresets() {
30709
+ return [...BRUSH_LOOK_PRESETS, ...this.customLooks.values()];
30710
+ }
30711
+ getLookPreset(id) {
30712
+ return this.listLookPresets().find((p) => p.id === id);
30713
+ }
30714
+ isFactoryLookPreset(id) {
30715
+ return BRUSH_LOOK_PRESETS.some((p) => p.id === id);
30716
+ }
30717
+ /** Changes a custom look preset; a factory preset is rejected. */
30718
+ setLookPreset(id, patch) {
30719
+ if (this.isFactoryLookPreset(id)) return {
30720
+ ok: false,
30721
+ error: `"${id}" is a factory preset and cannot be changed; copy it first`
30722
+ };
30723
+ const existing = this.customLooks.get(id);
30724
+ if (!existing) return {
30725
+ ok: false,
30726
+ error: `Unknown preset "${id}"`
30727
+ };
30728
+ this.customLooks.set(id, {
30729
+ ...existing,
30730
+ patch: mergeData(existing.patch ?? {}, patch)
30731
+ });
30732
+ return { ok: true };
30733
+ }
30734
+ copyLookPreset(fromId, newId, label = newId) {
30735
+ const from = this.getLookPreset(fromId);
30736
+ if (!from) return {
30737
+ ok: false,
30738
+ error: `Unknown preset "${fromId}"`
30739
+ };
30740
+ if (this.getLookPreset(newId)) return {
30741
+ ok: false,
30742
+ error: `A preset "${newId}" already exists`
30743
+ };
30744
+ this.customLooks.set(newId, {
30745
+ id: newId,
30746
+ label,
30747
+ description: `Copy of ${from.label}`,
30748
+ patch: from.patch === null ? null : mergeData(from.patch, {})
30749
+ });
30750
+ return { ok: true };
30751
+ }
30752
+ removeLookPreset(id) {
30753
+ if (this.isFactoryLookPreset(id)) return {
30754
+ ok: false,
30755
+ error: `"${id}" is a factory preset and cannot be removed`
30756
+ };
30757
+ return this.customLooks.delete(id) ? { ok: true } : {
30758
+ ok: false,
30759
+ error: `Unknown preset "${id}"`
30760
+ };
30761
+ }
30762
+ };
30763
+ //#endregion
30764
+ //#region src/actions/brush-tool/tunables/config-io.ts
30765
+ /** Version of the exported configuration document. */
30766
+ const BRUSH_CONFIG_DOCUMENT_VERSION = 1;
30767
+ const isObject$1 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
30768
+ /**
30769
+ * Reads and validates a configuration document, given as an object or as JSON
30770
+ * text. Nothing is applied: the result holds fully resolved values, or every
30771
+ * problem found.
30772
+ */
30773
+ function parseBrushConfigDocument(input) {
30774
+ let doc = input;
30775
+ if (typeof input === "string") try {
30776
+ doc = JSON.parse(input);
30777
+ } catch {
30778
+ return {
30779
+ ok: false,
30780
+ errors: ["The document is not valid JSON"]
30781
+ };
30782
+ }
30783
+ if (!isObject$1(doc)) return {
30784
+ ok: false,
30785
+ errors: ["The document must be an object"]
30786
+ };
30787
+ if (doc["version"] !== 1) return {
30788
+ ok: false,
30789
+ errors: [`Unsupported document version "${String(doc["version"])}"; expected 1`]
30790
+ };
30791
+ const errors = [];
30792
+ const profiles = {};
30793
+ if (doc["profiles"] !== void 0) {
30794
+ if (!isObject$1(doc["profiles"])) errors.push("\"profiles\" must be an object");
30795
+ else for (const [key, value] of Object.entries(doc["profiles"])) {
30796
+ if (!BRUSH_INPUT_PROFILE_KEYS.includes(key)) {
30797
+ errors.push(`Unknown profile "${key}"`);
30798
+ continue;
30799
+ }
30800
+ const problems = validateBrushTunablePatch("profile", value);
30801
+ if (problems.length > 0) errors.push(...problems.map((p) => `${key}: ${p}`));
30802
+ else profiles[key] = resolveBrushProfilePatch(value);
30803
+ }
30804
+ }
30805
+ let look;
30806
+ if (doc["look"] !== void 0) {
30807
+ if (doc["look"] === null) look = null;
30808
+ else if (!isObject$1(doc["look"])) errors.push("\"look\" must be an object or null");
30809
+ else {
30810
+ const { version, ...settings } = doc["look"];
30811
+ if (version !== WEAVE_STROKE_LEGACY_LOOK.version) errors.push(`Unsupported look version "${String(version)}"`);
30812
+ else {
30813
+ const problems = validateBrushTunablePatch("look", settings);
30814
+ if (problems.length > 0) errors.push(...problems.map((p) => `look: ${p}`));
30815
+ else look = mergeData(WEAVE_STROKE_LEGACY_LOOK, settings);
30816
+ }
30817
+ }
30818
+ }
30819
+ return errors.length > 0 ? {
30820
+ ok: false,
30821
+ errors
30822
+ } : {
30823
+ ok: true,
30824
+ profiles,
30825
+ look
30826
+ };
30827
+ }
30828
+ //#endregion
30829
+ //#region src/actions/brush-tool/brush-tool.ts
30830
+ var WeaveBrushToolAction = class extends WeaveAction {
30831
+ config;
30832
+ initialized = false;
30833
+ state;
30834
+ clickPoint;
30835
+ strokeId;
30836
+ isSpacePressed = false;
30837
+ isEraser;
30838
+ container;
30839
+ measureContainer;
30840
+ cancelAction;
30841
+ prevTouchAction;
30842
+ penActive = false;
30843
+ lastSmoothedPressure = .5;
30844
+ hasPressureSample = false;
30845
+ lastPointerPos = null;
30846
+ lastPointerTime = 0;
30847
+ predictedCount = 0;
30848
+ activeProfile;
30849
+ activeProfileKey = "mouse";
30850
+ look = null;
30851
+ captureState = createCaptureState();
30852
+ pendingTouch = null;
30853
+ /** Preset each profile currently holds: a preset id, `custom` or `imported`. */
30854
+ presetIds = {
30855
+ mouse: "legacy",
30856
+ touch: "legacy",
30857
+ "pen.applePencil": "legacy",
30858
+ "pen.desktop": "legacy"
30859
+ };
30860
+ /** Scenario applied last, until a profile is changed on its own. */
30861
+ scenarioId = null;
30862
+ /** Pointer that is drawing the stroke in progress. */
30863
+ strokePointerId = null;
30864
+ /** A pen has been used since the tool was activated. */
30865
+ penSeen = false;
30866
+ /** Last position the pen reported, before any stabilizing. */
30867
+ lastRawPoint = null;
30868
+ stabilizer;
30869
+ pressureStateView;
30870
+ onPropsChange = void 0;
30871
+ onInit = void 0;
30872
+ constructor(params) {
30873
+ super();
30874
+ this.config = mergeExceptArrays(BRUSH_TOOL_DEFAULT_CONFIG, params?.config ?? {});
30875
+ for (const key of Object.keys(params?.config?.input?.profiles ?? {})) this.presetIds[key] = "custom";
30876
+ this.initialize();
30877
+ }
30878
+ initialize() {
30879
+ this.initialized = false;
30880
+ this.state = BRUSH_TOOL_STATE.INACTIVE;
30881
+ this.strokeId = null;
30882
+ this.clickPoint = null;
30883
+ this.container = void 0;
30884
+ this.isEraser = false;
30885
+ this.measureContainer = void 0;
30886
+ this.props = this.initProps();
30887
+ this.isSpacePressed = false;
30888
+ this.setActiveProfile("mouse");
30889
+ }
30890
+ setActiveProfile(key) {
30891
+ this.activeProfileKey = key;
30892
+ this.activeProfile = this.config.input.profiles[key];
30893
+ this.stabilizer = createStabilizer(this.activeProfile.stabilizer);
30894
+ }
30895
+ /** Key of the profile used by the stroke in progress, or the last one. */
30896
+ getActiveProfileKey() {
30897
+ return this.activeProfileKey;
30898
+ }
30899
+ /** Preset a profile currently holds: a preset id, `custom` or `imported`. */
30900
+ getPresetId(key) {
30901
+ return this.presetIds[key];
30902
+ }
30903
+ /** Scenario applied last, or `null` once a profile was changed on its own. */
30904
+ getScenarioId() {
30905
+ return this.scenarioId;
30906
+ }
30907
+ /**
30908
+ * How a stroke was drawn, recorded on it only while the lab plugin is
30909
+ * active, so ordinary documents carry no such data.
30910
+ */
30911
+ getInputMeta() {
30912
+ const lab = this.instance.getPlugin(BRUSH_LAB_PLUGIN_NAME);
30913
+ if (!lab || lab.isEnabled?.() === false) return void 0;
30914
+ return {
30915
+ profile: this.activeProfileKey,
30916
+ preset: this.presetIds[this.activeProfileKey],
30917
+ ...this.scenarioId ? { scenario: this.scenarioId } : {}
30918
+ };
30919
+ }
30920
+ /** The lab plugin, when it is registered and on; it only listens. */
30921
+ getTraceSink() {
30922
+ const lab = this.instance.getPlugin(BRUSH_LAB_PLUGIN_NAME);
30923
+ if (!lab || lab.isEnabled?.() === false) return null;
30924
+ return typeof lab.onSample === "function" ? lab : null;
30925
+ }
30926
+ /** Current configuration of a profile (a copy). */
30927
+ getInputProfile(key) {
30928
+ return mergeExceptArrays(this.config.input.profiles[key], {});
30929
+ }
30930
+ /**
30931
+ * Changes a profile's configuration. The change applies from the next
30932
+ * stroke: the profile object is replaced, never mutated, so a stroke in
30933
+ * progress keeps the configuration it started with.
30934
+ */
30935
+ setInputProfile(key, patch) {
30936
+ if (!(key in this.config.input.profiles)) return {
30937
+ applied: false,
30938
+ errors: [`Unknown profile "${key}"`]
30939
+ };
30940
+ const errors = validateBrushTunablePatch("profile", patch);
30941
+ if (errors.length > 0) return {
30942
+ applied: false,
30943
+ errors
30944
+ };
30945
+ this.config.input.profiles[key] = mergeExceptArrays(this.config.input.profiles[key], patch);
30946
+ this.presetIds[key] = "custom";
30947
+ this.scenarioId = null;
30948
+ return {
30949
+ applied: true,
30950
+ errors: []
30951
+ };
30952
+ }
30953
+ /** The profiles and the look as a portable, versioned document. */
30954
+ exportConfig() {
30955
+ return {
30956
+ version: 1,
30957
+ profiles: {
30958
+ mouse: this.getInputProfile("mouse"),
30959
+ touch: this.getInputProfile("touch"),
30960
+ "pen.applePencil": this.getInputProfile("pen.applePencil"),
30961
+ "pen.desktop": this.getInputProfile("pen.desktop")
30962
+ },
30963
+ look: this.getLook()
30964
+ };
30965
+ }
30966
+ /** The configuration as JSON text. */
30967
+ exportConfigJson() {
30968
+ return JSON.stringify(this.exportConfig(), null, 2);
30969
+ }
30970
+ /**
30971
+ * Restores a configuration exported with `exportConfig`, given as an object
30972
+ * or JSON text. A document with an unsupported version or invalid values is
30973
+ * rejected as a whole and nothing changes.
30974
+ */
30975
+ importConfig(input) {
30976
+ const parsed = parseBrushConfigDocument(input);
30977
+ if (!parsed.ok) return {
30978
+ applied: false,
30979
+ errors: parsed.errors
30980
+ };
30981
+ Object.assign(this.config.input.profiles, parsed.profiles);
30982
+ for (const key of Object.keys(parsed.profiles)) this.presetIds[key] = "imported";
30983
+ this.scenarioId = null;
30984
+ if (parsed.look !== void 0) this.look = parsed.look;
30985
+ return {
30986
+ applied: true,
30987
+ errors: []
30988
+ };
30989
+ }
30990
+ /** Look saved on every new stroke, or `null` when none is saved. */
30991
+ getLook() {
30992
+ return this.look ? mergeData(this.look, {}) : null;
30993
+ }
30994
+ /**
30995
+ * Changes the look saved on new strokes, or clears it with `null` so new
30996
+ * strokes carry no look and are drawn as in earlier releases. Strokes
30997
+ * already drawn keep the look they were saved with.
30998
+ */
30999
+ setLook(patch) {
31000
+ if (patch === null) {
31001
+ this.look = null;
31002
+ return {
31003
+ applied: true,
31004
+ errors: []
31005
+ };
31006
+ }
31007
+ const errors = validateBrushTunablePatch("look", patch);
31008
+ if (errors.length > 0) return {
31009
+ applied: false,
31010
+ errors
31011
+ };
31012
+ this.look = mergeData(this.look ?? WEAVE_STROKE_LEGACY_LOOK, patch);
31013
+ return {
31014
+ applied: true,
31015
+ errors: []
31016
+ };
31017
+ }
31018
+ /**
31019
+ * Applies a scenario: one preset for each profile and one look preset.
31020
+ * Custom presets are looked up in `registry` when given.
31021
+ */
31022
+ applyScenario(scenario, registry = new WeaveBrushPresetRegistry()) {
31023
+ const resolved = typeof scenario === "string" ? getBrushScenario(scenario) : scenario;
31024
+ if (!resolved) return {
31025
+ applied: false,
31026
+ errors: [`Unknown scenario "${scenario}"`]
31027
+ };
31028
+ const errors = [];
31029
+ const profiles = {};
31030
+ for (const key of Object.keys(this.config.input.profiles)) {
31031
+ const preset = registry.getProfilePreset(key, resolved.profiles[key]);
31032
+ if (!preset) {
31033
+ errors.push(`Unknown preset "${resolved.profiles[key]}" for profile "${key}"`);
31034
+ continue;
31035
+ }
31036
+ profiles[key] = resolveBrushProfilePatch(preset.patch);
31037
+ }
31038
+ const lookPreset = registry.getLookPreset(resolved.look);
31039
+ if (!lookPreset) errors.push(`Unknown look preset "${resolved.look}"`);
31040
+ if (errors.length > 0 || !lookPreset) return {
31041
+ applied: false,
31042
+ errors
31043
+ };
31044
+ Object.assign(this.config.input.profiles, profiles);
31045
+ this.presetIds = { ...resolved.profiles };
31046
+ this.scenarioId = resolved.id;
31047
+ this.look = resolveBrushLookPatch(lookPreset.patch);
31048
+ return {
31049
+ applied: true,
31050
+ errors: []
31051
+ };
31052
+ }
31053
+ /** Forces a profile for every stroke, or `null` to resolve automatically. */
31054
+ setForcedProfile(key) {
31055
+ this.config.input.forceProfile = key;
31056
+ }
31057
+ /** Replaces the automatic profile resolution; `undefined` restores it. */
31058
+ setProfileResolver(resolver) {
31059
+ this.config.input.resolveProfile = resolver;
31060
+ }
31061
+ /**
31062
+ * The pressure-smoothing state, as a view over this action's own fields so
31063
+ * the stage functions mutate the same state the action exposes.
31064
+ */
31065
+ get pressureState() {
31066
+ if (!this.pressureStateView) {
31067
+ const self = this;
31068
+ this.pressureStateView = {
31069
+ get lastSmoothedPressure() {
31070
+ return self.lastSmoothedPressure;
31071
+ },
31072
+ set lastSmoothedPressure(v) {
31073
+ self.lastSmoothedPressure = v;
31074
+ },
31075
+ get hasPressureSample() {
31076
+ return self.hasPressureSample;
31077
+ },
31078
+ set hasPressureSample(v) {
31079
+ self.hasPressureSample = v;
31080
+ },
31081
+ get lastPointerPos() {
31082
+ return self.lastPointerPos;
31083
+ },
31084
+ set lastPointerPos(v) {
31085
+ self.lastPointerPos = v;
31086
+ },
31087
+ get lastPointerTime() {
31088
+ return self.lastPointerTime;
31089
+ },
31090
+ set lastPointerTime(v) {
31091
+ self.lastPointerTime = v;
31092
+ },
31093
+ get predictedCount() {
31094
+ return self.predictedCount;
31095
+ },
31096
+ set predictedCount(v) {
31097
+ self.predictedCount = v;
31098
+ },
31099
+ lastDerivative: 0,
31100
+ lastNonZeroPressure: null
31101
+ };
31102
+ }
31103
+ return this.pressureStateView;
31104
+ }
31105
+ getName() {
31106
+ return BRUSH_TOOL_ACTION_NAME;
31107
+ }
31108
+ initProps() {
31109
+ return {
31110
+ stroke: "#000000ff",
31111
+ strokeWidth: 1,
31112
+ opacity: 1
31113
+ };
31114
+ }
31115
+ /**
31116
+ * Smooths one raw pressure sample with the filter of the active profile.
31117
+ *
31118
+ * This is the one place pressure smoothing happens: every sample that
31119
+ * becomes a stroke point, including the high-frequency coalesced samples a
31120
+ * stylus reports, goes through it so the smoothing state advances for later
31121
+ * samples.
31122
+ */
31123
+ smoothPressureSample(raw, clientX, clientY, time) {
31124
+ return smoothPressure(this.pressureState, this.activeProfile.pressure, raw, clientX, clientY, this.sampleTime(time));
31125
+ }
31126
+ /**
31127
+ * Time of a sample, in ms. With the `event` clock it is the time the sample's
31128
+ * own event reported, so processing a batch in one step does not change the
31129
+ * time between its samples; otherwise (or when the event reports no usable
31130
+ * time) it is the time of processing.
31131
+ */
31132
+ sampleTime(eventTime) {
31133
+ if (this.activeProfile.capture.clock === "event" && typeof eventTime === "number" && Number.isFinite(eventTime)) return eventTime;
31134
+ return performance.now();
31135
+ }
31136
+ /**
31137
+ * Raw pressure a pointer sample reports: the device's own reading for a
31138
+ * pen, a neutral constant for devices that do not sense pressure.
31139
+ */
31140
+ getRawPressure(pointerType, pressure, commit = true) {
31141
+ return getRawPressure(pointerType, pressure, this.activeProfile.pressure.zero, this.pressureState, commit);
31142
+ }
31143
+ getEventPressure(e) {
31144
+ return this.smoothPressureSample(this.getRawPressure(e.evt.pointerType, e.evt.pressure), e.evt.clientX, e.evt.clientY, e.evt.timeStamp);
31145
+ }
31146
+ /**
31147
+ * Resets the stroke-scoped state (pressure smoothing, predicted-point
31148
+ * bookkeeping and the position stabilizer) to a neutral baseline.
31149
+ *
31150
+ * This state belongs to a single stroke: it must be reset before the first
31151
+ * pressure sample of a new stroke is computed (in `handlePointerDown`, ahead
31152
+ * of the `getEventPressure` call for point 0), not only afterwards -
31153
+ * otherwise that first sample can inherit state left behind by the previous
31154
+ * stroke, inflating the very first point's pressure.
31155
+ */
31156
+ resetPressureSmoothingState() {
31157
+ resetPressureState(this.pressureState);
31158
+ this.captureState = createCaptureState();
31159
+ this.lastRawPoint = null;
31160
+ this.stabilizer.reset();
31161
+ }
31162
+ /**
31163
+ * Maps a client position to the stroke container the same way the stage maps
31164
+ * its own pointer position (content rectangle, then the inverse of the
31165
+ * container's absolute transform), without changing any stage state.
31166
+ */
31167
+ clientToContainer(clientX, clientY) {
31168
+ const content = this.instance.getStage().getContent();
31169
+ const rect = content.getBoundingClientRect();
31170
+ const scaleX = rect.width / content.clientWidth || 1;
31171
+ const scaleY = rect.height / content.clientHeight || 1;
31172
+ const transform = this.measureContainer.getAbsoluteTransform().copy();
31173
+ transform.invert();
31174
+ return transform.point({
31175
+ x: (clientX - rect.left) / scaleX,
31176
+ y: (clientY - rect.top) / scaleY
31177
+ });
31178
+ }
31179
+ /** Captures the samples of one pointer move into the stroke in progress. */
31180
+ handleMoveEvent(e) {
31181
+ const deps = {
31182
+ smooth: (raw, clientX, clientY, time) => this.smoothPressureSample(raw, clientX, clientY, time),
31183
+ rawPressure: (pointerType, pressure, commit) => this.getRawPressure(pointerType, pressure, commit),
31184
+ predictedPressure: (raw) => peekPredictedPressure(this.pressureState, this.activeProfile.pressure, raw)
31185
+ };
31186
+ if (this.activeProfile.capture.source === "coalesced") this.applyMovementSamples(captureCoalescedSamples(e.evt, {
31187
+ ...deps,
31188
+ toContainerPoint: (clientX, clientY) => this.clientToContainer(clientX, clientY)
31189
+ }, this.activeProfile.capture, this.captureState));
31190
+ else {
31191
+ const samples = captureLegacySamples(e.evt, deps);
31192
+ if (samples) this.applyMovementSamples(samples);
31193
+ else {
31194
+ const pointPressure = this.getEventPressure(e);
31195
+ this.handleMovement(pointPressure, void 0, false);
31196
+ }
31197
+ }
31198
+ }
31199
+ setupEvents() {
31200
+ const stage = this.instance.getStage();
31201
+ this.prevTouchAction = stage.container().style.touchAction;
31202
+ stage.container().style.touchAction = "none";
31203
+ window.addEventListener("keyup", (e) => {
31204
+ if (e.code === "Space" && this.instance.getActiveAction() === "brushTool") this.isSpacePressed = false;
31205
+ }, { signal: this.instance.getEventsController().signal });
31206
+ window.addEventListener("keydown", (e) => {
31207
+ if (e.code === "Enter" && this.instance.getActiveAction() === "brushTool") {
31208
+ e.stopPropagation();
31209
+ this.cancelAction();
31210
+ return;
31211
+ }
31212
+ if (e.code === "Space" && this.instance.getActiveAction() === "brushTool") {
31213
+ e.stopPropagation();
31214
+ this.isSpacePressed = true;
31215
+ return;
31216
+ }
31217
+ if (e.code === "Escape" && this.instance.getActiveAction() === "brushTool") {
31218
+ e.stopPropagation();
31219
+ this.cancelAction();
31220
+ }
31221
+ }, { signal: this.instance.getEventsController().signal });
31222
+ const handlePointerDown = (e) => {
31223
+ if (this.state === BRUSH_TOOL_STATE.INACTIVE) return;
31224
+ if (this.pendingTouch && e.evt.pointerType === "touch" && e.evt.pointerId !== this.pendingTouch.pointerId) {
31225
+ if (this.activeProfile.touchGuard.cancelOnSecondTouch) this.cancelPendingTouch();
31226
+ return;
31227
+ }
31228
+ if (this.state !== BRUSH_TOOL_STATE.IDLE) return;
31229
+ if (this.getZoomPlugin()?.isPinching()) return;
31230
+ if (this.isSpacePressed) return;
31231
+ if (e?.evt?.button !== 0) return;
31232
+ if (e.evt.pointerType === "touch" && this.penActive) return;
31233
+ if (e.evt.pointerType === "pen") {
31234
+ this.penActive = true;
31235
+ this.penSeen = true;
31236
+ }
31237
+ this.setActiveProfile(resolveBrushInputProfileKey({
31238
+ pointerType: e.evt.pointerType,
31239
+ platform: detectBrushPlatform(),
31240
+ persistentDeviceId: e.evt.persistentDeviceId
31241
+ }, this.config.input));
31242
+ const guard = this.activeProfile.touchGuard;
31243
+ if (e.evt.pointerType === "touch" && guard.ignoreAfterPen && this.penSeen) return;
31244
+ this.resetPressureSmoothingState();
31245
+ const pointPressure = this.getEventPressure(e);
31246
+ this.strokePointerId = typeof e.evt.pointerId === "number" ? e.evt.pointerId : null;
31247
+ if (e.evt.pointerType === "touch" && (guard.waitMs > 0 || guard.movePx > 0)) {
31248
+ this.startPendingTouch(e, pointPressure);
31249
+ e.evt.stopPropagation();
31250
+ return;
31251
+ }
31252
+ this.handleStartStroke(pointPressure, e.evt.timeStamp);
31253
+ this.captureState.lastClient = {
31254
+ x: e.evt.clientX,
31255
+ y: e.evt.clientY
31256
+ };
31257
+ e.evt.stopPropagation();
31258
+ };
31259
+ stage.on("pointerdown", handlePointerDown);
31260
+ const handlePointerMove = (e) => {
31261
+ if (this.state === BRUSH_TOOL_STATE.INACTIVE) return;
31262
+ this.setCursor();
31263
+ if (this.pendingTouch && this.state === BRUSH_TOOL_STATE.IDLE) {
31264
+ this.handlePendingTouchMove(e);
31265
+ return;
31266
+ }
28599
31267
  if (this.state !== BRUSH_TOOL_STATE.DEFINE_STROKE) return;
28600
31268
  if (this.getZoomPlugin()?.isPinching()) return;
31269
+ this.handleMoveEvent(e);
31270
+ e.evt.stopPropagation();
31271
+ };
31272
+ stage.on("pointermove", handlePointerMove);
31273
+ const handlePointerUp = (e) => {
31274
+ this.penActive = false;
31275
+ if (this.pendingTouch && this.state === BRUSH_TOOL_STATE.IDLE) {
31276
+ if (e.evt.pointerId !== this.pendingTouch.pointerId) return;
31277
+ this.commitPendingTouch();
31278
+ }
31279
+ if (this.state !== BRUSH_TOOL_STATE.DEFINE_STROKE) return;
31280
+ if (this.strokePointerId !== null && typeof e.evt.pointerId === "number" && e.evt.pointerId !== this.strokePointerId) return;
28601
31281
  this.handleEndStroke();
31282
+ this.strokePointerId = null;
28602
31283
  e.evt.stopPropagation();
28603
31284
  };
28604
31285
  stage.on("pointerup", handlePointerUp);
@@ -28631,9 +31312,101 @@ var WeaveBrushToolAction = class extends WeaveAction {
28631
31312
  height: maxY - minY
28632
31313
  };
28633
31314
  }
28634
- handleStartStroke(pressure) {
31315
+ /** Puts a finger stroke on hold until it is clear it is not a gesture. */
31316
+ startPendingTouch(e, pressure) {
31317
+ const guard = this.activeProfile.touchGuard;
31318
+ const pending = {
31319
+ pointerId: e.evt.pointerId,
31320
+ startClient: {
31321
+ x: e.evt.clientX,
31322
+ y: e.evt.clientY
31323
+ },
31324
+ pressure,
31325
+ time: e.evt.timeStamp,
31326
+ start: this.instance.getMousePointer(),
31327
+ samples: [],
31328
+ timer: null
31329
+ };
31330
+ if (guard.waitMs > 0) pending.timer = setTimeout(() => this.commitPendingTouch(), guard.waitMs);
31331
+ this.pendingTouch = pending;
31332
+ }
31333
+ /** Drops a waiting finger stroke without leaving a mark. */
31334
+ cancelPendingTouch() {
31335
+ if (this.pendingTouch?.timer) clearTimeout(this.pendingTouch.timer);
31336
+ this.pendingTouch = null;
31337
+ this.strokePointerId = null;
31338
+ }
31339
+ /**
31340
+ * Starts the stroke of a waiting finger at the point where it touched down,
31341
+ * then replays the moves that were held back, so the path is not lost.
31342
+ */
31343
+ commitPendingTouch() {
31344
+ const pending = this.pendingTouch;
31345
+ if (!pending) return;
31346
+ if (pending.timer) clearTimeout(pending.timer);
31347
+ this.pendingTouch = null;
31348
+ if (this.state !== BRUSH_TOOL_STATE.IDLE) return;
31349
+ this.handleStartStroke(pending.pressure, pending.time, pending.start);
31350
+ this.captureState.lastClient = pending.startClient;
31351
+ if (this.activeProfile.capture.source === "coalesced") for (const move of pending.samples) this.handleMoveEvent({ evt: {
31352
+ pointerId: move.pointerId,
31353
+ pointerType: move.pointerType,
31354
+ clientX: move.clientX,
31355
+ clientY: move.clientY,
31356
+ pressure: move.pressure,
31357
+ timeStamp: move.timeStamp,
31358
+ getCoalescedEvents: () => move.coalesced,
31359
+ getPredictedEvents: () => [],
31360
+ stopPropagation: () => void 0
31361
+ } });
31362
+ }
31363
+ /** Holds a move of the waiting finger, and commits once it has moved enough. */
31364
+ handlePendingTouchMove(e) {
31365
+ const pending = this.pendingTouch;
31366
+ if (!pending || e.evt.pointerId !== pending.pointerId) return;
31367
+ const guard = this.activeProfile.touchGuard;
31368
+ if (this.getZoomPlugin()?.isPinching()) {
31369
+ if (guard.cancelOnSecondTouch) this.cancelPendingTouch();
31370
+ return;
31371
+ }
31372
+ const batch = e.evt.getCoalescedEvents ? e.evt.getCoalescedEvents() : [];
31373
+ const source = batch.length > 0 ? batch : [e.evt];
31374
+ pending.samples.push({
31375
+ pointerId: e.evt.pointerId,
31376
+ pointerType: e.evt.pointerType,
31377
+ clientX: e.evt.clientX,
31378
+ clientY: e.evt.clientY,
31379
+ pressure: e.evt.pressure,
31380
+ timeStamp: e.evt.timeStamp,
31381
+ coalesced: source.map((c) => ({
31382
+ pointerType: c.pointerType,
31383
+ pressure: c.pressure,
31384
+ clientX: c.clientX,
31385
+ clientY: c.clientY,
31386
+ timeStamp: c.timeStamp
31387
+ }))
31388
+ });
31389
+ if (guard.movePx > 0 && Math.hypot(e.evt.clientX - pending.startClient.x, e.evt.clientY - pending.startClient.y) >= guard.movePx) this.commitPendingTouch();
31390
+ e.evt.stopPropagation();
31391
+ }
31392
+ handleStartStroke(pressure, time, start) {
28635
31393
  this.resetPressureSmoothingState();
28636
- const { mousePoint, container, measureContainer } = this.instance.getMousePointer();
31394
+ const { mousePoint, container, measureContainer } = start ?? this.instance.getMousePointer();
31395
+ if (mousePoint) {
31396
+ const self = this;
31397
+ this.stabilizer.seed(mousePoint, {
31398
+ get now() {
31399
+ return self.sampleTime(time);
31400
+ },
31401
+ get zoom() {
31402
+ return self.instance.getStage().scaleX();
31403
+ }
31404
+ });
31405
+ this.lastRawPoint = {
31406
+ x: mousePoint.x,
31407
+ y: mousePoint.y
31408
+ };
31409
+ }
28637
31410
  this.clickPoint = mousePoint;
28638
31411
  this.container = container;
28639
31412
  this.measureContainer = measureContainer;
@@ -28646,8 +31419,11 @@ var WeaveBrushToolAction = class extends WeaveAction {
28646
31419
  y: mousePoint.y,
28647
31420
  pressure
28648
31421
  });
31422
+ const inputMeta = this.getInputMeta();
28649
31423
  const node = nodeHandler.create(this.strokeId, {
28650
31424
  ...this.props,
31425
+ ...this.look ? { look: this.look } : {},
31426
+ ...inputMeta ? { inputMeta } : {},
28651
31427
  isEraser: this.isEraser,
28652
31428
  strokeScaleEnabled: true,
28653
31429
  x: 0,
@@ -28659,6 +31435,14 @@ var WeaveBrushToolAction = class extends WeaveAction {
28659
31435
  const nodeInstance = nodeHandler.onRender(node.props);
28660
31436
  this.measureContainer?.add(nodeInstance);
28661
31437
  }
31438
+ this.getTraceSink()?.onStrokeStart({
31439
+ profile: this.activeProfileKey,
31440
+ preset: this.presetIds[this.activeProfileKey],
31441
+ ...this.scenarioId ? { scenario: this.scenarioId } : {},
31442
+ profileConfig: this.activeProfile,
31443
+ strokeWidth: this.props.strokeWidth ?? 1,
31444
+ zoom: this.instance.getStage().scaleX()
31445
+ });
28662
31446
  this.setState(BRUSH_TOOL_STATE.DEFINE_STROKE);
28663
31447
  }
28664
31448
  /**
@@ -28678,23 +31462,50 @@ var WeaveBrushToolAction = class extends WeaveAction {
28678
31462
  const stage = this.instance.getStage();
28679
31463
  const tempStroke = stage.findOne(`#${this.strokeId}`);
28680
31464
  if (!this.measureContainer || !tempStroke) return;
31465
+ const sink = this.getTraceSink();
31466
+ const batchStart = sink ? performance.now() : 0;
28681
31467
  let newStrokeElements = [...tempStroke.getAttrs().strokeElements];
31468
+ const skipPredicted = this.activeProfile.stabilizer.type !== "none";
28682
31469
  for (const sample of samples) {
31470
+ if (sample.isPredicted && skipPredicted) continue;
28683
31471
  if (sample.sourceEvent) stage.setPointersPositions(sample.sourceEvent);
28684
- const { mousePoint } = this.instance.getMousePointerRelativeToContainer(this.measureContainer);
31472
+ const mousePoint = sample.point ?? this.instance.getMousePointerRelativeToContainer(this.measureContainer).mousePoint;
31473
+ if (!sample.isPredicted) this.lastRawPoint = {
31474
+ x: mousePoint.x,
31475
+ y: mousePoint.y
31476
+ };
31477
+ const sampleTime = () => this.sampleTime(sample.time);
31478
+ const stabilized = this.stabilizer.apply(mousePoint, {
31479
+ get now() {
31480
+ return sampleTime();
31481
+ },
31482
+ get zoom() {
31483
+ return stage.scaleX();
31484
+ }
31485
+ });
31486
+ sink?.onSample({
31487
+ raw: {
31488
+ x: mousePoint.x,
31489
+ y: mousePoint.y
31490
+ },
31491
+ stabilized: {
31492
+ x: stabilized.x,
31493
+ y: stabilized.y
31494
+ },
31495
+ pressure: sample.pressure,
31496
+ time: sampleTime(),
31497
+ predicted: sample.isPredicted
31498
+ });
28685
31499
  const currentPoint = {
28686
- x: mousePoint.x - tempStroke.x(),
28687
- y: mousePoint.y - tempStroke.y(),
31500
+ x: stabilized.x - tempStroke.x(),
31501
+ y: stabilized.y - tempStroke.y(),
28688
31502
  pressure: sample.pressure
28689
31503
  };
28690
31504
  if (!sample.isPredicted && this.predictedCount > 0) {
28691
31505
  newStrokeElements = newStrokeElements.slice(0, -1 * this.predictedCount);
28692
31506
  this.predictedCount = 0;
28693
31507
  }
28694
- if (!sample.isPredicted && newStrokeElements.length === 1) newStrokeElements[0] = {
28695
- ...newStrokeElements[0],
28696
- pressure: currentPoint.pressure
28697
- };
31508
+ applyStartPolicy(newStrokeElements, currentPoint, sample.isPredicted, this.activeProfile.pressure);
28698
31509
  newStrokeElements.push(currentPoint);
28699
31510
  if (sample.isPredicted) this.predictedCount++;
28700
31511
  }
@@ -28708,6 +31519,10 @@ var WeaveBrushToolAction = class extends WeaveAction {
28708
31519
  });
28709
31520
  const nodeHandler = this.instance.getNodeHandler("stroke");
28710
31521
  if (nodeHandler) nodeHandler.onUpdate(tempStroke, tempStroke.getAttrs());
31522
+ sink?.onBatch({
31523
+ ms: performance.now() - batchStart,
31524
+ samples: samples.length
31525
+ });
28711
31526
  }
28712
31527
  handleMovement(pressure, predictedEvent, isPredicted = false) {
28713
31528
  this.applyMovementSamples([{
@@ -28716,26 +31531,60 @@ var WeaveBrushToolAction = class extends WeaveAction {
28716
31531
  isPredicted
28717
31532
  }]);
28718
31533
  }
31534
+ /**
31535
+ * The point that completes a stabilized stroke at the pen's last position,
31536
+ * or `null` when the stroke already ends there or has no stabilizer.
31537
+ */
31538
+ getStrokeCompletion(elements, tempStroke) {
31539
+ const cfg = this.activeProfile.stabilizer;
31540
+ if (cfg.type === "none" || !cfg.catchUpOnEnd) return null;
31541
+ if (!this.lastRawPoint || elements.length === 0) return null;
31542
+ const last = elements[elements.length - 1];
31543
+ const x = this.lastRawPoint.x - tempStroke.x();
31544
+ const y = this.lastRawPoint.y - tempStroke.y();
31545
+ if (x === last.x && y === last.y) return null;
31546
+ return {
31547
+ x,
31548
+ y,
31549
+ pressure: last.pressure
31550
+ };
31551
+ }
28719
31552
  finalizeStroke(tempStroke, nodeHandler) {
28720
- const box = this.getBoundingBox(tempStroke.getAttrs().strokeElements);
31553
+ let box = this.getBoundingBox(tempStroke.getAttrs().strokeElements);
28721
31554
  let newStrokeElements = [...tempStroke.getAttrs().strokeElements];
28722
31555
  if (this.predictedCount > 0) {
28723
31556
  newStrokeElements = newStrokeElements.slice(0, -1 * this.predictedCount);
28724
31557
  this.predictedCount = 0;
28725
31558
  }
28726
- if (newStrokeElements.length >= 2) {
28727
- const lastIndex = newStrokeElements.length - 1;
28728
- newStrokeElements[lastIndex] = {
28729
- ...newStrokeElements[lastIndex],
28730
- pressure: newStrokeElements[lastIndex - 1].pressure
28731
- };
31559
+ const completion = this.getStrokeCompletion(newStrokeElements, tempStroke);
31560
+ if (completion) {
31561
+ newStrokeElements = [...newStrokeElements, completion];
31562
+ box = this.getBoundingBox([...tempStroke.getAttrs().strokeElements, completion]);
28732
31563
  }
31564
+ newStrokeElements = applyEndPolicy(newStrokeElements, this.activeProfile.pressure);
28733
31565
  newStrokeElements = newStrokeElements.map((point) => ({
28734
31566
  ...point,
28735
31567
  x: point.x - box.x,
28736
31568
  y: point.y - box.y
28737
31569
  }));
28738
- const compressedPoints = simplify(newStrokeElements, this.config.simplifyTolerance, true);
31570
+ const finalize = this.activeProfile.finalize;
31571
+ const zoom = finalize.toleranceUnit === "screen" || finalize.mode === "bezierFit" || finalize.mode === "dpPressure" ? this.instance.getStage().scaleX() : 1;
31572
+ const finalizeStart = performance.now();
31573
+ const compressedPoints = finalizePoints(newStrokeElements, finalize, this.config.simplifyTolerance, zoom);
31574
+ this.getTraceSink()?.onStrokeEnd({
31575
+ beforeFinalize: newStrokeElements.map((p) => ({
31576
+ x: p.x + box.x,
31577
+ y: p.y + box.y,
31578
+ pressure: p.pressure
31579
+ })),
31580
+ finalPoints: compressedPoints.map((p) => ({
31581
+ x: p.x + box.x,
31582
+ y: p.y + box.y,
31583
+ pressure: p.pressure
31584
+ })),
31585
+ strokeWidth: tempStroke.getAttrs().strokeWidth ?? 1,
31586
+ finalizeMs: performance.now() - finalizeStart
31587
+ });
28739
31588
  const sw = tempStroke.getAttrs().strokeWidth ?? 1;
28740
31589
  const finalWidth = Math.max(box.width, sw);
28741
31590
  const finalHeight = Math.max(box.height, sw);
@@ -28808,6 +31657,8 @@ var WeaveBrushToolAction = class extends WeaveAction {
28808
31657
  stage.container().focus();
28809
31658
  this.cancelAction = cancel;
28810
31659
  if (selectionPlugin) selectionPlugin.setSelectedNodes([]);
31660
+ this.cancelPendingTouch();
31661
+ this.penSeen = false;
28811
31662
  this.props = this.initProps();
28812
31663
  this.setState(BRUSH_TOOL_STATE.IDLE);
28813
31664
  this.instance.emitEvent("onAddingBrush");
@@ -28828,6 +31679,7 @@ var WeaveBrushToolAction = class extends WeaveAction {
28828
31679
  if (node) selectionPlugin.setSelectedNodes([node]);
28829
31680
  this.instance.triggerAction(SELECTION_TOOL_ACTION_NAME);
28830
31681
  }
31682
+ this.cancelPendingTouch();
28831
31683
  this.clickPoint = null;
28832
31684
  this.setState(BRUSH_TOOL_STATE.INACTIVE);
28833
31685
  }
@@ -37522,4 +40374,4 @@ function getJSONFromYjsBinary(actualState) {
37522
40374
  return JSON.parse(actualStateString);
37523
40375
  }
37524
40376
  //#endregion
37525
- export { ALIGN_NODES_ALIGN_TO, ALIGN_NODES_TOOL_ACTION_NAME, ALIGN_NODES_TOOL_STATE, BRUSH_TOOL_ACTION_NAME, BRUSH_TOOL_DEFAULT_CONFIG, BRUSH_TOOL_STATE, CONNECTOR_TOOL_ACTION_NAME, CONNECTOR_TOOL_DEFAULT_CONFIG, CONNECTOR_TOOL_STATE, COPY_PASTE_NODES_PLUGIN_STATE, DEFAULT_GUIDE_TOOL_ACTION_CONFIG, DEFAULT_SNAPPING_MANAGER_CONFIG, ELLIPSE_TOOL_ACTION_NAME, ELLIPSE_TOOL_STATE, ERASER_TOOL_ACTION_NAME, ERASER_TOOL_STATE, FRAME_TOOL_ACTION_NAME, FRAME_TOOL_STATE, GUIDE_DISTANCE_NAME, GUIDE_DISTANCE_ORIGIN, GUIDE_KIND, GUIDE_NAME, GUIDE_ORIENTATION, GUIDE_STATE, GUIDE_TOOL_ACTION_NAME, GUIDE_TOOL_STATE, LINE_TOOL_ACTION_NAME, LINE_TOOL_DEFAULT_CONFIG, LINE_TOOL_STATE, MEASURE_TOOL_ACTION_NAME, MEASURE_TOOL_STATE, MOVE_ORIENTATION, MOVE_TOOL_ACTION_NAME, MOVE_TOOL_STATE, PEN_TOOL_ACTION_NAME, PEN_TOOL_STATE, POLYGON_TOOL_ACTION_NAME, POLYGON_TOOL_STATE, PREVIEW_HANDOVER_MAX_FRAMES, PREVIEW_ID_SUFFIX, RECTANGLE_TOOL_ACTION_NAME, RECTANGLE_TOOL_STATE, REGULAR_POLYGON_TOOL_ACTION_NAME, REGULAR_POLYGON_TOOL_STATE, SELECTION_TOOL_ACTION_NAME, SELECTION_TOOL_STATE, STAGE_MINIMAP_DEFAULT_CONFIG, STAR_TOOL_ACTION_NAME, STAR_TOOL_STATE, TEXT_LAYOUT, TEXT_TOOL_ACTION_NAME, TEXT_TOOL_STATE, TextLayoutEngine, VIDEO_TOOL_ACTION_NAME, VIDEO_TOOL_STATE, WEAVE_ARROW_NODE_TYPE, WEAVE_ARROW_TOOL_ACTION_NAME, WEAVE_ARROW_TOOL_STATE, WEAVE_COMMENTS_RENDERER_KEY, WEAVE_COMMENTS_TOOL_LAYER_ID, WEAVE_COMMENT_CREATE_ACTION, WEAVE_COMMENT_NODE_ACTION, WEAVE_COMMENT_NODE_DEFAULTS, WEAVE_COMMENT_NODE_TYPE, WEAVE_COMMENT_STATUS, WEAVE_COMMENT_TOOL_ACTION_NAME, WEAVE_COMMENT_TOOL_DEFAULT_CONFIG, WEAVE_COMMENT_TOOL_STATE, WEAVE_COMMENT_VIEW_ACTION, WEAVE_CONNECTOR_NODE_ANCHOR_ORIGIN, WEAVE_CONNECTOR_NODE_DECORATOR_TYPE, WEAVE_CONNECTOR_NODE_DEFAULT_CONFIG, WEAVE_CONNECTOR_NODE_LINE_ORIGIN, WEAVE_CONNECTOR_NODE_LINE_TYPE, WEAVE_CONNECTOR_NODE_TYPE, WEAVE_COPY_PASTE_CONFIG_DEFAULT, WEAVE_COPY_PASTE_NODES_KEY, WEAVE_COPY_PASTE_PASTE_CATCHER_ID, WEAVE_COPY_PASTE_PASTE_MODES, WEAVE_DEFAULT_USER_INFO_FUNCTION, WEAVE_ELLIPSE_NODE_TYPE, WEAVE_FRAME_DEFAULT_BACKGROUND_COLOR, WEAVE_FRAME_NODE_DEFAULT_CONFIG, WEAVE_FRAME_NODE_DEFAULT_PROPS, WEAVE_FRAME_NODE_TYPE, WEAVE_GRID_DEFAULT_CONFIG, WEAVE_GRID_DOT_TYPES, WEAVE_GRID_LAYER_ID, WEAVE_GRID_TYPES, WEAVE_GROUP_NODE_TYPE, WEAVE_IMAGES_TOOL_ACTION_NAME, WEAVE_IMAGES_TOOL_DEFAULT_CONFIG, WEAVE_IMAGES_TOOL_STATE, WEAVE_IMAGES_TOOL_UPLOAD_TYPE, WEAVE_IMAGE_CROP_ANCHOR_POSITION, WEAVE_IMAGE_CROP_END_TYPE, WEAVE_IMAGE_DEFAULT_CONFIG, WEAVE_IMAGE_NODE_TYPE, WEAVE_IMAGE_TOOL_ACTION_NAME, WEAVE_IMAGE_TOOL_CONFIG_DEFAULT, WEAVE_IMAGE_TOOL_STATE, WEAVE_IMAGE_TOOL_UPLOAD_TYPE, WEAVE_LAYER_NODE_TYPE, WEAVE_LINE_NODE_DEFAULT_CONFIG, WEAVE_LINE_NODE_TYPE, WEAVE_MEASURE_NODE_DEFAULT_CONFIG, WEAVE_MEASURE_NODE_TYPE, WEAVE_MEASURE_TOOL_DEFAULT_CONFIG, WEAVE_NODES_MULTI_SELECTION_FEEDBACK_PLUGIN_DEFAULT_CONFIG, WEAVE_NODES_MULTI_SELECTION_FEEDBACK_PLUGIN_KEY, WEAVE_NODES_MULTI_SELECTION_FEEDBACK_PLUGIN_LAYER_ID, WEAVE_NODES_SELECTION_DEFAULT_CONFIG, WEAVE_NODES_SELECTION_KEY, WEAVE_NODES_SELECTION_LAYER_ID, WEAVE_NODES_SNAPPING_PLUGIN_KEY, WEAVE_POLYGON_NODE_TYPE, WEAVE_POLYGON_PRESETS, WEAVE_RECTANGLE_NODE_TYPE, WEAVE_REGULAR_POLYGON_NODE_TYPE, WEAVE_SHAPE_LABEL_DEFAULTS, WEAVE_STAGE_DEFAULT_MODE, WEAVE_STAGE_DROP_AREA_KEY, WEAVE_STAGE_GRID_PLUGIN_KEY, WEAVE_STAGE_IMAGE_CROPPING_MODE, WEAVE_STAGE_KEYBOARD_MOVE_DEFAULT_CONFIG, WEAVE_STAGE_KEYBOARD_MOVE_KEY, WEAVE_STAGE_KEYBOARD_MOVE_ORIENTATION, WEAVE_STAGE_MINIMAP_KEY, WEAVE_STAGE_NODE_TYPE, WEAVE_STAGE_PANNING_DEFAULT_CONFIG, WEAVE_STAGE_PANNING_KEY, WEAVE_STAGE_PANNING_THROTTLE_MS, WEAVE_STAGE_SHAPE_LABEL_EDITION_MODE, WEAVE_STAGE_TEXT_EDITION_MODE, WEAVE_STAGE_ZOOM_DEFAULT_CONFIG, WEAVE_STAGE_ZOOM_KEY, WEAVE_STAGE_ZOOM_TYPE, WEAVE_STAR_NODE_TYPE, WEAVE_STROKE_NODE_DEFAULT_CONFIG, WEAVE_STROKE_NODE_TYPE, WEAVE_STROKE_SINGLE_NODE_DEFAULT_CONFIG, WEAVE_STROKE_SINGLE_NODE_TIP_SIDE, WEAVE_STROKE_SINGLE_NODE_TIP_TYPE, WEAVE_STROKE_SINGLE_NODE_TYPE, WEAVE_STROKE_TOOL_ACTION_NAME, WEAVE_STROKE_TOOL_ACTION_NAME_ALIASES, WEAVE_STROKE_TOOL_DEFAULT_CONFIG, WEAVE_STROKE_TOOL_STATE, WEAVE_TEXT_LINK_ALLOWED_PROTOCOLS, WEAVE_TEXT_NODE_DEFAULT_CONFIG, WEAVE_TEXT_NODE_TYPE, WEAVE_USERS_POINTERS_CONFIG_DEFAULT_PROPS, WEAVE_USERS_POINTERS_KEY, WEAVE_USERS_PRESENCE_CONFIG_DEFAULT_PROPS, WEAVE_USERS_PRESENCE_PLUGIN_KEY, WEAVE_USERS_SELECTION_KEY, WEAVE_USER_POINTER_KEY, WEAVE_USER_PRESENCE_KEY, WEAVE_USER_SELECTION_KEY, WEAVE_VIDEO_DEFAULT_CONFIG, WEAVE_VIDEO_NODE_TYPE, Weave, WeaveAction, WeaveAlignNodesToolAction, WeaveArrowNode, WeaveArrowToolAction, WeaveBrushToolAction, WeaveCommentNode, WeaveCommentToolAction, WeaveCommentsRendererPlugin, WeaveConnectedUsersPlugin, WeaveConnectorNode, WeaveConnectorToolAction, WeaveContextMenuPlugin, WeaveCopyPasteNodesPlugin, WeaveEllipseNode, WeaveEllipseToolAction, WeaveEraserToolAction, WeaveExportNodesToolAction, WeaveExportStageToolAction, WeaveFitToScreenToolAction, WeaveFitToSelectionToolAction, WeaveFrameNode, WeaveFrameToolAction, WeaveGroupNode, WeaveGuideToolAction, WeaveImageNode, WeaveImageToolAction, WeaveImagesToolAction, WeaveLayerNode, WeaveLineNode, WeaveLineToolAction, WeaveMeasureNode, WeaveMeasureToolAction, WeaveMoveToolAction, WeaveNode, WeaveNodesMultiSelectionFeedbackPlugin, WeaveNodesSelectionPlugin, WeaveNodesSnappingPlugin, WeavePenToolAction, WeavePlugin, WeavePolygonNode, WeavePolygonToolAction, WeaveRectangleNode, WeaveRectangleToolAction, WeaveRegularPolygonNode, WeaveRegularPolygonToolAction, WeaveRenderer, WeaveSelectionToolAction, WeaveStageDropAreaPlugin, WeaveStageGridPlugin, WeaveStageKeyboardMovePlugin, WeaveStageMinimapPlugin, WeaveStageNode, WeaveStagePanningPlugin, WeaveStageResizePlugin, WeaveStageZoomPlugin, WeaveStarNode, WeaveStarToolAction, WeaveStateManipulation, WeaveStore, WeaveStrokeNode, WeaveStrokeSingleNode, WeaveStrokeToolAction, WeaveTextNode, WeaveTextToolAction, WeaveTextV2Node, WeaveTextV2Shape, WeaveUsersPointersPlugin, WeaveUsersPresencePlugin, WeaveUsersSelectionPlugin, WeaveVideoNode, WeaveVideoToolAction, WeaveZoomInToolAction, WeaveZoomOutToolAction, applyLabelBlocksState, buildAncestorGroupIds, canComposite, clearContainerTargets, computeEllipseLabelMinSize, computePolygonLabelMinSize, computeRectangleLabelMinSize, containerOverCursor, containsNodeDeep, defaultInitialState, downscaleImageFile, downscaleImageFromURL, getBoundingBox, getDownscaleRatio, getExportBoundingBox, getImageSizeFromFile, getJSONFromYjsBinary, getSelectedNodesMetadata, getShapeLabelSchemaFields, getStageClickPoint, getTargetAndSkipNodes, getTargetedNode, getTopmostShadowHost, getVisibleNodes, getVisibleNodesInViewport, hasFrames, hasImages, instantiatePreset, intersectArrays, isArray, isIOS, isInShadowDOM, isNodeInSelection, isNumber, isObject, isServer, labelId, loadImageSource, mapJsonToYjsArray, mapJsonToYjsElements, mapJsonToYjsMap, memoize, mergeExceptArrays, moveNodeToContainer, moveNodeToContainerNT, resetScale, resolveLabelBlocks, sleep, spreadLabelProps, weavejsToYjsBinary };
40377
+ export { ALIGN_NODES_ALIGN_TO, ALIGN_NODES_TOOL_ACTION_NAME, ALIGN_NODES_TOOL_STATE, BRUSH_CONFIG_DOCUMENT_VERSION, BRUSH_INPUT_PROFILE_KEYS, BRUSH_LAB_PLUGIN_NAME, BRUSH_LEGACY_INPUT_PROFILE, BRUSH_LOOK_PRESETS, BRUSH_LOOK_TUNABLES, BRUSH_PROFILE_PRESETS, BRUSH_PROFILE_TUNABLES, BRUSH_SCENARIOS, BRUSH_TOOL_ACTION_NAME, BRUSH_TOOL_DEFAULT_CONFIG, BRUSH_TOOL_STATE, BRUSH_TUNABLES, CONNECTOR_TOOL_ACTION_NAME, CONNECTOR_TOOL_DEFAULT_CONFIG, CONNECTOR_TOOL_STATE, COPY_PASTE_NODES_PLUGIN_STATE, DEFAULT_GUIDE_TOOL_ACTION_CONFIG, DEFAULT_SNAPPING_MANAGER_CONFIG, ELLIPSE_TOOL_ACTION_NAME, ELLIPSE_TOOL_STATE, ERASER_TOOL_ACTION_NAME, ERASER_TOOL_STATE, FRAME_TOOL_ACTION_NAME, FRAME_TOOL_STATE, GUIDE_DISTANCE_NAME, GUIDE_DISTANCE_ORIGIN, GUIDE_KIND, GUIDE_NAME, GUIDE_ORIENTATION, GUIDE_STATE, GUIDE_TOOL_ACTION_NAME, GUIDE_TOOL_STATE, LINE_TOOL_ACTION_NAME, LINE_TOOL_DEFAULT_CONFIG, LINE_TOOL_STATE, MEASURE_TOOL_ACTION_NAME, MEASURE_TOOL_STATE, MOVE_ORIENTATION, MOVE_TOOL_ACTION_NAME, MOVE_TOOL_STATE, PEN_TOOL_ACTION_NAME, PEN_TOOL_STATE, POLYGON_TOOL_ACTION_NAME, POLYGON_TOOL_STATE, PREVIEW_HANDOVER_MAX_FRAMES, PREVIEW_ID_SUFFIX, RECTANGLE_TOOL_ACTION_NAME, RECTANGLE_TOOL_STATE, REGULAR_POLYGON_TOOL_ACTION_NAME, REGULAR_POLYGON_TOOL_STATE, SELECTION_TOOL_ACTION_NAME, SELECTION_TOOL_STATE, STAGE_MINIMAP_DEFAULT_CONFIG, STAR_TOOL_ACTION_NAME, STAR_TOOL_STATE, TEXT_LAYOUT, TEXT_TOOL_ACTION_NAME, TEXT_TOOL_STATE, TextLayoutEngine, VIDEO_TOOL_ACTION_NAME, VIDEO_TOOL_STATE, WEAVE_ARROW_NODE_TYPE, WEAVE_ARROW_TOOL_ACTION_NAME, WEAVE_ARROW_TOOL_STATE, WEAVE_COMMENTS_RENDERER_KEY, WEAVE_COMMENTS_TOOL_LAYER_ID, WEAVE_COMMENT_CREATE_ACTION, WEAVE_COMMENT_NODE_ACTION, WEAVE_COMMENT_NODE_DEFAULTS, WEAVE_COMMENT_NODE_TYPE, WEAVE_COMMENT_STATUS, WEAVE_COMMENT_TOOL_ACTION_NAME, WEAVE_COMMENT_TOOL_DEFAULT_CONFIG, WEAVE_COMMENT_TOOL_STATE, WEAVE_COMMENT_VIEW_ACTION, WEAVE_CONNECTOR_NODE_ANCHOR_ORIGIN, WEAVE_CONNECTOR_NODE_DECORATOR_TYPE, WEAVE_CONNECTOR_NODE_DEFAULT_CONFIG, WEAVE_CONNECTOR_NODE_LINE_ORIGIN, WEAVE_CONNECTOR_NODE_LINE_TYPE, WEAVE_CONNECTOR_NODE_TYPE, WEAVE_COPY_PASTE_CONFIG_DEFAULT, WEAVE_COPY_PASTE_NODES_KEY, WEAVE_COPY_PASTE_PASTE_CATCHER_ID, WEAVE_COPY_PASTE_PASTE_MODES, WEAVE_DEFAULT_USER_INFO_FUNCTION, WEAVE_ELLIPSE_NODE_TYPE, WEAVE_FRAME_DEFAULT_BACKGROUND_COLOR, WEAVE_FRAME_NODE_DEFAULT_CONFIG, WEAVE_FRAME_NODE_DEFAULT_PROPS, WEAVE_FRAME_NODE_TYPE, WEAVE_GRID_DEFAULT_CONFIG, WEAVE_GRID_DOT_TYPES, WEAVE_GRID_LAYER_ID, WEAVE_GRID_TYPES, WEAVE_GROUP_NODE_TYPE, WEAVE_IMAGES_TOOL_ACTION_NAME, WEAVE_IMAGES_TOOL_DEFAULT_CONFIG, WEAVE_IMAGES_TOOL_STATE, WEAVE_IMAGES_TOOL_UPLOAD_TYPE, WEAVE_IMAGE_CROP_ANCHOR_POSITION, WEAVE_IMAGE_CROP_END_TYPE, WEAVE_IMAGE_DEFAULT_CONFIG, WEAVE_IMAGE_NODE_TYPE, WEAVE_IMAGE_TOOL_ACTION_NAME, WEAVE_IMAGE_TOOL_CONFIG_DEFAULT, WEAVE_IMAGE_TOOL_STATE, WEAVE_IMAGE_TOOL_UPLOAD_TYPE, WEAVE_LAYER_NODE_TYPE, WEAVE_LINE_NODE_DEFAULT_CONFIG, WEAVE_LINE_NODE_TYPE, WEAVE_MEASURE_NODE_DEFAULT_CONFIG, WEAVE_MEASURE_NODE_TYPE, WEAVE_MEASURE_TOOL_DEFAULT_CONFIG, WEAVE_NODES_MULTI_SELECTION_FEEDBACK_PLUGIN_DEFAULT_CONFIG, WEAVE_NODES_MULTI_SELECTION_FEEDBACK_PLUGIN_KEY, WEAVE_NODES_MULTI_SELECTION_FEEDBACK_PLUGIN_LAYER_ID, WEAVE_NODES_SELECTION_DEFAULT_CONFIG, WEAVE_NODES_SELECTION_KEY, WEAVE_NODES_SELECTION_LAYER_ID, WEAVE_NODES_SNAPPING_PLUGIN_KEY, WEAVE_POLYGON_NODE_TYPE, WEAVE_POLYGON_PRESETS, WEAVE_RECTANGLE_NODE_TYPE, WEAVE_REGULAR_POLYGON_NODE_TYPE, WEAVE_SHAPE_LABEL_DEFAULTS, WEAVE_STAGE_DEFAULT_MODE, WEAVE_STAGE_DROP_AREA_KEY, WEAVE_STAGE_GRID_PLUGIN_KEY, WEAVE_STAGE_IMAGE_CROPPING_MODE, WEAVE_STAGE_KEYBOARD_MOVE_DEFAULT_CONFIG, WEAVE_STAGE_KEYBOARD_MOVE_KEY, WEAVE_STAGE_KEYBOARD_MOVE_ORIENTATION, WEAVE_STAGE_MINIMAP_KEY, WEAVE_STAGE_NODE_TYPE, WEAVE_STAGE_PANNING_DEFAULT_CONFIG, WEAVE_STAGE_PANNING_KEY, WEAVE_STAGE_PANNING_THROTTLE_MS, WEAVE_STAGE_SHAPE_LABEL_EDITION_MODE, WEAVE_STAGE_TEXT_EDITION_MODE, WEAVE_STAGE_ZOOM_DEFAULT_CONFIG, WEAVE_STAGE_ZOOM_KEY, WEAVE_STAGE_ZOOM_TYPE, WEAVE_STAR_NODE_TYPE, WEAVE_STROKE_LEGACY_LOOK, WEAVE_STROKE_NODE_DEFAULT_CONFIG, WEAVE_STROKE_NODE_TYPE, WEAVE_STROKE_SINGLE_NODE_DEFAULT_CONFIG, WEAVE_STROKE_SINGLE_NODE_TIP_SIDE, WEAVE_STROKE_SINGLE_NODE_TIP_TYPE, WEAVE_STROKE_SINGLE_NODE_TYPE, WEAVE_STROKE_TOOL_ACTION_NAME, WEAVE_STROKE_TOOL_ACTION_NAME_ALIASES, WEAVE_STROKE_TOOL_DEFAULT_CONFIG, WEAVE_STROKE_TOOL_STATE, WEAVE_TEXT_LINK_ALLOWED_PROTOCOLS, WEAVE_TEXT_NODE_DEFAULT_CONFIG, WEAVE_TEXT_NODE_TYPE, WEAVE_USERS_POINTERS_CONFIG_DEFAULT_PROPS, WEAVE_USERS_POINTERS_KEY, WEAVE_USERS_PRESENCE_CONFIG_DEFAULT_PROPS, WEAVE_USERS_PRESENCE_PLUGIN_KEY, WEAVE_USERS_SELECTION_KEY, WEAVE_USER_POINTER_KEY, WEAVE_USER_PRESENCE_KEY, WEAVE_USER_SELECTION_KEY, WEAVE_VIDEO_DEFAULT_CONFIG, WEAVE_VIDEO_NODE_TYPE, Weave, WeaveAction, WeaveAlignNodesToolAction, WeaveArrowNode, WeaveArrowToolAction, WeaveBrushPresetRegistry, WeaveBrushToolAction, WeaveCommentNode, WeaveCommentToolAction, WeaveCommentsRendererPlugin, WeaveConnectedUsersPlugin, WeaveConnectorNode, WeaveConnectorToolAction, WeaveContextMenuPlugin, WeaveCopyPasteNodesPlugin, WeaveEllipseNode, WeaveEllipseToolAction, WeaveEraserToolAction, WeaveExportNodesToolAction, WeaveExportStageToolAction, WeaveFitToScreenToolAction, WeaveFitToSelectionToolAction, WeaveFrameNode, WeaveFrameToolAction, WeaveGroupNode, WeaveGuideToolAction, WeaveImageNode, WeaveImageToolAction, WeaveImagesToolAction, WeaveLayerNode, WeaveLineNode, WeaveLineToolAction, WeaveMeasureNode, WeaveMeasureToolAction, WeaveMoveToolAction, WeaveNode, WeaveNodesMultiSelectionFeedbackPlugin, WeaveNodesSelectionPlugin, WeaveNodesSnappingPlugin, WeavePenToolAction, WeavePlugin, WeavePolygonNode, WeavePolygonToolAction, WeaveRectangleNode, WeaveRectangleToolAction, WeaveRegularPolygonNode, WeaveRegularPolygonToolAction, WeaveRenderer, WeaveSelectionToolAction, WeaveStageDropAreaPlugin, WeaveStageGridPlugin, WeaveStageKeyboardMovePlugin, WeaveStageMinimapPlugin, WeaveStageNode, WeaveStagePanningPlugin, WeaveStageResizePlugin, WeaveStageZoomPlugin, WeaveStarNode, WeaveStarToolAction, WeaveStateManipulation, WeaveStore, WeaveStrokeNode, WeaveStrokeSingleNode, WeaveStrokeToolAction, WeaveTextNode, WeaveTextToolAction, WeaveTextV2Node, WeaveTextV2Shape, WeaveUsersPointersPlugin, WeaveUsersPresencePlugin, WeaveUsersSelectionPlugin, WeaveVideoNode, WeaveVideoToolAction, WeaveZoomInToolAction, WeaveZoomOutToolAction, applyLabelBlocksState, automaticBrushProfileKey, buildAncestorGroupIds, canComposite, clearContainerTargets, computeEllipseLabelMinSize, computePolygonLabelMinSize, computeRectangleLabelMinSize, containerOverCursor, containsNodeDeep, defaultInitialState, detectBrushPlatform, downscaleImageFile, downscaleImageFromURL, getBoundingBox, getBrushScenario, getBrushTunable, getDownscaleRatio, getExportBoundingBox, getImageSizeFromFile, getJSONFromYjsBinary, getSelectedNodesMetadata, getShapeLabelSchemaFields, getStageClickPoint, getTargetAndSkipNodes, getTargetedNode, getTopmostShadowHost, getVisibleNodes, getVisibleNodesInViewport, hasFrames, hasImages, instantiatePreset, intersectArrays, isArray, isIOS, isInShadowDOM, isNodeInSelection, isNumber, isObject, isServer, labelId, loadImageSource, mapJsonToYjsArray, mapJsonToYjsElements, mapJsonToYjsMap, memoize, mergeExceptArrays, moveNodeToContainer, moveNodeToContainerNT, parseBrushConfigDocument, resetScale, resolveBrushInputProfileKey, resolveBrushLookPatch, resolveBrushProfilePatch, resolveLabelBlocks, sleep, spreadLabelProps, validateBrushTunablePatch, validateBrushTunableValue, weavejsToYjsBinary };