@rohal12/spindle 0.64.27 → 0.64.29

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/src/story-api.ts CHANGED
@@ -26,6 +26,7 @@ import { registerClass } from './class-registry';
26
26
  import {
27
27
  frozenCopy,
28
28
  readOnlyValue,
29
+ adoptStateValues,
29
30
  getActiveMutationScope,
30
31
  mutateState,
31
32
  } from './execute-mutation';
@@ -282,12 +283,18 @@ function warnIfUndeclared(isTransient: boolean, key: string): void {
282
283
  );
283
284
  }
284
285
 
285
- /** Set a single variable on an Immer draft, resolving dot-paths if present. */
286
- function setOne(draft: VariableNamespaces, name: string, value: unknown): void {
287
- const { isTransient, key } = parseName(name);
288
- const namespace = isTransient ? draft.transient : draft.variables;
289
-
290
- setByPath(namespace, key.split('.'), value);
286
+ /** Adopt the whole batch before writes can replace state-owned inputs. */
287
+ function setEntries(
288
+ draft: VariableNamespaces,
289
+ entries: readonly [string, unknown][],
290
+ adopt: (value: unknown) => unknown,
291
+ ): void {
292
+ const adopted = entries.map(([name, value]) => [name, adopt(value)] as const);
293
+ for (const [name, value] of adopted) {
294
+ const { isTransient, key } = parseName(name);
295
+ const namespace = isTransient ? draft.transient : draft.variables;
296
+ setByPath(namespace, key.split('.'), value);
297
+ }
291
298
  }
292
299
 
293
300
  /**
@@ -345,22 +352,20 @@ function createStoryAPI(): StoryAPI {
345
352
  warnIfUndeclared(isTransient, key);
346
353
  if (!isTransient) recordHookWrite(key.split('.'));
347
354
  }
348
- // One store update for all keys, so watchers see them together. Made
349
- // while mutation code runs ({do}, ctx.mutate, watcher run actions), it
350
- // follows the code's own pending writes (program order, #215): see
351
- // routeStoreUpdate.
355
+ // One store update for all keys, in program order with any running
356
+ // mutation. Nested writes use the mutation merge to preserve aliases.
352
357
  if (entries.some(([k]) => k.includes('.'))) {
353
- // A write below a variable goes through the commit mutation code
354
- // uses (nested in the running code, if any: it continues from the
355
- // code's pending writes, and they are committed first): an update of a draft would give the written path new
356
- // objects and leave the other references to the old ones (#295).
357
358
  mutateState((work, adopt) => {
358
- for (const [k, v] of entries) setOne(work, k, adopt(v));
359
+ setEntries(work, entries, adopt);
359
360
  });
360
361
  return;
361
362
  }
362
363
  useStoryStore.getState().updateVariables((draft) => {
363
- for (const [k, v] of entries) setOne(draft, k, v);
364
+ // One adopter for the batch keeps shared references and cycles,
365
+ // including references to state already owned by the running code.
366
+ // Freezing caller inputs alone cannot protect mutable internal slots.
367
+ const adopt = adoptStateValues(draft);
368
+ setEntries(draft, entries, adopt);
364
369
  });
365
370
  },
366
371
 
package/src/structural.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  // Temporal values, with shared references and cycles.
11
11
 
12
12
  import { registeredClassName } from './class-registry';
13
- import { hasOwn, setOwn } from './utils/namespace';
13
+ import { defineData, hasOwn } from './utils/namespace';
14
14
  import { deleteByPath, getByPath, setByPath } from './utils/object-path';
15
15
  import {
16
16
  ERROR_HIDDEN_KEYS,
@@ -54,7 +54,7 @@ function builtinLike<C extends object>(
54
54
  made(empty);
55
55
  if (registeredClassName(obj) === undefined) return empty;
56
56
  Object.setPrototypeOf(empty, Object.getPrototypeOf(obj) as object);
57
- for (const key of extraKeys(obj)) setOwn(empty, key, value(key));
57
+ for (const key of extraKeys(obj)) defineData(empty, key, value(key));
58
58
  return empty;
59
59
  }
60
60
 
@@ -102,13 +102,11 @@ export function deepClone<T>(value: T, options: DeepCloneOptions = {}): T {
102
102
  */
103
103
  function copyKeys(obj: object, copy: object): object {
104
104
  for (const key of Object.keys(obj)) {
105
- setOwn(copy, key, clone((obj as Record<string, unknown>)[key]));
105
+ defineData(copy, key, clone((obj as Record<string, unknown>)[key]));
106
106
  }
107
107
  for (const sym of Object.getOwnPropertySymbols(obj)) {
108
108
  if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) continue;
109
- (copy as Record<symbol, unknown>)[sym] = clone(
110
- (obj as Record<symbol, unknown>)[sym],
111
- );
109
+ defineData(copy, sym, clone((obj as Record<symbol, unknown>)[sym]));
112
110
  }
113
111
  return copy;
114
112
  }
