@dloizides/marketing-astro-kit 1.13.0 → 1.14.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.
Files changed (36) hide show
  1. package/README.md +3 -2
  2. package/package.json +1 -1
  3. package/src/ContactCard.astro +124 -107
  4. package/src/contactCard/CardBack.astro +31 -0
  5. package/src/contactCard/CardForm.ts +5 -0
  6. package/src/contactCard/CardFront.astro +27 -0
  7. package/src/contactCard/CardIconName.ts +1 -0
  8. package/src/contactCard/CardSave.astro +3 -1
  9. package/src/contactCard/CardShare.astro +32 -0
  10. package/src/contactCard/CardTurn.astro +15 -0
  11. package/src/contactCard/CardTwoSided.astro +48 -0
  12. package/src/contactCard/cardIcons.ts +1 -0
  13. package/src/contactCard/cssRaw.d.ts +4 -0
  14. package/src/contactCard/index.ts +20 -16
  15. package/src/contactCard/motion/FlipMotion.ts +5 -0
  16. package/src/contactCard/motion/OpenLanding.ts +6 -0
  17. package/src/contactCard/motion/OpenMotion.ts +5 -1
  18. package/src/contactCard/motion/ShareMode.ts +7 -0
  19. package/src/contactCard/motion/TiltMotion.ts +4 -1
  20. package/src/contactCard/motion/beats.ts +3 -3
  21. package/src/contactCard/motion/cardMotion.ts +25 -4
  22. package/src/contactCard/motion/holdDuringOpen.ts +4 -4
  23. package/src/contactCard/motion/mountFlip.ts +64 -0
  24. package/src/contactCard/motion/mountMotion.ts +33 -26
  25. package/src/contactCard/motion/mountOpenMark.ts +23 -20
  26. package/src/contactCard/motion/mountShare.ts +57 -0
  27. package/src/contactCard/motion/mountTilt.ts +84 -92
  28. package/src/contactCard/motion/openCss.ts +3 -3
  29. package/src/contactCard/motion/orientationAccess.ts +36 -0
  30. package/src/contactCard/motion/tiltLights.ts +14 -0
  31. package/src/contactCard/motion/tiltPose.ts +59 -38
  32. package/src/contactCard/motion/twoSidedBeats.ts +37 -0
  33. package/src/contactCard/motion.css +5 -0
  34. package/src/contactCard/share.css +16 -0
  35. package/src/contactCard/twoSided.css +43 -0
  36. package/src/contactCard/types.ts +52 -47
@@ -1,6 +1,9 @@
1
+ import { FlipMotion } from './FlipMotion';
2
+ import { OpenLanding } from './OpenLanding';
1
3
  import { OpenMotion } from './OpenMotion';
2
4
  import { QrMotion } from './QrMotion';
3
5
  import { SaveMotion } from './SaveMotion';
6
+ import { ShareMode } from './ShareMode';
4
7
  import { TiltMotion } from './TiltMotion';
5
8
 
