Skip to content

packages/core/src/lib/manipulation/controller.ts

Read as Markdown

This is the source snapshot used to build these API details. View this revision on GitHub.

Back to reference

1 import {
2   batch,
3   signal,
4   isSignal,
5   untracked,
6   assertSignalCommandAllowed,
7   assertDirectSignalWriteAllowed,
8 } from "../signals/graph.js";
9 import { resolveSignalValue } from "../signals/resolve-signal-value.js";
10 import { requireHookContext, useHookSlot } from "../hooks/hook-slot.js";
11 import { queueBeginCommand } from "../scheduler/realm-scheduler.js";
12 import type {
13   PibblEventHandlers,
14   PibblEventTarget,
15   PibblPointerEvent,
16   PibblKeyboardEvent,
17 } from "../events/types.js";
18 import type { PibblComponentRefs, PibblInstance } from "../types.js";
19 import type { WritableSignal } from "../signals/types.js";
20 import {
21   observeGestureInputs,
22   claimGeometryGeneration,
23   restoreReleasedGesture,
24 } from "./ownership.js";
25 import { suppressManipulationActivation } from "../events/dispatch.js";
26 import { solveManipulation } from "./solve.js";
27 import {
28   currentRootCoordinateMapping,
29   sameRootCoordinateMapping,
30 } from "./coordinates.js";
31 import type { PibblResizePosition } from "./types.js";
32 import type {
33   PibblManipulationActive,
34   PibblManipulationCancelReason,
35   PibblManipulationController,
36   PibblManipulationEvent,
37   PibblManipulationGeometry,
38   PibblManipulationOperation,
39   PibblManipulationOptions,
40   PibblManipulationSnapshot,
41 } from "./controller-types.js";
42 
43 type PointerSample = Pick<
44   PibblPointerEvent,
45   | "pointerId"
46   | "x"
47   | "y"
48   | "clientX"
49   | "clientY"
50   | "shiftKey"
51   | "altKey"
52   | "ctrlKey"
53   | "metaKey"
54 >;
55 interface Session {
56   operation: PibblManipulationOperation;
57   handle?: PibblResizePosition;
58   pointerId: number;
59   target: PibblEventTarget;
60   before: PibblManipulationGeometry;
61   last: PibblManipulationGeometry;
62   point: DOMPoint;
63   clientX: number;
64   clientY: number;
65   parent: DOMMatrix;
66   started: boolean;
67   angle: number;
68   rotationDelta: number;
69   snapshot: PibblManipulationSnapshot;
70   coordinateMapping: readonly number[];
71   source?: object;
72   releaseObservation?: () => void;
73   sample?: PointerSample;
74 }
75 export interface ManipulationState {
76   controller: PibblManipulationController;
77   options: PibblManipulationOptions;
78   alive: boolean;
79   root: PibblInstance;
80   frame?: PibblComponentRefs<any>;
81   parent: DOMMatrix;
82   coordinateMapping?: readonly number[];
83   session?: Session;
84   active: WritableSignal<PibblManipulationActive | null>;
85   snapshot: WritableSignal<PibblManipulationSnapshot | null>;
86 }
87 const states = new WeakMap<PibblManipulationController, ManipulationState>();
88 const owners = new WeakMap<object, ManipulationState>();
89 const claimedPresses = new WeakSet<Event>();
90 export function manipulationState(
91   controller: PibblManipulationController,
92 ): ManipulationState {
93   const state = states.get(controller);
94   if (!state || !state.alive)
95     throw new Error(
96       "Pibbl manipulation requires a live useManipulation controller.",
97     );
98   return state;
99 }
100 function geometry(state: ManipulationState): PibblManipulationGeometry {
101   return untracked(() =>
102     Object.freeze({
103       box: Object.freeze({ ...state.options.box.get() }),
104       rotation: state.options.rotation?.get() ?? 0,
105     }),
106   );
107 }
108 function same(a: PibblManipulationGeometry, b: PibblManipulationGeometry): boolean {
109   return (
110     a.rotation === b.rotation &&
111     a.box.left === b.box.left &&
112     a.box.top === b.box.top &&
113     a.box.width === b.box.width &&
114     a.box.height === b.box.height
115   );
116 }
117 function event(session: Session): PibblManipulationEvent {
118   return Object.freeze({
119     ...session.snapshot,
120     before: session.before,
121     after: session.last,
122   });
123 }
124 function publish(
125   state: ManipulationState,
126   next: PibblManipulationGeometry,
127 ): void {
128   assertDirectSignalWriteAllowed(state.options.box);
129   if (state.options.rotation)
130     assertDirectSignalWriteAllowed(state.options.rotation);
131   batch(() => {
132     state.options.box.set(next.box);
133     if (state.options.rotation) state.options.rotation.set(next.rotation);
134   });
135 }
136 function release(state: ManipulationState, session: Session): void {
137   if (state.session !== session) return;
138   state.session = undefined;
139   session.releaseObservation?.();
140   session.releaseObservation = undefined;
141   if (state.options.rotation && owners.get(state.options.rotation) === state)
142     owners.delete(state.options.rotation);
143   if (owners.get(state.options.box) === state) owners.delete(state.options.box);
144   if (session.target.hasPointerCapture(session.pointerId))
145     session.target.releasePointerCapture(session.pointerId);
146 }
147 function cancel(
148   state: ManipulationState,
149   reason: PibblManipulationCancelReason,
150 ): void {
151   const session = state.session;
152   if (!session) return;
153   const restore =
154     same(geometry(state), session.last) && reason !== "external-change";
155   release(state, session);
156   batch(() => {
157     if (restore && session.started) publish(state, session.before);
158     state.active.set(null);
159   });
160   if (session.started)
161     state.options.onCancel?.(
162       Object.freeze({ ...event(session), after: geometry(state), reason }),
163     );
164 }
165 /** Release capture synchronously; rollback can defer under renderer write guards. */
166 export function detachManipulationFrame(state: ManipulationState): void {
167   const session = state.session;
168   if (!session) return;
169   const restore = same(geometry(state), session.last);
170   release(state, session);
171   restoreReleasedGesture({
172     box: state.options.box,
173     rotation: state.options.rotation,
174     before: restore ? session.before : geometry(state),
175     active: state.active,
176   });
177 }
178 function dispose(state: ManipulationState): void {
179   if (!state.alive) return;
180   state.alive = false;
181   detachManipulationFrame(state);
182 }
183 /**
184  * Creates a mount-owned controller for moving, resizing, and rotating declared geometry.
185  *
186  * @param options - Target state, enabled operations, constraints, and lifecycle callbacks. See
187  * {@link PibblManipulationOptions} .
188  * @returns Stable controls and state for the mounted manipulation interaction. See
189  * {@link PibblManipulationController} .
190  *
191  * @see {@link PibblManipulationOptions}
192  * @see {@link PibblManipulationController}
193  */
194 export function useManipulation(
195   options: PibblManipulationOptions,
196 ): PibblManipulationController {
197   const { pibblInstance } = requireHookContext();
198   const slot = useHookSlot<ManipulationState>("manipulation", (teardowns) => {
199     const state = {
200       options,
201       root: pibblInstance.eventRoot.rootInstance ?? pibblInstance,
202       alive: true,
203       parent: new DOMMatrix(),
204       active: signal<PibblManipulationActive | null>(null),
205       snapshot: signal<PibblManipulationSnapshot | null>(null),
206     } as ManipulationState;
207     const controller: PibblManipulationController = Object.freeze({
208       active: state.active.asReadonly(),
209       snapshot: state.snapshot.asReadonly(),
210       get frameProps() {
211         return frameProps;
212       },
213       cancel() {
214         if (state.alive) {
215           assertSignalCommandAllowed();
216           cancel(state, "explicit");
217         }
218       },
219     });
220     const frameProps = Object.freeze({ controller, style: options.box });
221     state.controller = controller;
222     states.set(controller, state);
223     teardowns.add(() => dispose(state));
224     return state;
225   });
226   const state = slot.value;
227   if (options.rotate && !options.rotation)
228     throw new Error(
229       "useManipulation rotate requires a writable rotation signal in radians.",
230     );
231   if (
232     options.box !== state.options.box ||
233     options.rotation !== state.options.rotation
234   )
235     throw new Error(
236       "useManipulation geometry signal identity must remain stable.",
237     );
238   state.options = options;
239   if (state.session && !enabled(state, state.session.operation)) {
240     const session = state.session;
241     queueBeginCommand(() => {
242       if (state.alive && state.session === session) cancel(state, "disabled");
243     });
244   }
245   return state.controller;
246 }
247 function enabled(
248   state: ManipulationState,
249   operation: PibblManipulationOperation,
250 ): boolean {
251   const options =
252     operation === "move"
253       ? state.options.move
254       : operation === "resize"
255         ? state.options.resize
256         : state.options.rotate;
257   return options !== undefined && resolveSignalValue(options.enabled ?? true);
258 }
259 function validateSession(state: ManipulationState): Session | undefined {
260   const session = state.session;
261   if (!session) return;
262   if (!same(geometry(state), session.last)) {
263     cancel(state, "external-change");
264     return;
265   }
266   if (!enabled(state, session.operation)) {
267     cancel(state, "disabled");
268     return;
269   }
270   if (
271     !sameRootCoordinateMapping(
272       session.coordinateMapping,
273       currentRootCoordinateMapping(state.root),
274     ) ||
275     (state.coordinateMapping !== undefined &&
276       !sameRootCoordinateMapping(
277         session.coordinateMapping,
278         state.coordinateMapping,
279       ))
280   ) {
281     cancel(state, "coordinate-space-changed");
282     return;
283   }
284   if (
285     transformValueChanged(state.parent.a, session.parent.a) ||
286     transformValueChanged(state.parent.b, session.parent.b) ||
287     transformValueChanged(state.parent.c, session.parent.c) ||
288     transformValueChanged(state.parent.d, session.parent.d) ||
289     transformValueChanged(state.parent.e, session.parent.e) ||
290     transformValueChanged(state.parent.f, session.parent.f)
291   ) {
292     cancel(state, "coordinate-space-changed");
293     return;
294   }
295   return session;
296 }
297 function resolvedOptions(state: ManipulationState) {
298   const options = state.options;
299   const move = options.move && {
300     ...options.move,
301     snap: options.move.snap && {
302       ...options.move.snap,
303       enabled: resolveSignalValue(options.move.snap.enabled ?? true),
304     },
305   };
306   const resize = options.resize && {
307     ...options.resize,
308     snap: options.resize.snap && {
309       ...options.resize.snap,
310       enabled: resolveSignalValue(options.resize.snap.enabled ?? true),
311     },
312   };
313   const rotate = options.rotate && {
314     ...options.rotate,
315     snap: options.rotate.snap && {
316       ...options.rotate.snap,
317       enabled: resolveSignalValue(options.rotate.snap.enabled ?? true),
318     },
319   };
320   return { move, resize, rotate };
321 }
322 function apply(state: ManipulationState, pointer: PointerSample): void {
323   const session = validateSession(state);
324   if (!session || pointer.pointerId !== session.pointerId) return;
325   session.sample = {
326     pointerId: pointer.pointerId,
327     x: pointer.x,
328     y: pointer.y,
329     clientX: pointer.clientX,
330     clientY: pointer.clientY,
331     shiftKey: pointer.shiftKey,
332     altKey: pointer.altKey,
333     ctrlKey: pointer.ctrlKey,
334     metaKey: pointer.metaKey,
335   };
336   if (!session.started) {
337     if (
338       Math.hypot(
339         pointer.clientX - session.clientX,
340         pointer.clientY - session.clientY,
341       ) < 3
342     )
343       return;
344     session.started = true;
345     suppressManipulationActivation(state.root, session.pointerId);
346     state.active.set(
347       Object.freeze({
348         operation: session.operation,
349         handle: session.handle ?? null,
350         pointerId: session.pointerId,
351       }),
352     );
353     state.options.onStart?.(event(session));
354     if (validateSession(state) !== session) return;
355   }
356   const { move, resize, rotate } = resolvedOptions(state);
357   const currentPoint = session.parent
358     .inverse()
359     .transformPoint(new DOMPoint(pointer.x, pointer.y));
360   if (session.operation === "rotate") {
361     const centerX = session.before.box.left + session.before.box.width / 2;
362     const centerY = session.before.box.top + session.before.box.height / 2;
363     if (currentPoint.x !== centerX || currentPoint.y !== centerY) {
364       const angle = Math.atan2(
365         currentPoint.y - centerY,
366         currentPoint.x - centerX,
367       );
368       const delta = angle - session.angle;
369       session.rotationDelta += Math.atan2(Math.sin(delta), Math.cos(delta));
370       session.angle = angle;
371     }
372   }
373   let result: ReturnType<typeof solveManipulation>;
374   try {
375     result = solveManipulation({
376       operation: session.operation,
377       handle: session.handle,
378       initial: session.before.box,
379       initialPoint: session.point,
380       currentPoint,
381       initialRotation: session.before.rotation,
382       rotationDelta: session.rotationDelta,
383       modifiers: {
384         shift: pointer.shiftKey,
385         alt: pointer.altKey,
386         ctrl: pointer.ctrlKey,
387         meta: pointer.metaKey,
388       },
389       move,
390       resize,
391       rotate,
392     });
393   } catch {
394     // Options can change after activation; the original preview still belongs
395     // to this gesture and must be restored through the normal terminal path.
396     cancel(state, "constraints-unsatisfiable");
397     return;
398   }
399   const next = Object.freeze({
400     box: result.applied,
401     rotation: result.appliedRotation,
402   });
403   const changed = !same(next, session.last);
404   session.last = next;
405   session.snapshot = Object.freeze({
406     operation: session.operation,
407     handle: session.handle ?? null,
408     initial: session.before,
409     proposed: Object.freeze({
410       box: result.proposed,
411       rotation: result.proposedRotation,
412     }),
413     applied: next,
414     snapActive: result.snapActive,
415     snapSatisfied: result.snapSatisfied,
416   });
417   batch(() => {
418     if (changed) publish(state, next);
419     state.snapshot.set(session.snapshot);
420   });
421   if (validateSession(state) !== session) return;
422   if (changed) state.options.onChange?.(event(session));
423 }
424 function applySafely(state: ManipulationState, pointer: PointerSample): void {
425   try {
426     apply(state, pointer);
427   } catch (error) {
428     try {
429       cancel(state, "explicit");
430     } catch (cleanupError) {
431       throw new AggregateError(
432         [error, cleanupError],
433         "Manipulation callback and cleanup failed.",
434         { cause: cleanupError },
435       );
436     }
437     throw error;
438   }
439 }
440 function updateModifiers(
441   state: ManipulationState,
442   key: PibblKeyboardEvent,
443 ): void {
444   const sample = state.session?.sample;
445   if (!sample || !["Shift", "Alt", "Control", "Meta"].includes(key.key)) return;
446   applySafely(state, {
447     ...sample,
448     shiftKey: key.shiftKey,
449     altKey: key.altKey,
450     ctrlKey: key.ctrlKey,
451     metaKey: key.metaKey,
452   });
453 }
454 
455 /** @internal Identifies one private handle source for readout presentation. */
456 export function isManipulationSourceActive(
457   controller: PibblManipulationController,
458   source: object,
459 ): boolean {
460   const state = manipulationState(controller);
461   return state.session?.started === true && state.session.source === source;
462 }
463 
464 export function manipulationHandlers(
465   controller: PibblManipulationController,
466   operation: PibblManipulationOperation,
467   handle?: PibblResizePosition,
468   source?: object,
469 ): PibblEventHandlers {
470   const state = manipulationState(controller);
471   return {
472     onPointerDown(pointer) {
473       if (
474         !state.alive ||
475         state.session ||
476         pointer.defaultPrevented ||
477         claimedPresses.has(pointer.originalEvent) ||
478         pointer.button !== 0 ||
479         !enabled(state, operation)
480       )
481         return;
482       if (
483         owners.has(state.options.box) ||
484         (state.options.rotation && owners.has(state.options.rotation))
485       )
486         throw new Error(
487           "Pibbl manipulation geometry already has an active owner.",
488         );
489       const before = geometry(state);
490       const point = state.parent
491         .inverse()
492         .transformPoint(new DOMPoint(pointer.x, pointer.y));
493       if (!Number.isFinite(point.x) || !Number.isFinite(point.y))
494         throw new Error(
495           "Pibbl manipulation cannot use a singular parent transform.",
496         );
497       assertDirectSignalWriteAllowed(state.options.box);
498       if (state.options.rotation)
499         assertDirectSignalWriteAllowed(state.options.rotation);
500       const resolved = resolvedOptions(state);
501       if (
502         operation === "resize" &&
503         resolved.resize?.snap?.target === "grid" &&
504         (Math.abs(state.parent.b) > 1e-10 || Math.abs(state.parent.c) > 1e-10)
505       ) {
506         throw new Error(
507           "Grid resize snapping requires an aligned parent coordinate mapping.",
508         );
509       }
510       solveManipulation({
511         operation,
512         handle,
513         initial: before.box,
514         initialRotation: before.rotation,
515         initialPoint: point,
516         currentPoint: point,
517         modifiers: {},
518         ...resolved,
519       });
520       pointer.currentTarget.setPointerCapture(pointer.pointerId);
521       if (!pointer.currentTarget.hasPointerCapture(pointer.pointerId)) return;
522       const snapshot = Object.freeze({
523         operation,
524         handle: handle ?? null,
525         initial: before,
526         proposed: before,
527         applied: before,
528         snapActive: false,
529         snapSatisfied: false,
530       });
531       state.session = {
532         operation,
533         handle,
534         pointerId: pointer.pointerId,
535         target: pointer.currentTarget,
536         before,
537         last: before,
538         point,
539         clientX: pointer.clientX,
540         clientY: pointer.clientY,
541         parent: DOMMatrix.fromMatrix(state.parent),
542         started: false,
543         angle: Math.atan2(
544           point.y - before.box.top - before.box.height / 2,
545           point.x - before.box.left - before.box.width / 2,
546         ),
547         rotationDelta: 0,
548         snapshot,
549         coordinateMapping: currentRootCoordinateMapping(state.root),
550         source,
551       };
552       owners.set(state.options.box, state);
553       if (state.options.rotation) owners.set(state.options.rotation, state);
554       claimGeometryGeneration(state.options.box, state.options.rotation);
555       const operationOptions =
556         operation === "move"
557           ? state.options.move
558           : operation === "resize"
559             ? state.options.resize
560             : state.options.rotate;
561       const values: unknown[] = [
562         state.options.box,
563         state.options.rotation,
564         operationOptions?.enabled,
565       ];
566       const inputs = values.filter(isSignal);
567       state.session.releaseObservation = observeGestureInputs(inputs, () => {
568         validateSession(state);
569       });
570       claimedPresses.add(pointer.originalEvent);
571     },
572     onPointerMove(pointer) {
573       applySafely(state, pointer);
574     },
575     onPointerUp(pointer) {
576       if (state.session?.pointerId !== pointer.pointerId) return;
577       applySafely(state, pointer);
578       const session = state.session;
579       if (!session) return;
580       release(state, session);
581       state.active.set(null);
582       if (session.started)
583         state.options.onCommit?.(
584           Object.freeze({
585             ...event(session),
586             changed: !same(session.before, session.last),
587           }),
588         );
589     },
590     onPointerCancel(pointer) {
591       if (state.session?.pointerId === pointer.pointerId)
592         cancel(state, "pointer-cancel");
593     },
594     onLostPointerCapture(pointer) {
595       if (state.session?.pointerId === pointer.pointerId)
596         cancel(state, "capture-lost");
597     },
598     onKeyUp(key) {
599       updateModifiers(state, key);
600     },
601     onKeyDown(key) {
602       if (key.key === "Escape") cancel(state, "escape");
603       else updateModifiers(state, key);
604     },
605   };
606 }
607 
608 function transformValueChanged(current: number, previous: number): boolean {
609   return Math.abs(current - previous) > 1e-10 * Math.max(1, Math.abs(current), Math.abs(previous));
610 }
611 

Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.