@tremolo-ui/dom 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
- import { clamp, isBlackKey, isWhiteKey, linearScale, normalizeValue, noteKey, noteKeys, radian, stepValue, toFixed, toPrecision } from "@tremolo-ui/functions";
1
+ import { _ as DEFAULT_DRAG_SENSITIVITY, b as matchesAccept, h as notePosition, m as noteAt, o as createPointsEditor, t as toXY, u as createDrag, v as DEFAULT_KEYBOARD_OPTIONS, x as partitionByAccept, y as DEFAULT_WHEEL_OPTIONS } from "./xy-lNFl1CTO.js";
2
+ import { clamp, linearScale, normalizeValue, radian, stepValue, toFixed, toPrecision } from "@tremolo-ui/functions";
2
3
  //#region src/canvas/context.ts
3
4
  /**
4
5
  * The assignable parts of a 2D context's drawing state. They have to be
@@ -36,9 +37,6 @@ const drawingState = [
36
37
  "imageSmoothingEnabled",
37
38
  "imageSmoothingQuality"
38
39
  ];
39
- function isDrawingState(value) {
40
- return typeof value === "string" && drawingState.includes(value);
41
- }
42
40
  /** Copy the drawing state off a context, to put back after a resize. */
43
41
  function readDrawingState(context) {
44
42
  const state = {};
@@ -235,53 +233,6 @@ function createAnimationCanvas(canvas, options) {
235
233
  };
236
234
  }
237
235
  //#endregion
238
- //#region src/file/accept.ts
239
- /**
240
- * Does a file satisfy an `accept` attribute?
241
- *
242
- * `accept` is written the way the HTML attribute is: a comma separated list of
243
- * extensions (`.wav`), MIME types (`audio/wav`) and type groups (`audio/*`).
244
- * Anything that matches one entry is accepted, and an empty or missing
245
- * `accept` takes everything.
246
- *
247
- * **The browser's own `accept` is only a hint to the file picker.** A person
248
- * can switch it to "All Files", drag a file in, or pick one the picker was
249
- * never asked about, so what arrives still has to be checked.
250
- *
251
- * A rule that cannot be decided is not treated as a rejection: with no `name`,
252
- * an extension rule says nothing either way, and `accept=".wav"` reports a
253
- * match rather than refusing a file it has not seen the name of. The name is
254
- * there by the time the file is dropped, which is when the answer counts.
255
- */
256
- function matchesAccept(candidate, accept) {
257
- const rules = (accept ?? "").split(",").map((rule) => rule.trim().toLowerCase()).filter(Boolean);
258
- if (rules.length === 0) return true;
259
- const name = candidate.name?.toLowerCase();
260
- const type = candidate.type.toLowerCase();
261
- let undecided = false;
262
- for (const rule of rules) if (rule.startsWith(".")) {
263
- if (name === void 0) undecided = true;
264
- else if (name.endsWith(rule)) return true;
265
- } else if (rule.endsWith("/*")) {
266
- if (type.startsWith(rule.slice(0, -1))) return true;
267
- } else if (type === rule) return true;
268
- return undecided;
269
- }
270
- /**
271
- * Split files into those that satisfy `accept` and those that do not, keeping
272
- * their order. See {@link matchesAccept}.
273
- */
274
- function partitionByAccept(files, accept) {
275
- const accepted = [];
276
- const rejected = [];
277
- for (const file of files) if (matchesAccept(file, accept)) accepted.push(file);
278
- else rejected.push(file);
279
- return {
280
- accepted,
281
- rejected
282
- };
283
- }
284
- //#endregion
285
236
  //#region src/file/drop-zone.ts
286
237
  /**
287
238
  * Take files dropped onto an element.
@@ -405,295 +356,64 @@ function createDropZone(element, options = {}) {
405
356
  };
406
357
  }
407
358
  //#endregion
408
- //#region src/input/modifiers.ts
359
+ //#region src/input/change-gesture.ts
409
360
  /**
410
- * Checked in this order, and the first one that is both held and configured
411
- * wins. Fixing an order is what keeps two modifiers held at once from
412
- * behaving differently between browsers.
413
- */
414
- const MODIFIER_ORDER = [
415
- "meta",
416
- "ctrl",
417
- "alt",
418
- "shift"
419
- ];
420
- const MODIFIER_FLAG = {
421
- meta: "metaKey",
422
- ctrl: "ctrlKey",
423
- alt: "altKey",
424
- shift: "shiftKey"
425
- };
426
- /**
427
- * A map is the only form with a `default` key, which is what tells it apart
428
- * from a bare setting. Tuples are arrays, so they never match.
429
- */
430
- function isModifierMap(value) {
431
- return typeof value === "object" && value !== null && !Array.isArray(value) && "default" in value;
432
- }
433
- /**
434
- * Pick the setting that applies, given the modifier keys being held.
435
- *
436
- * @example
437
- * selectModifier({ default: 1, shift: 0.1 }, event)
438
- */
439
- function selectModifier(options, modifiers) {
440
- if (!isModifierMap(options)) return {
441
- value: options,
442
- modifier: null
443
- };
444
- if (modifiers) for (const modifier of MODIFIER_ORDER) {
445
- const value = options[modifier];
446
- if (value !== void 0 && modifiers[MODIFIER_FLAG[modifier]]) return {
447
- value,
448
- modifier
449
- };
450
- }
451
- return {
452
- value: options.default,
453
- modifier: null
454
- };
455
- }
456
- /**
457
- * Turn every entry of a setting into another kind of setting, keeping which
458
- * modifier each belongs to.
459
- *
460
- * A drag sensitivity is a number and a keyboard amount is a tuple, but the two
461
- * describe the same thing from the caller's side. This carries one over to the
462
- * other so that a component can hand a sensitivity to {@link applyDelta}
463
- * without unpicking the modifier map itself — which matters, since naming a
464
- * modifier is also what takes `step` out of the pipeline.
465
- *
466
- * @example
467
- * mapModifier({ default: 1, shift: 0.1 }, (f) => ['raw', step * f])
468
- * // { default: ['raw', 1], shift: ['raw', 0.1] }
469
- */
470
- function mapModifier(options, fn) {
471
- if (!isModifierMap(options)) return fn(options);
472
- const mapped = { default: fn(options.default) };
473
- for (const modifier of MODIFIER_ORDER) {
474
- const value = options[modifier];
475
- if (value !== void 0) mapped[modifier] = fn(value);
476
- }
477
- return mapped;
478
- }
479
- //#endregion
480
- //#region src/input/apply-delta.ts
481
- /**
482
- * Move a value by an amount of input, as reported by a wheel or an arrow key.
483
- *
484
- * The pipeline matches {@link createDragValue}: scale, then step, then clamp.
485
- * Which key or which sign of `deltaY` counts as which direction is left to the
486
- * caller, since it differs per component.
487
- *
488
- * @param direction which way, and how many times, to apply the option. The
489
- * size of one step is `option[1]`, so this is normally `1` or `-1`.
490
- *
491
- * @param modifiers the event, for `options` that name a modifier key. See
492
- * {@link selectModifier}.
493
- *
494
- * @example
495
- * // ArrowDown on a slider whose keyboard option is ['raw', 1]
496
- * applyDelta(value, -1, keyboard, { min, max, step, scale })
497
- *
498
- * @example
499
- * // Shift+ArrowDown, where `keyboard` is { default: …, shift: ['raw', 0.1] }
500
- * applyDelta(value, -1, keyboard, range, event)
501
- */
502
- function applyDelta(value, direction, options, { min, max, step, scale = linearScale }, modifiers) {
503
- if (min >= max) throw new RangeError("requirements: min < max");
504
- if (step !== void 0 && (!Number.isFinite(step) || step <= 0)) throw new RangeError("applyDelta step: requirements: finite and greater than 0");
505
- const { value: [mode, amount], modifier } = selectModifier(options, modifiers);
506
- const x = direction * amount;
507
- const next = mode === "normalized" ? scale.denormalize(scale.normalize(value, min, max) + x, min, max) : value + x;
508
- const quantum = modifier === null ? step : void 0;
509
- const stepped = quantum !== void 0 ? stepValue(next, quantum) : next;
510
- return clamp(toPrecision(stepped), min, max);
511
- }
512
- //#endregion
513
- //#region src/input/check-steps.ts
514
- /** Positions probed across the travel. The ends are left out so that the
515
- * clamp at `min` and `max` cannot be mistaken for a press that does nothing. */
516
- const PROBES = [
517
- .1,
518
- .2,
519
- .3,
520
- .4,
521
- .5,
522
- .6,
523
- .7,
524
- .8,
525
- .9
526
- ];
527
- const NONE = {
528
- shiftKey: false,
529
- altKey: false,
530
- ctrlKey: false,
531
- metaKey: false
532
- };
533
- const MODIFIER_STATE = {
534
- shift: {
535
- ...NONE,
536
- shiftKey: true
537
- },
538
- alt: {
539
- ...NONE,
540
- altKey: true
541
- },
542
- ctrl: {
543
- ...NONE,
544
- ctrlKey: true
545
- },
546
- meta: {
547
- ...NONE,
548
- metaKey: true
549
- }
550
- };
551
- /** The held keys that select each entry of a modifier-aware input option. */
552
- function entries(options) {
553
- if (Array.isArray(options)) return [NONE];
554
- return Object.keys(options).map((key) => MODIFIER_STATE[key] ?? NONE);
555
- }
556
- /**
557
- * Press every entry of `options` at nine points along the travel and report
558
- * whether anything came of it.
559
- *
560
- * Run against `applyDelta` itself rather than against a reading of `step`:
561
- * the whole point is that the amount, the step and the scale interact, and
562
- * the pipeline is the only thing that knows how.
361
+ * Track when a change of value starts and ends, whatever made it: a drag, the
362
+ * wheel, the keys or a reset. A host that records automation needs both ends
363
+ * to know when the control is touched.
563
364
  */