6
9
  export interface ContactCardMotion {
@@ -8,23 +11,38 @@ export interface ContactCardMotion {
8
11
  tiltMotion: TiltMotion;
9
12
  qrMotion: QrMotion;
10
13
  saveMotion: SaveMotion;
14
+ shareMode: ShareMode;
15
+ openLands: OpenLanding;
16
+ flipMotion: FlipMotion;
11
17
  }
12
18
 
13
19
  export type ContactCardMotionInput = Partial<Record<keyof ContactCardMotion, string>>;
14
20
 
15
21
  const CHOICES: Readonly<Record<keyof ContactCardMotion, readonly string[]>> = {
16
- openMotion: [OpenMotion.None, OpenMotion.MarkFirst, OpenMotion.MarkLands, OpenMotion.WrittenIn],
17
- tiltMotion: [TiltMotion.None, TiltMotion.CardLeans, TiltMotion.PortraitLeans, TiltMotion.LayersDrift],
22
+ openMotion: [
23
+ OpenMotion.None, OpenMotion.MarkFirst, OpenMotion.MarkLands, OpenMotion.WrittenIn,
24
+ OpenMotion.TileGrows, OpenMotion.MoonOpens, OpenMotion.TurnsFaceUp, OpenMotion.PassRises,
25
+ ],
26
+ tiltMotion: [
27
+ TiltMotion.None, TiltMotion.CardLeans, TiltMotion.PortraitLeans, TiltMotion.LayersDrift,
28
+ TiltMotion.LightSweeps, TiltMotion.GoldGloss, TiltMotion.DeepLayers,
29
+ ],
18
30
  qrMotion: [QrMotion.None, QrMotion.TurnOver, QrMotion.CubeTurn, QrMotion.ListTurns],
19
31
  saveMotion: [SaveMotion.None, SaveMotion.Tick, SaveMotion.LightCrosses, SaveMotion.CubeCloses],
32
+ shareMode: [ShareMode.None, ShareMode.WhiteSheet, ShareMode.NightFrame, ShareMode.FaceAbove],
33
+ openLands: [OpenLanding.TurnToFront, OpenLanding.Front, OpenLanding.Back],
34
+ flipMotion: [FlipMotion.None, FlipMotion.TurnOver],
20
35
  };
21
36
 
22
37
  /** The recommended motion, used for every setting the host leaves out. */
23
38
  export const DEFAULT_CARD_MOTION: Readonly<ContactCardMotion> = {
24
- openMotion: OpenMotion.MarkLands,
25
- tiltMotion: TiltMotion.CardLeans,
39
+ openMotion: OpenMotion.TileGrows,
40
+ tiltMotion: TiltMotion.LightSweeps,
26
41
  qrMotion: QrMotion.ListTurns,
27
42
  saveMotion: SaveMotion.Tick,
43
+ shareMode: ShareMode.FaceAbove,
44
+ openLands: OpenLanding.TurnToFront,
45
+ flipMotion: FlipMotion.TurnOver,
28
46
  };
29
47
 
30
48
  /** Fills the left-out settings with the defaults; throws on a value no option has. */
@@ -45,5 +63,8 @@ export function motionAttributes(motion: ContactCardMotion): Record<string, stri
45
63
  'data-tilt-motion': motion.tiltMotion,
46
64
  'data-qr-motion': motion.qrMotion,
47
65
  'data-save-motion': motion.saveMotion,
66
+ 'data-share-mode': motion.shareMode,
67
+ 'data-open-lands': motion.openLands,
68
+ 'data-flip-motion': motion.flipMotion,
48
69
  };
49
70
  }
@@ -1,13 +1,13 @@
1
- import { beatsFor } from './beats';
2
1
  import { partSelector } from './parts';
2
+ import { openingBeats } from './twoSidedBeats';
3
3
 
4
- const HELD_PARTS = ['home', 'qrBtn'];
4
+ const HELD_PARTS = ['home', 'qrBtn', 'turn'];
5
5
  const INERT = 'inert';
6
6
 