@@ -184,7 +182,7 @@ export function deepClone<T>(value: T, options: DeepCloneOptions = {}): T {
184
182
  // Holes stay holes
185
183
  const arr = builtin(obj, new Array(val.length) as unknown[]);
186
184
  for (const key of arrayIndices(val))
187
- arr[Number(key)] = clone(val[Number(key)]);
185
+ defineData(arr, key, clone(val[Number(key)]));
188
186
  return arr;
189
187
  }
190
188
 
@@ -360,13 +358,13 @@ export function shareEqual<T>(prev: unknown, curr: T): T {
360
358
  }
361
359
  if (Array.isArray(c) && Array.isArray(p)) {
362
360
  const out = collection(new Array(c.length) as unknown[]);
363
- for (const key of arrayIndices(c)) out[Number(key)] = shareKey(key);
361
+ for (const key of arrayIndices(c)) defineData(out, key, shareKey(key));
364
362
  return out;
365
363
  }
366
364
  if (mergesWith(p, c, false)) {
367
365
  const out = Object.create(Object.getPrototypeOf(c) as object | null);
368
366
  done.set(c, out);
369
- for (const key of Object.keys(cr)) setOwn(out, key, shareKey(key));
367
+ for (const key of Object.keys(cr)) defineData(out, key, shareKey(key));
370
368
  return out;
371
369
  }
372
370
  return fresh(c);
@@ -47,15 +47,49 @@ const SVG_NOT_TEXT = new Set([
47
47
  'marker',
48
48
  ]);
49
49
 
50
+ // DOM shims may omit the native hidden rules. Supply their defaults at zero
51
+ // specificity, before author rules, so the CSS cascade still decides visibility.
52
+ const hiddenDefaults = new WeakSet<Node>();
53
+ const needsHiddenDefaults = new WeakMap<Document, boolean>();
54
+ function ensureHiddenDefaults(el: Element): void {
55
+ if (!el.hasAttribute('hidden')) return;
56
+ const doc = el.ownerDocument;
57
+ const view = doc.defaultView ?? globalThis.window;
58
+ let needed = needsHiddenDefaults.get(doc);
59
+ if (needed === undefined) {
60
+ const detached = doc.implementation.createHTMLDocument('');
61
+ const probe = detached.createElement('div');
62
+ probe.hidden = true;
63
+ detached.body.append(probe);
64
+ // Browsers don't compute styles in documents without a browsing context.
65
+ needed = view?.getComputedStyle(probe).display === 'block';
66
+ needsHiddenDefaults.set(doc, needed);
67
+ }
68
+ const root = el.getRootNode() as Document | ShadowRoot;
69
+ if (!needed || hiddenDefaults.has(root)) return;
70
+ const container = root.nodeType === 9 ? (root as Document).head : root;
71
+ if (root.nodeType !== 9 && !('host' in root)) return;
72
+ const style = doc.createElement('style');
73
+ style.textContent =
74
+ ':where([hidden]:not([hidden="until-found" i])){display:none}' +
75
+ ':where([hidden="until-found" i]){content-visibility:hidden}';
76
+ container.prepend(style);
77
+ hiddenDefaults.add(root);
78
+ }
79
+
50
80
  /** Detached/headless DOMs may have no computed value; CSSOM still resolves
51
81
  * duplicate inline declarations and priorities correctly.
52
82
  */