564
- function probe(options, range, format) {
565
- const { min, max, scale = linearScale } = range;
566
- const outcome = {
567
- moved: false,
568
- visible: false
569
- };
570
- for (const modifiers of entries(options)) for (const position of PROBES) {
571
- const value = scale.denormalize(position, min, max);
572
- const up = applyDelta(value, 1, options, range, modifiers);
573
- const down = applyDelta(value, -1, options, range, modifiers);
574
- if (up !== value || down !== value) outcome.moved = true;
575
- if (!format) continue;
576
- const shown = format(value);
577
- if (format(up) !== shown || format(down) !== shown) outcome.visible = true;
365
+ function createChangeGesture(options = {}) {
366
+ let opts = options;
367
+ let current = null;
368
+ let timer = null;
369
+ function clearTimer() {
370
+ if (timer !== null) clearTimeout(timer);
371
+ timer = null;
578
372
  }
579
- return outcome;
580
- }
581
- /**
582
- * The warnings to show when a key press or a wheel notch cannot produce a
583
- * change the user can see. Empty when there is nothing to say.
584
- *
585
- * Two settings that are each fine on their own can cancel out, and nothing
586
- * fails when they do — the control simply sits there:
587
- *
588
- * - **`step` coarser than the amount.** `keyboard={['raw', 0.1]}` with
589
- * `step={1}` rounds every press straight back to where it started
590
- * - **the display coarser than the amount.** A `format` showing two decimals
591
- * of a kHz value cannot show a press worth 1 Hz
592
- *
593
- * The second is only reported when the press is invisible at *every* point
594
- * along the travel. A display that rounds is a deliberate choice and is
595
- * normally right — it is being too coarse everywhere that makes it a mistake.
596
- *
597
- * **Meant for development builds only.** It probes the whole travel, so call
598
- * it behind an inline `process.env.NODE_ENV` check: the bundler then drops
599
- * the call, and this function and its messages with it.
600
- */
601
- function checkSteps({ component, axis, range, keyboard, wheel, format }) {
602
- if (!range || !(range.min < range.max)) return [];
603
- const where = axis ? `${component} (${axis})` : component;
604
- const warnings = [];
605
- for (const [name, options] of [["keyboard", keyboard], ["wheel", wheel]]) {
606
- if (!options) continue;
607
- const { moved, visible } = probe(options, range, format);
608
- if (!moved) warnings.push(`[tremolo-ui] ${where}: \`${name}\` cannot move the value.` + (range.step !== void 0 ? ` Each press is smaller than \`step\` (${range.step}), so it rounds` : " Each press rounds") + " straight back to where it started.");
609
- else if (format && !visible) warnings.push(`[tremolo-ui] ${where}: \`${name}\` moves the value, but \`format\` shows the same text before and after, everywhere in the range. The display is too coarse for it to be seen.`);
373
+ function end() {
374
+ clearTimer();
375
+ if (!current) return;
376
+ const { source } = current;
377
+ current = null;
378
+ opts.onEnd?.(source);
379
+ }
380
+ function start(source, held) {
381
+ current = {
382
+ source,
383
+ held
384
+ };
385
+ opts.onStart?.(source);
610
386
  }
611
- return warnings;
612
- }
613
- //#endregion
614
- //#region src/input/defaults.ts
615
- /**
616
- * The keyboard amount used by Knob, NumberInput, Slider, and XYPad by default:
617
- * 1 per press in the units of the value, and 0.1 with shift held. That is one
618
- * `step` only while `step` is 1; a coarser `step` rounds 1 straight back, which
619
- * `checkSteps` warns about.
620
- *
621
- * A modifier entry is not snapped to `step`, which is what lets the finer
622
- * amount move at all — see `applyDelta`.
623
- */
624
- const DEFAULT_KEYBOARD_OPTIONS = {
625
- default: ["raw", 1],
626
- shift: ["raw", .1]
627
- };
628
- /**
629
- * The wheel amount used by Knob, NumberInput, Slider, and XYPad by default.
630
- *
631
- * Browsers turn shift+wheel into horizontal scrolling, which empties `deltaY`
632
- * and fills `deltaX`, so no modifier is bound here.
633
- */
634
- const DEFAULT_WHEEL_OPTIONS = ["raw", 1];
635
- /**
636
- * The drag sensitivity used by value controls by default. Shift makes the
637
- * same movement cover a tenth of the range, matching the arrow keys.
638
- */
639
- const DEFAULT_DRAG_SENSITIVITY = {
640
- default: 1,
641
- shift: .1
642
- };
643
- //#endregion
644
- //#region src/input/direction.ts
645
- /** Is `key` one of the four arrow keys? */
646
- function isArrowKey(key) {
647
- return key === "ArrowRight" || key === "ArrowLeft" || key === "ArrowUp" || key === "ArrowDown";
648
- }
649
- /**
650
- * The direction an arrow key moves a single value: right and up raise it.
651
- * `null` for any other key.
652
- */
653
- function arrowKeyDirection(key) {
654
- if (!isArrowKey(key)) return null;
655
- return key === "ArrowRight" || key === "ArrowUp" ? 1 : -1;
656
- }
657
- /**
658
- * The axis and direction an arrow key moves a position on screen. `null` for
659
- * any other key.
660
- *
661
- * The key picks the axis, whichever element inside the control holds the
662
- * focus: a two-dimensional control is one control to the person moving it.
663
- */
664
- function arrowKeyMove(key) {
665
- if (!isArrowKey(key)) return null;
666
387
  return {
667
- axis: key === "ArrowRight" || key === "ArrowLeft" ? 0 : 1,
668
- direction: key === "ArrowLeft" || key === "ArrowUp" ? -1 : 1
669
- };
670
- }
671
- /**
672
- * The direction one wheel event moves a single value: scrolling up raises it.
673
- * `null` when the event carries no movement the control reads.
674
- */
675
- function wheelDirection(event, { horizontal = false } = {}) {
676
- if (horizontal && event.deltaX !== 0) return event.deltaX > 0 ? 1 : -1;
677
- if (event.deltaY === 0) return null;
678
- return event.deltaY > 0 ? -1 : 1;
679
- }
680
- /**
681
- * The axis and direction one wheel event moves a position on screen. `null`
682
- * when the event carries no movement.
683
- *
684
- * Scrolling moves y, and shift switches to x. Browsers turn shift+wheel into
685
- * horizontal scrolling: `deltaY` comes out empty and `deltaX` carries the
686
- * movement. Reading whichever axis moved keeps shift working as the x-axis
687
- * modifier — and picks up a trackpad's own horizontal gesture, which never
688
- * had a modifier.
689
- */
690
- function wheelMove(event) {
691
- const horizontal = event.deltaX !== 0;
692
- const delta = horizontal ? event.deltaX : event.deltaY;
693
- if (delta === 0) return null;
694
- return {
695
- axis: horizontal || event.shiftKey ? 0 : 1,
696
- direction: delta < 0 ? -1 : 1
388
+ hold: (source) => {
389
+ if (current?.held && current.source === source) return;
390
+ end();
391
+ start(source, true);
392
+ },
393
+ pulse: (source) => {
394
+ if (current?.held) return;
395
+ if (!current || current.source !== source) {
396
+ end();
397
+ start(source, false);
398
+ }
399
+ clearTimer();
400
+ timer = setTimeout(end, opts.endDelay ?? 500);
401
+ },
402
+ instant: (source, change) => {
403
+ end();
404
+ start(source, false);
405
+ change();
406
+ end();
407
+ },
408
+ end,
409
+ active: () => current !== null,
410
+ update: (next) => {
411
+ opts = {
412
+ ...opts,
413
+ ...next
414
+ };
415
+ },
416
+ destroy: end
697
417
  };
698
418
  }
699
419
  //#endregion
@@ -752,12 +472,6 @@ function knobArcPath(startAngle, endAngle, radius) {
752
472
  }
753
473
  //#endregion
754
474
  //#region src/midi/access.ts
755
- /** @private */
756
- const PERMISSION_DENIED = "PERMISSION_DENIED";
757
- /** @private */
758
- const NOT_SUPPORTED = "NOT_SUPPORTED";
759
- /** @private */
760
- const UNAVAILABLE = "UNAVAILABLE";
761
475
  const INITIAL_STATE = {
762
476
  midiAccess: null,
763
477
  error: null,
@@ -771,9 +485,9 @@ const INITIAL_STATE = {
771
485
  */
772
486
  function toError(reason) {
773
487
  const name = typeof reason === "object" && reason !== null && "name" in reason ? String(reason.name) : "";
774
- if (name === "SecurityError" || name === "NotAllowedError") return PERMISSION_DENIED;
775
- if (name === "NotSupportedError" || name === "TypeError") return NOT_SUPPORTED;
776
- return UNAVAILABLE;
488
+ if (name === "SecurityError" || name === "NotAllowedError") return "PERMISSION_DENIED";
489
+ if (name === "NotSupportedError" || name === "TypeError") return "NOT_SUPPORTED";
490
+ return "UNAVAILABLE";
777
491
  }
778
492
  /**
779
493
  * Request MIDI access in the browser.
@@ -812,7 +526,7 @@ function createMIDIAccess() {
812
526
  if (typeof navigator === "undefined" || !navigator.requestMIDIAccess) {
813
527
  setState({
814
528
  ...state,
815
- error: NOT_SUPPORTED
529
+ error: "NOT_SUPPORTED"
816
530
  });
817
531
  return;
818
532
  }
@@ -910,13 +624,6 @@ const STATUS = {
910
624
  PITCH_BEND: 224
911
625
  };
912
626
  /**
913
- * Centre of the 14-bit pitch bend range: no bend.
914
- *
915
- * The range is not symmetric — 0 is 8192 below centre and 16383 is 8191 above
916
- * — so a wheel at rest reports exactly this rather than half of the maximum.
917
- */
918
- const PITCH_BEND_CENTER = 8192;
919
- /**
920
627
  * Handle the channel voice messages of every connected input. To be used with
921
628
  * {@link createMIDIAccess}. Internally uses {@link createMIDIMessage}, so
922
629
  * devices plugged in later are picked up.
@@ -964,619 +671,6 @@ function createMIDIInput(midiAccess, handlers) {
964
671
  };
965
672
  }
966
673
  //#endregion
967
- //#region src/pointer/drag.ts
968
- /**
969
- * Applied to the element for the lifetime of the instance.
970
- *
971
- * `touch-action` stops touch dragging from scrolling the page. That alone makes
972
- * the browser treat a long press as the start of a text selection, so selection
973
- * and the iOS callout are suppressed here too.
974
- */
975
- const MANAGED_STYLES = [
976
- ["touch-action", "none"],
977
- ["user-select", "none"],
978
- ["-webkit-user-select", "none"],
979
- ["-webkit-touch-callout", "none"]
980
- ];
981
- const managedStyleStates = /* @__PURE__ */ new WeakMap();
982
- /**
983
- * Track a pointer drag on an element.
984
- *
985
- * Uses Pointer Events only, and pointer capture so that the drag keeps working
986
- * once the pointer leaves the element. For the lifetime of the instance the
987
- * element gets `touch-action: none` so that touch dragging does not scroll the
988
- * page, plus `user-select: none` so that a long press does not start a text
989
- * selection instead.
990
- *
991
- * One pointer at a time by default; see {@link DragOptions.multiPointer}.
992
- */
993
- function createDrag(element, options = {}) {
994
- let opts = options;
995
- const multiPointer = options.multiPointer ?? false;
996
- const capture = element;
997
- const style = element.style;
998
- let managedStyles = managedStyleStates.get(element);
999
- if (style) {
1000
- if (managedStyles) managedStyles.count += 1;
1001
- else {
1002
- const previous = /* @__PURE__ */ new Map();
1003
- for (const [property, value] of MANAGED_STYLES) {
1004
- previous.set(property, {
1005
- value: style.getPropertyValue(property),
1006
- priority: style.getPropertyPriority(property)
1007
- });
1008
- style.setProperty(property, value);
1009
- }
1010
- managedStyles = {
1011
- count: 1,
1012
- previous
1013
- };
1014
- managedStyleStates.set(element, managedStyles);
1015
- }
1016
- }
1017
- const pointers = /* @__PURE__ */ new Map();
1018
- /**
1019
- * How many pointers each target carries. Adding the same listener twice is a
1020
- * no-op and removing it once removes it for good, so a target is subscribed
1021
- * to while at least one pointer is on it and no longer.
1022
- */
1023
- const targets = /* @__PURE__ */ new Map();
1024
- let previousCursor;
1025
- /** The pointer that asked for the lock, while it is still down. */
1026
- let lockedPointerId = null;
1027
- let lockRequest = 0;
1028
- let destroyed = false;
1029
- function state(event, pointer, deltaX, deltaY) {
1030
- return {
1031
- x: pointer.lockBaseX !== void 0 ? pointer.lockBaseX + pointer.lockMoveX : event.screenX - pointer.startX,
1032
- y: pointer.lockBaseY !== void 0 ? pointer.lockBaseY + pointer.lockMoveY : event.screenY - pointer.startY,
1033
- deltaX,
1034
- deltaY,
1035
- clientX: event.clientX,
1036
- clientY: event.clientY,
1037
- pointerId: event.pointerId,
1038
- event
1039
- };
1040
- }
1041
- /**
1042
- * `user-select: none` only makes the element's own text unselectable; the
1043
- * browser still starts a selection on long press and grabs whatever text it
1044
- * finds nearby. Cancelling the selection outright is what actually stops it.
1045
- */
1046
- function preventSelectStart(event) {
1047
- event.preventDefault();
1048
- }
1049
- function retainTarget(target) {
1050
- const count = targets.get(target) ?? 0;
1051
- if (count === 0) {
1052
- target.addEventListener("pointermove", handlePointerMove);
1053
- target.addEventListener("pointerup", handlePointerUp);
1054
- target.addEventListener("pointercancel", handlePointerUp);
1055
- if (target === element) target.addEventListener("lostpointercapture", handleLostPointerCapture);
1056
- }
1057
- targets.set(target, count + 1);
1058
- }
1059
- function releaseTarget(target) {
1060
- const count = targets.get(target) ?? 0;
1061
- if (count > 1) {
1062
- targets.set(target, count - 1);
1063
- return;
1064
- }
1065
- target.removeEventListener("pointermove", handlePointerMove);
1066
- target.removeEventListener("pointerup", handlePointerUp);
1067
- target.removeEventListener("pointercancel", handlePointerUp);
1068
- if (target === element) target.removeEventListener("lostpointercapture", handleLostPointerCapture);
1069
- targets.delete(target);
1070
- }
1071
- function handlePointerDown(event) {
1072
- const pointerEvent = event;
1073
- if (pointerEvent.button !== 0) return;
1074
- const pointerId = pointerEvent.pointerId;
1075
- if (pointers.has(pointerId)) return;
1076
- if (!multiPointer && pointers.size > 0) return;
1077
- if (opts.shouldStart && !opts.shouldStart(pointerEvent)) return;
1078
- const isFirst = pointers.size === 0;
1079
- if (isFirst && opts.cursor && style) {
1080
- previousCursor = style.cursor;
1081
- style.cursor = opts.cursor;
1082
- }
1083
- capture.setPointerCapture?.(pointerId);
1084
- const moveTarget = capture.hasPointerCapture?.(pointerId) === true ? element : globalThis.window ?? element;
1085
- const pointer = {
1086
- moveTarget,
1087
- startX: pointerEvent.screenX,
1088
- startY: pointerEvent.screenY,
1089
- lastX: pointerEvent.screenX,
1090
- lastY: pointerEvent.screenY,
1091
- lockMoveX: 0,
1092
- lockMoveY: 0,
1093
- lastEvent: pointerEvent
1094
- };
1095
- pointers.set(pointerId, pointer);
1096
- retainTarget(moveTarget);
1097
- if (isFirst) globalThis.document?.addEventListener("selectstart", preventSelectStart);
1098
- if (isFirst && opts.pointerLock) {
1099
- const requestId = ++lockRequest;
1100
- lockedPointerId = pointerId;
1101
- globalThis.document?.addEventListener("pointerlockchange", handleLockChange);
1102
- try {
1103
- (capture.requestPointerLock?.())?.then?.(() => {
1104
- if (requestId === lockRequest && (!pointers.has(pointerId) || destroyed) && globalThis.document?.pointerLockElement === element) globalThis.document.exitPointerLock?.();
1105
- }, () => {});
1106
- } catch {}
1107
- }
1108
- opts.onDragStart?.(state(pointerEvent, pointer, 0, 0));
1109
- }
1110
- function handlePointerMove(event) {
1111
- const pointerEvent = event;
1112
- const pointer = pointers.get(pointerEvent.pointerId);
1113
- if (!pointer) return;
1114
- const locked = pointer.lockBaseX !== void 0;
1115
- const deltaX = locked ? pointerEvent.movementX ?? 0 : pointerEvent.screenX - pointer.lastX;
1116
- const deltaY = locked ? pointerEvent.movementY ?? 0 : pointerEvent.screenY - pointer.lastY;
1117
- const threshold = opts.threshold ?? 0;
1118
- if (Math.abs(deltaX) < threshold && Math.abs(deltaY) < threshold) return;
1119
- pointer.lastX = pointerEvent.screenX;
1120
- pointer.lastY = pointerEvent.screenY;
1121
- pointer.lastEvent = pointerEvent;
1122
- if (locked) {
1123
- pointer.lockMoveX += deltaX;
1124
- pointer.lockMoveY += deltaY;
1125
- }
1126
- opts.onDrag?.(state(pointerEvent, pointer, deltaX, deltaY));
1127
- }
1128
- function handleLockChange() {
1129
- if (lockedPointerId === null) return;
1130
- const pointer = pointers.get(lockedPointerId);
1131
- if (!pointer) return;
1132
- if (globalThis.document?.pointerLockElement === element) {
1133
- pointer.lockBaseX = pointer.lastX - pointer.startX;
1134
- pointer.lockBaseY = pointer.lastY - pointer.startY;
1135
- pointer.lockMoveX = 0;
1136
- pointer.lockMoveY = 0;
1137
- return;
1138
- }
1139
- if (pointer.lockBaseX === void 0) return;
1140
- finishDrag(lockedPointerId);
1141
- }
1142
- function handlePointerUp(event) {
1143
- const pointerEvent = event;
1144
- finishDrag(pointerEvent.pointerId, pointerEvent);
1145
- }
1146
- function handleLostPointerCapture(event) {
1147
- finishDrag(event.pointerId);
1148
- }
1149
- function finishDrag(pointerId, event) {
1150
- const pointer = pointers.get(pointerId);
1151
- if (!pointer) return;
1152
- const finalState = event ? state(event, pointer, event.screenX - pointer.lastX, event.screenY - pointer.lastY) : state(pointer.lastEvent, pointer, 0, 0);
1153
- stopTracking(pointerId);
1154
- opts.onDragEnd?.(finalState);
1155
- }
1156
- function stopTracking(pointerId) {
1157
- const pointer = pointers.get(pointerId);
1158
- if (!pointer) return;
1159
- pointers.delete(pointerId);
1160
- releaseTarget(pointer.moveTarget);
1161
- try {
1162
- if (capture.hasPointerCapture?.(pointerId) === true) capture.releasePointerCapture?.(pointerId);
1163
- } catch {}
1164
- if (lockedPointerId === pointerId) {
1165
- lockedPointerId = null;
1166
- const document = globalThis.document;
1167
- document?.removeEventListener("pointerlockchange", handleLockChange);
1168
- if (document?.pointerLockElement === element) document.exitPointerLock?.();
1169
- }
1170
- if (pointers.size > 0) return;
1171
- globalThis.document?.removeEventListener("selectstart", preventSelectStart);
1172
- if (previousCursor !== void 0 && style) {
1173
- style.cursor = previousCursor;
1174
- previousCursor = void 0;
1175
- }
1176
- }
1177
- element.addEventListener("pointerdown", handlePointerDown);
1178
- return {
1179
- update: (next) => {
1180
- opts = {
1181
- ...opts,
1182
- ...next,
1183
- multiPointer
1184
- };
1185
- },
1186
- destroy: () => {
1187
- if (destroyed) return;
1188
- destroyed = true;
1189
- element.removeEventListener("pointerdown", handlePointerDown);
1190
- for (const pointerId of [...pointers.keys()]) finishDrag(pointerId);
1191
- if (style && managedStyles && --managedStyles.count === 0) {
1192
- for (const [property] of MANAGED_STYLES) {
1193
- const previous = managedStyles.previous.get(property);
1194
- if (previous?.value) style.setProperty(property, previous.value, previous.priority);
1195
- else style.removeProperty(property);
1196
- }
1197
- managedStyleStates.delete(element);
1198
- }
1199
- }
1200
- };
1201
- }
1202
- //#endregion
1203
- //#region src/number-input/stepper-drag.ts
1204
- /**
1205
- * Drag up and down on the steppers of a number input to move its value, one
1206
- * `step` every `pixels` — up raises it, as on a knob.
1207
- *
1208
- * Counted from where the drag started moving rather than added up per
1209
- * event, so rounding cannot accumulate. The start is taken on the first
1210
- * move, not on pointerdown: a stepper button acts on pointerdown, so by then
1211
- * the value may already have been nudged once, and the drag carries on from
1212
- * there.
1213
- */
1214
- function createStepperDrag(element, options) {
1215
- let opts = options;
1216
- let origin = null;
1217
- let moved = false;
1218
- /**
1219
- * Which sensitivity the drag is counting at, and where the previous event
1220
- * was — a key produces no pointer event of its own, so a change is only
1221
- * seen on the next move and has to be dated back to the one before it.
1222
- */
1223
- let factor = 1;
1224
- let previousY = 0;
1225
- const drag = createDrag(element, {
1226
- threshold: 1,
1227
- cursor: "ns-resize",
1228
- pointerLock: opts.pointerLock,
1229
- onDragStart: (state) => {
1230
- origin = null;
1231
- moved = false;
1232
- factor = selectModifier(opts.sensitivity ?? DEFAULT_DRAG_SENSITIVITY, state.event).value;
1233
- },
1234
- onDrag: (state) => {
1235
- const { y } = state;
1236
- if (!origin) {
1237
- origin = {
1238
- y,
1239
- value: opts.getValue()
1240
- };
1241
- previousY = y;
1242
- return;
1243
- }
1244
- const sensitivity = opts.sensitivity ?? DEFAULT_DRAG_SENSITIVITY;
1245
- const next = selectModifier(sensitivity, state.event).value;
1246
- if (next !== factor) {
1247
- origin = {
1248
- y: previousY,
1249
- value: opts.getValue()
1250
- };
1251
- factor = next;
1252
- }
1253
- previousY = y;
1254
- const steps = Math.round(-(y - origin.y) / (opts.pixels ?? 1));
1255
- if (steps === 0) return;
1256
- moved = true;
1257
- const step = opts.range.step ?? 1;
1258
- const amounts = mapModifier(sensitivity, (f) => ["raw", step * f]);
1259
- opts.onChange(applyDelta(origin.value, steps, amounts, opts.range, state.event));
1260
- },
1261
- onDragEnd: () => {
1262
- moved = false;
1263
- }
1264
- });
1265
- return {
1266
- update: (next) => {
1267
- opts = {
1268
- ...opts,
1269
- ...next
1270
- };
1271
- if ("pointerLock" in next) drag.update({ pointerLock: opts.pointerLock });
1272
- },
1273
- moved: () => moved,
1274
- destroy: () => drag.destroy()
1275
- };
1276
- }
1277
- //#endregion
1278
- //#region src/number-input/value.ts
1279
- /**
1280
- * The ranges a number input moves its value across, with the open ends
1281
- * filled in.
1282
- *
1283
- * A normalized amount needs a finite span even when an end is unbounded or
1284
- * clamping is off. Safe integers provide one without overflowing the span a
1285
- * scale calculates. A raw amount needs no span, so its open ends can cover
1286
- * every finite number instead of stopping at the safe-integer range.
1287
- */
1288
- function numberInputRanges({ min, max, step, scale, clampValue = true }) {
1289
- const lo = clampValue ? min : void 0;
1290
- const hi = clampValue ? max : void 0;
1291
- return {
1292
- normalized: {
1293
- min: lo ?? Number.MIN_SAFE_INTEGER,
1294
- max: hi ?? Number.MAX_SAFE_INTEGER,
1295
- step,
1296
- scale
1297
- },
1298
- raw: {
1299
- min: lo ?? -Number.MAX_VALUE,
1300
- max: hi ?? Number.MAX_VALUE,
1301
- step,
1302
- scale
1303
- }
1304
- };
1305
- }
1306
- /**
1307
- * Move a number input's value by one press of a key, a wheel notch or a
1308
- * stepper, picking the range that suits the kind of amount. See `applyDelta`.
1309
- */
1310
- function nudgeNumberInput(value, direction, options, ranges, modifiers) {
1311
- const [mode] = selectModifier(options, modifiers).value;
1312
- return applyDelta(value, direction, options, mode === "raw" ? ranges.raw : ranges.normalized, modifiers);
1313
- }
1314
- /**
1315
- * Where the value stands against the ends: whether it can go no further
1316
- * down or up, and whether it lies outside them — which only an unclamped
1317
- * input, or a value set from outside, can do.
1318
- */
1319
- function numberInputBounds(value, { min, max, clampValue = true }) {
1320
- return {
1321
- atMin: clampValue && min !== void 0 && value <= min,
1322
- atMax: clampValue && max !== void 0 && value >= max,
1323
- outOfRange: min !== void 0 && value < min || max !== void 0 && value > max
1324
- };
1325
- }
1326
- /**
1327
- * The value typed text commits to, or `null` when there is no number in it.
1328
- *
1329
- * Text with no number is not a value: the input should go back to what it
1330
- * was showing rather than commit a zero the user never typed. What is read
1331
- * is clamped here and not while typing, since clamping as the user types
1332
- * would make "1500" impossible to enter into an input whose max is 100.
1333
- */
1334
- function commitNumberInputText(text, parse, { min, max, clampValue = true }) {
1335
- const parsed = parse(text);
1336
- if (!Number.isFinite(parsed)) return null;
1337
- let committed = parsed;
1338
- if (clampValue && min !== void 0) committed = Math.max(committed, min);
1339
- if (clampValue && max !== void 0) committed = Math.min(committed, max);
1340
- return committed;
1341
- }
1342
- //#endregion
1343
- //#region src/number-input/text.ts
1344
- /**
1345
- * Reading a number out of the text of a number input, and keeping the caret
1346
- * in place while the number under it changes.
1347
- *
1348
- * The text is whatever `format` made of the value — `"440 Hz"`, `"-6.0 dB"` —
1349
- * or a half-typed entry, so none of this assumes the text is a number alone.
1350
- */
1351
- /** The signs a number can carry. U+2212 is what some `Intl.NumberFormat` locales write. */
1352
- const SIGNS = "+-−";
1353
- /**
1354
- * Where the number is in the text: from its first digit to its last, with the
1355
- * sign and the decimal point in front of it. Whatever is left on either side
1356
- * is taken for the unit, so it does not matter whether a space separates them,
1357
- * or what the number looks like — `+6.0`, `1e+21`, `1,000` and `1:30` are each
1358
- * one number. `null` when the text has no digit at all.
1359
- */
1360
- function numberSpan(text) {
1361
- const first = text.search(/\d/);
1362
- if (first === -1) return null;
1363
- let start = first;
1364
- if (text[start - 1] === ".") start -= 1;
1365
- if (start > 0 && SIGNS.includes(text[start - 1])) start -= 1;
1366
- return {
1367
- start,
1368
- end: text.search(/\d\D*$/) + 1
1369
- };
1370
- }
1371
- /** A plain number, and nothing else: no grouping, no other separators. */
1372
- const PLAIN_NUMBER = /^[+\-\u2212]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+\-\u2212]?\d+)?$/;
1373
- /**
1374
- * The number in the text, with the unit after it ignored: the default `parse`
1375
- * of a number input.
1376
- *
1377
- * `NaN`, which leaves the value alone, whenever the number cannot be read
1378
- * safely, rather than a part of it: text with no number, a number that is not
1379
- * a plain one (`1,000` would otherwise read as 1, and `1:30` as 1), and text
1380
- * with something in front of the number, which can change what it means (the
1381
- * `L` of a pan reading `L 30`). A `format` that writes any of those needs its
1382
- * own `parse`.
1383
- */
1384
- function parseNumberText(text) {
1385
- const span = numberSpan(text);
1386
- if (!span || text.slice(0, span.start).trim() !== "") return NaN;
1387
- const number = text.slice(span.start, span.end);
1388
- return PLAIN_NUMBER.test(number) ? Number(number.replace(/\u2212/g, "-")) : NaN;
1389
- }
1390
- /**
1391
- * The index the caret is measured against: the decimal point, or where one
1392
- * would go if the number has none — in front of an exponent, if there is one.
1393
- *
1394
- * Measuring from an end instead would slide the caret across a digit whenever
1395
- * the number changed length — `9.9` to `10.0` gains a character in front, `10`
1396
- * to `9` loses one, and so does `9e+9` to `1e+10` behind — which is exactly
1397
- * what stepping does.
1398
- */
1399
- function decimalAnchor(text, span) {
1400
- const number = text.slice(span.start, span.end);
1401
- const exponent = number.search(/[eE][+\-\u2212]?\d/);
1402
- const mantissa = exponent === -1 ? number : number.slice(0, exponent);
1403
- const dot = mantissa.indexOf(".");
1404
- return span.start + (dot === -1 ? mantissa.length : dot);
1405
- }
1406
- const NO_NUMBER = {
1407
- start: 0,
1408
- end: 0
1409
- };
1410
- /**
1411
- * Where the caret is, relative to the decimal point, so that it can be put
1412
- * back at the same digit once the value has changed. See
1413
- * {@link caretAtDecimalOffset}.
1414
- */
1415
- function caretDecimalOffset(text, caret) {
1416
- return caret - decimalAnchor(text, numberSpan(text) ?? NO_NUMBER);
1417
- }
1418
- /**
1419
- * The caret position `offset` characters from the decimal point of the new
1420
- * text, kept within the number.
1421
- *
1422
- * @example
1423
- * // The caret sits in front of the point of "9.9" when ArrowUp turns it
1424
- * // into "10.0"
1425
- * const offset = caretDecimalOffset('9.9', 1) // 0
1426
- * caretAtDecimalOffset('10.0', offset) // 2: still in front of the point
1427
- */
1428
- function caretAtDecimalOffset(text, offset) {
1429
- const span = numberSpan(text) ?? NO_NUMBER;
1430
- const place = decimalAnchor(text, span) + offset;
1431
- return Math.max(span.start, Math.min(place, span.end));
1432
- }
1433
- //#endregion
1434
- //#region src/options/replace.ts
1435
- /**
1436
- * The `update()` argument that leaves an instance with exactly `next` as its
1437
- * options.
1438
- *
1439
- * `update()` merges into what the instance has, which suits a wrapper that
1440
- * pushes one setting at a time. A wrapper handed the whole new set instead —
1441
- * a Svelte action, a Vue composable — has to clear what the new set no longer
1442
- * carries, or a handler taken away, or an option left to its default, keeps
1443
- * working.
1444
- *
1445
- * @example
1446
- * instance.update(replaceOptions(previous, next))
1447
- */
1448
- function replaceOptions(previous, next) {
1449
- return {
1450
- ...Object.fromEntries(Object.keys(previous ?? {}).map((key) => [key, void 0])),
1451
- ...next
1452
- };
1453
- }
1454
- //#endregion
1455
- //#region src/piano/layout.ts
1456
- /**
1457
- * `[noteRange.first, noteRange.first + 1, ..., noteRange.last]`
1458
- */
1459
- function getNoteRangeArray(noteRange) {
1460
- return Array.from({ length: noteRange.last - noteRange.first + 1 }, (_, i) => i + noteRange.first);
1461
- }
1462
- const DEFAULT_KEY_GAP = 1;
1463
- const DEFAULT_BLACK_KEY_WIDTH_RATIO = .65;
1464
- const DEFAULT_BLACK_KEY_HEIGHT_RATIO = .6;
1465
- /**
1466
- * How many white keys sit at or before each pitch class, counting from C.
1467
- *
1468
- * A black key shares the number of the white key to its left plus one, which
1469
- * puts it on the boundary between the two; {@link notePosition} then shifts it
1470
- * back by half its width to centre it there.
1471
- */
1472
- const whiteKeysBefore = {
1473
- C: 0,
1474
- "C#": 1,
1475
- D: 1,
1476
- "D#": 2,
1477
- E: 2,
1478
- F: 3,
1479
- "F#": 4,
1480
- G: 4,
1481
- "G#": 5,
1482
- A: 5,
1483
- "A#": 6,
1484
- B: 6
1485
- };
1486
- /** Width of a black key in pixels. */
1487
- function blackKeyWidth(layout) {
1488
- return layout.whiteKeyWidth * (layout.blackKeyWidthRatio ?? DEFAULT_BLACK_KEY_WIDTH_RATIO);
1489
- }
1490
- function rawNotePosition(note, layout) {
1491
- const slot = layout.whiteKeyWidth + (layout.keyGap ?? DEFAULT_KEY_GAP);
1492
- const target = noteKey(note);
1493
- const first = noteKey(layout.noteRange.first);
1494
- const octave = Math.floor((note - layout.noteRange.first) / 12);
1495
- const octaveOffset = noteKeys.indexOf(first) > noteKeys.indexOf(target) ? 1 : 0;
1496
- const whiteKeysIn = whiteKeysBefore[target] - whiteKeysBefore[first] + (octave + octaveOffset) * 7;
1497
- return isBlackKey(note) ? whiteKeysIn * slot - blackKeyWidth(layout) / 2 : whiteKeysIn * slot;
1498
- }
1499
- function pianoBounds(layout) {
1500
- const notes = getNoteRangeArray(layout.noteRange);
1501
- if (notes.length === 0) return {
1502
- left: 0,
1503
- right: 0
1504
- };
1505
- let left = Infinity;
1506
- let right = -Infinity;
1507
- const whiteWidth = layout.whiteKeyWidth + (layout.keyGap ?? DEFAULT_KEY_GAP);
1508
- for (const note of notes) {
1509
- const noteLeft = rawNotePosition(note, layout);
1510
- const width = isBlackKey(note) ? blackKeyWidth(layout) : whiteWidth;
1511
- left = Math.min(left, noteLeft);
1512
- right = Math.max(right, noteLeft + width);
1513
- }
1514
- return {
1515
- left,
1516
- right
1517
- };
1518
- }
1519
- /** Width of the whole keyboard in pixels. */
1520
- function pianoWidth(layout) {
1521
- const { left, right } = pianoBounds(layout);
1522
- return right - left;
1523
- }
1524
- /**
1525
- * Offset of the left edge of a key from the left edge of the keyboard, in
1526
- * pixels.
1527
- *
1528
- * Notes outside `noteRange` are placed too, so the value is negative below
1529
- * `noteRange.first`.
1530
- */
1531
- function notePosition(note, layout) {
1532
- return rawNotePosition(note, layout) - pianoBounds(layout).left;
1533
- }
1534
- /**
1535
- * The note drawn at a point, or null where there is none.
1536
- *
1537
- * Black keys are tested first, so they win where they overlap a white one. A
1538
- * white key covers its gap as well as its width, so the whole width of the
1539
- * keyboard belongs to some key and a click cannot fall between two.
1540
- *
1541
- * @param x offset from the left edge of the keyboard, in pixels
1542
- * @param y offset from its top edge, in pixels
1543
- * @param height height of the keyboard, in pixels
1544
- */
1545
- function noteAt(x, y, height, layout) {
1546
- if (x < 0 || x >= pianoWidth(layout) || y < 0 || y >= height) return null;
1547
- const notes = getNoteRangeArray(layout.noteRange);
1548
- if (y < height * (layout.blackKeyHeightRatio ?? DEFAULT_BLACK_KEY_HEIGHT_RATIO)) for (const note of notes) {
1549
- if (isWhiteKey(note)) continue;
1550
- const left = notePosition(note, layout);
1551
- if (left <= x && x < left + blackKeyWidth(layout)) return note;
1552
- }
1553
- const slot = layout.whiteKeyWidth + (layout.keyGap ?? DEFAULT_KEY_GAP);
1554
- for (const note of notes) {
1555
- if (isBlackKey(note)) continue;
1556
- const left = notePosition(note, layout);
1557
- if (left <= x && x < left + slot) return note;
1558
- }
1559
- return null;
1560
- }
1561
- /**
1562
- * The white key width that makes the keyboard exactly `width` wide, for a
1563
- * keyboard that follows the size of its container.
1564
- *
1565
- * Solved from {@link pianoWidth} rather than by dividing among the white
1566
- * keys, so that a range that starts or ends on a black key — which sticks out
1567
- * by a fraction of a white key — still fills the container. The width grows
1568
- * linearly with the white key width, so two samples pin it down.
1569
- */
1570
- function fitWhiteKeyWidth(width, layout) {
1571
- const at = (whiteKeyWidth) => pianoWidth({
1572
- ...layout,
1573
- whiteKeyWidth
1574
- });
1575
- const slope = at(2) - at(1);
1576
- if (slope <= 0) return 0;
1577
- return (width - (at(1) - slope)) / slope;
1578
- }
1579
- //#endregion
1580
674
  //#region src/piano/shortcuts.ts
1581
675
  /**
1582
676
  * Ready-made keyboard layouts. Both assume `noteRange.first` is a C.
@@ -1823,285 +917,6 @@ function createPianoInput(element, options) {
1823
917
  };
1824
918
  }
1825
919
  //#endregion
1826
- //#region src/selection/box.ts
1827
- function rectOf(from, to) {
1828
- return {
1829
- x: Math.min(from[0], to[0]),
1830
- y: Math.min(from[1], to[1]),
1831
- width: Math.abs(to[0] - from[0]),
1832
- height: Math.abs(to[1] - from[1])
1833
- };
1834
- }
1835
- /** Whether the box covers the point, edges included. */
1836
- function selectionBoxCovers(box, [x, y]) {
1837
- return x >= box.x && x <= box.x + box.width && y >= box.y && y <= box.y + box.height;
1838
- }
1839
- /**
1840
- * Selecting by dragging a box over a set of items.
1841
- *
1842
- * The drag itself is not here: the caller owns the pointer, and reports where
1843
- * it went in the same 0..1 space the items are given in.
1844
- */
1845
- function createSelectionBox(options) {
1846
- let opts = options;
1847
- let drag = null;
1848
- let box = null;
1849
- function setBox(next) {
1850
- box = next;
1851
- opts.onBoxChange?.(next);
1852
- }
1853
- function apply(rect, base) {
1854
- const inside = [];
1855
- for (const [id, at] of opts.items()) if (selectionBoxCovers(rect, at) && !base.includes(id)) inside.push(id);
1856
- opts.onSelectionChange?.([...base, ...inside]);
1857
- }
1858
- return {
1859
- update: (next) => {
1860
- opts = {
1861
- ...opts,
1862
- ...next
1863
- };
1864
- },
1865
- begin: (at, { additive = false, selection = [] } = {}) => {
1866
- drag = {
1867
- from: at,
1868
- base: additive ? [...selection] : []
1869
- };
1870
- setBox(rectOf(at, at));
1871
- if (!additive) opts.onSelectionChange?.([]);
1872
- },
1873
- move: (to) => {
1874
- if (!drag) return;
1875
- const rect = rectOf(drag.from, to);
1876
- setBox(rect);
1877
- apply(rect, drag.base);
1878
- },
1879
- end: () => {
1880
- const running = drag !== null;
1881
- drag = null;
1882
- if (box !== null) setBox(null);
1883
- return running;
1884
- },
1885
- box: () => box,
1886
- destroy: () => {
1887
- drag = null;
1888
- box = null;
1889
- }
1890
- };
1891
- }
1892
- //#endregion
1893
- //#region src/points-editor/index.ts
1894
- /**
1895
- * A point's value is its position in the editor, so its range is the editor:
1896
- * no scaling, and no rounding to a step.
1897
- */
1898
- const POINT_AXIS = {
1899
- min: 0,
1900
- max: 1
1901
- };
1902
- /**
1903
- * How much one wheel notch moves a point by default: a hundredth of the
1904
- * editor, whatever its pixel size.
1905
- */
1906
- const POINTS_EDITOR_DEFAULT_WHEEL = ["normalized", .01];
1907
- /**
1908
- * How much one arrow key press moves a point by default. Shift is the
1909
- * fine-adjustment key everywhere else, so it is bound here too — but only on
1910
- * the keyboard. On the wheel it already means the x axis, and browsers hand
1911
- * shift+wheel over as horizontal scrolling anyway.
1912
- */
1913
- const POINTS_EDITOR_DEFAULT_KEYBOARD = {
1914
- default: ["normalized", .01],
1915
- shift: ["normalized", .001]
1916
- };
1917
- /** Keep a point within its range. An axis left out runs from 0 to 1. */
1918
- function clampPoint(point, min, max) {
1919
- return {
1920
- x: clamp(point.x, min?.x ?? 0, max?.x ?? 1),
1921
- y: clamp(point.y, min?.y ?? 0, max?.y ?? 1)
1922
- };
1923
- }
1924
- const EMPTY = [];
1925
- /**
1926
- * How far a group may move before something in it leaves its range.
1927
- *
1928
- * Clamping each point on its own would break the shape of the selection: the
1929
- * one that reached the edge would stop while the rest carried on. One amount
1930
- * for all of them means the whole selection stops together.
1931
- */
1932
- function allowedDelta(delta, entries) {
1933
- let loX = -Infinity;
1934
- let hiX = Infinity;
1935
- let loY = -Infinity;
1936
- let hiY = Infinity;
1937
- for (const { start, point } of entries) {
1938
- if (point.readonly) continue;
1939
- loX = Math.max(loX, (point.min?.x ?? 0) - start.x);
1940
- hiX = Math.min(hiX, (point.max?.x ?? 1) - start.x);
1941
- loY = Math.max(loY, (point.min?.y ?? 0) - start.y);
1942
- hiY = Math.min(hiY, (point.max?.y ?? 1) - start.y);
1943
- }
1944
- return {
1945
- x: hiX < loX ? 0 : clamp(delta.x, loX, hiX),
1946
- y: hiY < loY ? 0 : clamp(delta.y, loY, hiY)
1947
- };
1948
- }
1949
- /**
1950
- * The selection and the moves of a points editor: which points a press or a
1951
- * box selects, and how a selection moves as one.
1952
- *
1953
- * The points stay with the wrapper, which registers each one; the editor only
1954
- * reads them when it needs to, so a point's value can change on every frame
1955
- * of a drag without anything being re-registered.
1956
- */
1957
- function createPointsEditor(options = {}) {
1958
- let opts = options;
1959
- const points = /* @__PURE__ */ new Map();
1960
- /** What the current drag picked up, and where those points started. */
1961
- let dragged = [];
1962
- const selection = () => opts.selectable ? opts.selection ?? EMPTY : EMPTY;
1963
- function changeSelection(next) {
1964
- opts = {
1965
- ...opts,
1966
- selection: next
1967
- };
1968
- opts.onSelectionChange?.(next);
1969
- }
1970
- function snapshot(ids) {
1971
- return ids.flatMap((id) => {
1972
- const point = points.get(id)?.();
1973
- return point ? [{
1974
- id,
1975
- start: { ...point.value }
1976
- }] : [];
1977
- });
1978
- }
1979
- function moveFrom(entries, delta) {
1980
- const withPoint = entries.flatMap((entry) => {
1981
- const point = points.get(entry.id)?.();
1982
- return point ? [{
1983
- ...entry,
1984
- point
1985
- }] : [];
1986
- });
1987
- const allowed = allowedDelta(delta, withPoint);
1988
- for (const { start, point } of withPoint) {
1989
- if (point.readonly) continue;
1990
- point.onChange?.({
1991
- x: toPrecision(start.x + allowed.x),
1992
- y: toPrecision(start.y + allowed.y)
1993
- });
1994
- }
1995
- }
1996
- function nudgeSelection(id, delta) {
1997
- const current = selection();
1998
- moveFrom(snapshot(current.includes(id) ? current : [id]), delta);
1999
- }
2000
- function nudgePoint(id, axis, direction, option, modifiers) {
2001
- const point = points.get(id)?.();
2002
- if (!point) return;
2003
- const { value } = point;
2004
- const next = applyDelta(value[axis], direction, option, POINT_AXIS, modifiers);
2005
- nudgeSelection(id, {
2006
- x: axis === "x" ? next - value.x : 0,
2007
- y: axis === "y" ? next - value.y : 0
2008
- });
2009
- }
2010
- const box = createSelectionBox({
2011
- *items() {
2012
- for (const [id, read] of points) {
2013
- const { x, y } = read().value;
2014
- yield [id, [x, y]];
2015
- }
2016
- },
2017
- onBoxChange: (rect) => opts.onSelectionBoxChange?.(rect),
2018
- onSelectionChange: changeSelection
2019
- });
2020
- return {
2021
- update: (next) => {
2022
- opts = {
2023
- ...opts,
2024
- ...next
2025
- };
2026
- },
2027
- registerPoint: (id, read) => {
2028
- points.set(id, read);
2029
- return () => {
2030
- if (points.get(id) === read) points.delete(id);
2031
- };
2032
- },
2033
- isPointElement: (element) => {
2034
- if (!element) return false;
2035
- for (const read of points.values()) if (read().element?.contains(element)) return true;
2036
- return false;
2037
- },
2038
- beginPointDrag: (id, modifiers) => {
2039
- if (!opts.selectable) {
2040
- dragged = snapshot([id]);
2041
- return;
2042
- }
2043
- const current = selection();
2044
- const additive = modifiers.ctrlKey || modifiers.metaKey;
2045
- let next;
2046
- if (additive) next = current.includes(id) ? current.filter((x) => x !== id) : [...current, id];
2047
- else if (current.includes(id)) next = current;
2048
- else next = [id];
2049
- changeSelection([...next]);
2050
- dragged = next.includes(id) ? snapshot(next) : [];
2051
- },
2052
- movePointDrag: (delta) => moveFrom(dragged, delta),
2053
- nudgeSelection,
2054
- nudgePoint,
2055
- nudgeFocusedPoint: (axis, direction, modifiers) => {
2056
- for (const [id, read] of points) {
2057
- const { element, wheel, readonly, onChange } = read();
2058
- const active = element?.ownerDocument.activeElement;
2059
- if (!active || !element?.contains(active)) continue;
2060
- if (!wheel || readonly || !onChange) return false;
2061
- nudgePoint(id, axis, direction, wheel, modifiers);
2062
- return true;
2063
- }
2064
- return false;
2065
- },
2066
- beginSelectionBox: (at, modifiers) => {
2067
- if (!opts.selectable) return;
2068
- box.begin([at.x, at.y], {
2069
- additive: modifiers.ctrlKey || modifiers.metaKey,
2070
- selection: selection()
2071
- });
2072
- },
2073
- moveSelectionBox: (to) => box.move([to.x, to.y]),
2074
- endSelectionBox: () => {
2075
- if (!box.end()) return;
2076
- const [first] = selection();
2077
- const element = first ? points.get(first)?.().element : null;
2078
- if (element && "focus" in element) element.focus();
2079
- },
2080
- destroy: () => {
2081
- box.destroy();
2082
- dragged = [];
2083
- }
2084
- };
2085
- }
2086
- //#endregion
2087
- //#region src/xy.ts
2088
- function isPair(value) {
2089
- return Array.isArray(value);
2090
- }
2091
- /**
2092
- * Spread a setting that may have been given as a single value.
2093
- *
2094
- * The parameter is written out rather than taken as `XYInput<T>`: a
2095
- * conditional type cannot be narrowed, so the constraint stays where it is
2096
- * declared and this takes both forms.
2097
- *
2098
- * The pair is copied rather than passed along, so that the result is a tuple
2099
- * the caller owns even when a readonly one was given.
2100
- */
2101
- function toXY(value) {
2102
- return isPair(value) ? [value[0], value[1]] : [value, value];
2103
- }
2104
- //#endregion
2105
920
  //#region src/pointer/drag-value.ts
2106
921
  /**
2107
922
  * Map the pointer onto the bounding rect of an element: the value *is* the
@@ -2222,8 +1037,8 @@ function createDragValue(element, options) {
2222
1037
  if (!position) return;
2223
1038
  active = true;
2224
1039
  lastValue = valueOf(position);
2225
- if (opts.updateOnPointerDown) opts.onChange?.(lastValue, state);
2226
1040
  opts.onDragStart?.(lastValue, state);
1041
+ if (opts.updateOnPointerDown) opts.onChange?.(lastValue, state);
2227
1042
  },
2228
1043
  onDrag: (state) => {
2229
1044
  if (!active) return;
@@ -2336,18 +1151,15 @@ function createLongPress(options) {
2336
1151
  * The listener is registered with `passive: false` so that the handler can call
2337
1152
  * `preventDefault()` to stop the page from scrolling.
2338
1153
  */
2339
- function createWheel(element, onWheel, options = {}) {
2340
- let opts = {
2341
- ...options,
2342
- onWheel
2343
- };
1154
+ function createWheel(element, options) {
1155
+ let opts = options;
2344
1156
  function hasFocus() {
2345
1157
  const active = element.ownerDocument?.activeElement;
2346
1158
  return !!active && element.contains(active);
2347
1159
  }
2348
1160
  const handler = (event) => {
2349
1161
  if (opts.requireFocus && !hasFocus()) return;
2350
- opts.onWheel?.(event);
1162
+ opts.onWheel(event);
2351
1163
  };
2352
1164
  element.addEventListener("wheel", handler, { passive: false });
2353
1165
  return {
@@ -2377,91 +1189,6 @@ function valuePercent(value, { min, max, scale = linearScale }, reversed = false
2377
1189
  return toFixed((reversed ? 1 - normalized : normalized) * 100);
2378
1190
  }
2379
1191
  //#endregion
2380
- //#region src/slider/decimal-digits.ts
2381
- /**
2382
- * How many digits a number carries after the decimal point.
2383
- *
2384
- * `Slider.Marks` builds its labels by multiplying an interval, which leaves
2385
- * binary debris in the last digits (`0.1 * 3` is `0.30000000000000004`). The
2386
- * count is what tells `toFixed` how far to round that back.
2387
- *
2388
- * The exponent form has to be handled separately: `String(1e-7)` is `'1e-7'`,
2389
- * which has no decimal point at all, so reading the text after the point
2390
- * reports no digits and the interval rounds away to whole numbers.
2391
- */
2392
- function decimalDigits(x) {
2393
- if (!Number.isFinite(x)) return 0;
2394
- const text = String(x);
2395
- const e = text.indexOf("e");
2396
- if (e === -1) return text.split(".")[1]?.length ?? 0;
2397
- const fraction = text.slice(0, e).split(".")[1]?.length ?? 0;
2398
- return Math.max(0, fraction - Number(text.slice(e + 1)));
2399
- }
2400
- //#endregion
2401
- //#region src/slider/marks.ts
2402
- /**
2403
- * The marks `options` asks for between `min` and `max`, in ascending order.
2404
- *
2405
- * Each value is a whole multiple of the interval, rounded to the digits the
2406
- * interval has: stepping by 0.1 would otherwise put binary debris in the
2407
- * labels (`0.1 * 3` is `0.30000000000000004`).
2408
- */
2409
- function sliderMarks(options, min, max, step) {
2410
- const { per, mark = true, label = true } = typeof options === "object" ? options : { per: options };
2411
- const optionsList = [];
2412
- const interval = per === "step" ? step : per;
2413
- const count = Math.floor(max / interval) - Math.ceil(min / interval) + 1;
2414
- for (let i = 0; i < count; i++) {
2415
- const value = toFixed(interval * (Math.ceil(min / interval) + i), decimalDigits(interval));
2416
- optionsList.push({
2417
- value,
2418
- mark,
2419
- label
2420
- });
2421
- }
2422
- return optionsList;
2423
- }
2424
- //#endregion
2425
- //#region src/style.ts
2426
- /**
2427
- * A number as a CSS length, for a custom property.
2428
- *
2429
- * A custom property takes whatever text it is given, so `--size: 50` comes out
2430
- * as the invalid `50` rather than `50px`. React appends `px` to a bare number
2431
- * only for the properties it knows take a length, and a custom property is
2432
- * never one of them; Vue and Svelte append nothing at all. Anything already a
2433
- * string is passed through, so `'3rem'` and `'100%'` still work.
2434
- */
2435
- function cssLength(value) {
2436
- return typeof value === "number" ? `${value}px` : value;
2437
- }
2438
- /**
2439
- * Take an element out of sight while leaving it in the accessibility tree and
2440
- * in the tab order.
2441
- *
2442
- * `display: none` and `visibility: hidden` would remove it from both, and the
2443
- * native control underneath a headless component is what carries the ARIA and
2444
- * the keyboard behaviour. `pointer-events: none` is safe because nothing is
2445
- * ever clicked here directly: a `<label>` forwards its click, and a drag is
2446
- * handled by the part that is visible.
2447
- *
2448
- * Every value is a string with its unit, so the object can be handed to any
2449
- * framework's `style` binding as it is.
2450
- */
2451
- const visuallyHiddenStyle = {
2452
- position: "absolute",
2453
- width: "1px",
2454
- height: "1px",
2455
- padding: "0",
2456
- margin: "-1px",
2457
- overflow: "hidden",
2458
- clip: "rect(0, 0, 0, 0)",
2459
- clipPath: "inset(50%)",
2460
- whiteSpace: "nowrap",
2461
- border: "0",
2462
- pointerEvents: "none"
2463
- };
2464
- //#endregion
2465
- export { DEFAULT_DRAG_SENSITIVITY, DEFAULT_KEYBOARD_OPTIONS, DEFAULT_WHEEL_OPTIONS, KNOB_VIEWBOX_SIZE, NOT_SUPPORTED, PERMISSION_DENIED, PITCH_BEND_CENTER, POINTS_EDITOR_DEFAULT_KEYBOARD, POINTS_EDITOR_DEFAULT_WHEEL, POINT_AXIS, SHORTCUTS, UNAVAILABLE, applyDelta, arrowKeyDirection, arrowKeyMove, blackKeyWidth, caretAtDecimalOffset, caretDecimalOffset, checkSteps, clampPoint, commitNumberInputText, createAnimationCanvas, createDrag, createDragValue, createDropZone, createLongPress, createMIDIAccess, createMIDIInput, createMIDIMessage, createPianoInput, createPointsEditor, createSelectionBox, createStepperDrag, createWheel, cssLength, drawingState, elementMapping, fitWhiteKeyWidth, getNoteRangeArray, isArrowKey, isDrawingState, knobAngles, knobArcPath, knobArcPoint, knobArcRadius, mapModifier, matchesAccept, noteAt, notePosition, nudgeNumberInput, numberInputBounds, numberInputRanges, numberSpan, parseNumberText, partitionByAccept, pianoWidth, relativeMapping, replaceOptions, selectModifier, selectionBoxCovers, sliderMarks, toXY, valuePercent, visuallyHiddenStyle, wheelDirection, wheelMove };
1192
+ export { DEFAULT_DRAG_SENSITIVITY, DEFAULT_KEYBOARD_OPTIONS, DEFAULT_WHEEL_OPTIONS, KNOB_VIEWBOX_SIZE, SHORTCUTS, createAnimationCanvas, createChangeGesture, createDrag, createDragValue, createDropZone, createLongPress, createMIDIAccess, createMIDIInput, createMIDIMessage, createPianoInput, createPointsEditor, createWheel, elementMapping, knobAngles, knobArcPath, knobArcRadius, notePosition, relativeMapping, valuePercent };
2466
1193
 
2467
1194
  //# sourceMappingURL=index.js.map