7
- /** Keeps Add to home screen and Show my QR untappable while the opening still hides them. */
7
+ /** Keeps Add to home screen, Show my QR and the turn button untappable while the opening still hides them. */
8
8
  export function holdDuringOpen(card: HTMLElement, openMotion: string, reduced: boolean, signal?: AbortSignal): void {
9
9
  if (reduced) return;
10
- const shownAtMs = beatsFor(openMotion)
10
+ const shownAtMs = openingBeats(openMotion)
11
11
  .filter((beat) => HELD_PARTS.includes(beat.part))
12
12
  .reduce((latest, beat) => Math.max(latest, beat.atMs + beat.lengthMs), 0);
13
13
  if (shownAtMs === 0) return;
@@ -0,0 +1,64 @@
1
+ import { EASINGS } from './easings';
2
+ import { FlipMotion } from './FlipMotion';
3
+
4
+ const TURN_MS = 560;
5
+ const BACK_DEG = 180;
6
+ const HALF = 2;
7
+ const BACK = 'back';
8
+ const CONTROLS = 'a,button,input,select,textarea';
9
+
10
+ interface Faces {
11
+ flip: HTMLElement;
12
+ front: HTMLElement;
13
+ back: HTMLElement;
14
+ button: HTMLElement;
15
+ }
16
+
17
+ function findFaces(card: HTMLElement): Faces | null {
18
+ const flip = card.querySelector<HTMLElement>('[data-part="flip"]');
19
+ const front = card.querySelector<HTMLElement>('[data-part="front"]');
20
+ const back = card.querySelector<HTMLElement>('[data-part="back"]');
21
+ const button = card.querySelector<HTMLElement>('[data-card-turn]');
22
+ return flip === null || front === null || back === null || button === null ? null : { flip, front, back, button };
23
+ }
24
+
25
+ function show(card: HTMLElement, faces: Faces, onBack: boolean): void {
26
+ faces.flip.dataset['face'] = onBack ? BACK : 'front';
27
+ faces.flip.style.transform = `rotateY(${onBack ? BACK_DEG : 0}deg)`;
28
+ faces.front.toggleAttribute('inert', onBack);
29
+ faces.back.toggleAttribute('inert', !onBack);
30
+ faces.button.setAttribute('aria-label', (onBack ? faces.button.dataset['labelFront'] : faces.button.dataset['labelBack']) ?? '');
31
+ const live = card.querySelector('[data-part="turn-live"]');
32
+ if (live !== null) live.textContent = (onBack ? faces.back : faces.front).getAttribute('aria-label') ?? '';
33
+ }
34
+
35
+ function turnKeyframes(onBack: boolean): Keyframe[] {
36
+ const [from, to] = onBack ? [0, BACK_DEG] : [BACK_DEG, 0];
37
+ return [
38
+ { transform: `rotateY(${from}deg)`, easing: EASINGS['turnOut'] },
39
+ { transform: `rotateY(${(from + to) / HALF}deg)`, easing: EASINGS['turnIn'] },
40
+ { transform: `rotateY(${to}deg)` },
41
+ ];
42
+ }
43
+
44
+ /** Turns the two-sided card on a tap outside its links, its turn button, Enter or Space; a tap mid-turn reverses it. */
45
+ export function mountFlip(card: HTMLElement, flipMotion: FlipMotion, reduced: boolean, signal?: AbortSignal): void {
46
+ const faces = findFaces(card);
47
+ if (faces === null) return;
48
+ let running: Animation | null = null;
49
+ const turn = (): void => {
50
+ const onBack = faces.flip.dataset['face'] !== BACK;
51
+ show(card, faces, onBack);
52
+ if (reduced || flipMotion === FlipMotion.None || typeof faces.flip.animate !== 'function') return;
53
+ if (running?.playState === 'running') {
54
+ running.reverse();
55
+ return;
56
+ }
57
+ running = faces.flip.animate(turnKeyframes(onBack), { duration: TURN_MS });
58
+ };
59
+ faces.button.addEventListener('click', turn, { signal });
60
+ card.querySelector('[data-part="stage"]')?.addEventListener('click', (event) => {
61
+ if (event.target instanceof Element && event.target.closest(CONTROLS) !== null) return;
62
+ turn();
63
+ }, { signal });
64
+ }
@@ -1,26 +1,33 @@
1
- import { holdDuringOpen } from './holdDuringOpen';
2
- import { mountOpenMark } from './mountOpenMark';
3
- import { mountQrTurn } from './mountQrTurn';
4
- import { mountSave } from './mountSave';
5
- import { mountTilt } from './mountTilt';
6
- import { resolveCardMotion } from './cardMotion';
7
-
8
- const REDUCED_QUERY = '(prefers-reduced-motion: reduce)';
9
-
10
- /** Wires the four motion settings the card carries in its data attributes. */
11
- export function mountCardMotion(card: HTMLElement, signal?: AbortSignal): void {
12
- const reduced = window.matchMedia(REDUCED_QUERY).matches;
13
- const settings = card.dataset;
14
- const none = 'none';
15
- const motion = resolveCardMotion({
16
- openMotion: settings['openMotion'] ?? none,
17
- tiltMotion: settings['tiltMotion'] ?? none,
18
- qrMotion: settings['qrMotion'] ?? none,
19
- saveMotion: settings['saveMotion'] ?? none,
20
- });
21
- mountOpenMark(card, motion.openMotion, reduced);
22
- holdDuringOpen(card, motion.openMotion, reduced, signal);
23
- mountQrTurn(card, motion.qrMotion, reduced, signal);
24
- mountSave(card, motion.saveMotion, reduced, signal);
25
- mountTilt(card, motion.tiltMotion, signal);
26
- }
1
+ import { holdDuringOpen } from './holdDuringOpen';
2
+ import { mountOpenMark } from './mountOpenMark';
3
+ import { mountQrTurn } from './mountQrTurn';
4
+ import { mountSave } from './mountSave';
5
+ import { mountTilt } from './mountTilt';
6
+ import { resolveCardMotion } from './cardMotion';
7
+ import { mountFlip } from './mountFlip';
8
+ import { mountShare } from './mountShare';
9
+
10
+ const REDUCED_QUERY = '(prefers-reduced-motion: reduce)';
11
+
12
+ /** Wires the motion, turn and share settings the card carries in its data attributes. */
13
+ export function mountCardMotion(card: HTMLElement, signal?: AbortSignal): void {
14
+ const reduced = window.matchMedia(REDUCED_QUERY).matches;
15
+ const settings = card.dataset;
16
+ const none = 'none';
17
+ const motion = resolveCardMotion({
18
+ openMotion: settings['openMotion'] ?? none,
19
+ tiltMotion: settings['tiltMotion'] ?? none,
20
+ qrMotion: settings['qrMotion'] ?? none,
21
+ saveMotion: settings['saveMotion'] ?? none,
22
+ shareMode: settings['shareMode'] ?? none,
23
+ openLands: settings['openLands'],
24
+ flipMotion: settings['flipMotion'] ?? none,
25
+ });
26
+ mountOpenMark(card, motion.openMotion, reduced);
27
+ holdDuringOpen(card, motion.openMotion, reduced, signal);
28
+ mountQrTurn(card, motion.qrMotion, reduced, signal);
29
+ mountSave(card, motion.saveMotion, reduced, signal);
30
+ mountTilt(card, motion.tiltMotion, signal);
31
+ mountShare(card, motion.shareMode, signal);
32
+ mountFlip(card, motion.flipMotion, reduced, signal);
33
+ }
@@ -1,20 +1,23 @@
1
- import { OpenMotion } from './OpenMotion';
2
-
3
- const LOGO_RATE: Readonly<Record<string, number>> = { [OpenMotion.MarkFirst]: 1.8, [OpenMotion.MarkLands]: 2, [OpenMotion.WrittenIn]: 1.8 };
4
- const FADE_MS = 300;
5
-
6
- /** Speeds the logo-kit mark intro to the option's rate, or shows its still under reduced motion or without `d:path`. */
7
- export function mountOpenMark(card: HTMLElement, openMotion: OpenMotion, reduced: boolean): void {
8
- const mark = card.querySelector<HTMLElement>('[data-part="mark"][data-logo-intro]');
9
- const still = card.querySelector<HTMLTemplateElement>('template[data-mark-still]');
10
- if (mark === null || still === null) return;
11
- const drawable = typeof CSS !== 'undefined' && CSS.supports('d', "path('M0 0')");
12
- const moves = !reduced && openMotion !== OpenMotion.None;
13
- if (moves && drawable) {
14
- const rate = LOGO_RATE[openMotion] ?? 1;
15
- mark.getAnimations({ subtree: true }).forEach((animation) => { animation.playbackRate = rate; });
16
- return;
17
- }
18
- mark.replaceChildren(still.content.cloneNode(true));
19
- if (moves) mark.animate?.([{ opacity: 0 }, { opacity: 1 }], { duration: FADE_MS, fill: 'backwards' });
20
- }
1
+ import { OpenMotion } from './OpenMotion';
2
+
3
+ const LOGO_RATE: Readonly<Record<string, number>> = {
4
+ [OpenMotion.MarkFirst]: 1.8, [OpenMotion.MarkLands]: 2, [OpenMotion.WrittenIn]: 1.8, [OpenMotion.TileGrows]: 1.8,
5
+ [OpenMotion.MoonOpens]: 1.8, [OpenMotion.TurnsFaceUp]: 1.4, [OpenMotion.PassRises]: 1.8,
6
+ };
7
+ const FADE_MS = 300;
8
+
9
+ /** Speeds the logo-kit mark intro to the option's rate, or shows its still under reduced motion or without `d:path`. */
10
+ export function mountOpenMark(card: HTMLElement, openMotion: OpenMotion, reduced: boolean): void {
11
+ const mark = card.querySelector<HTMLElement>('[data-part="mark"][data-logo-intro]');
12
+ const still = card.querySelector<HTMLTemplateElement>('template[data-mark-still]');
13
+ if (mark === null || still === null) return;
14
+ const drawable = typeof CSS !== 'undefined' && CSS.supports('d', "path('M0 0')");
15
+ const moves = !reduced && openMotion !== OpenMotion.None;
16
+ if (moves && drawable) {
17
+ const rate = LOGO_RATE[openMotion] ?? 1;
18
+ mark.getAnimations({ subtree: true }).forEach((animation) => { animation.playbackRate = rate; });
19
+ return;
20
+ }
21
+ mark.replaceChildren(still.content.cloneNode(true));
22
+ if (moves) mark.animate?.([{ opacity: 0 }, { opacity: 1 }], { duration: FADE_MS, fill: 'backwards' });
23
+ }
@@ -0,0 +1,57 @@
1
+ import { ShareMode } from './ShareMode';
2
+
3
+ const SCREEN = 'screen';
4
+ const OPENED = 'tmk-share-open';
5
+
6
+ interface WakeLockHandle {
7
+ release: () => Promise<void>;
8
+ }
9
+
10
+ interface WakeLockNavigator {
11
+ wakeLock?: { request: (type: typeof SCREEN) => Promise<WakeLockHandle> };
12
+ }
13
+
14
+ const warn = (error: unknown): void => console.warn(error);
15
+
16
+ function keepAwake(share: HTMLDialogElement, signal?: AbortSignal): void {
17
+ const wakeLock = (navigator as WakeLockNavigator).wakeLock;
18
+ if (wakeLock === undefined) return;
19
+ let held: WakeLockHandle | null = null;
20
+ const take = (): void => {
21
+ if (!share.open || document.hidden || held !== null) return;
22
+ wakeLock.request(SCREEN).then((handle) => {
23
+ if (share.open) held = handle;
24
+ else handle.release().catch(warn);
25
+ }).catch(warn);
26
+ };
27
+ const letGo = (): void => {
28
+ held?.release().catch(warn);
29
+ held = null;
30
+ };
31
+ share.addEventListener(OPENED, take, { signal });
32
+ share.addEventListener('close', letGo, { signal });
33
+ document.addEventListener('visibilitychange', () => {
34
+ if (document.hidden) held = null;
35
+ else take();
36
+ }, { signal });
37
+ signal?.addEventListener('abort', letGo, { once: true });
38
+ }
39
+
40
+ /** Opens the full-screen, motionless share view from Show my QR and keeps the screen awake while it is open. */
41
+ export function mountShare(card: HTMLElement, shareMode: ShareMode, signal?: AbortSignal): void {
42
+ if (shareMode === ShareMode.None) return;
43
+ const share = card.querySelector<HTMLDialogElement>('[data-card-share]');
44
+ const button = card.querySelector<HTMLElement>('[data-card-qr]');
45
+ if (share === null || button === null) return;
46
+ keepAwake(share, signal);
47
+ button.addEventListener('click', () => {
48
+ share.showModal();
49
+ button.setAttribute('aria-expanded', 'true');
50
+ share.dispatchEvent(new Event(OPENED));
51
+ }, { signal });
52
+ share.addEventListener('close', () => {
53
+ button.setAttribute('aria-expanded', 'false');
54
+ button.focus();
55
+ }, { signal });
56
+ share.querySelector('[data-card-share-close]')?.addEventListener('click', () => share.close(), { signal });
57
+ }
@@ -1,92 +1,84 @@
1
- import { MotionState, createMotionController } from '../../motionController';
2
- import { EASINGS } from './easings';
3
- import { partSelector } from './parts';
4
- import { TiltMotion } from './TiltMotion';
5
- import { dragToUnit, gammaToUnit, tiltPose } from './tiltPose';
6
-
7
- const START_PX = 8;
8
- const RETURN_MS = 600;
9
- const SENSOR_SHOWS_LIGHT = 0.1;
10
- const TILTING = 'data-tilting';
11
-
12
- interface OrientationGlobal {
13
- DeviceOrientationEvent?: { requestPermission?: unknown };
14
- }
15
-
16
- function sensorAllowed(): boolean {
17
- const orientation = (window as OrientationGlobal).DeviceOrientationEvent;
18
- return orientation !== undefined && orientation.requestPermission === undefined;
19
- }
20
-
21
- function partFinder(card: HTMLElement): (part: string) => HTMLElement[] {
22
- return (part) => (part === 'card' ? [card] : Array.from(card.querySelectorAll<HTMLElement>(partSelector(part))));
23
- }
24
-
25
- function swallowNextClick(card: HTMLElement, signal?: AbortSignal): void {
26
- const stopClick = (event: Event): void => {
27
- event.preventDefault();
28
- event.stopPropagation();
29
- };
30
- card.addEventListener('click', stopClick, { capture: true, once: true, signal });
31
- setTimeout(() => card.removeEventListener('click', stopClick, { capture: true }), 0);
32
- }
33
-
34
- function easeBack(find: (part: string) => HTMLElement[], tiltMotion: TiltMotion): void {
35
- const restPose = tiltPose(tiltMotion, 0);
36
- Object.entries(restPose).forEach(([part, transform]) => find(part).forEach((element) => {
37
- const from = element.style.transform !== '' ? element.style.transform : transform;
38
- element.animate?.([{ transform: from }, { transform }], { duration: RETURN_MS, easing: EASINGS['settle'] });
39
- }));
40
- }
41
-
42
- /** Leans the card with a sideways drag or a permission-free motion sensor; still under reduced motion. */
43
- export function mountTilt(card: HTMLElement, tiltMotion: TiltMotion, signal?: AbortSignal): void {
44
- if (tiltMotion === TiltMotion.None) return;
45
- const find = partFinder(card);
46
- const moving = Object.keys(tiltPose(tiltMotion, 1)).flatMap(find);
47
- const drag = { unit: 0, pointer: null as number | null, startX: 0, active: false, sensing: false, gammaAtLoad: null as number | null };
48
- const apply = (): void => Object.entries(tiltPose(tiltMotion, drag.unit)).forEach(([part, transform]) => find(part).forEach((element) => { element.style.transform = transform; }));
49
- const rest = (): void => {
50
- Object.assign(drag, { unit: 0, active: false, sensing: false });
51
- moving.forEach((element) => { element.style.transform = ''; });
52
- card.removeAttribute(TILTING);
53
- };
54
- const controller = createMotionController({ target: card, onFrame: apply, onStill: rest, canRun: () => drag.active || drag.sensing, signal });
55
- const settle = (): void => { rest(); controller.sync(); };
56
- const running = (): boolean => controller.getState() === MotionState.Running;
57
- card.addEventListener('pointerdown', (event) => {
58
- if (drag.pointer !== null) return;
59
- drag.pointer = event.pointerId;
60
- drag.startX = event.clientX;
61
- }, { signal });
62
- card.addEventListener('pointermove', (event) => {
63
- if (event.pointerId !== drag.pointer) return;
64
- const dx = event.clientX - drag.startX;
65
- if (!drag.active && Math.abs(dx) > START_PX && running()) {
66
- drag.active = true;
67
- card.setAttribute(TILTING, '');
68
- controller.sync();
69
- }
70
- if (drag.active) drag.unit = dragToUnit(dx);
71
- }, { signal });
72
- const end = (event: PointerEvent): void => {
73
- if (event.pointerId !== drag.pointer) return;
74
- drag.pointer = null;
75
- if (!drag.active) return;
76
- swallowNextClick(card, signal);
77
- easeBack(find, tiltMotion);
78
- settle();
79
- };
80
- signal?.addEventListener('abort', settle, { once: true });
81
- card.addEventListener('pointerup', end, { signal });
82
- card.addEventListener('pointercancel', end, { signal });
83
- if (!sensorAllowed()) return;
84
- window.addEventListener('deviceorientation', (event) => {
85
- if (event.gamma === null || drag.active || !running()) return;
86
- drag.gammaAtLoad ??= event.gamma;
87
- drag.unit = gammaToUnit(event.gamma, drag.gammaAtLoad);
88
- drag.sensing = true;
89
- card.toggleAttribute(TILTING, Math.abs(drag.unit) > SENSOR_SHOWS_LIGHT);
90
- controller.sync();
91
- }, { signal });
92
- }
1
+ import { MotionState, createMotionController } from '../../motionController';
2
+ import { EASINGS } from './easings';
3
+ import { listenOrientation } from './orientationAccess';
4
+ import { partSelector } from './parts';
5
+ import { TiltMotion } from './TiltMotion';
6
+ import { dragToUnit, gammaToUnit, tiltPose } from './tiltPose';
7
+
8
+ const START_PX = 8;
9
+ const RETURN_MS = 600;
10
+ const SENSOR_SHOWS_LIGHT = 0.1;
11
+ const TILTING = 'data-tilting';
12
+
13
+ function partFinder(card: HTMLElement): (part: string) => HTMLElement[] {
14
+ const layer = card.querySelector<HTMLElement>('[data-part="tilt"]') ?? card;
15
+ return (part) => (part === 'card' ? [layer] : Array.from(card.querySelectorAll<HTMLElement>(partSelector(part))));
16
+ }
17
+
18
+ function swallowNextClick(card: HTMLElement, signal?: AbortSignal): void {
19
+ const stopClick = (event: Event): void => {
20
+ event.preventDefault();
21
+ event.stopPropagation();
22
+ };
23
+ card.addEventListener('click', stopClick, { capture: true, once: true, signal });
24
+ setTimeout(() => card.removeEventListener('click', stopClick, { capture: true }), 0);
25
+ }
26
+
27
+ function easeBack(find: (part: string) => HTMLElement[], tiltMotion: TiltMotion): void {
28
+ const restPose = tiltPose(tiltMotion, 0);
29
+ Object.entries(restPose).forEach(([part, transform]) => find(part).forEach((element) => {
30
+ const from = element.style.transform !== '' ? element.style.transform : transform;
31
+ element.animate?.([{ transform: from }, { transform }], { duration: RETURN_MS, easing: EASINGS['settle'] });
32
+ }));
33
+ }
34
+
35
+ /** Leans the card with a sideways drag or the motion sensor (asked for on iOS); still under reduced motion. */
36
+ export function mountTilt(card: HTMLElement, tiltMotion: TiltMotion, signal?: AbortSignal): void {
37
+ if (tiltMotion === TiltMotion.None) return;
38
+ const find = partFinder(card);
39
+ const moving = Object.keys(tiltPose(tiltMotion, 1)).flatMap(find);
40
+ const drag = { unit: 0, pointer: null as number | null, startX: 0, active: false, sensing: false, gammaAtLoad: null as number | null };
41
+ const apply = (): void => Object.entries(tiltPose(tiltMotion, drag.unit)).forEach(([part, transform]) => find(part).forEach((element) => { element.style.transform = transform; }));
42
+ const rest = (): void => {
43
+ Object.assign(drag, { unit: 0, active: false, sensing: false });
44
+ moving.forEach((element) => { element.style.transform = ''; });
45
+ card.removeAttribute(TILTING);
46
+ };
47
+ const controller = createMotionController({ target: card, onFrame: apply, onStill: rest, canRun: () => drag.active || drag.sensing, signal });
48
+ const settle = (): void => { rest(); controller.sync(); };
49
+ const running = (): boolean => controller.getState() === MotionState.Running;
50
+ card.addEventListener('pointerdown', (event) => {
51
+ if (drag.pointer !== null) return;
52
+ drag.pointer = event.pointerId;
53
+ drag.startX = event.clientX;
54
+ }, { signal });
55
+ card.addEventListener('pointermove', (event) => {
56
+ if (event.pointerId !== drag.pointer) return;
57
+ const dx = event.clientX - drag.startX;
58
+ if (!drag.active && Math.abs(dx) > START_PX && running()) {
59
+ drag.active = true;
60
+ card.setAttribute(TILTING, '');
61
+ controller.sync();
62
+ }
63
+ if (drag.active) drag.unit = dragToUnit(dx);
64
+ }, { signal });
65
+ const end = (event: PointerEvent): void => {
66
+ if (event.pointerId !== drag.pointer) return;
67
+ drag.pointer = null;
68
+ if (!drag.active) return;
69
+ swallowNextClick(card, signal);
70
+ easeBack(find, tiltMotion);
71
+ settle();
72
+ };
73
+ signal?.addEventListener('abort', settle, { once: true });
74
+ card.addEventListener('pointerup', end, { signal });
75
+ card.addEventListener('pointercancel', end, { signal });
76
+ listenOrientation(card, (event) => {
77
+ if (event.gamma === null || drag.active || !running()) return;
78
+ drag.gammaAtLoad ??= event.gamma;
79
+ drag.unit = gammaToUnit(event.gamma, drag.gammaAtLoad);
80
+ drag.sensing = true;
81
+ card.toggleAttribute(TILTING, Math.abs(drag.unit) > SENSOR_SHOWS_LIGHT);
82
+ controller.sync();
83
+ }, running, signal);
84
+ }
@@ -1,9 +1,9 @@
1
- import { beatsFor } from './beats';
2
1
  import { partSelector } from './parts';
2
+ import { openingBeats } from './twoSidedBeats';
3
3
 
4
4
  /** The opening as CSS animations scoped to the option, played only when motion is allowed; `''` for `none`. */
5
- export function buildOpenCss(openMotion: string): string {
6
- const beats = beatsFor(openMotion);
5
+ export function buildOpenCss(openMotion: string, openLands?: string): string {
6
+ const beats = openingBeats(openMotion, openLands);
7
7
  if (beats.length === 0) return '';
8
8
  const scope = `.tmk-card[data-open-motion="${openMotion}"]`;
9
9
  const byPart = new Map<string, string[]>();
@@ -0,0 +1,36 @@
1
+ const GRANTED = 'granted';
2
+ const CONTROLS = 'a,button,input,select,textarea,dialog';
3
+
4
+ interface OrientationGlobal {
5
+ DeviceOrientationEvent?: { requestPermission?: unknown };
6
+ }
7
+
8
+ type AskPermission = () => Promise<string>;
9
+
10
+ function askFunction(): AskPermission | null | undefined {
11
+ const orientation = (window as OrientationGlobal).DeviceOrientationEvent;
12
+ if (orientation === undefined) return undefined;
13
+ const ask = orientation.requestPermission;
14
+ return typeof ask === 'function' ? (ask.bind(orientation) as AskPermission) : null;
15
+ }
16
+
17
+ function tappedControl(event: Event): boolean {
18
+ return event.target instanceof Element && event.target.closest(CONTROLS) !== null;
19
+ }
20
+
21
+ /** Listens to the motion sensor; where the browser asks first (iOS), asks on the first tap on the card outside its controls. */
22
+ export function listenOrientation(card: HTMLElement, onTurn: (event: DeviceOrientationEvent) => void, canAsk: () => boolean, signal?: AbortSignal): void {
23
+ const ask = askFunction();
24
+ if (ask === undefined) return;
25
+ const listen = (): void => window.addEventListener('deviceorientation', onTurn, { signal });
26
+ if (ask === null) {
27
+ listen();
28
+ return;
29
+ }
30
+ const askOnTap = (event: Event): void => {
31
+ if (tappedControl(event) || !canAsk()) return;
32
+ card.removeEventListener('click', askOnTap);
33
+ ask().then((state) => { if (state === GRANTED && signal?.aborted !== true) listen(); }).catch((error: unknown) => console.warn(error));
34
+ };
35
+ card.addEventListener('click', askOnTap, { signal });
36
+ }
@@ -0,0 +1,14 @@
1
+ import { TiltMotion } from './TiltMotion';
2
+
3
+ const EDGE_LIGHT = new Set<string>([TiltMotion.CardLeans, TiltMotion.DeepLayers]);
4
+ const HEX_LIGHT = new Set<string>([TiltMotion.PortraitLeans, TiltMotion.LayersDrift, TiltMotion.GoldGloss]);
5
+
6
+ /** Which light layers a tilt option needs drawn into the card. */
7
+ export function tiltLights(tiltMotion: TiltMotion): { edge: boolean; hex: boolean; sweep: boolean; gloss: boolean } {
8
+ return {
9
+ edge: EDGE_LIGHT.has(tiltMotion),
10
+ hex: HEX_LIGHT.has(tiltMotion),
11
+ sweep: tiltMotion === TiltMotion.LightSweeps,
12
+ gloss: tiltMotion === TiltMotion.GoldGloss,
13
+ };
14
+ }