@tremolo-ui/dom 0.4.0 → 0.5.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.cjs +541 -55
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +366 -12
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.ts +366 -12
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +534 -56
- package/dist/index.js.map +1 -1
- package/package.json +4 -1
- package/src/canvas/animation.ts +304 -0
- package/src/canvas/context.ts +81 -0
- package/src/index.ts +37 -1
- package/src/piano/input.ts +185 -0
- package/src/pointer/drag.ts +137 -57
- package/src/pointer/dragValue.ts +229 -0
- package/src/pointer/wheel.ts +34 -1
- package/src/xy.ts +38 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/midi/access.ts","../src/midi/message.ts","../src/midi/input.ts","../src/pointer/drag.ts","../src/pointer/wheel.ts"],"sourcesContent":["/** @private */\nexport const PERMISSION_DENIED = 'PERMISSION_DENIED'\n/** @private */\nexport const NOT_SUPPORTED = 'NOT_SUPPORTED'\n\n/** @private */\nexport type MIDIAccessError = typeof PERMISSION_DENIED | typeof NOT_SUPPORTED\n\nexport type MIDIAccessState = {\n readonly midiAccess: MIDIAccess | null\n readonly error: MIDIAccessError | null\n}\n\nconst INITIAL_STATE: MIDIAccessState = {\n midiAccess: null,\n error: null,\n}\n\nexport interface MIDIAccessInstance {\n /** Request MIDI access. Safe to call more than once. */\n request: () => void\n getState: () => MIDIAccessState\n /** Snapshot for server side rendering. Always the initial state. */\n getServerState: () => MIDIAccessState\n /** @returns unsubscribe function */\n subscribe: (listener: () => void) => () => void\n destroy: () => void\n}\n\n/**\n * Request MIDI access in the browser.\n *\n * The returned instance holds the state and notifies subscribers when it changes,\n * so it can be consumed from any framework.\n */\nexport function createMIDIAccess(): MIDIAccessInstance {\n let state = INITIAL_STATE\n let destroyed = false\n const listeners = new Set<() => void>()\n\n function setState(next: MIDIAccessState) {\n state = next\n for (const listener of listeners) listener()\n }\n\n function request() {\n if (destroyed) return\n if (typeof navigator === 'undefined' || !navigator.requestMIDIAccess) {\n setState({ ...state, error: NOT_SUPPORTED })\n return\n }\n navigator\n .requestMIDIAccess()\n .then((access) => {\n if (destroyed) return\n setState({ midiAccess: access, error: null })\n })\n .catch(() => {\n if (destroyed) return\n setState({ ...state, error: PERMISSION_DENIED })\n })\n }\n\n return {\n request,\n getState: () => state,\n getServerState: () => INITIAL_STATE,\n subscribe: (listener) => {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n destroy: () => {\n destroyed = true\n listeners.clear()\n },\n }\n}\n","export interface MIDIMessageInstance {\n destroy: () => void\n}\n\n/**\n * Listen to raw `midimessage` events on every input of a MIDIAccess.\n *\n * Use this when you need more detail than {@link createMIDIInput} provides.\n */\nexport function createMIDIMessage(\n midiAccess: MIDIAccess | null,\n onMIDIMessage: (event: MIDIMessageEvent) => void,\n): MIDIMessageInstance {\n if (!midiAccess) {\n return { destroy: () => {} }\n }\n\n const inputs = [...midiAccess.inputs.values()]\n for (const input of inputs) {\n input.addEventListener('midimessage', onMIDIMessage)\n }\n\n return {\n destroy: () => {\n for (const input of inputs) {\n input.removeEventListener('midimessage', onMIDIMessage)\n }\n },\n }\n}\n","import { createMIDIMessage, type MIDIMessageInstance } from './message'\n\nconst MIDI_EVENT_TO_NUMBER = {\n NOTE_ON: 0x90,\n NOTE_OFF: 0x80,\n PITCH_BEND: 0xe0,\n}\n\nexport type MIDIInputHandlers = {\n onNoteOnEvent?: (note: number, velocity: number) => void\n onNoteOffEvent?: (note: number) => void\n onPitchBendEvent?: (msb: number, lsb: number) => void\n}\n\nexport type MIDIInputInstance = MIDIMessageInstance\n\n/**\n * Handle note on/off and pitch bend events. To be used with {@link createMIDIAccess}.\n * Internally uses {@link createMIDIMessage}.\n */\nexport function createMIDIInput(\n midiAccess: MIDIAccess | null,\n { onNoteOnEvent, onNoteOffEvent, onPitchBendEvent }: MIDIInputHandlers,\n): MIDIInputInstance {\n return createMIDIMessage(midiAccess, (event) => {\n if (!event.data) return\n // event.data[0] ... command\n // event.data[1] ... note, MSB (Most Significant Byte)\n // event.data[2] ... velocity, LSB (Least Significant Byte)\n const kind = event.data[0] & 0xf0\n\n if (\n kind == MIDI_EVENT_TO_NUMBER.NOTE_OFF ||\n (kind == MIDI_EVENT_TO_NUMBER.NOTE_ON && event.data[2] == 0)\n ) {\n onNoteOffEvent?.(event.data[1])\n } else if (kind == MIDI_EVENT_TO_NUMBER.NOTE_ON) {\n onNoteOnEvent?.(event.data[1], event.data[2])\n } else if (kind == MIDI_EVENT_TO_NUMBER.PITCH_BEND) {\n onPitchBendEvent?.(event.data[1], event.data[2])\n }\n })\n}\n","export type DragState = {\n /** Total movement from the drag start, in screen coordinates. */\n x: number\n y: number\n /** Movement since the previous event, in screen coordinates. */\n deltaX: number\n deltaY: number\n /** Pointer position in viewport coordinates. */\n clientX: number\n clientY: number\n event: PointerEvent\n}\n\nexport type DragOptions = {\n /**\n * Minimum movement in pixels before `onDrag` fires.\n * Prevents `onDrag` from firing on, for example, a double click.\n * Values below 1 are clamped to 1.\n *\n * @default 1\n */\n threshold?: number\n\n /**\n * CSS cursor to show while dragging. Applied to the element itself: pointer\n * capture keeps it in effect even once the pointer leaves the element, so\n * there is no need to touch the document.\n */\n cursor?: string\n\n onDragStart?: (state: DragState) => void\n onDrag?: (state: DragState) => void\n onDragEnd?: (state: DragState) => void\n}\n\nexport interface DragInstance {\n destroy: () => void\n}\n\n/**\n * Applied to the element for the lifetime of the instance.\n *\n * `touch-action` stops touch dragging from scrolling the page. That alone makes\n * the browser treat a long press as the start of a text selection, so selection\n * and the iOS callout are suppressed here too.\n */\nconst MANAGED_STYLES = [\n ['touch-action', 'none'],\n ['user-select', 'none'],\n ['-webkit-user-select', 'none'],\n ['-webkit-touch-callout', 'none'],\n] as const\n\ntype CaptureTarget = {\n setPointerCapture?: (pointerId: number) => void\n releasePointerCapture?: (pointerId: number) => void\n hasPointerCapture?: (pointerId: number) => boolean\n}\n\n/**\n * Track a pointer drag on an element.\n *\n * Uses Pointer Events only, and pointer capture so that the drag keeps working\n * once the pointer leaves the element. For the lifetime of the instance the\n * element gets `touch-action: none` so that touch dragging does not scroll the\n * page, plus `user-select: none` so that a long press does not start a text\n * selection instead.\n */\nexport function createDrag(\n element: Element,\n {\n threshold: _threshold = 1,\n cursor,\n onDragStart,\n onDrag,\n onDragEnd,\n }: DragOptions = {},\n): DragInstance {\n const threshold = Math.max(_threshold, 1)\n const capture = element as CaptureTarget\n const style = (element as Partial<HTMLElement>).style\n\n const previousStyles = new Map<string, string>()\n if (style) {\n for (const [property, value] of MANAGED_STYLES) {\n previousStyles.set(property, style.getPropertyValue(property))\n style.setProperty(property, value)\n }\n }\n\n let pointerId: number | null = null\n /** Where the listeners for the current drag live. */\n let moveTarget: EventTarget | null = null\n let startX = 0\n let startY = 0\n let lastX = 0\n let lastY = 0\n let previousCursor: string | undefined\n\n function state(\n event: PointerEvent,\n deltaX: number,\n deltaY: number,\n ): DragState {\n return {\n x: event.screenX - startX,\n y: event.screenY - startY,\n deltaX,\n deltaY,\n clientX: event.clientX,\n clientY: event.clientY,\n event,\n }\n }\n\n /**\n * `user-select: none` only makes the element's own text unselectable; the\n * browser still starts a selection on long press and grabs whatever text it\n * finds nearby. Cancelling the selection outright is what actually stops it.\n */\n function preventSelectStart(event: Event) {\n event.preventDefault()\n }\n\n function handlePointerDown(event: Event) {\n const pointerEvent = event as PointerEvent\n // Only one pointer drives the drag; ignore additional touches.\n if (pointerId !== null) return\n\n pointerId = pointerEvent.pointerId\n startX = lastX = pointerEvent.screenX\n startY = lastY = pointerEvent.screenY\n\n if (cursor && style) {\n previousCursor = style.cursor\n style.cursor = cursor\n }\n\n capture.setPointerCapture?.(pointerId)\n // With pointer capture the element receives the rest of the gesture.\n // Without it (older engines, jsdom) fall back to the window.\n moveTarget =\n capture.hasPointerCapture?.(pointerId) === true\n ? element\n : (globalThis.window ?? element)\n\n moveTarget.addEventListener('pointermove', handlePointerMove)\n moveTarget.addEventListener('pointerup', handlePointerUp)\n moveTarget.addEventListener('pointercancel', handlePointerUp)\n globalThis.document?.addEventListener('selectstart', preventSelectStart)\n\n onDragStart?.(state(pointerEvent, 0, 0))\n }\n\n function handlePointerMove(event: Event) {\n const pointerEvent = event as PointerEvent\n if (pointerEvent.pointerId !== pointerId) return\n\n const deltaX = pointerEvent.screenX - lastX\n const deltaY = pointerEvent.screenY - lastY\n lastX = pointerEvent.screenX\n lastY = pointerEvent.screenY\n\n // Movement below the threshold is dropped rather than accumulated.\n if (Math.abs(deltaX) < threshold && Math.abs(deltaY) < threshold) return\n\n onDrag?.(state(pointerEvent, deltaX, deltaY))\n }\n\n function handlePointerUp(event: Event) {\n const pointerEvent = event as PointerEvent\n if (pointerEvent.pointerId !== pointerId) return\n\n const deltaX = pointerEvent.screenX - lastX\n const deltaY = pointerEvent.screenY - lastY\n const finalState = state(pointerEvent, deltaX, deltaY)\n\n stopTracking()\n onDragEnd?.(finalState)\n }\n\n function stopTracking() {\n if (pointerId === null) return\n capture.releasePointerCapture?.(pointerId)\n moveTarget?.removeEventListener('pointermove', handlePointerMove)\n moveTarget?.removeEventListener('pointerup', handlePointerUp)\n moveTarget?.removeEventListener('pointercancel', handlePointerUp)\n globalThis.document?.removeEventListener('selectstart', preventSelectStart)\n if (cursor && style) {\n style.cursor = previousCursor ?? ''\n previousCursor = undefined\n }\n moveTarget = null\n pointerId = null\n }\n\n element.addEventListener('pointerdown', handlePointerDown)\n\n return {\n destroy: () => {\n stopTracking()\n element.removeEventListener('pointerdown', handlePointerDown)\n if (style) {\n for (const [property] of MANAGED_STYLES) {\n const previous = previousStyles.get(property)\n if (previous) {\n style.setProperty(property, previous)\n } else {\n style.removeProperty(property)\n }\n }\n }\n },\n }\n}\n","export interface WheelInstance {\n destroy: () => void\n}\n\n/**\n * Listen to wheel events on an element.\n *\n * The listener is registered with `passive: false` so that the handler can call\n * `preventDefault()` to stop the page from scrolling.\n */\nexport function createWheel(\n element: Element,\n onWheel: (event: WheelEvent) => void,\n): WheelInstance {\n const handler = (event: Event) => onWheel(event as WheelEvent)\n\n element.addEventListener('wheel', handler, { passive: false })\n\n return {\n destroy: () => {\n // Only `capture` matters when removing, and it is false here.\n element.removeEventListener('wheel', handler)\n },\n }\n}\n"],"mappings":";;AACA,MAAa,oBAAoB;;AAEjC,MAAa,gBAAgB;AAU7B,MAAM,gBAAiC;CACrC,YAAY;CACZ,OAAO;CACR;;;;;;;AAmBD,SAAgB,mBAAuC;CACrD,IAAI,QAAQ;CACZ,IAAI,YAAY;CAChB,MAAM,4BAAY,IAAI,KAAiB;CAEvC,SAAS,SAAS,MAAuB;AACvC,UAAQ;AACR,OAAK,MAAM,YAAY,UAAW,WAAU;;CAG9C,SAAS,UAAU;AACjB,MAAI,UAAW;AACf,MAAI,OAAO,cAAc,eAAe,CAAC,UAAU,mBAAmB;AACpE,YAAS;IAAE,GAAG;IAAO,OAAO;IAAe,CAAC;AAC5C;;AAEF,YACG,mBAAmB,CACnB,MAAM,WAAW;AAChB,OAAI,UAAW;AACf,YAAS;IAAE,YAAY;IAAQ,OAAO;IAAM,CAAC;IAC7C,CACD,YAAY;AACX,OAAI,UAAW;AACf,YAAS;IAAE,GAAG;IAAO,OAAO;IAAmB,CAAC;IAChD;;AAGN,QAAO;EACL;EACA,gBAAgB;EAChB,sBAAsB;EACtB,YAAY,aAAa;AACvB,aAAU,IAAI,SAAS;AACvB,gBAAa;AACX,cAAU,OAAO,SAAS;;;EAG9B,eAAe;AACb,eAAY;AACZ,aAAU,OAAO;;EAEpB;;;;;;;;;ACpEH,SAAgB,kBACd,YACA,eACqB;AACrB,KAAI,CAAC,WACH,QAAO,EAAE,eAAe,IAAI;CAG9B,MAAM,SAAS,CAAC,GAAG,WAAW,OAAO,QAAQ,CAAC;AAC9C,MAAK,MAAM,SAAS,OAClB,OA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Ae,kBAAkB;AACjE,cAAY,oBAAoB,aAAa,gBAAgB;AAC7D,cAAY,oBAAoB,iBAAiB,gBAAgB;AACjE,aAAW,UAAU,oBAAoB,eAAe,mBAAmB;AAC3E,MAAI,UAAU,OAAO;AACnB,SAAM,SAAS,kBAAkB;AACjC,oBAAiB,KAAA;;AAEnB,eAAa;AACb,cAAY;;AAGd,SAAQ,iBAAiB,eAAe,kBAAkB;AAE1D,QAAO,EACL,eAAe;AACb,gBAAc;AACd,UAAQ,oBAAoB,eAAe,kBAAkB;AAC7D,MAAI,MACF,MAAK,MAAM,CAAC,aAAa,gBAAgB;GACvC,MAAM,WAAW,eAAe,IAAI,SAAS;AAC7C,OAAI,SACF,OAAM,YAAY,UAAU,SAAS;OAErC,OAAM,eAAe,SAAS;;IAKvC;;;;;;;;;;AC3MH,SAAgB,YACd,SACA,SACe;CACf,MAAM,WAAW,UAAiB,QAAQ,MAAoB;AAE9D,SAAQ,iBAAiB,SAAS,SAAS,EAAE,SAAS,OAAO,CAAC;AAE9D,QAAO,EACL,eAAe;AAEb,UAAQ,oBAAoB,SAAS,QAAQ;IAEhD"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/canvas/context.ts","../src/canvas/animation.ts","../src/midi/access.ts","../src/midi/message.ts","../src/midi/input.ts","../src/pointer/drag.ts","../src/piano/input.ts","../src/xy.ts","../src/pointer/dragValue.ts","../src/pointer/wheel.ts"],"sourcesContent":["/**\n * The properties of a 2D context that survive `save()` / `restore()`, and so\n * are what has to be carried across a resize by hand: setting `canvas.width`\n * resets the context to its defaults.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/save\n */\nexport const drawingState = [\n 'strokeStyle',\n 'fillStyle',\n 'globalAlpha',\n 'lineWidth',\n 'lineCap',\n 'lineJoin',\n 'miterLimit',\n 'lineDashOffset',\n 'shadowOffsetX',\n 'shadowOffsetY',\n 'shadowBlur',\n 'shadowColor',\n 'globalCompositeOperation',\n 'font',\n 'textAlign',\n 'textBaseline',\n 'direction',\n 'imageSmoothingEnabled',\n] as const\n\nexport type DrawingState = (typeof drawingState)[number]\nexport type DrawingStateValue = CanvasRenderingContext2D[DrawingState]\nexport type DrawingContext = Pick<CanvasRenderingContext2D, DrawingState>\n\nexport function isDrawingState(value: unknown): value is DrawingState {\n const names: readonly string[] = drawingState\n return typeof value == 'string' && names.includes(value)\n}\n\n/** Copy the drawing state off a context, to put back after a resize. */\nexport function readDrawingState(\n context: CanvasRenderingContext2D,\n): DrawingContext {\n const state = {} as DrawingContext\n for (const property of drawingState) {\n ;(state[property] as DrawingStateValue) = context[property]\n }\n return state\n}\n\n/** Put a state read by {@link readDrawingState} back onto a context. */\nexport function writeDrawingState(\n context: CanvasRenderingContext2D,\n state: DrawingContext,\n) {\n for (const property of drawingState) {\n ;(context[property] as DrawingStateValue) = state[property]\n }\n}\n\n/**\n * Give the canvas a backing store of `width * dpr` by `height * dpr` device\n * pixels while keeping it `width` by `height` in CSS pixels, and scale the\n * context so that drawing code can work in CSS pixels throughout.\n *\n * Assigning to `canvas.width` clears the canvas and resets the context, so\n * this both resizes and re-establishes the transform.\n */\nexport function applyDevicePixelRatio(\n canvas: HTMLCanvasElement,\n context: CanvasRenderingContext2D,\n width: number,\n height: number,\n dpr: number,\n) {\n canvas.width = width * dpr\n canvas.height = height * dpr\n // Reset the current transformation matrix to the identity matrix\n context.setTransform(1, 0, 0, 1, 0, 0)\n context.scale(dpr, dpr)\n canvas.style.width = `${width}px`\n canvas.style.height = `${height}px`\n}\n","import {\n applyDevicePixelRatio,\n readDrawingState,\n writeDrawingState,\n type DrawingContext,\n} from './context'\n\n/** What the canvas looked like when a frame was drawn. */\nexport interface AnimationFrame {\n /** Width of the canvas in CSS pixels. */\n width: number\n /** Height of the canvas in CSS pixels. */\n height: number\n /** Frames drawn so far, starting at 0. */\n count: number\n /** Milliseconds since the previous frame. */\n deltaTime: number\n /** Milliseconds since the instance was created. */\n elapsedTime: number\n /** Frames per second implied by `deltaTime`. */\n fps: number\n}\n\nexport type CanvasDrawFunction = (\n context: CanvasRenderingContext2D,\n frame: AnimationFrame,\n) => void\n\nexport type CanvasInitFunction = (\n context: CanvasRenderingContext2D,\n size: { width: number; height: number },\n) => void\n\nexport interface AnimationCanvasOptions {\n /** Called for every frame. */\n draw: CanvasDrawFunction\n\n /** Called once, after the first size is known and before the first frame. */\n init?: CanvasInitFunction\n\n /**\n * Keep drawing on every animation frame. When off, a frame is drawn only on\n * a resize or an explicit {@link AnimationCanvasInstance.redraw}.\n *\n * @default true\n */\n animate?: boolean\n\n /**\n * Size in CSS pixels. Ignored when `relativeSize` is on.\n *\n * @default { width: 100, height: 100 }\n */\n size?: { width: number; height: number }\n\n /**\n * Follow the size of the canvas's parent element instead of `size`.\n *\n * Fixed for the lifetime of the instance: it decides whether a\n * `ResizeObserver` is attached.\n *\n * @default false\n */\n relativeSize?: boolean\n\n /**\n * Carry the drawing across a resize, so that the canvas does not blank for a\n * frame while the new size is drawn.\n *\n * @default true\n */\n reduceFlickering?: boolean\n\n /**\n * Passed to `getContext('2d', …)`. Read once when the context is created, so\n * it is fixed for the lifetime of the instance.\n *\n * @see https://developer.mozilla.org/docs/Web/API/HTMLCanvasElement/getContext#contextattributes\n */\n contextAttributes?: CanvasRenderingContext2DSettings\n}\n\nexport interface AnimationCanvasInstance {\n /**\n * Replace the given options. Lets a wrapper feed a fresh `draw` in on every\n * render without restarting the animation, so the frame count and the\n * elapsed time keep running.\n *\n * `relativeSize` and `contextAttributes` are fixed for the lifetime of the\n * instance and are ignored here.\n *\n * While `animate` is off this also draws a frame, since nothing else would.\n */\n update: (options: Partial<AnimationCanvasOptions>) => void\n\n /** Draw one frame now, whether or not `animate` is on. */\n redraw: () => void\n\n destroy: () => void\n}\n\n/**\n * Drive a canvas from `requestAnimationFrame`, keeping its backing store in\n * step with the device pixel ratio and, optionally, with the size of its\n * parent.\n *\n * Drawing code works in CSS pixels: the context is scaled by the device pixel\n * ratio, and `width` / `height` of each {@link AnimationFrame} are CSS pixels.\n */\nexport function createAnimationCanvas(\n canvas: HTMLCanvasElement,\n options: AnimationCanvasOptions,\n): AnimationCanvasInstance {\n let opts = options\n\n const context2d = canvas.getContext('2d', opts.contextAttributes)\n if (!context2d) {\n throw new Error('createAnimationCanvas: cannot get a 2d context')\n }\n const context: CanvasRenderingContext2D = context2d\n\n const relativeSize = opts.relativeSize ?? false\n\n /** Off-document canvas holding the drawing while the real one is resized. */\n let memo: HTMLCanvasElement | null = null\n let memoContext: CanvasRenderingContext2D | null = null\n\n let width = 0\n let height = 0\n /** Whether a size has been applied, so a frame can be drawn. */\n let sized = false\n let initialized = false\n\n let frameId: number | null = null\n let count = -1\n const startTime = performance.now()\n let previousTime = startTime\n\n function devicePixelRatio() {\n return globalThis.devicePixelRatio || 1\n }\n\n /**\n * Copy the canvas onto the memo canvas at its full device resolution, 1:1.\n *\n * Assigning to `memo.width` resets the memo's transform to the identity, so\n * the copy neither scales nor resamples.\n */\n function takeSnapshot(): DrawingContext | null {\n if (!(opts.reduceFlickering ?? true)) return null\n if (!memo) {\n memo = globalThis.document?.createElement('canvas') ?? null\n memoContext = memo?.getContext('2d', opts.contextAttributes) ?? null\n }\n if (!memo || !memoContext) return null\n\n const state = readDrawingState(context)\n memo.width = canvas.width\n memo.height = canvas.height\n if (canvas.width > 0 && canvas.height > 0) {\n memoContext.drawImage(canvas, 0, 0)\n }\n return state\n }\n\n /**\n * Put the snapshot back, given the size in CSS pixels it was taken at.\n *\n * The context is scaled to CSS pixels, so drawing the snapshot at its old\n * CSS size leaves it exactly where it was. While the device pixel ratio\n * stays put that is a 1:1 copy of device pixels, and when it changes the\n * snapshot is rescaled once, from its full resolution.\n */\n function restoreSnapshot(\n state: DrawingContext | null,\n previousWidth: number,\n previousHeight: number,\n ) {\n if (!state || !memo || !memoContext) return\n if (memo.width <= 0 || memo.height <= 0) return\n writeDrawingState(context, state)\n context.drawImage(memo, 0, 0, previousWidth, previousHeight)\n }\n\n function applySize(w: number, h: number) {\n const dpr = devicePixelRatio()\n const previousWidth = width\n const previousHeight = height\n const state = takeSnapshot()\n applyDevicePixelRatio(canvas, context, w, h, dpr)\n width = w\n height = h\n sized = true\n restoreSnapshot(state, previousWidth, previousHeight)\n }\n\n function drawFrame() {\n if (!sized) return\n if (!initialized) {\n initialized = true\n opts.init?.(context, { width, height })\n }\n const now = performance.now()\n const deltaTime = now - previousTime\n previousTime = now\n count += 1\n opts.draw(context, {\n width,\n height,\n count,\n deltaTime,\n elapsedTime: now - startTime,\n fps: 1000 / deltaTime,\n })\n }\n\n function tick() {\n // Scheduled before drawing so that a slow frame does not delay the next\n // request, matching how requestAnimationFrame loops are usually written.\n frameId = requestAnimationFrame(tick)\n drawFrame()\n }\n\n function startLoop() {\n if (frameId != null) return\n previousTime = performance.now()\n frameId = requestAnimationFrame(tick)\n }\n\n function stopLoop() {\n if (frameId == null) return\n cancelAnimationFrame(frameId)\n frameId = null\n }\n\n let observer: ResizeObserver | null = null\n\n if (relativeSize) {\n const parent = canvas.parentElement\n if (!parent) {\n throw new Error(\n 'createAnimationCanvas: relativeSize needs the canvas to have a parent element',\n )\n }\n // The observer reports the current size as soon as it starts, so it is the\n // single source of the size — including the first one. Reading the parent\n // here instead would mix the padding box with the content box the observer\n // reports.\n observer = new ResizeObserver((entries) => {\n for (const entry of entries) {\n const { width: w, height: h } = entry.contentRect\n applySize(w, h)\n // With the loop running the next frame covers the new size already.\n if (!(opts.animate ?? true)) drawFrame()\n }\n })\n observer.observe(parent)\n } else {\n const { width: w = 100, height: h = 100 } = opts.size ?? {}\n applySize(w, h)\n }\n\n if (opts.animate ?? true) {\n startLoop()\n } else if (sized) {\n drawFrame()\n }\n\n return {\n update: (next) => {\n const wasAnimating = opts.animate ?? true\n opts = {\n ...opts,\n ...next,\n relativeSize,\n contextAttributes: opts.contextAttributes,\n }\n\n if (!relativeSize) {\n const { width: w = 100, height: h = 100 } = opts.size ?? {}\n if (w != width || h != height) applySize(w, h)\n }\n\n const animating = opts.animate ?? true\n if (animating && !wasAnimating) startLoop()\n if (!animating && wasAnimating) stopLoop()\n\n // Without a loop running, a resize and this call are the only things\n // that can put anything new on the canvas — so a new `draw` has to be\n // painted here. That is what makes a canvas driven by state rather than\n // by time work: the wrapper re-renders, pushes the new handler in, and\n // the frame it draws reflects it.\n if (!animating) drawFrame()\n },\n redraw: drawFrame,\n destroy: () => {\n stopLoop()\n observer?.disconnect()\n observer = null\n memo = null\n memoContext = null\n },\n }\n}\n","/** @private */\nexport const PERMISSION_DENIED = 'PERMISSION_DENIED'\n/** @private */\nexport const NOT_SUPPORTED = 'NOT_SUPPORTED'\n\n/** @private */\nexport type MIDIAccessError = typeof PERMISSION_DENIED | typeof NOT_SUPPORTED\n\nexport type MIDIAccessState = {\n readonly midiAccess: MIDIAccess | null\n readonly error: MIDIAccessError | null\n}\n\nconst INITIAL_STATE: MIDIAccessState = {\n midiAccess: null,\n error: null,\n}\n\nexport interface MIDIAccessInstance {\n /** Request MIDI access. Safe to call more than once. */\n request: () => void\n getState: () => MIDIAccessState\n /** Snapshot for server side rendering. Always the initial state. */\n getServerState: () => MIDIAccessState\n /** @returns unsubscribe function */\n subscribe: (listener: () => void) => () => void\n destroy: () => void\n}\n\n/**\n * Request MIDI access in the browser.\n *\n * The returned instance holds the state and notifies subscribers when it changes,\n * so it can be consumed from any framework.\n */\nexport function createMIDIAccess(): MIDIAccessInstance {\n let state = INITIAL_STATE\n let destroyed = false\n const listeners = new Set<() => void>()\n\n function setState(next: MIDIAccessState) {\n state = next\n for (const listener of listeners) listener()\n }\n\n function request() {\n if (destroyed) return\n if (typeof navigator === 'undefined' || !navigator.requestMIDIAccess) {\n setState({ ...state, error: NOT_SUPPORTED })\n return\n }\n navigator\n .requestMIDIAccess()\n .then((access) => {\n if (destroyed) return\n setState({ midiAccess: access, error: null })\n })\n .catch(() => {\n if (destroyed) return\n setState({ ...state, error: PERMISSION_DENIED })\n })\n }\n\n return {\n request,\n getState: () => state,\n getServerState: () => INITIAL_STATE,\n subscribe: (listener) => {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n destroy: () => {\n destroyed = true\n listeners.clear()\n },\n }\n}\n","export interface MIDIMessageInstance {\n destroy: () => void\n}\n\n/**\n * Listen to raw `midimessage` events on every input of a MIDIAccess.\n *\n * Use this when you need more detail than {@link createMIDIInput} provides.\n */\nexport function createMIDIMessage(\n midiAccess: MIDIAccess | null,\n onMIDIMessage: (event: MIDIMessageEvent) => void,\n): MIDIMessageInstance {\n if (!midiAccess) {\n return { destroy: () => {} }\n }\n\n const inputs = [...midiAccess.inputs.values()]\n for (const input of inputs) {\n input.addEventListener('midimessage', onMIDIMessage)\n }\n\n return {\n destroy: () => {\n for (const input of inputs) {\n input.removeEventListener('midimessage', onMIDIMessage)\n }\n },\n }\n}\n","import { createMIDIMessage, type MIDIMessageInstance } from './message'\n\nconst MIDI_EVENT_TO_NUMBER = {\n NOTE_ON: 0x90,\n NOTE_OFF: 0x80,\n PITCH_BEND: 0xe0,\n}\n\nexport type MIDIInputHandlers = {\n onNoteOnEvent?: (note: number, velocity: number) => void\n onNoteOffEvent?: (note: number) => void\n onPitchBendEvent?: (msb: number, lsb: number) => void\n}\n\nexport type MIDIInputInstance = MIDIMessageInstance\n\n/**\n * Handle note on/off and pitch bend events. To be used with {@link createMIDIAccess}.\n * Internally uses {@link createMIDIMessage}.\n */\nexport function createMIDIInput(\n midiAccess: MIDIAccess | null,\n { onNoteOnEvent, onNoteOffEvent, onPitchBendEvent }: MIDIInputHandlers,\n): MIDIInputInstance {\n return createMIDIMessage(midiAccess, (event) => {\n if (!event.data) return\n // event.data[0] ... command\n // event.data[1] ... note, MSB (Most Significant Byte)\n // event.data[2] ... velocity, LSB (Least Significant Byte)\n const kind = event.data[0] & 0xf0\n\n if (\n kind == MIDI_EVENT_TO_NUMBER.NOTE_OFF ||\n (kind == MIDI_EVENT_TO_NUMBER.NOTE_ON && event.data[2] == 0)\n ) {\n onNoteOffEvent?.(event.data[1])\n } else if (kind == MIDI_EVENT_TO_NUMBER.NOTE_ON) {\n onNoteOnEvent?.(event.data[1], event.data[2])\n } else if (kind == MIDI_EVENT_TO_NUMBER.PITCH_BEND) {\n onPitchBendEvent?.(event.data[1], event.data[2])\n }\n })\n}\n","export type DragState = {\n /** Total movement from the drag start, in screen coordinates. */\n x: number\n y: number\n /** Movement since the previous event, in screen coordinates. */\n deltaX: number\n deltaY: number\n /** Pointer position in viewport coordinates. */\n clientX: number\n clientY: number\n /**\n * Which pointer this is. Always the same value for one drag; with\n * {@link DragOptions.multiPointer} it tells concurrent drags apart.\n */\n pointerId: number\n event: PointerEvent\n}\n\nexport type DragOptions = {\n /**\n * Minimum movement in pixels before `onDrag` fires. Movement below it is\n * carried over to the next event rather than discarded, so a slow drag still\n * reports once it adds up.\n *\n * Prevents `onDrag` from firing on, for example, a double click.\n *\n * @default 0\n */\n threshold?: number\n\n /**\n * CSS cursor to show while dragging. Applied to the element itself: pointer\n * capture keeps it in effect even once the pointer leaves the element, so\n * there is no need to touch the document.\n *\n * With {@link DragOptions.multiPointer} it is set for the first pointer and\n * restored once the last one is up.\n */\n cursor?: string\n\n /**\n * Track every pointer that goes down on the element, rather than only the\n * first. Each one gets its own `onDragStart` / `onDrag` / `onDragEnd` and\n * carries its own totals; {@link DragState.pointerId} says which is which.\n *\n * Fixed for the lifetime of the instance: switching part way through a drag\n * has no meaning, so `update()` ignores it.\n *\n * @default false\n */\n multiPointer?: boolean\n\n onDragStart?: (state: DragState) => void\n onDrag?: (state: DragState) => void\n onDragEnd?: (state: DragState) => void\n}\n\nexport interface DragInstance {\n /**\n * Replace the given options. Lets a wrapper feed fresh handlers in without\n * tearing down the listeners, which would abort a drag in progress.\n *\n * `multiPointer` is fixed for the lifetime of the instance and is ignored\n * here.\n */\n update: (options: DragOptions) => void\n destroy: () => void\n}\n\n/**\n * Applied to the element for the lifetime of the instance.\n *\n * `touch-action` stops touch dragging from scrolling the page. That alone makes\n * the browser treat a long press as the start of a text selection, so selection\n * and the iOS callout are suppressed here too.\n */\nconst MANAGED_STYLES = [\n ['touch-action', 'none'],\n ['user-select', 'none'],\n ['-webkit-user-select', 'none'],\n ['-webkit-touch-callout', 'none'],\n] as const\n\ntype CaptureTarget = {\n setPointerCapture?: (pointerId: number) => void\n releasePointerCapture?: (pointerId: number) => void\n hasPointerCapture?: (pointerId: number) => boolean\n}\n\n/** What one pointer needs to report its own movement. */\ntype PointerState = {\n /** Where the listeners for this pointer live. */\n moveTarget: EventTarget\n startX: number\n startY: number\n lastX: number\n lastY: number\n}\n\n/**\n * Track a pointer drag on an element.\n *\n * Uses Pointer Events only, and pointer capture so that the drag keeps working\n * once the pointer leaves the element. For the lifetime of the instance the\n * element gets `touch-action: none` so that touch dragging does not scroll the\n * page, plus `user-select: none` so that a long press does not start a text\n * selection instead.\n *\n * One pointer at a time by default; see {@link DragOptions.multiPointer}.\n */\nexport function createDrag(\n element: Element,\n options: DragOptions = {},\n): DragInstance {\n let opts = options\n const multiPointer = options.multiPointer ?? false\n const capture = element as CaptureTarget\n const style = (element as Partial<HTMLElement>).style\n\n const previousStyles = new Map<string, string>()\n if (style) {\n for (const [property, value] of MANAGED_STYLES) {\n previousStyles.set(property, style.getPropertyValue(property))\n style.setProperty(property, value)\n }\n }\n\n const pointers = new Map<number, PointerState>()\n /**\n * How many pointers each target carries. Adding the same listener twice is a\n * no-op and removing it once removes it for good, so a target is subscribed\n * to while at least one pointer is on it and no longer.\n */\n const targets = new Map<EventTarget, number>()\n let previousCursor: string | undefined\n\n function state(\n event: PointerEvent,\n pointer: PointerState,\n deltaX: number,\n deltaY: number,\n ): DragState {\n return {\n x: event.screenX - pointer.startX,\n y: event.screenY - pointer.startY,\n deltaX,\n deltaY,\n clientX: event.clientX,\n clientY: event.clientY,\n pointerId: event.pointerId,\n event,\n }\n }\n\n /**\n * `user-select: none` only makes the element's own text unselectable; the\n * browser still starts a selection on long press and grabs whatever text it\n * finds nearby. Cancelling the selection outright is what actually stops it.\n */\n function preventSelectStart(event: Event) {\n event.preventDefault()\n }\n\n function retainTarget(target: EventTarget) {\n const count = targets.get(target) ?? 0\n if (count === 0) {\n target.addEventListener('pointermove', handlePointerMove)\n target.addEventListener('pointerup', handlePointerUp)\n target.addEventListener('pointercancel', handlePointerUp)\n }\n targets.set(target, count + 1)\n }\n\n function releaseTarget(target: EventTarget) {\n const count = targets.get(target) ?? 0\n if (count > 1) {\n targets.set(target, count - 1)\n return\n }\n target.removeEventListener('pointermove', handlePointerMove)\n target.removeEventListener('pointerup', handlePointerUp)\n target.removeEventListener('pointercancel', handlePointerUp)\n targets.delete(target)\n }\n\n function handlePointerDown(event: Event) {\n const pointerEvent = event as PointerEvent\n const pointerId = pointerEvent.pointerId\n // Without multiPointer only one pointer drives the drag; ignore the rest.\n if (pointers.has(pointerId)) return\n if (!multiPointer && pointers.size > 0) return\n\n const isFirst = pointers.size === 0\n if (isFirst && opts.cursor && style) {\n previousCursor = style.cursor\n style.cursor = opts.cursor\n }\n\n capture.setPointerCapture?.(pointerId)\n // With pointer capture the element receives the rest of the gesture.\n // Without it (older engines, jsdom) fall back to the window.\n const moveTarget =\n capture.hasPointerCapture?.(pointerId) === true\n ? element\n : (globalThis.window ?? element)\n\n const pointer: PointerState = {\n moveTarget,\n startX: pointerEvent.screenX,\n startY: pointerEvent.screenY,\n lastX: pointerEvent.screenX,\n lastY: pointerEvent.screenY,\n }\n pointers.set(pointerId, pointer)\n\n retainTarget(moveTarget)\n if (isFirst) {\n globalThis.document?.addEventListener('selectstart', preventSelectStart)\n }\n\n opts.onDragStart?.(state(pointerEvent, pointer, 0, 0))\n }\n\n function handlePointerMove(event: Event) {\n const pointerEvent = event as PointerEvent\n const pointer = pointers.get(pointerEvent.pointerId)\n if (!pointer) return\n\n const deltaX = pointerEvent.screenX - pointer.lastX\n const deltaY = pointerEvent.screenY - pointer.lastY\n\n // Movement below the threshold accumulates until it crosses it. Dropping it\n // instead would swallow a slow drag entirely: pointer coordinates are\n // fractional, so each event can move less than a pixel and never report.\n const threshold = opts.threshold ?? 0\n if (Math.abs(deltaX) < threshold && Math.abs(deltaY) < threshold) return\n\n pointer.lastX = pointerEvent.screenX\n pointer.lastY = pointerEvent.screenY\n\n opts.onDrag?.(state(pointerEvent, pointer, deltaX, deltaY))\n }\n\n function handlePointerUp(event: Event) {\n const pointerEvent = event as PointerEvent\n const pointer = pointers.get(pointerEvent.pointerId)\n if (!pointer) return\n\n const deltaX = pointerEvent.screenX - pointer.lastX\n const deltaY = pointerEvent.screenY - pointer.lastY\n const finalState = state(pointerEvent, pointer, deltaX, deltaY)\n\n stopTracking(pointerEvent.pointerId)\n opts.onDragEnd?.(finalState)\n }\n\n function stopTracking(pointerId: number) {\n const pointer = pointers.get(pointerId)\n if (!pointer) return\n\n capture.releasePointerCapture?.(pointerId)\n releaseTarget(pointer.moveTarget)\n pointers.delete(pointerId)\n\n if (pointers.size > 0) return\n\n globalThis.document?.removeEventListener('selectstart', preventSelectStart)\n if (previousCursor !== undefined && style) {\n style.cursor = previousCursor\n previousCursor = undefined\n }\n }\n\n element.addEventListener('pointerdown', handlePointerDown)\n\n return {\n update: (next) => {\n opts = { ...opts, ...next, multiPointer }\n },\n destroy: () => {\n for (const pointerId of [...pointers.keys()]) stopTracking(pointerId)\n element.removeEventListener('pointerdown', handlePointerDown)\n if (style) {\n for (const [property] of MANAGED_STYLES) {\n const previous = previousStyles.get(property)\n if (previous) {\n style.setProperty(property, previous)\n } else {\n style.removeProperty(property)\n }\n }\n }\n },\n }\n}\n","import { noteAt, type PianoLayout } from '@tremolo-ui/functions'\n\nimport { createDrag } from '../pointer/drag'\n\n/**\n * What asked for a note to sound.\n *\n * A note stops only once everything that asked for it has let go, so two\n * fingers on one key, or a key held by both the mouse and a MIDI keyboard,\n * behave the way they look.\n *\n * Pointers use `pointer:<pointerId>`; everything else names its own source.\n */\nexport type NoteSource = string\n\nexport interface PianoInputOptions {\n /** Geometry of the drawn keyboard, used to find the note under a pointer. */\n layout: PianoLayout\n\n /**\n * Let a pointer slide from one key to the next while it is down. With it off,\n * the key that was pressed keeps sounding until the pointer is released.\n *\n * @default true\n */\n glissando?: boolean\n\n /**\n * Highest note that can sound. Above it a note is refused, whichever source\n * asks for it.\n *\n * @default 127\n */\n midiMax?: number\n\n /** Called when a note starts sounding, not for each source that asks. */\n onPlayNote?: (note: number, velocity?: number) => void\n /** Called once the last source holding a note has let go. */\n onStopNote?: (note: number) => void\n /** Called whenever {@link PianoInputInstance.activeNotes} would change. */\n onActiveNotesChange?: (notes: number[]) => void\n}\n\nexport interface PianoInputInstance {\n /**\n * Replace the given options. Lets a wrapper feed a fresh layout in without\n * tearing down the listeners, which would abort a drag in progress.\n */\n update: (options: Partial<PianoInputOptions>) => void\n\n /**\n * Start a note from something other than a pointer: a keyboard shortcut, a\n * MIDI message, an imperative call.\n */\n noteOn: (\n note: number,\n options?: { source?: NoteSource; velocity?: number },\n ) => void\n /** Release a note held by `source`. */\n noteOff: (note: number, options?: { source?: NoteSource }) => void\n\n /** The notes currently sounding, ascending. */\n activeNotes: () => number[]\n\n destroy: () => void\n}\n\nconst DEFAULT_SOURCE: NoteSource = 'api'\n\n/**\n * Drive a piano keyboard with pointers, and own what is sounding.\n *\n * Every way of playing a note goes through the one instance — pointers here,\n * keyboard shortcuts and MIDI through {@link PianoInputInstance.noteOn} — so\n * there is a single answer to what is currently held, and drawing the keys is\n * left entirely to the wrapper.\n *\n * Tracks every pointer at once, so a chord can be played with several fingers.\n */\nexport function createPianoInput(\n element: Element,\n options: PianoInputOptions,\n): PianoInputInstance {\n let opts = options\n\n /** Which sources are holding each sounding note. */\n const held = new Map<number, Set<NoteSource>>()\n /** The note each pointer is currently on. */\n const pointerNotes = new Map<number, number>()\n\n function activeNotes(): number[] {\n return [...held.keys()].sort((a, b) => a - b)\n }\n\n function noteOn(\n note: number,\n {\n source = DEFAULT_SOURCE,\n velocity,\n }: { source?: NoteSource; velocity?: number } = {},\n ) {\n if (note > (opts.midiMax ?? 127)) return\n\n const sources = held.get(note)\n if (sources) {\n // Already sounding: remember the extra holder and leave it alone.\n sources.add(source)\n return\n }\n\n held.set(note, new Set([source]))\n opts.onPlayNote?.(note, velocity)\n opts.onActiveNotesChange?.(activeNotes())\n }\n\n function noteOff(\n note: number,\n { source = DEFAULT_SOURCE }: { source?: NoteSource } = {},\n ) {\n const sources = held.get(note)\n if (!sources) return\n\n sources.delete(source)\n if (sources.size > 0) return\n\n held.delete(note)\n opts.onStopNote?.(note)\n opts.onActiveNotesChange?.(activeNotes())\n }\n\n /** The note under a pointer, or null where the pointer is off the keys. */\n function noteUnder(clientX: number, clientY: number): number | null {\n const { left, top, height } = element.getBoundingClientRect()\n return noteAt(clientX - left, clientY - top, height, opts.layout)\n }\n\n /** Move a pointer onto a note, releasing whatever it held before. */\n function movePointer(pointerId: number, note: number | null) {\n const source = `pointer:${pointerId}`\n const previous = pointerNotes.get(pointerId)\n if (previous === note) return\n\n if (previous !== undefined) noteOff(previous, { source })\n\n if (note === null) {\n pointerNotes.delete(pointerId)\n } else {\n pointerNotes.set(pointerId, note)\n noteOn(note, { source })\n }\n }\n\n const drag = createDrag(element, {\n multiPointer: true,\n onDragStart: (state) =>\n movePointer(state.pointerId, noteUnder(state.clientX, state.clientY)),\n onDrag: (state) => {\n // Without glissando the pressed key holds until the pointer is released,\n // so where the pointer wanders to does not matter.\n if (opts.glissando === false) return\n movePointer(state.pointerId, noteUnder(state.clientX, state.clientY))\n },\n onDragEnd: (state) => movePointer(state.pointerId, null),\n })\n\n return {\n update: (next) => {\n opts = { ...opts, ...next }\n },\n noteOn,\n noteOff,\n activeNotes,\n destroy: () => {\n drag.destroy()\n // Anything still held is released, so a caller that mirrors these\n // callbacks into a synth is not left with a stuck note.\n for (const note of activeNotes()) {\n held.delete(note)\n opts.onStopNote?.(note)\n }\n pointerNotes.clear()\n opts.onActiveNotesChange?.([])\n },\n }\n}\n","/**\n * A pair of per-axis values. The tuple elements are labelled, so editors show\n * `[x: number, y: number]` rather than a bare pair.\n */\nexport type XY<T> = [x: T, y: T]\n\n/**\n * A setting that may be given once for both axes, or per axis.\n *\n * A single value is told from a pair with `Array.isArray`, so the single form\n * is only offered while `T` cannot itself be an array. Where it can, the pair\n * is the only way to write it, since a lone array would be read as a pair.\n */\nexport type XYInput<T> = [T] extends [readonly unknown[]]\n ? readonly [x: T, y: T]\n : T | readonly [x: T, y: T]\n\n// `Array.isArray` narrows a mutable tuple on its own, but not a readonly one,\n// hence the explicit predicate.\nfunction isPair<T>(\n value: T | readonly [x: T, y: T],\n): value is readonly [x: T, y: T] {\n return Array.isArray(value)\n}\n\n/**\n * Spread a setting that may have been given as a single value.\n *\n * The parameter is written out rather than taken as `XYInput<T>`: a\n * conditional type cannot be narrowed, so the constraint stays where it is\n * declared and this takes both forms.\n *\n * The pair is copied rather than passed along, so that the result is a tuple\n * the caller owns even when a readonly one was given.\n */\nexport function toXY<T>(value: T | readonly [x: T, y: T]): XY<T> {\n return isPair(value) ? [value[0], value[1]] : [value, value]\n}\n","import {\n clamp,\n linearScale,\n normalizeValue,\n stepValue,\n type ValueRange,\n} from '@tremolo-ui/functions'\n\nimport { toXY, type XY, type XYInput } from '../xy'\n\nimport { createDrag, type DragState } from './drag'\n\n/**\n * How the 0-1 travel of one axis maps onto a value.\n *\n * Extends `ValueRange` so that a drag and an `applyDelta` nudge from a wheel\n * or an arrow key share one description of the scaling.\n */\nexport interface AxisOptions extends ValueRange {\n /**\n * Flip the axis so that its far end is `min`.\n *\n * Positions follow the screen: x grows to the right, y downwards. A vertical\n * slider whose maximum is at the top therefore reverses its y axis.\n *\n * @default false\n */\n reverse?: boolean\n}\n\n/** Where the value of each axis currently sits, as a position (see {@link DragValueMapping}). */\nexport interface MappingContext {\n position: () => XY<number>\n}\n\n/**\n * Turns pointer movement into a position on each axis: 0 is the `min` end of\n * the travel and 1 the `max` end, before `reverse` and the scaling of\n * {@link AxisOptions} are applied.\n *\n * A mapping holds the state of the drag in progress, so an instance belongs to\n * a single {@link createDragValue} instance.\n */\nexport interface DragValueMapping {\n /**\n * @returns the position, or null when it cannot be determined and the event\n * should be ignored.\n */\n start: (state: DragState, context: MappingContext) => XY<number> | null\n move: (state: DragState, context: MappingContext) => XY<number> | null\n}\n\n/**\n * Map the pointer onto the bounding rect of an element: the value *is* the\n * position pointed at, so the middle of the element is 0.5.\n *\n * The element is read on every event, so it may be mounted after the drag is\n * set up and may change size while a drag is in progress.\n */\nexport function elementMapping(\n getElement: () => Element | null | undefined,\n): DragValueMapping {\n function positionIn(state: DragState): XY<number> | null {\n const element = getElement()\n if (!element) return null\n const { left, top, right, bottom } = element.getBoundingClientRect()\n // A collapsed element has no travel to normalize against, and\n // normalizeValue rejects an empty range.\n return [\n right > left ? normalizeValue(state.clientX, left, right) : 0,\n bottom > top ? normalizeValue(state.clientY, top, bottom) : 0,\n ]\n }\n\n return { start: positionIn, move: positionIn }\n}\n\n/**\n * Move the value away from where it stood when the drag started, by the\n * distance dragged. The pointer position itself carries no meaning, so the\n * value can be adjusted from anywhere on the screen.\n */\nexport function relativeMapping({\n pixelRange = 100,\n}: {\n /**\n * Pixels of movement that span the whole range.\n * @default 100\n */\n pixelRange?: XYInput<number>\n} = {}): DragValueMapping {\n const [rangeX, rangeY] = toXY(pixelRange)\n let origin: XY<number> = [0, 0]\n\n return {\n start: (_state, context) => {\n origin = context.position()\n return origin\n },\n // `x` and `y` are measured from the start of the drag, so the position\n // never accumulates a rounding error of its own.\n move: (state) => [\n origin[0] + state.x / rangeX,\n origin[1] + state.y / rangeY,\n ],\n }\n}\n\nexport interface DragValueOptions {\n /** Scaling of each axis; a single value applies to both. */\n axis: XYInput<AxisOptions>\n\n /** How pointer movement becomes a position. */\n mapping: DragValueMapping\n\n /**\n * The current value of each axis. Read when a drag starts, by mappings that\n * move the value relative to it, such as {@link relativeMapping}.\n */\n getValue?: () => XY<number>\n\n /**\n * Report the value on pointer down, before any movement.\n *\n * Enable it where the pointer position *is* the value, so that a plain click\n * jumps to it. Leave it off where the element being dragged is an object in\n * its own right, so that grabbing its edge does not shift it under the\n * pointer.\n *\n * @default false\n */\n updateOnPointerDown?: boolean\n\n /** @see DragOptions.threshold */\n threshold?: number\n /** @see DragOptions.cursor */\n cursor?: string\n\n onChange?: (value: XY<number>, state: DragState) => void\n onDragStart?: (value: XY<number>, state: DragState) => void\n onDragEnd?: (value: XY<number>, state: DragState) => void\n}\n\nexport interface DragValueInstance {\n /**\n * Replace the given options. Lets a wrapper feed fresh values in without\n * tearing down the listeners, which would abort a drag in progress.\n *\n * `mapping` is fixed for the lifetime of the instance and is ignored here.\n */\n update: (options: Partial<DragValueOptions>) => void\n destroy: () => void\n}\n\n/**\n * Drive a value with a pointer drag.\n *\n * Combines {@link createDrag} with the scaling of `@tremolo-ui/functions`: the\n * mapping decides where the pointer sits on the 0-1 travel of each axis, and\n * the axis options turn that into a value.\n */\nexport function createDragValue(\n element: Element,\n options: DragValueOptions,\n): DragValueInstance {\n let opts = options\n let lastValue: XY<number> = [0, 0]\n\n const axes = () => toXY(opts.axis)\n\n function valueOf(position: XY<number>): XY<number> {\n return axes().map((axis, i) => {\n const p = axis.reverse ? 1 - position[i] : position[i]\n // A scale clamps the position, so a mapping may report outside 0-1.\n const scale = axis.scale ?? linearScale\n const value = scale.denormalize(p, axis.min, axis.max)\n const stepped = axis.step ? stepValue(value, axis.step) : value\n // Rounding to the step can leave the range.\n return clamp(stepped, axis.min, axis.max)\n }) as XY<number>\n }\n\n const context: MappingContext = {\n position: () => {\n const getValue = opts.getValue\n if (!getValue) {\n throw new Error(\n 'createDragValue: getValue is required by the given mapping',\n )\n }\n const value = getValue()\n return axes().map((axis, i) => {\n const scale = axis.scale ?? linearScale\n const n = scale.normalize(value[i], axis.min, axis.max)\n return axis.reverse ? 1 - n : n\n }) as XY<number>\n },\n }\n\n const drag = createDrag(element, {\n threshold: opts.threshold,\n cursor: opts.cursor,\n onDragStart: (state) => {\n const position = opts.mapping.start(state, context)\n if (position) {\n lastValue = valueOf(position)\n if (opts.updateOnPointerDown) opts.onChange?.(lastValue, state)\n }\n opts.onDragStart?.(lastValue, state)\n },\n onDrag: (state) => {\n const position = opts.mapping.move(state, context)\n if (!position) return\n lastValue = valueOf(position)\n opts.onChange?.(lastValue, state)\n },\n // The pointer has not moved since the last reported value, so `lastValue`\n // is where the drag ended.\n onDragEnd: (state) => opts.onDragEnd?.(lastValue, state),\n })\n\n return {\n update: (next) => {\n opts = { ...opts, ...next, mapping: opts.mapping }\n drag.update({ threshold: opts.threshold, cursor: opts.cursor })\n },\n destroy: () => drag.destroy(),\n }\n}\n","export interface WheelOptions {\n /**\n * Only report events while the focus is inside the element.\n *\n * A control that reacts to the wheel on hover alone takes the scroll away\n * from the page, so passing over one in a long form silently changes its\n * value. Requiring focus makes that an explicit act.\n *\n * The check is `contains`, not an identity test: the element that actually\n * takes focus is usually a descendant, such as a thumb or an `<input>`, and\n * a caller may have replaced it with markup of their own.\n *\n * @default false\n */\n requireFocus?: boolean\n}\n\nexport interface WheelInstance {\n /** Replace the given options, keeping the listener in place. */\n update: (options: WheelOptions) => void\n destroy: () => void\n}\n\n/**\n * Listen to wheel events on an element.\n *\n * The listener is registered with `passive: false` so that the handler can call\n * `preventDefault()` to stop the page from scrolling.\n */\nexport function createWheel(\n element: Element,\n onWheel: (event: WheelEvent) => void,\n options: WheelOptions = {},\n): WheelInstance {\n let opts = options\n\n function hasFocus() {\n const active = element.ownerDocument?.activeElement\n return !!active && element.contains(active)\n }\n\n const handler = (event: Event) => {\n if (opts.requireFocus && !hasFocus()) return\n onWheel(event as WheelEvent)\n }\n\n element.addEventListener('wheel', handler, { passive: false })\n\n return {\n update: (next) => {\n opts = { ...opts, ...next }\n },\n destroy: () => {\n // Only `capture` matters when removing, and it is false here.\n element.removeEventListener('wheel', handler)\n },\n }\n}\n"],"mappings":";;;;;;;;;AAOA,MAAa,eAAe;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AA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e,KAAK,SAAS;EAC9B;;;;;;;;;;ACtMH,SAAgB,YACd,SACA,SACA,UAAwB,EAAE,EACX;CACf,IAAI,OAAO;CAEX,SAAS,WAAW;EAClB,MAAM,SAAS,QAAQ,eAAe;AACtC,SAAO,CAAC,CAAC,UAAU,QAAQ,SAAS,OAAO;;CAG7C,MAAM,WAAW,UAAiB;AAChC,MAAI,KAAK,gBAAgB,CAAC,UAAU,CAAE;AACtC,UAAQ,MAAoB;;AAG9B,SAAQ,iBAAiB,SAAS,SAAS,EAAE,SAAS,OAAO,CAAC;AAE9D,QAAO;EACL,SAAS,SAAS;AAChB,UAAO;IAAE,GAAG;IAAM,GAAG;IAAM;;EAE7B,eAAe;AAEb,WAAQ,oBAAoB,SAAS,QAAQ;;EAEhD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tremolo-ui/dom",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "framework-agnostic DOM layer used in @tremolo-ui/*",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -17,6 +17,9 @@
|
|
|
17
17
|
"lint": "eslint --fix --ext .ts,.tsx .",
|
|
18
18
|
"format": "prettier --write ."
|
|
19
19
|
},
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"@tremolo-ui/functions": "^0.5.0"
|
|
22
|
+
},
|
|
20
23
|
"files": [
|
|
21
24
|
"dist",
|
|
22
25
|
"src"
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import {
|
|
2
|
+
applyDevicePixelRatio,
|
|
3
|
+
readDrawingState,
|
|
4
|
+
writeDrawingState,
|
|
5
|
+
type DrawingContext,
|
|
6
|
+
} from './context'
|
|
7
|
+
|
|
8
|
+
/** What the canvas looked like when a frame was drawn. */
|
|
9
|
+
export interface AnimationFrame {
|
|
10
|
+
/** Width of the canvas in CSS pixels. */
|
|
11
|
+
width: number
|
|
12
|
+
/** Height of the canvas in CSS pixels. */
|
|
13
|
+
height: number
|
|
14
|
+
/** Frames drawn so far, starting at 0. */
|
|
15
|
+
count: number
|
|
16
|
+
/** Milliseconds since the previous frame. */
|
|
17
|
+
deltaTime: number
|
|
18
|
+
/** Milliseconds since the instance was created. */
|
|
19
|
+
elapsedTime: number
|
|
20
|
+
/** Frames per second implied by `deltaTime`. */
|
|
21
|
+
fps: number
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type CanvasDrawFunction = (
|
|
25
|
+
context: CanvasRenderingContext2D,
|
|
26
|
+
frame: AnimationFrame,
|
|
27
|
+
) => void
|
|
28
|
+
|
|
29
|
+
export type CanvasInitFunction = (
|
|
30
|
+
context: CanvasRenderingContext2D,
|
|
31
|
+
size: { width: number; height: number },
|
|
32
|
+
) => void
|
|
33
|
+
|
|
34
|
+
export interface AnimationCanvasOptions {
|
|
35
|
+
/** Called for every frame. */
|
|
36
|
+
draw: CanvasDrawFunction
|
|
37
|
+
|
|
38
|
+
/** Called once, after the first size is known and before the first frame. */
|
|
39
|
+
init?: CanvasInitFunction
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Keep drawing on every animation frame. When off, a frame is drawn only on
|
|
43
|
+
* a resize or an explicit {@link AnimationCanvasInstance.redraw}.
|
|
44
|
+
*
|
|
45
|
+
* @default true
|
|
46
|
+
*/
|
|
47
|
+
animate?: boolean
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Size in CSS pixels. Ignored when `relativeSize` is on.
|
|
51
|
+
*
|
|
52
|
+
* @default { width: 100, height: 100 }
|
|
53
|
+
*/
|
|
54
|
+
size?: { width: number; height: number }
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Follow the size of the canvas's parent element instead of `size`.
|
|
58
|
+
*
|
|
59
|
+
* Fixed for the lifetime of the instance: it decides whether a
|
|
60
|
+
* `ResizeObserver` is attached.
|
|
61
|
+
*
|
|
62
|
+
* @default false
|
|
63
|
+
*/
|
|
64
|
+
relativeSize?: boolean
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Carry the drawing across a resize, so that the canvas does not blank for a
|
|
68
|
+
* frame while the new size is drawn.
|
|
69
|
+
*
|
|
70
|
+
* @default true
|
|
71
|
+
*/
|
|
72
|
+
reduceFlickering?: boolean
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Passed to `getContext('2d', …)`. Read once when the context is created, so
|
|
76
|
+
* it is fixed for the lifetime of the instance.
|
|
77
|
+
*
|
|
78
|
+
* @see https://developer.mozilla.org/docs/Web/API/HTMLCanvasElement/getContext#contextattributes
|
|
79
|
+
*/
|
|
80
|
+
contextAttributes?: CanvasRenderingContext2DSettings
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface AnimationCanvasInstance {
|
|
84
|
+
/**
|
|
85
|
+
* Replace the given options. Lets a wrapper feed a fresh `draw` in on every
|
|
86
|
+
* render without restarting the animation, so the frame count and the
|
|
87
|
+
* elapsed time keep running.
|
|
88
|
+
*
|
|
89
|
+
* `relativeSize` and `contextAttributes` are fixed for the lifetime of the
|
|
90
|
+
* instance and are ignored here.
|
|
91
|
+
*
|
|
92
|
+
* While `animate` is off this also draws a frame, since nothing else would.
|
|
93
|
+
*/
|
|
94
|
+
update: (options: Partial<AnimationCanvasOptions>) => void
|
|
95
|
+
|
|
96
|
+
/** Draw one frame now, whether or not `animate` is on. */
|
|
97
|
+
redraw: () => void
|
|
98
|
+
|
|
99
|
+
destroy: () => void
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Drive a canvas from `requestAnimationFrame`, keeping its backing store in
|
|
104
|
+
* step with the device pixel ratio and, optionally, with the size of its
|
|
105
|
+
* parent.
|
|
106
|
+
*
|
|
107
|
+
* Drawing code works in CSS pixels: the context is scaled by the device pixel
|
|
108
|
+
* ratio, and `width` / `height` of each {@link AnimationFrame} are CSS pixels.
|
|
109
|
+
*/
|
|
110
|
+
export function createAnimationCanvas(
|
|
111
|
+
canvas: HTMLCanvasElement,
|
|
112
|
+
options: AnimationCanvasOptions,
|
|
113
|
+
): AnimationCanvasInstance {
|
|
114
|
+
let opts = options
|
|
115
|
+
|
|
116
|
+
const context2d = canvas.getContext('2d', opts.contextAttributes)
|
|
117
|
+
if (!context2d) {
|
|
118
|
+
throw new Error('createAnimationCanvas: cannot get a 2d context')
|
|
119
|
+
}
|
|
120
|
+
const context: CanvasRenderingContext2D = context2d
|
|
121
|
+
|
|
122
|
+
const relativeSize = opts.relativeSize ?? false
|
|
123
|
+
|
|
124
|
+
/** Off-document canvas holding the drawing while the real one is resized. */
|
|
125
|
+
let memo: HTMLCanvasElement | null = null
|
|
126
|
+
let memoContext: CanvasRenderingContext2D | null = null
|
|
127
|
+
|
|
128
|
+
let width = 0
|
|
129
|
+
let height = 0
|
|
130
|
+
/** Whether a size has been applied, so a frame can be drawn. */
|
|
131
|
+
let sized = false
|
|
132
|
+
let initialized = false
|
|
133
|
+
|
|
134
|
+
let frameId: number | null = null
|
|
135
|
+
let count = -1
|
|
136
|
+
const startTime = performance.now()
|
|
137
|
+
let previousTime = startTime
|
|
138
|
+
|
|
139
|
+
function devicePixelRatio() {
|
|
140
|
+
return globalThis.devicePixelRatio || 1
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Copy the canvas onto the memo canvas at its full device resolution, 1:1.
|
|
145
|
+
*
|
|
146
|
+
* Assigning to `memo.width` resets the memo's transform to the identity, so
|
|
147
|
+
* the copy neither scales nor resamples.
|
|
148
|
+
*/
|
|
149
|
+
function takeSnapshot(): DrawingContext | null {
|
|
150
|
+
if (!(opts.reduceFlickering ?? true)) return null
|
|
151
|
+
if (!memo) {
|
|
152
|
+
memo = globalThis.document?.createElement('canvas') ?? null
|
|
153
|
+
memoContext = memo?.getContext('2d', opts.contextAttributes) ?? null
|
|
154
|
+
}
|
|
155
|
+
if (!memo || !memoContext) return null
|
|
156
|
+
|
|
157
|
+
const state = readDrawingState(context)
|
|
158
|
+
memo.width = canvas.width
|
|
159
|
+
memo.height = canvas.height
|
|
160
|
+
if (canvas.width > 0 && canvas.height > 0) {
|
|
161
|
+
memoContext.drawImage(canvas, 0, 0)
|
|
162
|
+
}
|
|
163
|
+
return state
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Put the snapshot back, given the size in CSS pixels it was taken at.
|
|
168
|
+
*
|
|
169
|
+
* The context is scaled to CSS pixels, so drawing the snapshot at its old
|
|
170
|
+
* CSS size leaves it exactly where it was. While the device pixel ratio
|
|
171
|
+
* stays put that is a 1:1 copy of device pixels, and when it changes the
|
|
172
|
+
* snapshot is rescaled once, from its full resolution.
|
|
173
|
+
*/
|
|
174
|
+
function restoreSnapshot(
|
|
175
|
+
state: DrawingContext | null,
|
|
176
|
+
previousWidth: number,
|
|
177
|
+
previousHeight: number,
|
|
178
|
+
) {
|
|
179
|
+
if (!state || !memo || !memoContext) return
|
|
180
|
+
if (memo.width <= 0 || memo.height <= 0) return
|
|
181
|
+
writeDrawingState(context, state)
|
|
182
|
+
context.drawImage(memo, 0, 0, previousWidth, previousHeight)
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function applySize(w: number, h: number) {
|
|
186
|
+
const dpr = devicePixelRatio()
|
|
187
|
+
const previousWidth = width
|
|
188
|
+
const previousHeight = height
|
|
189
|
+
const state = takeSnapshot()
|
|
190
|
+
applyDevicePixelRatio(canvas, context, w, h, dpr)
|
|
191
|
+
width = w
|
|
192
|
+
height = h
|
|
193
|
+
sized = true
|
|
194
|
+
restoreSnapshot(state, previousWidth, previousHeight)
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function drawFrame() {
|
|
198
|
+
if (!sized) return
|
|
199
|
+
if (!initialized) {
|
|
200
|
+
initialized = true
|
|
201
|
+
opts.init?.(context, { width, height })
|
|
202
|
+
}
|
|
203
|
+
const now = performance.now()
|
|
204
|
+
const deltaTime = now - previousTime
|
|
205
|
+
previousTime = now
|
|
206
|
+
count += 1
|
|
207
|
+
opts.draw(context, {
|
|
208
|
+
width,
|
|
209
|
+
height,
|
|
210
|
+
count,
|
|
211
|
+
deltaTime,
|
|
212
|
+
elapsedTime: now - startTime,
|
|
213
|
+
fps: 1000 / deltaTime,
|
|
214
|
+
})
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function tick() {
|
|
218
|
+
// Scheduled before drawing so that a slow frame does not delay the next
|
|
219
|
+
// request, matching how requestAnimationFrame loops are usually written.
|
|
220
|
+
frameId = requestAnimationFrame(tick)
|
|
221
|
+
drawFrame()
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function startLoop() {
|
|
225
|
+
if (frameId != null) return
|
|
226
|
+
previousTime = performance.now()
|
|
227
|
+
frameId = requestAnimationFrame(tick)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function stopLoop() {
|
|
231
|
+
if (frameId == null) return
|
|
232
|
+
cancelAnimationFrame(frameId)
|
|
233
|
+
frameId = null
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
let observer: ResizeObserver | null = null
|
|
237
|
+
|
|
238
|
+
if (relativeSize) {
|
|
239
|
+
const parent = canvas.parentElement
|
|
240
|
+
if (!parent) {
|
|
241
|
+
throw new Error(
|
|
242
|
+
'createAnimationCanvas: relativeSize needs the canvas to have a parent element',
|
|
243
|
+
)
|
|
244
|
+
}
|
|
245
|
+
// The observer reports the current size as soon as it starts, so it is the
|
|
246
|
+
// single source of the size — including the first one. Reading the parent
|
|
247
|
+
// here instead would mix the padding box with the content box the observer
|
|
248
|
+
// reports.
|
|
249
|
+
observer = new ResizeObserver((entries) => {
|
|
250
|
+
for (const entry of entries) {
|
|
251
|
+
const { width: w, height: h } = entry.contentRect
|
|
252
|
+
applySize(w, h)
|
|
253
|
+
// With the loop running the next frame covers the new size already.
|
|
254
|
+
if (!(opts.animate ?? true)) drawFrame()
|
|
255
|
+
}
|
|
256
|
+
})
|
|
257
|
+
observer.observe(parent)
|
|
258
|
+
} else {
|
|
259
|
+
const { width: w = 100, height: h = 100 } = opts.size ?? {}
|
|
260
|
+
applySize(w, h)
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
if (opts.animate ?? true) {
|
|
264
|
+
startLoop()
|
|
265
|
+
} else if (sized) {
|
|
266
|
+
drawFrame()
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
return {
|
|
270
|
+
update: (next) => {
|
|
271
|
+
const wasAnimating = opts.animate ?? true
|
|
272
|
+
opts = {
|
|
273
|
+
...opts,
|
|
274
|
+
...next,
|
|
275
|
+
relativeSize,
|
|
276
|
+
contextAttributes: opts.contextAttributes,
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
if (!relativeSize) {
|
|
280
|
+
const { width: w = 100, height: h = 100 } = opts.size ?? {}
|
|
281
|
+
if (w != width || h != height) applySize(w, h)
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
const animating = opts.animate ?? true
|
|
285
|
+
if (animating && !wasAnimating) startLoop()
|
|
286
|
+
if (!animating && wasAnimating) stopLoop()
|
|
287
|
+
|
|
288
|
+
// Without a loop running, a resize and this call are the only things
|
|
289
|
+
// that can put anything new on the canvas — so a new `draw` has to be
|
|
290
|
+
// painted here. That is what makes a canvas driven by state rather than
|
|
291
|
+
// by time work: the wrapper re-renders, pushes the new handler in, and
|
|
292
|
+
// the frame it draws reflects it.
|
|
293
|
+
if (!animating) drawFrame()
|
|
294
|
+
},
|
|
295
|
+
redraw: drawFrame,
|
|
296
|
+
destroy: () => {
|
|
297
|
+
stopLoop()
|
|
298
|
+
observer?.disconnect()
|
|
299
|
+
observer = null
|
|
300
|
+
memo = null
|
|
301
|
+
memoContext = null
|
|
302
|
+
},
|
|
303
|
+
}
|
|
304
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The properties of a 2D context that survive `save()` / `restore()`, and so
|
|
3
|
+
* are what has to be carried across a resize by hand: setting `canvas.width`
|
|
4
|
+
* resets the context to its defaults.
|
|
5
|
+
*
|
|
6
|
+
* @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/save
|
|
7
|
+
*/
|
|
8
|
+
export const drawingState = [
|
|
9
|
+
'strokeStyle',
|
|
10
|
+
'fillStyle',
|
|
11
|
+
'globalAlpha',
|
|
12
|
+
'lineWidth',
|
|
13
|
+
'lineCap',
|
|
14
|
+
'lineJoin',
|
|
15
|
+
'miterLimit',
|
|
16
|
+
'lineDashOffset',
|
|
17
|
+
'shadowOffsetX',
|
|
18
|
+
'shadowOffsetY',
|
|
19
|
+
'shadowBlur',
|
|
20
|
+
'shadowColor',
|
|
21
|
+
'globalCompositeOperation',
|
|
22
|
+
'font',
|
|
23
|
+
'textAlign',
|
|
24
|
+
'textBaseline',
|
|
25
|
+
'direction',
|
|
26
|
+
'imageSmoothingEnabled',
|
|
27
|
+
] as const
|
|
28
|
+
|
|
29
|
+
export type DrawingState = (typeof drawingState)[number]
|
|
30
|
+
export type DrawingStateValue = CanvasRenderingContext2D[DrawingState]
|
|
31
|
+
export type DrawingContext = Pick<CanvasRenderingContext2D, DrawingState>
|
|
32
|
+
|
|
33
|
+
export function isDrawingState(value: unknown): value is DrawingState {
|
|
34
|
+
const names: readonly string[] = drawingState
|
|
35
|
+
return typeof value == 'string' && names.includes(value)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Copy the drawing state off a context, to put back after a resize. */
|
|
39
|
+
export function readDrawingState(
|
|
40
|
+
context: CanvasRenderingContext2D,
|
|
41
|
+
): DrawingContext {
|
|
42
|
+
const state = {} as DrawingContext
|
|
43
|
+
for (const property of drawingState) {
|
|
44
|
+
;(state[property] as DrawingStateValue) = context[property]
|
|
45
|
+
}
|
|
46
|
+
return state
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Put a state read by {@link readDrawingState} back onto a context. */
|
|
50
|
+
export function writeDrawingState(
|
|
51
|
+
context: CanvasRenderingContext2D,
|
|
52
|
+
state: DrawingContext,
|
|
53
|
+
) {
|
|
54
|
+
for (const property of drawingState) {
|
|
55
|
+
;(context[property] as DrawingStateValue) = state[property]
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Give the canvas a backing store of `width * dpr` by `height * dpr` device
|
|
61
|
+
* pixels while keeping it `width` by `height` in CSS pixels, and scale the
|
|
62
|
+
* context so that drawing code can work in CSS pixels throughout.
|
|
63
|
+
*
|
|
64
|
+
* Assigning to `canvas.width` clears the canvas and resets the context, so
|
|
65
|
+
* this both resizes and re-establishes the transform.
|
|
66
|
+
*/
|
|
67
|
+
export function applyDevicePixelRatio(
|
|
68
|
+
canvas: HTMLCanvasElement,
|
|
69
|
+
context: CanvasRenderingContext2D,
|
|
70
|
+
width: number,
|
|
71
|
+
height: number,
|
|
72
|
+
dpr: number,
|
|
73
|
+
) {
|
|
74
|
+
canvas.width = width * dpr
|
|
75
|
+
canvas.height = height * dpr
|
|
76
|
+
// Reset the current transformation matrix to the identity matrix
|
|
77
|
+
context.setTransform(1, 0, 0, 1, 0, 0)
|
|
78
|
+
context.scale(dpr, dpr)
|
|
79
|
+
canvas.style.width = `${width}px`
|
|
80
|
+
canvas.style.height = `${height}px`
|
|
81
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,3 +1,18 @@
|
|
|
1
|
+
export {
|
|
2
|
+
createAnimationCanvas,
|
|
3
|
+
type AnimationCanvasInstance,
|
|
4
|
+
type AnimationCanvasOptions,
|
|
5
|
+
type AnimationFrame,
|
|
6
|
+
type CanvasDrawFunction,
|
|
7
|
+
type CanvasInitFunction,
|
|
8
|
+
} from './canvas/animation'
|
|
9
|
+
export {
|
|
10
|
+
drawingState,
|
|
11
|
+
isDrawingState,
|
|
12
|
+
type DrawingContext,
|
|
13
|
+
type DrawingState,
|
|
14
|
+
type DrawingStateValue,
|
|
15
|
+
} from './canvas/context'
|
|
1
16
|
export {
|
|
2
17
|
createMIDIAccess,
|
|
3
18
|
NOT_SUPPORTED,
|
|
@@ -12,10 +27,31 @@ export {
|
|
|
12
27
|
type MIDIInputInstance,
|
|
13
28
|
} from './midi/input'
|
|
14
29
|
export { createMIDIMessage, type MIDIMessageInstance } from './midi/message'
|
|
30
|
+
export {
|
|
31
|
+
createPianoInput,
|
|
32
|
+
type NoteSource,
|
|
33
|
+
type PianoInputInstance,
|
|
34
|
+
type PianoInputOptions,
|
|
35
|
+
} from './piano/input'
|
|
15
36
|
export {
|
|
16
37
|
createDrag,
|
|
17
38
|
type DragInstance,
|
|
18
39
|
type DragOptions,
|
|
19
40
|
type DragState,
|
|
20
41
|
} from './pointer/drag'
|
|
21
|
-
export {
|
|
42
|
+
export {
|
|
43
|
+
createDragValue,
|
|
44
|
+
elementMapping,
|
|
45
|
+
relativeMapping,
|
|
46
|
+
type AxisOptions,
|
|
47
|
+
type DragValueInstance,
|
|
48
|
+
type DragValueMapping,
|
|
49
|
+
type DragValueOptions,
|
|
50
|
+
type MappingContext,
|
|
51
|
+
} from './pointer/dragValue'
|
|
52
|
+
export {
|
|
53
|
+
createWheel,
|
|
54
|
+
type WheelInstance,
|
|
55
|
+
type WheelOptions,
|
|
56
|
+
} from './pointer/wheel'
|
|
57
|
+
export { toXY, type XY, type XYInput } from './xy'
|