@milesroxas/design-hub 0.4.3 → 0.6.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.
@@ -0,0 +1,107 @@
1
+ // On a phone the card is a bottom sheet: docked to the edge, lifted over the
2
+ // iOS keyboard, dragged down by its head to dismiss. These hooks are that
3
+ // behaviour; Card.tsx applies them only while the screen is narrow.
4
+ import { type PointerEvent, type RefObject, useEffect, useRef, useSyncExternalStore } from 'react';
5
+ import { dragOffset, shouldDismiss } from './place';
6
+
7
+ /** Narrow enough for the sheet; the same line as review.css. Layout, so width is the right test. */
8
+ const NARROW = '(max-width: 560px)';
9
+
10
+ const subscribeNarrow = (fn: () => void) => {
11
+ const q = matchMedia(NARROW);
12
+ q.addEventListener('change', fn);
13
+ return () => q.removeEventListener('change', fn);
14
+ };
15
+ export const useNarrow = () => useSyncExternalStore(subscribeNarrow, () => matchMedia(NARROW).matches);
16
+
17
+ /**
18
+ * iOS never resizes the layout viewport for the keyboard, only the visual one,
19
+ * so a sheet fixed to the bottom ends up behind the keys. This writes how far
20
+ * the keyboard reaches up (--rv-kb) and how tall the visible area is (--rv-vh)
21
+ * onto the sheet. Android resizes the layout itself (interactive-widget in
22
+ * index.html), where the keyboard reach comes out as 0.
23
+ */
24
+ export function useKeyboardInset(ref: RefObject<HTMLElement | null>, active: boolean) {
25
+ useEffect(() => {
26
+ const vv = visualViewport;
27
+ const el = ref.current;
28
+ if (!active || !vv || !el) return;
29
+ const sync = () => {
30
+ el.style.setProperty('--rv-kb', `${Math.max(0, innerHeight - vv.height - vv.offsetTop)}px`);
31
+ el.style.setProperty('--rv-vh', `${vv.height}px`);
32
+ };
33
+ sync();
34
+ vv.addEventListener('resize', sync);
35
+ vv.addEventListener('scroll', sync);
36
+ return () => {
37
+ vv.removeEventListener('resize', sync);
38
+ vv.removeEventListener('scroll', sync);
39
+ };
40
+ }, [ref, active]);
41
+ }
42
+
43
+ /** Drag the sheet down by its head; let go past the line, or with a flick, and it leaves. */
44
+ export function useSheetDrag(ref: RefObject<HTMLElement | null>, active: boolean, onDismiss?: () => void) {
45
+ const drag = useRef<{ id: number; y: number; t: number; last: number; lastT: number } | null>(null);
46
+
47
+ const release = (el: HTMLElement, dy: number, velocity: number) => {
48
+ delete el.dataset.dragging;
49
+ if (onDismiss && shouldDismiss(dy, velocity)) {
50
+ el.dataset.leaving = '';
51
+ el.style.transform = 'translateY(100%)';
52
+ setTimeout(onDismiss, 200);
53
+ } else el.style.transform = '';
54
+ };
55
+
56
+ return {
57
+ onPointerDown(e: PointerEvent<HTMLElement>) {
58
+ const el = ref.current;
59
+ if (!active || !onDismiss || !el || !(e.target as Element).closest('.rv-card-head, .rv-grab')) return;
60
+ if ((e.target as Element).closest('button')) return;
61
+ drag.current = { id: e.pointerId, y: e.clientY, t: e.timeStamp, last: e.clientY, lastT: e.timeStamp };
62
+ e.currentTarget.setPointerCapture(e.pointerId);
63
+ el.dataset.dragging = '';
64
+ },
65
+ onPointerMove(e: PointerEvent<HTMLElement>) {
66
+ const d = drag.current;
67
+ const el = ref.current;
68
+ if (!d || !el || e.pointerId !== d.id) return;
69
+ el.style.transform = `translateY(${dragOffset(e.clientY - d.y)}px)`;
70
+ d.last = e.clientY;
71
+ d.lastT = e.timeStamp;
72
+ },
73
+ onPointerUp(e: PointerEvent<HTMLElement>) {
74
+ const d = drag.current;
75
+ const el = ref.current;
76
+ drag.current = null;
77
+ if (!d || !el) return;
78
+ const dy = e.clientY - d.y;
79
+ release(el, dy, dy / Math.max(1, e.timeStamp - d.t));
80
+ },
81
+ onPointerCancel() {
82
+ const el = ref.current;
83
+ drag.current = null;
84
+ if (el) release(el, 0, 0);
85
+ },
86
+ };
87
+ }
88
+
89
+ /** On a phone, a pin the sheet would cover scrolls up into the space above it. */
90
+ export function useRevealPin(
91
+ ref: RefObject<HTMLElement | null>,
92
+ at: { x: number; y: number } | null,
93
+ active: boolean,
94
+ ) {
95
+ const y = at?.y ?? null;
96
+ // biome-ignore lint/correctness/useExhaustiveDependencies: once per card, when it opens; following the pin after that is the page's scroll
97
+ useEffect(() => {
98
+ const el = ref.current;
99
+ if (!active || y === null || !el) return;
100
+ const top = el.getBoundingClientRect().top;
101
+ if (y > 48 && y < top - 32) return;
102
+ scrollBy({
103
+ top: y - top * 0.4,
104
+ behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth',
105
+ });
106
+ }, [active]);
107
+ }
@@ -0,0 +1,44 @@
1
+ import assert from 'node:assert/strict';
2
+ import { test } from 'node:test';
3
+ import { centreOf, isSpot, nearestSpot, SPOTS, stepSpot } from './snap.ts';
4
+
5
+ const viewport = { width: 1280, height: 800 };
6
+ const still = { x: 0, y: 0 };
7
+ const at = (x: number, y: number) => nearestSpot({ x, y }, still, viewport, 40, 16);
8
+
9
+ test('every spot rests the button gap pixels in from its edges', () => {
10
+ assert.deepEqual(centreOf('bottom-right', viewport, 40, 16), { x: 1244, y: 764 });
11
+ assert.deepEqual(centreOf('top-left', viewport, 40, 16), { x: 36, y: 36 });
12
+ assert.deepEqual(centreOf('left', viewport, 40, 16), { x: 36, y: 400 });
13
+ });
14
+
15
+ test('a drop lands in the spot nearest it', () => {
16
+ assert.equal(at(1200, 760), 'bottom-right');
17
+ assert.equal(at(60, 700), 'bottom-left');
18
+ assert.equal(at(100, 60), 'top-left');
19
+ assert.equal(at(1250, 80), 'top-right');
20
+ assert.equal(at(1250, 420), 'right');
21
+ assert.equal(at(20, 380), 'left');
22
+ });
23
+
24
+ test('a flick carries the button toward where it was thrown', () => {
25
+ const centre = { x: 640, y: 420 };
26
+ assert.equal(nearestSpot(centre, { x: -6, y: 0 }, viewport, 40, 16), 'left');
27
+ assert.equal(nearestSpot(centre, { x: 4, y: 3 }, viewport, 40, 16), 'bottom-right');
28
+ assert.equal(nearestSpot(centre, { x: 0, y: -5 }, viewport, 40, 16) !== 'bottom-right', true);
29
+ });
30
+
31
+ test('Alt and an arrow step along the edge and across it, stopping at the ends', () => {
32
+ assert.equal(stepSpot('bottom-right', 'ArrowLeft'), 'bottom-left');
33
+ assert.equal(stepSpot('bottom-right', 'ArrowUp'), 'right');
34
+ assert.equal(stepSpot('right', 'ArrowUp'), 'top-right');
35
+ assert.equal(stepSpot('top-right', 'ArrowUp'), 'top-right');
36
+ assert.equal(stepSpot('bottom-left', 'ArrowDown'), 'bottom-left');
37
+ assert.equal(stepSpot('left', 'Enter'), 'left');
38
+ });
39
+
40
+ test('only the six spots are spots', () => {
41
+ for (const s of SPOTS) assert.equal(isSpot(s), true);
42
+ assert.equal(isSpot('middle'), false);
43
+ assert.equal(isSpot(null), false);
44
+ });
@@ -0,0 +1,59 @@
1
+ // Where the Comments button rests: one of six spots on the screen's edge,
2
+ // and which one a drag lands in. Pure, so node:test runs it.
3
+
4
+ export const SPOTS = ['top-left', 'top-right', 'left', 'right', 'bottom-left', 'bottom-right'] as const;
5
+ export type Spot = (typeof SPOTS)[number];
6
+ export const DEFAULT_SPOT: Spot = 'bottom-right';
7
+
8
+ type Point = { x: number; y: number };
9
+ type Size = { width: number; height: number };
10
+
11
+ /** How far ahead a release is projected along its velocity, in ms: a flick carries the button, a slow drop does not. */
12
+ const PROJECT_MS = 120;
13
+
14
+ export const isSpot = (value: unknown): value is Spot => SPOTS.includes(value as Spot);
15
+
16
+ /** The centre of the button resting at a spot, for a button `size` wide, `gap` in from the edges. */
17
+ export function centreOf(spot: Spot, viewport: Size, size: number, gap: number): Point {
18
+ const half = size / 2;
19
+ const x = spot.endsWith('left') ? gap + half : viewport.width - gap - half;
20
+ const y = spot.startsWith('top')
21
+ ? gap + half
22
+ : spot.startsWith('bottom')
23
+ ? viewport.height - gap - half
24
+ : viewport.height / 2;
25
+ return { x, y };
26
+ }
27
+
28
+ /** The spot nearest where the button would come to rest: its centre at release, carried a little along its velocity (px per ms). */
29
+ export function nearestSpot(at: Point, velocity: Point, viewport: Size, size: number, gap: number): Spot {
30
+ const land = { x: at.x + velocity.x * PROJECT_MS, y: at.y + velocity.y * PROJECT_MS };
31
+ let best: Spot = DEFAULT_SPOT;
32
+ let bestDistance = Number.POSITIVE_INFINITY;
33
+ for (const spot of SPOTS) {
34
+ const c = centreOf(spot, viewport, size, gap);
35
+ const distance = Math.hypot(c.x - land.x, c.y - land.y);
36
+ if (distance < bestDistance) {
37
+ best = spot;
38
+ bestDistance = distance;
39
+ }
40
+ }
41
+ return best;
42
+ }
43
+
44
+ const ROWS: Spot[][] = [
45
+ ['top-left', 'top-right'],
46
+ ['left', 'right'],
47
+ ['bottom-left', 'bottom-right'],
48
+ ];
49
+
50
+ /** The spot one step away by keyboard: Alt and an arrow move the button across or along the edge. */
51
+ export function stepSpot(spot: Spot, key: string): Spot {
52
+ const row = ROWS.findIndex((r) => r.includes(spot));
53
+ const col = ROWS[row].indexOf(spot);
54
+ if (key === 'ArrowLeft') return ROWS[row][0];
55
+ if (key === 'ArrowRight') return ROWS[row][1];
56
+ if (key === 'ArrowUp') return ROWS[Math.max(0, row - 1)][col];
57
+ if (key === 'ArrowDown') return ROWS[Math.min(ROWS.length - 1, row + 1)][col];
58
+ return spot;
59
+ }
@@ -0,0 +1,155 @@
1
+ import assert from 'node:assert/strict';
2
+ import { test } from 'node:test';
3
+ import {
4
+ type Draft,
5
+ draftOf,
6
+ initialView,
7
+ roundOf,
8
+ scopeOf,
9
+ stepFrom,
10
+ stepTarget,
11
+ threadOf,
12
+ type View,
13
+ type ViewAction,
14
+ view,
15
+ } from './view.ts';
16
+
17
+ const run = (start: View, ...actions: ViewAction[]) => actions.reduce(view, start);
18
+ const wholePage: Draft = { target: null, offset: null };
19
+
20
+ test('the layer starts with comment mode off, hidden or not as it was left', () => {
21
+ assert.deepEqual(initialView(false), { hidden: false, commenting: false, card: null, resolved: false });
22
+ assert.equal(initialView(true).hidden, true);
23
+ });
24
+
25
+ test('start turns comment mode on with no card; stop turns it off and drops the card', () => {
26
+ const on = view(initialView(false), { type: 'start' });
27
+ assert.deepEqual([on.commenting, on.card], [true, null]);
28
+ const off = run(on, { type: 'open', id: 'c1' }, { type: 'stop' });
29
+ assert.deepEqual([off.commenting, off.card], [false, null]);
30
+ });
31
+
32
+ test('opening a thread turns comment mode on and shows the layer even when it was hidden', () => {
33
+ const opened = view(initialView(true), { type: 'open', id: 'c7' });
34
+ assert.deepEqual(
35
+ [opened.hidden, opened.commenting, opened.card],
36
+ [false, true, { type: 'thread', id: 'c7' }],
37
+ );
38
+ });
39
+
40
+ test('one card at a time: a draft replaces a thread, a thread replaces a draft', () => {
41
+ const draft = run(
42
+ initialView(false),
43
+ { type: 'start' },
44
+ { type: 'open', id: 'c1' },
45
+ { type: 'draft', draft: wholePage },
46
+ );
47
+ assert.deepEqual(draft.card, { type: 'draft', draft: wholePage });
48
+ const thread = view(draft, { type: 'open', id: 'c2' });
49
+ assert.deepEqual(thread.card, { type: 'thread', id: 'c2' });
50
+ });
51
+
52
+ test('people toggles its card and turns comment mode on', () => {
53
+ const shown = view(initialView(false), { type: 'people' });
54
+ assert.deepEqual([shown.commenting, shown.card], [true, { type: 'people' }]);
55
+ assert.equal(view(shown, { type: 'people' }).card, null);
56
+ });
57
+
58
+ test('escape steps back one level: the card, then comment mode', () => {
59
+ const start = run(initialView(false), { type: 'start' }, { type: 'open', id: 'c1' });
60
+ const once = view(start, { type: 'escape' });
61
+ assert.deepEqual([once.commenting, once.card], [true, null]);
62
+ const twice = view(once, { type: 'escape' });
63
+ assert.equal(twice.commenting, false);
64
+ });
65
+
66
+ test('close drops the card and keeps comment mode', () => {
67
+ const state = run(
68
+ initialView(false),
69
+ { type: 'start' },
70
+ { type: 'draft', draft: wholePage },
71
+ { type: 'close' },
72
+ );
73
+ assert.deepEqual([state.commenting, state.card], [true, null]);
74
+ });
75
+
76
+ test('hide turns everything off; show brings back the button only', () => {
77
+ const hidden = run(initialView(false), { type: 'open', id: 'c1' }, { type: 'hide' });
78
+ assert.deepEqual([hidden.hidden, hidden.commenting, hidden.card], [true, false, null]);
79
+ const shown = view(hidden, { type: 'show' });
80
+ assert.deepEqual([shown.hidden, shown.commenting], [false, false]);
81
+ });
82
+
83
+ test('resolved toggles and survives the mode turning off and on', () => {
84
+ const state = run(
85
+ initialView(false),
86
+ { type: 'resolved' },
87
+ { type: 'start' },
88
+ { type: 'stop' },
89
+ { type: 'start' },
90
+ );
91
+ assert.equal(state.resolved, true);
92
+ assert.equal(view(state, { type: 'resolved' }).resolved, false);
93
+ });
94
+
95
+ test('every action returns a new value and leaves the old one alone', () => {
96
+ const start = initialView(false);
97
+ const frozen = Object.freeze({ ...start });
98
+ const next = view(frozen, { type: 'hide' });
99
+ assert.notEqual(next, frozen);
100
+ assert.deepEqual(frozen, start);
101
+ });
102
+
103
+ const t = (id: string, status: 'open' | 'resolved') => ({ id, status });
104
+ const roots = [t('a', 'open'), t('b', 'resolved'), t('c', 'open')];
105
+
106
+ test('the round is the open threads, plus resolved when shown, plus the open card always', () => {
107
+ assert.deepEqual(
108
+ roundOf(roots, false, null).map((c) => c.id),
109
+ ['a', 'c'],
110
+ );
111
+ assert.deepEqual(
112
+ roundOf(roots, true, null).map((c) => c.id),
113
+ ['a', 'b', 'c'],
114
+ );
115
+ assert.deepEqual(
116
+ roundOf(roots, false, 'b').map((c) => c.id),
117
+ ['a', 'b', 'c'],
118
+ );
119
+ });
120
+
121
+ test('stepping wraps at both ends', () => {
122
+ const round = roundOf(roots, false, null);
123
+ assert.equal(stepFrom(round, 'c', 1)?.id, 'a');
124
+ assert.equal(stepFrom(round, 'a', -1)?.id, 'c');
125
+ assert.equal(stepFrom(round, 'a', 1)?.id, 'c');
126
+ assert.equal(stepFrom([], 'a', 1), undefined);
127
+ });
128
+
129
+ test('the card names a thread only when it shows one', () => {
130
+ assert.equal(threadOf({ type: 'thread', id: 'x' }), 'x');
131
+ assert.equal(threadOf({ type: 'people' }), null);
132
+ assert.equal(threadOf(null), null);
133
+ });
134
+
135
+ test('the card holds a draft only when it is one', () => {
136
+ assert.deepEqual(draftOf({ type: 'draft', draft: wholePage }), wholePage);
137
+ assert.equal(draftOf({ type: 'thread', id: 'x' }), null);
138
+ assert.equal(draftOf(null), null);
139
+ });
140
+
141
+ test('the bar steps on from the open thread, or in from an end with none open', () => {
142
+ const round = roundOf(roots, false, null);
143
+ assert.equal(stepTarget(round, null, 1)?.id, 'a');
144
+ assert.equal(stepTarget(round, null, -1)?.id, 'c');
145
+ assert.equal(stepTarget(round, 'a', 1)?.id, 'c');
146
+ assert.equal(stepTarget(round, 'gone', 1)?.id, 'a');
147
+ assert.equal(stepTarget([], null, 1), undefined);
148
+ });
149
+
150
+ test('the toggle reads Page only while a page comment is being written', () => {
151
+ assert.equal(scopeOf(null), 'pin');
152
+ assert.equal(scopeOf({ type: 'draft', draft: wholePage }), 'page');
153
+ assert.equal(scopeOf({ type: 'draft', draft: { target: {} as Element, offset: { x: 0, y: 0 } } }), 'pin');
154
+ assert.equal(scopeOf({ type: 'thread', id: 'x' }), 'pin');
155
+ });
@@ -0,0 +1,101 @@
1
+ // What the review layer shows. Pure, so node:test runs it: no React, no DOM
2
+ // beyond the Element type a draft points at.
3
+
4
+ /** A new comment being placed: the element it is about and where on it, as fractions of its box, or neither for the whole page. */
5
+ export type Draft = { target: Element | null; offset: { x: number; y: number } | null };
6
+
7
+ /** The one card on screen: a thread, a comment being written, or the people. */
8
+ export type Card = { type: 'thread'; id: string } | { type: 'draft'; draft: Draft } | { type: 'people' };
9
+
10
+ /**
11
+ * One value, so a transition (start, open a pin, close, hide) changes every
12
+ * field it touches at once and no two fields can disagree. `commenting` is
13
+ * comment mode: pins on the page and a click anywhere starts a comment. Off,
14
+ * the page carries only the button. `hidden` tucks even the button into the
15
+ * screen's edge; it is the one field that outlives the page (kit/prefs.ts).
16
+ */
17
+ export type View = {
18
+ hidden: boolean;
19
+ commenting: boolean;
20
+ card: Card | null;
21
+ resolved: boolean;
22
+ };
23
+
24
+ export type ViewAction =
25
+ | { type: 'start' }
26
+ | { type: 'stop' }
27
+ | { type: 'open'; id: string }
28
+ | { type: 'draft'; draft: Draft }
29
+ | { type: 'people' }
30
+ | { type: 'close' }
31
+ | { type: 'escape' }
32
+ | { type: 'resolved' }
33
+ | { type: 'hide' }
34
+ | { type: 'show' };
35
+
36
+ export const initialView = (hidden: boolean): View => ({
37
+ hidden,
38
+ commenting: false,
39
+ card: null,
40
+ resolved: false,
41
+ });
42
+
43
+ export function view(state: View, action: ViewAction): View {
44
+ switch (action.type) {
45
+ case 'start':
46
+ return { ...state, hidden: false, commenting: true };
47
+ case 'stop':
48
+ return { ...state, commenting: false, card: null };
49
+ // A link to a comment opens its thread even when comments are hidden: the link is the request to see it.
50
+ case 'open':
51
+ return { ...state, hidden: false, commenting: true, card: { type: 'thread', id: action.id } };
52
+ case 'draft':
53
+ return { ...state, card: { type: 'draft', draft: action.draft } };
54
+ case 'people':
55
+ return { ...state, commenting: true, card: state.card?.type === 'people' ? null : { type: 'people' } };
56
+ case 'close':
57
+ return { ...state, card: null };
58
+ // Esc steps back one level: the card first, then comment mode.
59
+ case 'escape':
60
+ return state.card ? { ...state, card: null } : { ...state, commenting: false };
61
+ case 'resolved':
62
+ return { ...state, resolved: !state.resolved };
63
+ case 'hide':
64
+ return { ...state, hidden: true, commenting: false, card: null };
65
+ case 'show':
66
+ return { ...state, hidden: false };
67
+ }
68
+ }
69
+
70
+ type Thread = { id: string; status: 'open' | 'resolved' };
71
+
72
+ /** The threads comment mode steps through: the open ones, the resolved too when shown, and always the open card's, so resolving it never pulls the card away. */
73
+ export const roundOf = <T extends Thread>(roots: T[], resolved: boolean, current: string | null): T[] =>
74
+ roots.filter((c) => c.status === 'open' || resolved || c.id === current);
75
+
76
+ /** The thread `by` steps from `id` in the round, wrapping at both ends. */
77
+ export function stepFrom<T extends Thread>(round: T[], id: string, by: number): T | undefined {
78
+ const at = round.findIndex((c) => c.id === id);
79
+ return round[(at + by + round.length) % round.length];
80
+ }
81
+
82
+ /** The thread the card shows, when it shows one. */
83
+ export const threadOf = (card: Card | null): string | null => (card?.type === 'thread' ? card.id : null);
84
+
85
+ /** The comment being placed, when the card is one. */
86
+ export const draftOf = (card: Card | null): Draft | null => (card?.type === 'draft' ? card.draft : null);
87
+
88
+ /** Where the bar's arrows go: on from the open thread, or in from an end when none is open. */
89
+ export function stepTarget<T extends Thread>(round: T[], current: string | null, by: number): T | undefined {
90
+ if (current && round.some((c) => c.id === current)) return stepFrom(round, current, by);
91
+ return by > 0 ? round[0] : round.at(-1);
92
+ }
93
+
94
+ /** What a new comment is about: a spot on the page, or the page as a whole. */
95
+ export type Scope = 'pin' | 'page';
96
+
97
+ /** The bar's toggle reads the card: a draft with no element is a page comment, anything else is pinning. */
98
+ export const scopeOf = (card: Card | null): Scope => {
99
+ const d = draftOf(card);
100
+ return d && !d.target ? 'page' : 'pin';
101
+ };