@johnmorrisdotca/fuda-cards 0.6.0 → 0.7.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/element.js CHANGED
@@ -11,7 +11,7 @@ const reducedMotion = () => typeof matchMedia === 'function' && matchMedia('(pre
11
11
  document.addEventListener('pointerdown', event => { if (focusedCard && !event.composedPath().includes(focusedCard))
12
12
  focusedCard.setFocused(false); }, true);
13
13
  export class FudaCard extends HTMLElement {
14
- static observedAttributes = ['title', 'category', 'subtitle', 'description', 'number', 'rarity', 'motion', 'playing', 'thickness', 'autoplay', 'material', 'stack', 'stack-messiness', 'stack-seed', 'stack-depth', 'wear', 'wear-seed', 'wear-corners', 'wear-edges', 'wear-surface', 'wear-creases'];
14
+ static observedAttributes = ['title', 'category', 'subtitle', 'description', 'number', 'rarity', 'motion', 'playing', 'thickness', 'autoplay', 'material', 'stack', 'stack-messiness', 'stack-seed', 'stack-depth', 'wear', 'wear-seed', 'wear-corners', 'wear-edges', 'wear-surface', 'wear-creases', 'fan', 'taken-off', 'deck-land', 'animate', 'speed', 'pile-controls'];
15
15
  focused = false;
16
16
  hushed = false;
17
17
  focusedAtPress;
@@ -97,6 +97,35 @@ export class FudaCard extends HTMLElement {
97
97
  get stackCount() { const n = Math.floor(Number.parseFloat(this.getAttribute('stack') ?? '')); return n >= 1 ? Math.min(1000, n) : 1; }
98
98
  /** Height of the stack in millimetres: the count times a card's thickness. */
99
99
  get stackHeight() { return stackHeightMm(this.stackCount, this.cardThicknessMm); }
100
+ /** How many cards are still in the stack: `stack` less the `taken-off` ones (at least one stays). */
101
+ get heldCount() { const n = this.stackCount, t = Math.floor(Number.parseFloat(this.getAttribute('taken-off') ?? '')); return t > 0 ? Math.max(1, n - t) : n; }
102
+ /** True while the stack is fanned open (`fan="open"`, with more than one card). */
103
+ get fanOpen() { return this.getAttribute('fan') === 'open' && this.heldCount > 1; }
104
+ /** How far the pile reaches beyond the card's own box, in card widths: an open fan and the pile of cards taken off. It is zero until a pile feature is used. Pages use it to fit the view; `fuda-pile` is sent when it changes. */
105
+ pileBounds = { left: 0, right: 0, top: 0, bottom: 0 };
106
+ /** Take the top card (or `count` cards) off the stack: it flies to a pile at the stack's side and lands as `deck-land` says. At least one card stays. */
107
+ takeOff(count = 1) { const t = Math.max(0, Math.floor(Number.parseFloat(this.getAttribute('taken-off') ?? '')) || 0); this.setAttribute('taken-off', String(Math.min(this.stackCount - 1, t + Math.max(1, count)))); }
108
+ /** Bring the card (or `count` cards) back from the pile onto the stack. */
109
+ putBack(count = 1) { const t = Math.max(0, Math.floor(Number.parseFloat(this.getAttribute('taken-off') ?? '')) || 0); if (t - Math.max(1, count) > 0)
110
+ this.setAttribute('taken-off', String(t - Math.max(1, count)));
111
+ else
112
+ this.removeAttribute('taken-off'); }
113
+ pileUsed = false;
114
+ pileModule;
115
+ /** Fanning, the pile of cards taken off and the controls are drawn by a module that is loaded only when a stack asks for them; a card without them never loads it. */
116
+ applyPile() {
117
+ const asked = this.stackCount > 1 && (this.getAttribute('fan') === 'open' || this.hasAttribute('taken-off') || this.hasAttribute('pile-controls'));
118
+ if (!asked && !this.pileModule)
119
+ return;
120
+ if (asked)
121
+ this.pileUsed = true;
122
+ const draw = (m) => { if (!this.shadowRoot)
123
+ return; this.pileModule = m; m.applyPile(this, this.shadowRoot); };
124
+ if (this.pileModule)
125
+ draw(this.pileModule);
126
+ else
127
+ void import('./pile-card.js').then(draw);
128
+ }
100
129
  wearKey = '';
101
130
  wearToken = 0;
102
131
  wearModule;
@@ -127,7 +156,7 @@ export class FudaCard extends HTMLElement {
127
156
  drawStills(card, count) {
128
157
  const num = (name, fallback) => { const n = Number.parseFloat(this.getAttribute(name) ?? ''); return Number.isFinite(n) ? n : fallback; };
129
158
  const messiness = num('stack-messiness', 0.3), seed = num('stack-seed', 1), depth = Math.min(52, Math.max(0, Math.floor(num('stack-depth', 10))));
130
- const places = count > 1 && messiness > 0 ? stackLayout(count, { messiness, seed, depth }) : [];
159
+ const places = count > 1 && (messiness > 0 || this.pileUsed) ? stackLayout(count, { messiness, seed, depth }) : [];
131
160
  const key = places.length ? JSON.stringify([count, messiness, seed, depth]) : '';
132
161
  if (key === this.stillsKey)
133
162
  return;
@@ -137,16 +166,16 @@ export class FudaCard extends HTMLElement {
137
166
  holder.innerHTML = places.map((p, at) => `<i class="still" style="--x:${p.x};--y:${p.y};--r:${p.rotate};--k:${count - places.length + at}"></i>`).join('');
138
167
  }
139
168
  render() { const card = this.shadowRoot?.querySelector('.card'); if (card) {
140
- const mm = this.cardThicknessMm, count = this.stackCount, material = cardMaterial(this.getAttribute('material'));
141
- card.style.setProperty('--mm', String(mm * count));
169
+ const mm = this.cardThicknessMm, count = this.heldCount, fan = this.fanOpen, material = cardMaterial(this.getAttribute('material'));
170
+ card.style.setProperty('--mm', String(fan ? mm : mm * count));
142
171
  card.style.setProperty('--mm1', String(mm));
143
- card.classList.toggle('stacked', count > 1);
172
+ card.classList.toggle('stacked', count > 1 && !fan);
144
173
  if (material)
145
174
  card.style.setProperty('--edge', material.edge);
146
175
  else
147
176
  card.style.removeProperty('--edge');
148
177
  this.drawStills(card, count);
149
- } this.applyWear(); const button = this.shadowRoot?.querySelector('.motion-button'); if (button) {
178
+ } this.applyWear(); this.applyPile(); const button = this.shadowRoot?.querySelector('.motion-button'); if (button) {
150
179
  button.hidden = this.getAttribute('motion') !== 'pan';
151
180
  const active = this.isMoving;
152
181
  this.toggleAttribute('moving', active);
@@ -0,0 +1,17 @@
1
+ interface PileHost extends HTMLElement {
2
+ stackCount: number;
3
+ heldCount: number;
4
+ fanOpen: boolean;
5
+ cardThicknessMm: number;
6
+ pileBounds: {
7
+ left: number;
8
+ right: number;
9
+ top: number;
10
+ bottom: number;
11
+ };
12
+ takeOff(count?: number): void;
13
+ putBack(count?: number): void;
14
+ }
15
+ /** Draw the pile features for the stack's current attributes: `fan`, `taken-off`, `deck-land`, `animate`, `speed` and `pile-controls`. */
16
+ export declare function applyPile(host: PileHost, root: ShadowRoot): void;
17
+ export {};
@@ -0,0 +1,223 @@
1
+ /**
2
+ * The pile features of `<fuda-card stack>`: the stack fans open and closes, the top card comes off onto a pile at its side and goes back,
3
+ * and an optional bar of three buttons does it. Loaded by `element.js` only when a stack asks for one of them, so a card without them
4
+ * is exactly what it was.
5
+ *
6
+ * It shares everything with the collection's deck through `pile.js`: the fan's layout, how a card lands and how it flies.
7
+ */
8
+ import { fanBounds, fanLayout, fanRelative, fanShift, flight, normalizeLanding, timing } from './pile.js';
9
+ import { stackLayout } from './stack.js';
10
+ const states = new WeakMap();
11
+ /** The gap between the stack and the pile at its side, in card widths (the collection's deck uses the same 0.28). */
12
+ const GAP = 0.28;
13
+ const PILE_CSS = `:host{position:relative}.rotation{position:relative}:host(:not([card-spin=corner])) .rotation{transform-origin:calc(50% + var(--pivot,0) * 100cqw) 50%}
14
+ .card{transition:transform var(--fuda-move,.65s) cubic-bezier(.2,.8,.2,1),transform-origin var(--fuda-move,.65s) cubic-bezier(.2,.8,.2,1)}
15
+ .card.fanned{transform-origin:50% 165%;transform:translate(calc(var(--fx,0) * 100cqw),0) rotate(calc(var(--fa,0) * 1deg))}
16
+ :host([flipped]) .card.fanned{transform:translate(calc(var(--fx,0) * 100cqw),0) rotate(calc(var(--fa,0) * 1deg)) rotateY(180deg)}
17
+ .still{transition:transform var(--fuda-move,.65s) cubic-bezier(.2,.8,.2,1),transform-origin var(--fuda-move,.65s) cubic-bezier(.2,.8,.2,1);transition-delay:calc(var(--j,0) * var(--stag,22ms))}
18
+ .card.fanned .still{transform-origin:50% 165%;transform:translate3d(calc(var(--rx,0) * 100cqw),calc(var(--ry,0) * 100cqw),calc(var(--t) / -2 - var(--j,1) * 1.5px)) rotate(calc(var(--ra,0) * 1deg));transition-delay:calc(var(--j,0) * var(--stag,28ms))}
19
+ .still.far{display:none}.still.faced{background:none;border:0;transform-style:preserve-3d}.still .face,.flyer .face,.discard .face{position:absolute;inset:0}
20
+ .art>img.copy{width:100%;height:100%;object-fit:contain;display:block}:host([motion="pan"]) .art>img.copy{object-fit:cover;object-position:var(--fuda-focus-x,50%) var(--fuda-focus-y,25%)}
21
+ .discard{position:absolute;left:0;top:0;width:100%;height:100%;transform-style:preserve-3d;translate:calc(var(--dx,1.28) * 100cqw) 0;transition:translate var(--fuda-move,.65s) cubic-bezier(.2,.8,.2,1);pointer-events:none}
22
+ .discard .card{transition:none}.discard[data-land=face-down] .card{transform:rotateY(180deg)}
23
+ .flyer{position:absolute;left:0;top:0;width:100%;height:100%;transform-style:preserve-3d;pointer-events:none;--t:calc(var(--mm,.3) * 100cqw / 63)}.flyer .fly,.flyer .turn{position:absolute;inset:0;transform-style:preserve-3d}
24
+ .bar{position:absolute;left:50%;top:calc(100% + 14px);translate:-50% 0;display:flex;gap:.5rem;flex-wrap:wrap;justify-content:center;width:max-content;max-width:min(100vw - 24px,22rem);filter:none;font:600 .9rem system-ui,sans-serif}
25
+ .bar button{box-sizing:border-box;min-height:48px;min-width:48px;padding:.45rem .9rem;font:inherit;color:#f6f4f1;background:#2a2d3c;border:2px solid #8a8ca0;border-radius:.7rem;cursor:pointer}.bar button:hover{border-color:#ffd27e}.bar button[aria-pressed=true]{background:#ffd27e;border-color:#ffd27e;color:#241a05}.bar button:disabled{opacity:.45;cursor:default}.bar button:focus-visible{outline:3px solid #ffd27e;outline-offset:3px}
26
+ @media(prefers-reduced-motion:reduce){.card,.still,.discard{transition:none}}`;
27
+ function num(host, name, fallback) { const n = Number.parseFloat(host.getAttribute(name) ?? ''); return Number.isFinite(n) ? n : fallback; }
28
+ /** Copies of the card's front and back faces for a card that is not the live one: the picture as an `img` copy (a 3D viewer is never copied), no ids, no Animate button. */
29
+ function faceCopies(host, root) {
30
+ const front = root.querySelector('.card > .front').cloneNode(true), back = root.querySelector('.card > .back').cloneNode(true);
31
+ for (const el of [front, back]) {
32
+ el.querySelectorAll('[id]').forEach((e) => e.removeAttribute('id'));
33
+ el.querySelectorAll('.motion-button').forEach((e) => e.remove());
34
+ }
35
+ const slot = front.querySelector('slot'), img = host.querySelector('img');
36
+ if (slot) {
37
+ if (img) {
38
+ const copy = img.cloneNode();
39
+ copy.removeAttribute('id');
40
+ copy.className = 'copy';
41
+ slot.replaceWith(copy);
42
+ }
43
+ else
44
+ slot.remove();
45
+ }
46
+ return [front, back];
47
+ }
48
+ function stillsMarkup(count, host) {
49
+ const messiness = num(host, 'stack-messiness', 0.3), seed = num(host, 'stack-seed', 1) + 7, depth = Math.min(52, Math.max(0, Math.floor(num(host, 'stack-depth', 10))));
50
+ if (count < 2)
51
+ return '';
52
+ const places = stackLayout(count, { messiness, seed, depth });
53
+ return places.map((p, at) => `<i class="still" style="--x:${p.x};--y:${p.y};--r:${p.rotate};--k:${count - places.length + at}"></i>`).join('');
54
+ }
55
+ /** The pile of cards taken off: a thick block of `count` cards like the stack, its top card face up or turned over, at the stack's side. */
56
+ function drawDiscard(host, root, state, count, land, dx) {
57
+ const rotation = root.querySelector('.rotation');
58
+ if (count < 1) {
59
+ state.discard?.remove();
60
+ state.discard = undefined;
61
+ return;
62
+ }
63
+ let box = state.discard;
64
+ if (!box) {
65
+ box = document.createElement('div');
66
+ box.className = 'discard';
67
+ rotation.append(box);
68
+ state.discard = box;
69
+ }
70
+ box.dataset.land = land;
71
+ box.style.setProperty('--dx', String(dx));
72
+ const live = root.querySelector('.card'), copy = live.cloneNode(true);
73
+ copy.className = 'card';
74
+ copy.removeAttribute('style');
75
+ const [front, back] = faceCopies(host, root);
76
+ copy.querySelector('.front').replaceWith(front);
77
+ copy.querySelector('.back').replaceWith(back);
78
+ const mm = host.cardThicknessMm;
79
+ copy.style.setProperty('--mm', String(mm * count));
80
+ copy.style.setProperty('--mm1', String(mm));
81
+ copy.classList.toggle('stacked', count > 1);
82
+ copy.querySelector('.stills').innerHTML = stillsMarkup(count, host);
83
+ box.replaceChildren(copy);
84
+ }
85
+ function fanState(host, root, on) {
86
+ const card = root.querySelector('.card'), stills = Array.from(root.querySelectorAll('.card > .stills > .still'));
87
+ card.classList.toggle('fanned', on);
88
+ const n = Math.min(10, 1 + stills.length), places = fanLayout(n, num(host, 'stack-seed', 1), 0.34), rel = fanRelative(places);
89
+ if (on) {
90
+ card.style.setProperty('--fx', String(places[0].x));
91
+ card.style.setProperty('--fa', String(places[0].angle));
92
+ const [front, back] = stills.length ? faceCopies(host, root) : [null, null];
93
+ stills.forEach((still, at) => {
94
+ const i = stills.length - at;
95
+ still.classList.toggle('far', i >= n);
96
+ if (i >= n)
97
+ return;
98
+ still.style.setProperty('--rx', String(rel[i].x));
99
+ still.style.setProperty('--ry', String(rel[i].y));
100
+ still.style.setProperty('--ra', String(rel[i].angle));
101
+ still.style.setProperty('--j', String(i));
102
+ if (!still.classList.contains('faced') || still.dataset.sig !== host.innerHTML + host.getAttribute('title')) {
103
+ still.classList.add('faced');
104
+ still.dataset.sig = host.innerHTML + host.getAttribute('title');
105
+ const [f, b] = [front.cloneNode(true), back.cloneNode(true)];
106
+ still.replaceChildren(f, b);
107
+ }
108
+ });
109
+ }
110
+ else {
111
+ stills.forEach((still, at) => { still.style.setProperty('--j', String(stills.length - at)); still.classList.remove('far'); });
112
+ }
113
+ return { places, bounds: on ? fanBounds(places) : { left: 0, right: 0, top: 0, bottom: 0 } };
114
+ }
115
+ /** Draw the pile features for the stack's current attributes: `fan`, `taken-off`, `deck-land`, `animate`, `speed` and `pile-controls`. */
116
+ export function applyPile(host, root) {
117
+ let state = states.get(host);
118
+ if (!state) {
119
+ state = { taken: 0, token: 0 };
120
+ states.set(host, state);
121
+ }
122
+ if (!root.querySelector('style[data-pile]')) {
123
+ const style = document.createElement('style');
124
+ style.dataset.pile = '';
125
+ style.textContent = PILE_CSS;
126
+ root.append(style);
127
+ }
128
+ const t = timing(host, true), land = normalizeLanding(host.getAttribute('deck-land'));
129
+ host.style.setProperty('--fuda-move', t.on ? `${t.ms}ms` : '0s');
130
+ if (t.on)
131
+ host.style.removeProperty('--stag');
132
+ else
133
+ host.style.setProperty('--stag', '0ms');
134
+ const total = host.stackCount, taken = Math.min(total - 1, Math.max(0, Math.floor(num(host, 'taken-off', 0)))), fan = host.fanOpen;
135
+ const was = state.taken, token = ++state.token;
136
+ const { places, bounds } = fanState(host, root, fan);
137
+ if (!fan) {
138
+ const faced = Array.from(root.querySelectorAll('.card > .stills > .still.faced'));
139
+ // The copies of the faces go once the cards have closed (at once when nothing is animated).
140
+ const clean = () => { if (!host.fanOpen)
141
+ faced.forEach((s) => { s.classList.remove('faced'); s.replaceChildren(); delete s.dataset.sig; }); };
142
+ if (faced.length) {
143
+ if (t.on)
144
+ void Promise.all(root.querySelector('.card').getAnimations({ subtree: true }).map((a) => a.finished.catch(() => undefined))).then(clean);
145
+ else
146
+ clean();
147
+ }
148
+ }
149
+ const dx = 1 + GAP + bounds.right, mmPx = (host.cardThicknessMm * host.offsetWidth) / 63;
150
+ // The pile at the side: where it is, how many cards and how its top card lies. While a card flies to it, it holds the cards that were there before.
151
+ const moving = taken !== was && t.on && host.offsetWidth > 0;
152
+ state.flyer?.remove();
153
+ state.flyer = undefined;
154
+ drawDiscard(host, root, state, moving && taken > was ? was : taken, land, dx);
155
+ if (moving) {
156
+ const off = taken > was, rotation = root.querySelector('.rotation'), [front, back] = faceCopies(host, root);
157
+ const flyer = document.createElement('div');
158
+ flyer.className = 'flyer';
159
+ flyer.style.setProperty('--mm', String(host.cardThicknessMm));
160
+ const fly = document.createElement('div');
161
+ fly.className = 'fly';
162
+ const turn = document.createElement('div');
163
+ turn.className = 'turn';
164
+ turn.append(front, back);
165
+ fly.append(turn);
166
+ flyer.append(fly);
167
+ rotation.append(flyer);
168
+ state.flyer = flyer;
169
+ const w = host.offsetWidth, heldBefore = off ? total - was : total - taken, zStack = (heldBefore * mmPx) / 2, zPile = (Math.max(1, off ? taken : was) * mmPx) / 2;
170
+ const lead = fan && places.length > 1 ? places[0] : null, shift = lead ? fanShift(lead) : { x: 0, y: 0 };
171
+ // The flyer sits at its landing place; it flies from (off) or to (back) the stack, where an open fan holds the top card.
172
+ flyer.style.transform = off ? `translate3d(${dx * w}px,0,${zPile}px)` : `translate3d(${shift.x * w}px,${shift.y * w}px,${zStack}px) rotate(${lead ? lead.angle : 0}deg)`;
173
+ const away = off ? { x: -dx * w + shift.x * w, y: shift.y * w, z: zStack - zPile } : { x: dx * w - shift.x * w, y: -shift.y * w, z: zPile - zStack };
174
+ const anims = flight(fly, turn, away, land, off ? 'off' : 'back', Math.round(t.ms * 1.15), lead ? (off ? lead.angle : -lead.angle) : 0);
175
+ void Promise.all(anims.map((a) => a.finished)).then(() => {
176
+ if (token !== state.token)
177
+ return;
178
+ flyer.remove();
179
+ state.flyer = undefined;
180
+ drawDiscard(host, root, state, taken, land, dx);
181
+ }, () => undefined);
182
+ }
183
+ state.taken = taken;
184
+ // The bar of three buttons, when asked for.
185
+ if (host.hasAttribute('pile-controls')) {
186
+ if (!state.bar) {
187
+ const bar = document.createElement('div');
188
+ bar.className = 'bar';
189
+ bar.setAttribute('role', 'group');
190
+ bar.setAttribute('aria-label', 'Pile');
191
+ const make = (label, run) => { const b = document.createElement('button'); b.type = 'button'; b.textContent = label; b.addEventListener('click', run); return b; };
192
+ const fanButton = make('Fan', () => { if (host.getAttribute('fan') === 'open')
193
+ host.removeAttribute('fan');
194
+ else
195
+ host.setAttribute('fan', 'open'); });
196
+ fanButton.dataset.role = 'fan';
197
+ fanButton.setAttribute('aria-pressed', 'false');
198
+ const off = make('Take a card off', () => host.takeOff());
199
+ off.dataset.role = 'off';
200
+ const back = make('Put it back', () => host.putBack());
201
+ back.dataset.role = 'back';
202
+ bar.append(fanButton, off, back);
203
+ root.append(bar);
204
+ state.bar = bar;
205
+ }
206
+ const q = (role) => state.bar.querySelector(`[data-role=${role}]`);
207
+ q('fan').setAttribute('aria-pressed', String(fan));
208
+ q('fan').textContent = fan ? 'Close the fan' : 'Fan open';
209
+ q('off').disabled = taken >= total - 1;
210
+ q('back').disabled = taken < 1;
211
+ }
212
+ else if (state.bar) {
213
+ state.bar.remove();
214
+ state.bar = undefined;
215
+ }
216
+ const right = Math.max(bounds.right, taken > 0 || (moving && taken < was) ? dx : 0);
217
+ const next = { left: bounds.left, right, top: bounds.top, bottom: bounds.bottom };
218
+ const old = host.pileBounds;
219
+ host.pileBounds = next;
220
+ host.style.setProperty('--pivot', String((next.right - next.left) / 2));
221
+ if (old.left !== next.left || old.right !== next.right || old.top !== next.top || old.bottom !== next.bottom)
222
+ host.dispatchEvent(new CustomEvent('fuda-pile', { detail: next }));
223
+ }
package/dist/pile.d.ts ADDED
@@ -0,0 +1,73 @@
1
+ /**
2
+ * How a card taken off a pile lands on the pile at its side: still facing up, or turned over sideways (as a person turns a card, like a
3
+ * page) to show its back. `upside-down` was a 0.6.0 value that spun the picture half way round in its plane; it is still accepted and
4
+ * means `face-down`, so nothing breaks. A card never ends with its picture on its head.
5
+ */
6
+ export type DeckLanding = 'face-up' | 'face-down' | 'upside-down';
7
+ export declare const deckLandings: ReadonlyArray<{
8
+ id: 'face-up' | 'face-down';
9
+ label: string;
10
+ }>;
11
+ /** The landing a value means: `face-down` (also `upside-down` and `turned-over`) is turned over; anything else is still facing up. */
12
+ export declare function normalizeLanding(value: string | null | undefined): 'face-up' | 'face-down';
13
+ /** Where the cards of a fan lie, first card on the left when open and on top when closed. `open` is the fan spread like a hand of playing cards; `closed` is the squared-up deck it starts from and closes back to. */
14
+ export interface FanPlace {
15
+ angle: number;
16
+ x: number;
17
+ y: number;
18
+ closedAngle: number;
19
+ closedX: number;
20
+ closedY: number;
21
+ }
22
+ /** `step` is how far apart neighbouring cards lie across, in card widths; the angle does the rest of the spreading. A phone uses a smaller one. */
23
+ export declare function fanLayout(count: number, seed?: number, step?: number): FanPlace[];
24
+ /** The card's height over its width, and where a fan turns: 165% of a card's height down from its top. The CSS uses the same two numbers. */
25
+ export declare const CARD_RATIO: number;
26
+ export declare const FAN_PIVOT = 1.65;
27
+ /**
28
+ * How far an open fan reaches beyond the box of one squared-up card, in card widths: `left` and `right` past the box's sides, `top` and
29
+ * `bottom` past its top and bottom (never negative). Pages use it to leave room and to fit the view.
30
+ */
31
+ export declare function fanBounds(places: FanPlace[]): {
32
+ left: number;
33
+ right: number;
34
+ top: number;
35
+ bottom: number;
36
+ };
37
+ /**
38
+ * The cards of a fan as they lie relative to the first one, for a pile whose first card is the one that carries the rest (a stack's live top
39
+ * card, with the other cards laid inside it). Card by card: the turn and the shift, in card widths, that put it where the fan wants it.
40
+ */
41
+ export declare function fanRelative(places: FanPlace[]): Array<{
42
+ angle: number;
43
+ x: number;
44
+ y: number;
45
+ }>;
46
+ /** The fan's own centre of gravity: where a card of an open fan has moved from its squared-up place, in card widths (before the pile's own turn). */
47
+ export declare function fanShift(place: FanPlace): {
48
+ x: number;
49
+ y: number;
50
+ };
51
+ /** How long things take: the animation is on (the page did not turn it off and the reader did not ask for reduced motion) and how long a move lasts, in milliseconds. */
52
+ export interface Timing {
53
+ on: boolean;
54
+ ms: number;
55
+ }
56
+ export declare const SPEEDS: Record<string, number>;
57
+ /** The base length of a move, 600 ms; `speed` stretches or shortens every move at once. */
58
+ export declare const BASE_MS = 600;
59
+ export declare function reducedMotion(): boolean;
60
+ /**
61
+ * `animate="off"` turns every move off; `animate="on"` turns them on; with no `animate` a move is on only where `dflt` says (the pieces that
62
+ * already moved before the option existed). The reader's reduced-motion setting always wins.
63
+ */
64
+ export declare function timing(host: Element, dflt: boolean): Timing;
65
+ /**
66
+ * A card taken off a pile flies to the pile at its side, and turns over sideways on the way if it lands face down; coming back it
67
+ * does the same in reverse. `fly` carries the card across, `turn` carries the turn. `from` is how far the card is from where it ends.
68
+ */
69
+ export declare function flight(fly: HTMLElement, turn: HTMLElement, from: {
70
+ x: number;
71
+ y: number;
72
+ z?: number;
73
+ }, land: 'face-up' | 'face-down', direction: 'off' | 'back', ms: number, spin?: number): Animation[];
package/dist/pile.js ADDED
@@ -0,0 +1,107 @@
1
+ /**
2
+ * What every pile of cards shares: how a card taken off lands, how a fan lies, and how long things take.
3
+ *
4
+ * `<fuda-collection>` (the Overlapping Deck and the other displays that draw a pile) and `<fuda-card stack>` both use this one
5
+ * piece, so a pile fans open and closed, and a card comes off it and goes back, the same way everywhere.
6
+ */
7
+ import { stackLayout } from './stack.js';
8
+ export const deckLandings = [
9
+ { id: 'face-up', label: 'Still facing up' }, { id: 'face-down', label: 'Turned over' }
10
+ ];
11
+ /** The landing a value means: `face-down` (also `upside-down` and `turned-over`) is turned over; anything else is still facing up. */
12
+ export function normalizeLanding(value) {
13
+ return value === 'face-down' || value === 'upside-down' || value === 'turned-over' ? 'face-down' : 'face-up';
14
+ }
15
+ /** `step` is how far apart neighbouring cards lie across, in card widths; the angle does the rest of the spreading. A phone uses a smaller one. */
16
+ export function fanLayout(count, seed = 1, step = 0.34) {
17
+ const n = Math.max(0, Math.floor(count));
18
+ if (!n)
19
+ return [];
20
+ const spread = Math.min(110, 11 * (n - 1)), turn = n > 1 ? spread / (n - 1) : 0;
21
+ const nudge = stackLayout(n, { messiness: 0.25, seed, depth: n });
22
+ return Array.from({ length: n }, (_, i) => {
23
+ const under = i >= 1 ? nudge[i - 1] : undefined;
24
+ return {
25
+ angle: Math.round((-spread / 2 + i * turn) * 100) / 100,
26
+ x: Math.round((i - (n - 1) / 2) * step * 1000) / 1000,
27
+ y: 0,
28
+ closedAngle: under ? under.rotate / 3 : 0,
29
+ closedX: under ? under.x : 0,
30
+ closedY: under ? under.y : 0
31
+ };
32
+ });
33
+ }
34
+ /** The card's height over its width, and where a fan turns: 165% of a card's height down from its top. The CSS uses the same two numbers. */
35
+ export const CARD_RATIO = 3.5 / 2.5;
36
+ export const FAN_PIVOT = 1.65;
37
+ /**
38
+ * How far an open fan reaches beyond the box of one squared-up card, in card widths: `left` and `right` past the box's sides, `top` and
39
+ * `bottom` past its top and bottom (never negative). Pages use it to leave room and to fit the view.
40
+ */
41
+ export function fanBounds(places) {
42
+ let x0 = 0, x1 = 1, y0 = 0, y1 = CARD_RATIO;
43
+ const px = 0.5, py = FAN_PIVOT * CARD_RATIO;
44
+ for (const p of places) {
45
+ const a = (p.angle * Math.PI) / 180, c = Math.cos(a), s = Math.sin(a);
46
+ for (const [cx, cy] of [[0, 0], [1, 0], [0, CARD_RATIO], [1, CARD_RATIO]]) {
47
+ const dx = cx - px, dy = cy - py;
48
+ const x = px + dx * c - dy * s + p.x, y = py + dx * s + dy * c;
49
+ x0 = Math.min(x0, x);
50
+ x1 = Math.max(x1, x);
51
+ y0 = Math.min(y0, y);
52
+ y1 = Math.max(y1, y);
53
+ }
54
+ }
55
+ const r = (v) => Math.round(v * 1000) / 1000;
56
+ return { left: r(-x0), right: r(x1 - 1), top: r(-y0), bottom: r(y1 - CARD_RATIO) };
57
+ }
58
+ /**
59
+ * The cards of a fan as they lie relative to the first one, for a pile whose first card is the one that carries the rest (a stack's live top
60
+ * card, with the other cards laid inside it). Card by card: the turn and the shift, in card widths, that put it where the fan wants it.
61
+ */
62
+ export function fanRelative(places) {
63
+ if (!places.length)
64
+ return [];
65
+ const a0 = (places[0].angle * Math.PI) / 180, c = Math.cos(a0), s = Math.sin(a0);
66
+ const r = (v) => Math.round(v * 1000) / 1000;
67
+ return places.map((p) => {
68
+ const dx = p.x - places[0].x;
69
+ return { angle: r(p.angle - places[0].angle), x: r(dx * c), y: r(-dx * s) };
70
+ });
71
+ }
72
+ /** The fan's own centre of gravity: where a card of an open fan has moved from its squared-up place, in card widths (before the pile's own turn). */
73
+ export function fanShift(place) {
74
+ const a = (place.angle * Math.PI) / 180, lever = (FAN_PIVOT - 0.5) * CARD_RATIO;
75
+ return { x: place.x + lever * Math.sin(a), y: lever * (1 - Math.cos(a)) };
76
+ }
77
+ export const SPEEDS = { slow: 1.6, normal: 1, quick: 0.6 };
78
+ /** The base length of a move, 600 ms; `speed` stretches or shortens every move at once. */
79
+ export const BASE_MS = 600;
80
+ export function reducedMotion() {
81
+ return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
82
+ }
83
+ /**
84
+ * `animate="off"` turns every move off; `animate="on"` turns them on; with no `animate` a move is on only where `dflt` says (the pieces that
85
+ * already moved before the option existed). The reader's reduced-motion setting always wins.
86
+ */
87
+ export function timing(host, dflt) {
88
+ const a = host.getAttribute('animate');
89
+ const asked = a === 'off' ? false : a === 'on' ? true : dflt;
90
+ const scale = SPEEDS[host.getAttribute('speed') ?? 'normal'] ?? 1;
91
+ return { on: asked && !reducedMotion(), ms: Math.round(BASE_MS * scale) };
92
+ }
93
+ /**
94
+ * A card taken off a pile flies to the pile at its side, and turns over sideways on the way if it lands face down; coming back it
95
+ * does the same in reverse. `fly` carries the card across, `turn` carries the turn. `from` is how far the card is from where it ends.
96
+ */
97
+ export function flight(fly, turn, from, land, direction, ms, spin = 0) {
98
+ const options = { duration: ms, easing: 'cubic-bezier(.3,.1,.2,1)' };
99
+ const out = [fly.animate([
100
+ { transform: `translate3d(${from.x}px,${from.y}px,${from.z ?? 0}px) rotate(${spin}deg)` },
101
+ { transform: `translate3d(${from.x / 2}px,${from.y / 2 - 34}px,${(from.z ?? 0) / 2 + 80}px) rotate(${spin / 2}deg) scale(1.07)`, offset: 0.5 },
102
+ { transform: 'translate3d(0,0,0) rotate(0deg)' }
103
+ ], options)];
104
+ if (land === 'face-down')
105
+ out.push(turn.animate(direction === 'off' ? [{ transform: 'none' }, { transform: 'rotateY(180deg)' }] : [{ transform: 'rotateY(180deg)' }, { transform: 'none' }], options));
106
+ return out;
107
+ }
package/dist/zoom.d.ts CHANGED
@@ -37,6 +37,14 @@ export interface ZoomView {
37
37
  zoomed(): boolean;
38
38
  /** Let the reader turn the view in 3D (angle, tilt, Auto-turn) or only zoom and move it. Off by default. */
39
39
  setTurnable(on: boolean): void;
40
+ /** The selector of the items that must be visible at Fit. It can change with the display. */
41
+ items: string;
42
+ /** Run a change that moves the view (a refit, a pan) so that the view glides to its new place over `ms` instead of jumping; 0 jumps. */
43
+ animated(change: () => void, ms: number): void;
44
+ /** Move the view so the item is in the middle of the stage, gliding over `ms` (0 jumps). Does nothing when the item is not in the view. */
45
+ reveal(item: Element, ms: number): void;
46
+ /** True while the view is turned in 3D. */
47
+ turned(): boolean;
40
48
  }
41
49
  /**
42
50
  * Zoom, Fit and pan for a flat view. `stage` clips, `view` is its absolutely positioned child that holds the items and is
package/dist/zoom.js CHANGED
@@ -7,7 +7,6 @@ const TAPPABLE = 'button:not(:disabled), a[href], [role=button]';
7
7
  * moved and scaled. Fit shows every item at once; the reader's zoom and pan are never reset by a change of content.
8
8
  */
9
9
  export function zoomView(stage, view, options = {}) {
10
- const items = options.items ?? '.card';
11
10
  const controls = document.createElement('kazoku-view-controls');
12
11
  controls.setAttribute('flat', '');
13
12
  controls.setAttribute('ignore', '');
@@ -23,14 +22,21 @@ export function zoomView(stage, view, options = {}) {
23
22
  let box = { w: 0, h: 0, cx: 0, cy: 0, bw: 0, bh: 0 };
24
23
  let fit = 1;
25
24
  let turnable = false;
26
- const self = { controls, minOpen: 0, refresh, reset: () => refresh(true), zoomed: () => controls.state.zoom > ZOOMED, setTurnable };
25
+ const self = { controls, minOpen: 0, items: options.items ?? '.card', refresh, reset: () => refresh(true), zoomed: () => controls.state.zoom > ZOOMED, setTurnable, animated, reveal, turned: () => turnable && Boolean(controls.state.yaw || controls.state.tilt) };
26
+ let glide;
27
+ /** A glide that is still running would be measured as if it were the layout, so a new measure ends it first. */
28
+ function settleGlide() { if (glide) {
29
+ glide.cancel();
30
+ glide = undefined;
31
+ } }
27
32
  function measure() {
33
+ settleGlide();
28
34
  const previous = view.style.transform;
29
35
  view.style.transform = 'none';
30
36
  const origin = stage.getBoundingClientRect();
31
37
  const left = origin.left + stage.clientLeft, top = origin.top + stage.clientTop;
32
38
  let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
33
- for (const item of Array.from(view.querySelectorAll(items))) {
39
+ for (const item of Array.from(view.querySelectorAll(self.items))) {
34
40
  const r = item.getBoundingClientRect();
35
41
  if (!r.width || !r.height)
36
42
  continue;
@@ -64,6 +70,31 @@ export function zoomView(stage, view, options = {}) {
64
70
  controls.toggleAttribute('flat', !on);
65
71
  draw(controls.state);
66
72
  }
73
+ const EASE = 'cubic-bezier(.2,.8,.2,1)';
74
+ function animated(change, ms) {
75
+ const from = ms > 0 ? getComputedStyle(view).transform : '';
76
+ change();
77
+ const to = view.style.transform;
78
+ if (ms > 0 && from && from !== 'none' && to && from !== to) {
79
+ settleGlide();
80
+ glide = view.animate([{ transform: from }, { transform: to }], { duration: ms, easing: EASE });
81
+ }
82
+ }
83
+ function reveal(item, ms) {
84
+ animated(() => {
85
+ measure();
86
+ const previous = view.style.transform;
87
+ view.style.transform = 'none';
88
+ const origin = stage.getBoundingClientRect(), r = item.getBoundingClientRect();
89
+ view.style.transform = previous;
90
+ if (!r.width)
91
+ return;
92
+ const s = fit * controls.state.zoom;
93
+ const px = r.left + r.width / 2 - origin.left - stage.clientLeft, py = r.top + r.height / 2 - origin.top - stage.clientTop;
94
+ controls.set({ panX: -s * (px - box.cx), panY: -s * (py - box.cy) });
95
+ draw(controls.state);
96
+ }, ms);
97
+ }
67
98
  function refresh(open = false) {
68
99
  measure();
69
100
  if (!box.w || !box.h)
@@ -2,12 +2,14 @@
2
2
 
3
3
  Fuda supplies reusable frames for a caller's cards and reusable ways to display collections on websites. The hosting site supplies the card data and artwork or interactive content. Initial versions of twelve layouts now exist in `<fuda-collection>`. They are prototypes; the detailed capabilities below remain design goals unless described as implemented in the README.
4
4
 
5
- ## Choosing a display, the deck and the fan (0.6.0)
5
+ ## Choosing a display, piles, the fan and animation (0.6.0, 0.7.0)
6
6
 
7
7
  - **Display buttons.** All twelve displays are buttons on screen at once, in a row that spans the width, each with a small picture of its layout. No drop-down. At least 48 px high; 4 to a row on a phone, 6 on a desk; arrow keys move the choice; light and dark follow the reader.
8
- - **Deck.** A deck and a pile. Next flips the top card off to the pile on the deck's other side, Previous brings it back. The landing is a choice: still facing up, upside down (spun half way round in its plane) or face down (turned over, showing the back image, or the package's own back). One element flies, so a card is never drawn twice. The deck turns in 3D with the angle, tilt and Auto-turn controls.
9
- - **Fan.** `view="fan"`: the cards of the deck spread in an arc like a hand of playing cards (about half of each card shows) and close back to the squared-up deck, each card back where it started. The state is in the address (`?fan=open`).
10
- - Not done: a fan or a pile inside `<fuda-card stack>` (those cards all carry the same picture), dealing more than one card at a time, a pile that fills up with the whole discard history (the pile shows the last ten).
8
+ - **Piles (0.7.0).** The Overlapping Deck, Random Draw, the Jukebox Carousel and the Flip Tower (the last three drew a pile of three cards) are the same pile with their own look. Every pile turns in 3D (angle, tilt, Auto-turn), fans open and closed, and has a card taken off it. `<fuda-card stack>` is a pile too. Rolodex and Spotlight spread their cards and are carousels, not piles.
9
+ - **Deck.** A deck and a pile. Next flips the top card off to the pile on the deck's other side, Previous brings it back. The landing is a choice: still facing up, or turned over (a sideways turn about the card's vertical axis, like turning a page, showing the back image or the package's own back). A card never lands with its picture on its head; the 0.6.0 value `upside-down` still works and means turned over. One element flies, so a card is never drawn twice.
10
+ - **Fan.** Every pile fans open and closed with a control right under the view: up to ten cards in an arc, most of each card showing, closing back exactly. `view="fan"` is the same pile with only the fan. In the address (`?fan=open`).
11
+ - **Animate (0.7.0).** `animate="off"` and `speed` for every move: the fan, a card taken off, Next in the carousels, a binder page turn, a switch of display, a pan to the card in the wall, story and atlas. On when the attribute is missing; reduced motion always wins. One shared timing, CSS transforms and one-shot animations, nothing running when idle. Moves with it on and off end in exactly the same place.
12
+ - Not done: dealing more than one card at a time, a pile that fills up with the whole discard history (the pile shows the last ten), wear on the cards of a fan.
11
13
 
12
14
  ## Zoom, Fit and move (every view)
13
15
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnmorrisdotca/fuda-cards",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Fuda Cards: collectible card frames for images and interactive 3D content.",
5
5
  "type": "module",
6
6
  "sideEffects": [