@tristan2828/ui-foundation 5.0.0 → 5.0.1

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.
@@ -24,8 +24,10 @@ export type MarkdownProps = {
24
24
  * folds what's under it (to the next heading of its level or higher).
25
25
  * A plain heading never folds. What's folded is remembered on this device under this key
26
26
  * (name it for the app and the record: `"my-app:task:84:notes"`), and
27
- * shared with a RichTextEditor or NotesOutline given the same key. The
28
- * text is never changed.
27
+ * shared with a RichTextEditor or NotesOutline given the same key.
28
+ * Find in page reaching folded text opens its section (Chromium,
29
+ * Firefox; Safari's find skips folded text). The text is never
30
+ * changed.
29
31
  */
30
32
  foldKey?: string;
31
33
  /**
@@ -73,13 +73,13 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
73
73
  // is a real checkbox, named for its item's words, that ticks or unticks the
74
74
  // item and hands the whole new text over to save (src/lib/markdown-tasks.ts):
75
75
  // only that item's `[ ]` or `[x]` changes.
76
- import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
76
+ import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
77
77
  import ReactMarkdown, {} from 'react-markdown';
78
78
  import remarkGfm from 'remark-gfm';
79
79
  import { cn } from 'cn';
80
80
  import { ChevronDownIcon, ExternalLinkIcon, SquareCheckIcon, SquareIcon } from 'lucide-react';
81
81
  import { Checkbox } from '../ui/checkbox.js';
82
- import { useFolds } from '../../hooks/fold-store.js';
82
+ import { foldStore, useFolds } from '../../hooks/fold-store.js';
83
83
  import { CALLOUT_KINDS, remarkCallouts } from '../../lib/markdown-callout.js';
84
84
  import { rehypeFold, toggleFold } from '../../lib/markdown-fold.js';
85
85
  import { rehypeInline } from '../../lib/markdown-inline.js';
@@ -113,7 +113,7 @@ function omitNode(props) {
113
113
  // A GFM table in its box that scrolls sideways: a tab stop and a named
114
114
  // region only while the table overflows it. Watched again after each
115
115
  // render, so a header row with new words renames it.
116
- function NotesTable({ hidden, ...props }) {
116
+ function NotesTable({ hidden, 'data-fold-in': foldIn, ...props }) {
117
117
  const boxRef = useRef(null);
118
118
  useEffect(() => {
119
119
  const box = boxRef.current;
@@ -123,7 +123,7 @@ function NotesTable({ hidden, ...props }) {
123
123
  const region = watchTableScroll(box, table, headerTexts(table));
124
124
  return () => region.destroy();
125
125
  });
126
- return (_jsx("div", { ref: boxRef, "data-slot": "table-container", className: cn('prose-table', TABLE_SCROLL_FOCUS, hidden && 'hidden'), children: _jsx("table", { ...props }) }));
126
+ return (_jsx("div", { ref: boxRef, "data-slot": "table-container", hidden: hidden, "data-fold-in": foldIn, className: cn('prose-table', TABLE_SCROLL_FOCUS), children: _jsx("table", { ...props }) }));
127
127
  }
128
128
  // Ticks a task item by where it starts in the text: given only with
129
129
  // `onTasksChange`. Each task item hands its box its own start and words.
@@ -220,16 +220,16 @@ function heading(level, top, textTop) {
220
220
  const Tag = headingTag(level, top, textTop);
221
221
  return function Heading(props) {
222
222
  const toggle = useContext(FoldContext);
223
- const { 'data-fold-id': foldId, 'data-foldable': foldable, 'data-folded': folded, 'data-fold-label': label, 'data-toggle': isToggle, hidden, ...rest } = omitNode(props);
223
+ const { 'data-fold-id': foldId, 'data-foldable': foldable, 'data-folded': folded, 'data-fold-label': label, 'data-toggle': isToggle, 'data-fold-in': foldIn, hidden, ...rest } = omitNode(props);
224
224
  const look = cn('text-foreground', headingClass(level));
225
225
  const band = headingBand(level) || undefined;
226
226
  if (!toggle || foldId === undefined)
227
- return _jsx(Tag, { ...rest, hidden: hidden, "data-band": band, className: look });
227
+ return _jsx(Tag, { ...rest, hidden: hidden, "data-fold-in": foldIn, "data-band": band, className: look });
228
228
  // Plain: still found by its fold id (NotesOutline's jump), never folded.
229
229
  if (isToggle !== 'true')
230
- return _jsx(Tag, { ...rest, "data-fold-id": foldId, hidden: hidden, "data-band": band, className: look });
230
+ return _jsx(Tag, { ...rest, "data-fold-id": foldId, hidden: hidden, "data-fold-in": foldIn, "data-band": band, className: look });
231
231
  const open = folded !== 'true';
232
- return (_jsxs("div", { "data-fold-id": foldId, hidden: hidden, "data-band": band, className: cn(FOLD_HEADING, look), children: [foldable === 'true' ? (_jsx("button", { type: "button", "aria-expanded": open, "aria-label": label || 'Section', "data-slot": "fold-button", className: FOLD_BUTTON, onClick: () => toggle(foldId), children: _jsx(ChevronDownIcon, { "aria-hidden": "true", className: cn('size-4 transition-transform', !open && '-rotate-90') }) })) : (_jsx("span", { "aria-hidden": "true", className: "-ml-1 w-5 shrink-0" })), _jsx(Tag, { ...rest, className: "min-w-0 flex-1" })] }));
232
+ return (_jsxs("div", { "data-fold-id": foldId, hidden: hidden, "data-fold-in": foldIn, "data-band": band, className: cn(FOLD_HEADING, look), children: [foldable === 'true' ? (_jsx("button", { type: "button", "aria-expanded": open, "aria-label": label || 'Section', "data-slot": "fold-button", className: FOLD_BUTTON, onClick: () => toggle(foldId), children: _jsx(ChevronDownIcon, { "aria-hidden": "true", className: cn('size-4 transition-transform', !open && '-rotate-90') }) })) : (_jsx("span", { "aria-hidden": "true", className: "-ml-1 w-5 shrink-0" })), _jsx(Tag, { ...rest, className: "min-w-0 flex-1" })] }));
233
233
  };
234
234
  }
235
235
  // Everything but the headings, which follow `headingLevel` (componentsFor).
@@ -277,7 +277,7 @@ const COMPONENTS = {
277
277
  return _jsx("div", { ...rest, children: children });
278
278
  const look = CALLOUT_LOOK[kind];
279
279
  const Icon = look.icon;
280
- return (_jsxs("div", { role: "note", "data-callout": kind, hidden: rest.hidden, className: cn(CALLOUT_BOX, look.box), children: [_jsx(Icon, { "aria-hidden": "true", className: cn('mt-0.5 size-4 shrink-0', look.tint) }), _jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-2", children: [_jsxs("span", { className: "sr-only", children: [look.label, ": "] }), children] })] }));
280
+ return (_jsxs("div", { role: "note", "data-callout": kind, hidden: rest.hidden, "data-fold-in": rest['data-fold-in'], className: cn(CALLOUT_BOX, look.box), children: [_jsx(Icon, { "aria-hidden": "true", className: cn('mt-0.5 size-4 shrink-0', look.tint) }), _jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-2", children: [_jsxs("span", { className: "sr-only", children: [look.label, ": "] }), children] })] }));
281
281
  },
282
282
  pre: (props) => (_jsx("pre", { ...omitNode(props), className: "overflow-x-auto rounded-lg bg-muted p-3 font-mono text-foreground [&_code]:bg-transparent [&_code]:p-0" })),
283
283
  code: (props) => _jsx("code", { ...omitNode(props), className: "rounded bg-muted px-1 py-0.5 font-mono text-foreground" }),
@@ -324,6 +324,33 @@ function BlockMarkdown({ children, headingLevel = DEFAULT_HEADING_LEVEL, heading
324
324
  const [folded, setFolded] = useFolds(foldKey);
325
325
  const rehypePlugins = useMemo(() => (foldKey === undefined ? [rehypeTables] : [rehypeTables, [rehypeFold, { folded }]]), [foldKey, folded]);
326
326
  const toggle = useCallback((id) => setFolded(toggleFold(folded, id)), [folded, setFolded]);
327
+ // Find in page reaching folded text (`hidden="until-found"`, where the
328
+ // browser has it): the browser shows the block, and the headings folding
329
+ // it open, so what's folded stays what's shown.
330
+ const rootRef = useRef(null);
331
+ // React sets `hidden` as a boolean (`hidden=""`), so the folded blocks
332
+ // get their value here, before they're painted; React leaves it until the
333
+ // block opens (and drops the attribute).
334
+ useLayoutEffect(() => {
335
+ for (const block of rootRef.current?.querySelectorAll('[data-fold-in][hidden]') ?? [])
336
+ block.setAttribute('hidden', 'until-found');
337
+ });
338
+ useEffect(() => {
339
+ const root = rootRef.current;
340
+ if (!root || foldKey === undefined)
341
+ return;
342
+ const onMatch = (event) => {
343
+ const block = event.target instanceof HTMLElement ? event.target.closest('[data-fold-in]') : null;
344
+ if (!block?.dataset.foldIn)
345
+ return;
346
+ const ids = JSON.parse(block.dataset.foldIn);
347
+ const now = foldStore.get(foldKey);
348
+ if (ids.some((id) => now.has(id)))
349
+ foldStore.set(foldKey, new Set([...now].filter((id) => !ids.includes(id))));
350
+ };
351
+ root.addEventListener('beforematch', onMatch);
352
+ return () => root.removeEventListener('beforematch', onMatch);
353
+ }, [foldKey]);
327
354
  // Ticks not yet back as `children`: shown, and built on by the next
328
355
  // tick, so two quick ticks on a slow save both land. Kept while
329
356
  // `children` is the text they started from or one of their own saves
@@ -338,5 +365,5 @@ function BlockMarkdown({ children, headingLevel = DEFAULT_HEADING_LEVEL, heading
338
365
  if (saving && typeof saving.then === 'function')
339
366
  saving.then(undefined, () => setPending((current) => (current?.sent.includes(next) ? null : current)));
340
367
  }, [onTasksChange, children, shown, live]);
341
- return (_jsx("div", { "data-slot": "markdown", "data-table-look": tableLook, "data-fold-scope": foldKey, ...rest, className: cn('flex min-w-0 flex-col gap-3 type-body text-foreground break-words', PROSE_INSET, className), children: _jsx(PageLinkContext.Provider, { value: pageLink ?? null, children: _jsx(FoldContext.Provider, { value: foldKey === undefined ? null : toggle, children: _jsx(TaskToggleContext.Provider, { value: onTasksChange ? tickTask : null, children: _jsx(ReactMarkdown, { remarkPlugins: REMARK_PLUGINS, rehypePlugins: rehypePlugins, components: components, children: onTasksChange ? shown : children }) }) }) }) }));
368
+ return (_jsx("div", { ref: rootRef, "data-slot": "markdown", "data-table-look": tableLook, "data-fold-scope": foldKey, ...rest, className: cn('flex min-w-0 flex-col gap-3 type-body text-foreground break-words', PROSE_INSET, className), children: _jsx(PageLinkContext.Provider, { value: pageLink ?? null, children: _jsx(FoldContext.Provider, { value: foldKey === undefined ? null : toggle, children: _jsx(TaskToggleContext.Provider, { value: onTasksChange ? tickTask : null, children: _jsx(ReactMarkdown, { remarkPlugins: REMARK_PLUGINS, rehypePlugins: rehypePlugins, components: components, children: onTasksChange ? shown : children }) }) }) }) }));
342
369
  }
@@ -123,7 +123,8 @@ export type RichTextEditorProps = {
123
123
  * top level has a button that folds what's under it (a plain heading
124
124
  * never folds), Ctrl/Cmd+Alt+[ folds the section the caret is in and
125
125
  * Ctrl/Cmd+Alt+] opens the heading it's on, and the caret moving into a
126
- * folded section opens it. Remembered on this device under this key,
126
+ * folded section opens it, as find in page reaching its text does
127
+ * (Chromium, Firefox; Safari's find skips folded text). Remembered on this device under this key,
127
128
  * and shared with `<Markdown>` and NotesOutline given the same one.
128
129
  * Only the view folds: the Markdown saved never changes. Read once,
129
130
  * when it mounts.
@@ -16,7 +16,7 @@ function build(doc, folded) {
16
16
  const heading = headings.get(index);
17
17
  const attrs = {};
18
18
  if (plan.hidden.has(index))
19
- attrs.hidden = '';
19
+ attrs.hidden = 'until-found';
20
20
  if (heading) {
21
21
  const spec = {
22
22
  id: heading.id,
@@ -148,6 +148,21 @@ export function foldPlugin(options) {
148
148
  let sent = foldPluginKey.getState(editorView.state)?.plan.headings ?? [];
149
149
  let frame = 0;
150
150
  options.onHeadings?.(sent);
151
+ // Find in page reached folded text: the headings folding its block
152
+ // open, before the browser shows it, so the two never disagree.
153
+ const onMatch = (event) => {
154
+ const fold = foldPluginKey.getState(editorView.state);
155
+ if (!fold)
156
+ return;
157
+ let found = -1;
158
+ editorView.state.doc.forEach((_node, offset, index) => {
159
+ if (editorView.nodeDOM(offset) === event.target)
160
+ found = index;
161
+ });
162
+ if (found >= 0 && fold.plan.hidden.has(found))
163
+ options.onChange(openAt(fold.plan, fold.folded, found));
164
+ };
165
+ editorView.dom.addEventListener('beforematch', onMatch);
151
166
  const sendHeadings = (view) => {
152
167
  frame = 0;
153
168
  const headings = foldPluginKey.getState(view.state)?.plan.headings;
@@ -157,7 +172,10 @@ export function foldPlugin(options) {
157
172
  options.onHeadings?.(headings);
158
173
  };
159
174
  return {
160
- destroy: () => cancelAnimationFrame(frame),
175
+ destroy: () => {
176
+ cancelAnimationFrame(frame);
177
+ editorView.dom.removeEventListener('beforematch', onMatch);
178
+ },
161
179
  update: (view, previous) => {
162
180
  const fold = foldPluginKey.getState(view.state);
163
181
  if (!fold)
@@ -54,10 +54,15 @@ export declare function openTo(plan: {
54
54
  export declare function openAt(plan: FoldPlan, folded: ReadonlySet<string>, index: number): Set<string>;
55
55
  /** `folded` with `id` turned the other way. */
56
56
  export declare function toggleFold(folded: ReadonlySet<string>, id: string): Set<string>;
57
+ /** The folded headings whose sections hold the top-level block at `index`: what opening it opens. */
58
+ export declare function foldedAround(plan: FoldPlan, folded: ReadonlySet<string>, index: number): string[];
57
59
  /**
58
60
  * For <Markdown> (react-markdown's rehype plugins): marks each top-level
59
61
  * heading with its fold id and state, and hides every top-level block a
60
- * folded heading covers (`hidden`). Raw HTML at the top level, which
62
+ * folded heading covers (`hidden="until-found"`, so the browser's find in
63
+ * page still reaches it), naming the headings that fold it
64
+ * (`data-fold-in`, a JSON list of ids) for the `beforematch` that opens
65
+ * them. Raw HTML at the top level, which
61
66
  * <Markdown> shows as its characters, is hidden as a paragraph of the same
62
67
  * characters. GFM's footnotes, gathered at the end, are never hidden.
63
68
  */
@@ -127,10 +127,17 @@ function hastText(node) {
127
127
  return (node.children ?? []).map(hastText).join('');
128
128
  }
129
129
  const HEADING = /^h([1-6])$/;
130
+ /** The folded headings whose sections hold the top-level block at `index`: what opening it opens. */
131
+ export function foldedAround(plan, folded, index) {
132
+ return plan.headings.filter((heading) => heading.index < index && index < heading.end && folded.has(heading.id)).map((heading) => heading.id);
133
+ }
130
134
  /**
131
135
  * For <Markdown> (react-markdown's rehype plugins): marks each top-level
132
136
  * heading with its fold id and state, and hides every top-level block a
133
- * folded heading covers (`hidden`). Raw HTML at the top level, which
137
+ * folded heading covers (`hidden="until-found"`, so the browser's find in
138
+ * page still reaches it), naming the headings that fold it
139
+ * (`data-fold-in`, a JSON list of ids) for the `beforematch` that opens
140
+ * them. Raw HTML at the top level, which
134
141
  * <Markdown> shows as its characters, is hidden as a paragraph of the same
135
142
  * characters. GFM's footnotes, gathered at the end, are never hidden.
136
143
  */
@@ -171,7 +178,7 @@ export function rehypeFold(options) {
171
178
  node = { type: 'element', tagName: 'p', properties: {}, children: [{ type: 'text', value: node.value ?? '' }] };
172
179
  children[index] = node;
173
180
  }
174
- node.properties = { ...node.properties, hidden: true };
181
+ node.properties = { ...node.properties, hidden: 'until-found', dataFoldIn: JSON.stringify(foldedAround(plan, options.folded, block)) };
175
182
  }
176
183
  };