53
- function styleValue(el: Element, name: 'display' | 'visibility'): string {
83
+ function styleValue(
84
+ el: Element,
85
+ name: 'display' | 'visibility' | 'content-visibility',
86
+ ): string {
87
+ ensureHiddenDefaults(el);
54
88
  return (
55
- (el.ownerDocument.defaultView ?? globalThis.window)?.getComputedStyle?.(el)[
56
- name
57
- ] ||
58
- (el as HTMLElement).style?.[name] ||
89
+ (el.ownerDocument.defaultView ?? globalThis.window)
90
+ ?.getComputedStyle?.(el)
91
+ .getPropertyValue(name) ||
92
+ (el as HTMLElement).style?.getPropertyValue(name) ||
59
93
  ''
60
94
  );
61
95
  }
@@ -66,10 +100,13 @@ function styleValue(el: Element, name: 'display' | 'visibility'): string {
66
100
  * A symbol referenced by SVG use is rendered only as an instance root.
67
101
  */
68
102
  export function isHidden(el: Element, svgInstanceRoot = false): boolean {
103
+ const display = styleValue(el, 'display');
69
104
  return (
70
- el.hasAttribute('hidden') ||
105
+ (el.hasAttribute('hidden') &&
106
+ el.getAttribute('hidden')?.toLowerCase() !== 'until-found' &&
107
+ display === '') ||
71
108
  el.getAttribute('aria-hidden') === 'true' ||
72
- styleValue(el, 'display') === 'none' ||
109
+ display === 'none' ||
73
110
  NOT_TEXT.has(el.localName.toLowerCase()) ||
74
111
  (el.namespaceURI === 'http://www.w3.org/2000/svg' &&
75
112
  SVG_NOT_TEXT.has(el.localName.toLowerCase()) &&
@@ -83,6 +120,50 @@ export function isHidden(el: Element, svgInstanceRoot = false): boolean {
83
120
  );
84
121
  }
85
122
 
123
+ // Layout containment cannot apply to these box types. In particular, an
124
+ // ordinary inline span still paints its contents with content-visibility:hidden.
125
+ const NO_LAYOUT_CONTAINMENT = new Set([
126
+ 'none',
127
+ 'contents',
128
+ 'ruby',
129
+ 'ruby-base',
130
+ 'ruby-text',
131
+ 'ruby-base-container',
132
+ 'ruby-text-container',
133
+ 'table-row',
134
+ 'table-row-group',
135
+ 'table-header-group',
136
+ 'table-footer-group',
137
+ 'table-column',
138
+ 'table-column-group',
139
+ ]);
140
+
141
+ /** content-visibility suppresses contents only in layout containment boxes. */
142
+ export function hidesContents(el: Element): boolean {
143
+ const value = styleValue(el, 'content-visibility');
144
+ const hidden =
145
+ value === 'hidden' ||
146
+ (value === '' &&
147
+ el.getAttribute('hidden')?.toLowerCase() === 'until-found');
148
+ if (!hidden) return false;
149
+ // Some headless DOMs omit the native table-cell and inline display defaults.
150
+ const display =
151
+ styleValue(el, 'display') ||
152
+ (el.localName === 'td' || el.localName === 'th' ? 'table-cell' : 'inline');
153
+ if (NO_LAYOUT_CONTAINMENT.has(display)) return false;
154
+ if (display === 'inline' || display === 'inline list-item') {
155
+ // SVG rendering and native replaced/formatting contexts still suppress
156
+ // their contents even when the computed display is inline.
157
+ return (
158
+ el.namespaceURI === 'http://www.w3.org/2000/svg' ||
159
+ el.matches(
160
+ 'img, input, textarea, select, button, fieldset, video, audio, canvas, iframe, embed',
161
+ )
162
+ );
163
+ }
164
+ return true;
165
+ }
166
+
86
167
  /**
87
168
  * Whether `el` is in a closed `<details>`, other than in the summary that
88
169
  * toggles it: the browser renders none of that content (#389).
@@ -119,6 +200,7 @@ export function isRendered(
119
200
  return false;
120
201
  for (let e: Element | null = el; e; e = composedParent(e)) {
121
202
  if (styleValue(e, 'display') === 'none') return false;
203
+ if (e !== el && hidesContents(e)) return false;
122
204
  if (e === root) break;
123
205
  const parent = e.parentElement;
124
206
  // Connected light DOM may have no place in its host's rendered tree.
@@ -52,18 +52,27 @@ export const ownValue = (
52
52
  key: string,
53
53
  ): unknown => (ns && hasOwn(ns, key) ? (ns as Namespace)[key] : undefined);
54
54
 
55
+ /** Define an own data field without invoking an inherited accessor. */
56
+ export function defineData(
57
+ target: object,
58
+ key: PropertyKey,
59
+ value: unknown,
60
+ ): void {
61
+ Object.defineProperty(target, key, {
62
+ value,
63
+ enumerable: true,
64
+ writable: true,
65
+ configurable: true,
66
+ });
67
+ }
68
+
55
69
  /**
56
70
  * Set an own enumerable property. A "__proto__" key is defined as an own
57
71
  * property (as JSON.parse does) instead of replacing the prototype.
58
72
  */
59
73
  export function setOwn(target: object, key: string, value: unknown): void {
60
74
  if (key === '__proto__') {
61
- Object.defineProperty(target, key, {
62
- value,
63
- enumerable: true,
64
- writable: true,
65
- configurable: true,
66
- });
75
+ defineData(target, key, value);
67
76
  } else {
68
77
  (target as Record<string, unknown>)[key] = value;
69
78
  }
@@ -1,6 +1,6 @@
1
1
  import { current as draftState, isDraft, original } from 'immer';
2
2
  import { registeredClassName } from '../class-registry';
3
- import { hasOwn, isArrayIndex } from './namespace';
3
+ import { defineData, hasOwn, isArrayIndex } from './namespace';
4
4
  import { atomicName } from './value-kinds';
5
5
 
6
6
  /**
@@ -56,12 +56,7 @@ export function shallowCopy(value: object): Record<string, unknown> {
56
56
  // Define rather than assign (Object.assign), so that a "__proto__" key
57
57
  // stays a key instead of replacing the copy's prototype
58
58
  for (const key of Object.keys(value)) {
59
- Object.defineProperty(copy, key, {
60
- value: (value as Record<string, unknown>)[key],
61
- enumerable: true,
62
- writable: true,
63
- configurable: true,
64
- });
59
+ defineData(copy, key, (value as Record<string, unknown>)[key]);
65
60
  }
66
61
  return copy as Record<string, unknown>;
67
62
  }
@@ -0,0 +1,55 @@
1
+ import { composedElements, composedParent } from './element-visibility';
2
+
3
+ /** Remaining revealed characters at this node, across nested typewriters. */
4
+ function revealedCharacters(node: Node): number {
5
+ let available = Infinity;
6
+ const element = node.nodeType === 1 ? (node as Element) : node.parentElement;
7
+ for (let at = element; at; at = composedParent(at)) {
8
+ const count = at.getAttribute('data-type-revealed');
9
+ if (count === null) continue;
10
+ let left = Number(count);
11
+ if (!Number.isFinite(left)) continue;
12
+ // The visual clip counts DOM text, including text hidden by other CSS.
13
+ // Shadow content has no measured range until its containing type finishes.
14
+ if (!at.contains(node)) return 0;
15
+ for (let child = node; child !== at; child = child.parentNode!) {
16
+ for (
17
+ let sibling = child.previousSibling;
18
+ sibling;
19
+ sibling = sibling.previousSibling
20
+ ) {
21
+ if (sibling.nodeType === 1 || sibling.nodeType === 3)
22
+ left -= sibling.textContent?.length ?? 0;
23
+ }
24
+ }
25
+ available = Math.min(available, Math.max(0, left));
26
+ }
27
+ return available;
28
+ }
29
+
30
+ /** Only the prefix that every containing typewriter has revealed. */
31
+ export function revealedText(node: Text): string {
32
+ return node.data.slice(0, revealedCharacters(node));
33
+ }
34
+
35
+ /** Offer a control once its entire label is revealed, avoiding label spoilers.
36
+ * Controls without DOM text have no measured clip boxes; wait for completion.
37
+ */
38
+ export function isFullyRevealed(el: Element): boolean {
39
+ const available = revealedCharacters(el);
40
+ if (
41
+ available !== Infinity &&
42
+ (!el.textContent || available < el.textContent.length)
43
+ )
44
+ return false;
45
+ // Custom controls may wrap a typewriter in their label. An enclosing
46
+ // typewriter finishing does not reveal a slower one inside the control.
47
+ for (const child of composedElements(el)) {
48
+ if (
49
+ child.hasAttribute('data-type-revealed') &&
50
+ revealedCharacters(child) < (child.textContent?.length ?? 0)
51
+ )
52
+ return false;
53
+ }
54
+ return true;
55
+ }