177
184
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tristan2828/ui-foundation",
3
- "version": "5.0.0",
3
+ "version": "5.0.1",
4
4
  "description": "Shared UI foundation for contract-first, database-backed React apps: shadcn primitives, DataTable/EntityForm composites, auth, the gateway error seam, design tokens, lint rules and the AI playbook.",
5
5
  "license": "MIT",
6
6
  "repository": {
package/styles/index.css CHANGED
@@ -359,6 +359,24 @@
359
359
  }
360
360
  }
361
361
 
362
+ /* A folded block in written text (<Markdown>'s `foldKey`, the editor's):
363
+ `hidden="until-found"`, so find in page still reaches it. Where the
364
+ browser has it, the block keeps a box (its content unpainted), so it is
365
+ drawn as nothing: no height, padding, border or fill, and a margin that
366
+ takes back the gap the text's column puts before it (`gap-3`, the gap
367
+ of both). Where the browser hasn't, it's `display: none`, as `hidden`.
368
+ A folded block always follows its heading, so never the first. */
369
+ :is([data-slot="markdown"], .ProseMirror) > [hidden="until-found"] {
370
+ block-size: 0;
371
+ min-block-size: 0;
372
+ margin: calc(var(--spacing) * -3) 0 0;
373
+ padding: 0;
374
+ border: 0;
375
+ background: none;
376
+ box-shadow: none;
377
+ outline: none;
378
+ }
379
+
362
380
  /* Tables in written text (<Markdown> and the rich-text editor; each puts
363
381
  its table in a `.prose-table` box that scrolls sideways). Columns fit
364
382
  their content: the table is only as wide as its words, a cell wraps at