@tristan2828/ui-foundation 5.0.1 → 5.1.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.
@@ -38,19 +38,19 @@
38
38
  - [The table opens the view, and the form returns to it](#the-table-opens-the-view-and-the-form-returns-to-it) · lines 884–895
39
39
  - [`<SelectValue>` shows the value, not the label](#selectvalue-shows-the-value-not-the-label) · lines 897–943
40
40
  - [Choosing how each column looks](#choosing-how-each-column-looks) · lines 945–959
41
- - [How a list opens a record](#how-a-list-opens-a-record) · lines 961–1472
41
+ - [How a list opens a record](#how-a-list-opens-a-record) · lines 961–1473
42
42
  - [The record view](#the-record-view) · lines 1104–1291
43
- - [Forms](#forms) · lines 1293–1376
44
- - [Dialogs](#dialogs) · lines 1378–1411
45
- - [Toasts and feedback](#toasts-and-feedback) · lines 1413–1472
46
- - [What not to copy](#what-not-to-copy) · lines 1474–1501
47
- - [After a commit, in the backend](#after-a-commit-in-the-backend) · lines 1503–1520
48
- - [Saves that don't overwrite](#saves-that-dont-overwrite) · lines 1522–1582
49
- - [Deleting](#deleting) · lines 1584–1614
50
- - [Fields only a script writes](#fields-only-a-script-writes) · lines 1616–1635
51
- - [Searching one part of the app](#searching-one-part-of-the-app) · lines 1637–1646
52
- - [What a chat is told about an entity](#what-a-chat-is-told-about-an-entity) · lines 1649–1691
53
- - [Behind a sign-in proxy](#behind-a-sign-in-proxy) · lines 1693–1726
43
+ - [Forms](#forms) · lines 1293–1377
44
+ - [Dialogs](#dialogs) · lines 1379–1412
45
+ - [Toasts and feedback](#toasts-and-feedback) · lines 1414–1473
46
+ - [What not to copy](#what-not-to-copy) · lines 1475–1502
47
+ - [After a commit, in the backend](#after-a-commit-in-the-backend) · lines 1504–1521
48
+ - [Saves that don't overwrite](#saves-that-dont-overwrite) · lines 1523–1583
49
+ - [Deleting](#deleting) · lines 1585–1615
50
+ - [Fields only a script writes](#fields-only-a-script-writes) · lines 1617–1636
51
+ - [Searching one part of the app](#searching-one-part-of-the-app) · lines 1638–1647
52
+ - [What a chat is told about an entity](#what-a-chat-is-told-about-an-entity) · lines 1650–1692
53
+ - [Behind a sign-in proxy](#behind-a-sign-in-proxy) · lines 1694–1727
54
54
 
55
55
  <!-- /index -->
56
56
 
@@ -1319,7 +1319,8 @@ shape:
1319
1319
  Give it the app's `upload` (the one
1320
1320
  `ImageField` takes) for the Image button and for pasted and dropped
1321
1321
  pictures, which go in as `![](url)`; a refused or failed picture says
1322
- why in a toast. Without `upload` there's no Image button, and a picture
1322
+ why in a toast. A picture's description (its alt text) is set from the
1323
+ button on it once it's selected. Without `upload` there's no Image button, and a picture
1323
1324
  can't go in at all.
1324
1325
  - **Required:** `<FieldLabel required>` (an asterisk, and `aria-required`
1325
1326
  on the control it names). Nothing on an optional field: never
@@ -26,26 +26,26 @@
26
26
  - [A variant: a pressed icon inside another value's cell](#a-variant-a-pressed-icon-inside-another-values-cell) · lines 636–715
27
27
  - [16. Title linking to the record's view](#16-title-linking-to-the-records-view) · lines 717–758
28
28
  - [17. Quick action on the view](#17-quick-action-on-the-view) · lines 760–832
29
- - [18. Editable value](#18-editable-value) · lines 834–1705
30
- - [Presets: one line per field](#presets-one-line-per-field) · lines 1240–1312
31
- - [Several fields edited as one](#several-fields-edited-as-one) · lines 1314–1350
32
- - [A link and its label](#a-link-and-its-label) · lines 1352–1376
33
- - [A list of sub-items](#a-list-of-sub-items) · lines 1378–1511
34
- - [On a page of the app's own: `EditInPlaceScope`](#on-a-page-of-the-apps-own-editinplacescope) · lines 1513–1622
35
- - [In a table's rows](#in-a-tables-rows) · lines 1624–1698
36
- - [A table of a few short columns: `width="content"`](#a-table-of-a-few-short-columns-widthcontent) · lines 1700–1705
37
- - [19. Stage circle for an ordered status](#19-stage-circle-for-an-ordered-status) · lines 1707–1773
38
- - [20. Count linking to the related records](#20-count-linking-to-the-related-records) · lines 1775–1829
39
- - [21. Rows grouped under headings, and a pill filter](#21-rows-grouped-under-headings-and-a-pill-filter) · lines 1831–1913
40
- - [22. A highlighted row, and rows that are done](#22-a-highlighted-row-and-rows-that-are-done) · lines 1915–1940
41
- - [28. A list's rows: hover, lines, rows per page](#28-a-lists-rows-hover-lines-rows-per-page) · lines 1942–1975
42
- - [23. A Group menu, and a record read beside the list](#23-a-group-menu-and-a-record-read-beside-the-list) · lines 1977–2028
43
- - [24. A stored colour beside its name](#24-a-stored-colour-beside-its-name) · lines 2030–2104
44
- - [Picking one on a form: `ColorField`](#picking-one-on-a-form-colorfield) · lines 2050–2104
45
- - [25. A list's tools: views, filters, columns, row actions, a phone's rows](#25-a-lists-tools-views-filters-columns-row-actions-a-phones-rows) · lines 2106–2318
46
- - [The framed look, and sibling lists beside the title](#the-framed-look-and-sibling-lists-beside-the-title) · lines 2267–2318
47
- - [26. A record's related list, capped](#26-a-records-related-list-capped) · lines 2320–2354
48
- - [27. A repeat and its next time](#27-a-repeat-and-its-next-time) · lines 2356–2403
29
+ - [18. Editable value](#18-editable-value) · lines 834–1710
30
+ - [Presets: one line per field](#presets-one-line-per-field) · lines 1245–1317
31
+ - [Several fields edited as one](#several-fields-edited-as-one) · lines 1319–1355
32
+ - [A link and its label](#a-link-and-its-label) · lines 1357–1381
33
+ - [A list of sub-items](#a-list-of-sub-items) · lines 1383–1516
34
+ - [On a page of the app's own: `EditInPlaceScope`](#on-a-page-of-the-apps-own-editinplacescope) · lines 1518–1627
35
+ - [In a table's rows](#in-a-tables-rows) · lines 1629–1703
36
+ - [A table of a few short columns: `width="content"`](#a-table-of-a-few-short-columns-widthcontent) · lines 1705–1710
37
+ - [19. Stage circle for an ordered status](#19-stage-circle-for-an-ordered-status) · lines 1712–1778
38
+ - [20. Count linking to the related records](#20-count-linking-to-the-related-records) · lines 1780–1834
39
+ - [21. Rows grouped under headings, and a pill filter](#21-rows-grouped-under-headings-and-a-pill-filter) · lines 1836–1918
40
+ - [22. A highlighted row, and rows that are done](#22-a-highlighted-row-and-rows-that-are-done) · lines 1920–1945
41
+ - [28. A list's rows: hover, lines, rows per page](#28-a-lists-rows-hover-lines-rows-per-page) · lines 1947–1980
42
+ - [23. A Group menu, and a record read beside the list](#23-a-group-menu-and-a-record-read-beside-the-list) · lines 1982–2033
43
+ - [24. A stored colour beside its name](#24-a-stored-colour-beside-its-name) · lines 2035–2109
44
+ - [Picking one on a form: `ColorField`](#picking-one-on-a-form-colorfield) · lines 2055–2109
45
+ - [25. A list's tools: views, filters, columns, row actions, a phone's rows](#25-a-lists-tools-views-filters-columns-row-actions-a-phones-rows) · lines 2111–2323
46
+ - [The framed look, and sibling lists beside the title](#the-framed-look-and-sibling-lists-beside-the-title) · lines 2272–2323
47
+ - [26. A record's related list, capped](#26-a-records-related-list-capped) · lines 2325–2359
48
+ - [27. A repeat and its next time](#27-a-repeat-and-its-next-time) · lines 2361–2408
49
49
 
50
50
  <!-- /index -->
51
51
 
@@ -1228,6 +1228,11 @@ const price = editInPlace({
1228
1228
  in as `![](url)`, a placeholder showing meanwhile (never saved, and
1229
1229
  read out from a live region named "Uploads"), a
1230
1230
  refusal or failure in a toast. No `upload`, no file handling at all.
1231
+ A selected image (clicked, tapped, or reached with the arrow keys) shows
1232
+ an Add Description button on it; it, Enter, or Alt+F10 then Enter opens
1233
+ a small box for the image's description, its alt text, saved as
1234
+ `![description](url)` in one undo step. An empty description stays
1235
+ `![](url)`: the picture only decorates.
1231
1236
  - **The save is the single-field save** (`useRecordUpdate` with
1232
1237
  `optimistic: false, toastOnError: false`, the entity's
1233
1238
  `useEdit<Entity>Field`), `mutateAsync` of one field's PATCH.
@@ -48,13 +48,17 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
48
48
  // - A fixed toolbar above the text (rich-text-toolbar.tsx) and a floating
49
49
  // one over selected words (rich-text-floating-toolbar.tsx), unless
50
50
  // `toolbar={false}`; `toolbar="floating"` leaves out the fixed one.
51
- // Alt+F10 reaches the floating one when it shows, else the fixed one.
51
+ // Alt+F10 reaches a selected image's button, else the floating toolbar
52
+ // when it shows, else the fixed one.
52
53
  // The slash menu (rich-text-slash.ts) goes with them.
53
54
  // - `inline`: the field drawn as the text it edits (no border, no box),
54
55
  // for notes that are always editable where they're read.
55
56
  // - Images show at most the field's width. With `upload`, an image pasted,
56
57
  // dropped or picked is uploaded through it and goes in as `![](url)`
57
58
  // (rich-text-image-upload.ts); a refusal or a failed upload is a toast.
59
+ // A selected image gets its description (its alt text) from a small box
60
+ // (rich-text-image-box.tsx, rich-text-image-select.ts): its Description
61
+ // button, or Enter.
58
62
  // What's uploading is read from a live region named "Uploads"
59
63
  // (`role="status"`, empty while nothing uploads).
60
64
  // - `foldKey`: the text folds by its toggle headings, as <Markdown> does
@@ -107,6 +111,8 @@ import { taskItemView, toggleTaskItem } from './rich-text-task-item-view.js';
107
111
  import { applyLink, followLink, linkTarget, notePress } from './rich-text-links.js';
108
112
  import { anchorAt } from './rich-text-box-anchor.js';
109
113
  import { LinkForm } from './rich-text-link-box.js';
114
+ import { ImageDescriptionForm, RichTextImageButton } from './rich-text-image-box.js';
115
+ import { imageAnchor, selectedImage, selectTappedImage, setImageDescription } from './rich-text-image-select.js';
110
116
  import { PageForm } from './rich-text-page-box.js';
111
117
  import { RichTextFloatingToolbar } from './rich-text-floating-toolbar.js';
112
118
  import { formatOn, tableAt, toggleFormat } from './rich-text-formats.js';
@@ -262,13 +268,15 @@ const SHOWN_FORMATS = [
262
268
  // What the editor's React parts draw from its state, as one string: the
263
269
  // formats on, the selection (where only when there is one: a caret's
264
270
  // place matters to nothing drawn but the slash menu and a table's grips),
265
- // the slash menu's query, a table's caret cell and the uploads. A key
271
+ // the slash menu's query, a table's caret cell, a selected image's
272
+ // description and the uploads. A key
266
273
  // that doesn't change it re-renders nothing.
267
274
  function shownKey(state) {
268
275
  const { selection } = state;
269
276
  const parts = [selection.empty ? 'caret' : `${selection.from}-${selection.to}`];
277
+ // A selected image's description is its button's label.
270
278
  if (selection instanceof NodeSelection)
271
- parts.push('node');
279
+ parts.push(selection.node.type.name === 'image' ? `node:alt=${String(selection.node.attrs.alt)}` : 'node');
272
280
  if (selection.$from.parent.type.spec.code)
273
281
  parts.push('code');
274
282
  if (!selection.empty && selection.$from.sameParent(selection.$to))
@@ -307,6 +315,9 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
307
315
  const rootRef = useRef(null);
308
316
  const editorRef = useRef(null);
309
317
  const [linkBox, setLinkBox] = useState(null);
318
+ // The selected image's description box, and its button's element.
319
+ const [imageBox, setImageBox] = useState(null);
320
+ const imageButtonRef = useRef(null);
310
321
  // The new page's title box, and whether the app is making the page.
311
322
  const [pageBox, setPageBox] = useState(null);
312
323
  const [pageBusy, setPageBusy] = useState(false);
@@ -351,6 +362,8 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
351
362
  const slashMenuRef = useRef(null);
352
363
  // Opens the link box: made with the editor, used by the toolbar's Link.
353
364
  const openLinkRef = useRef(() => { });
365
+ // Opens the selected image's description box (Enter, the button).
366
+ const openImageRef = useRef(() => false);
354
367
  // The node views' slots (a callout's icon, a table's bars), each
355
368
  // rendered into through a portal.
356
369
  const [widgets, setWidgets] = useState([]);
@@ -563,6 +576,15 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
563
576
  setLinkBox({ ...target, anchor: anchorAt(view, target.from) });
564
577
  };
565
578
  openLinkRef.current = openLink;
579
+ // Opens the description box for the selected image, if one is.
580
+ const openImage = (view) => {
581
+ const image = view.editable ? selectedImage(view.state) : null;
582
+ if (!image)
583
+ return false;
584
+ setImageBox({ ...image, anchor: imageAnchor(view, image.pos) });
585
+ return true;
586
+ };
587
+ openImageRef.current = openImage;
566
588
  // Folding by headings, with `foldKey` (read once, when it mounts):
567
589
  // the fold store is the state, the plugin draws it, and publishes the
568
590
  // headings for NotesOutline under the same key.
@@ -688,11 +710,17 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
688
710
  setFocused(false);
689
711
  return false;
690
712
  },
691
- // A click on a link follows it (followLink).
692
- click: (view, event) => followLink(view, event, {
693
- resolve: latest.current.pageLink,
694
- open: (href) => (navigateRef.current ? navigateRef.current(href) : window.location.assign(href)),
695
- }),
713
+ // A click on a link follows it (followLink); a tap on an
714
+ // image selects it (selectTappedImage).
715
+ click: (view, event) => {
716
+ const followed = followLink(view, event, {
717
+ resolve: latest.current.pageLink,
718
+ open: (href) => (navigateRef.current ? navigateRef.current(href) : window.location.assign(href)),
719
+ });
720
+ if (!followed)
721
+ selectTappedImage(view, event);
722
+ return followed;
723
+ },
696
724
  // The floating toolbar waits for the mouse to be up: a drag
697
725
  // is still choosing the words.
698
726
  mousedown: (view, event) => {
@@ -713,8 +741,9 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
713
741
  emit();
714
742
  // Alt+F10: to the floating toolbar when it shows, else the
715
743
  // fixed one (the convention editors share).
744
+ // A selected image's Description button comes first.
716
745
  if (event.altKey && event.key === 'F10') {
717
- const bar = floatingOpenRef.current ? floatingRef.current : (toolbarRef.current ?? toolsRef.current);
746
+ const bar = imageButtonRef.current ?? (floatingOpenRef.current ? floatingRef.current : (toolbarRef.current ?? toolsRef.current));
718
747
  const button = bar?.querySelector('button[tabindex="0"]');
719
748
  if (!button)
720
749
  return false;
@@ -741,6 +770,12 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
741
770
  if (event.key === 'Escape')
742
771
  passEscapeThrough(event);
743
772
  const mod = event.metaKey || event.ctrlKey;
773
+ // Enter on a selected image opens its description box, where
774
+ // it would otherwise replace the image with a new line.
775
+ if (event.key === 'Enter' && !mod && !event.shiftKey && !event.altKey && openImage(view)) {
776
+ event.preventDefault();
777
+ return true;
778
+ }
744
779
  if (mod && !event.shiftKey && !event.altKey && event.key.toLowerCase() === 'k') {
745
780
  event.preventDefault();
746
781
  openLink(view);
@@ -1205,6 +1240,9 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
1205
1240
  useEffect(() => {
1206
1241
  floatingOpenRef.current = floatingOpen;
1207
1242
  });
1243
+ // The selected image's Description button: the text editable and
1244
+ // focused, and no box open over it.
1245
+ const imageSelected = editorState && !readOnly && focused && linkBox === null && pageBox === null && imageBox === null ? selectedImage(editorState) : null;
1208
1246
  const returnToText = () => editorView?.focus();
1209
1247
  // The tools strip of a field with only the floating toolbar.
1210
1248
  const toolsOpen = Boolean(toolbar === 'floating' && !coarse && editorView && (focused || fullScreen));
@@ -1287,6 +1325,10 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
1287
1325
  view.focus();
1288
1326
  return null;
1289
1327
  };
1328
+ const closeImage = () => {
1329
+ setImageBox(null);
1330
+ editorRef.current?.action((ctx) => ctx.get(editorViewCtx).focus());
1331
+ };
1290
1332
  const closeLink = () => {
1291
1333
  setLinkBox(null);
1292
1334
  editorRef.current?.action((ctx) => ctx.get(editorViewCtx).focus());
@@ -1355,13 +1397,20 @@ export default function MilkdownEditor({ id, defaultValue, onChange, onProblem,
1355
1397
  const next = event.relatedTarget;
1356
1398
  if (editorView && !editorView.dom.contains(next) && !inFloating(next))
1357
1399
  setFocused(false);
1400
+ } })), imageSelected && editorView && editorState && (_jsx(RichTextImageButton, { ref: imageButtonRef, view: editorView, state: editorState, image: imageSelected, field: field, onOpen: () => openImageRef.current(editorView), onReturn: returnToText, onBlur: (event) => {
1401
+ const next = event.relatedTarget;
1402
+ if (!editorView.dom.contains(next) && !inFloating(next))
1403
+ setFocused(false);
1358
1404
  } })), floatingOpen && editorView && editorState && (_jsx(RichTextFloatingToolbar, { ref: floatingRef, view: editorView, state: editorState, field: field, controls: editableId, onFormat: runFormat, onPage: onCreatePage && selectionInOneBlock ? pageFromSelection : undefined, onDismiss: () => setDismissed({ from: editorState.selection.from, to: editorState.selection.to }), onReturn: returnToText, onBlur: (event) => {
1359
1405
  const next = event.relatedTarget;
1360
1406
  if (!editorView.dom.contains(next) && !inFloating(next))
1361
1407
  setFocused(false);
1362
1408
  } }))] }), upload && (_jsx("p", { role: "status", "aria-label": "Uploads", className: "sr-only", children: uploading > 0 ? `Uploading ${uploading === 1 ? 'an image' : `${uploading} images`}…` : '' })), showCount && (_jsx("p", { id: counterId, "data-slot": "rich-text-editor-count", className: cn('text-right type-caption tabular-nums', length > maxLength ? 'text-destructive-text' : 'text-muted-foreground'), children: length > maxLength
1363
1409
  ? `${(length - maxLength).toLocaleString()} characters over the limit of ${maxLength.toLocaleString()}`
1364
- : `${length.toLocaleString()} of ${maxLength.toLocaleString()} characters` })), inRouter && _jsx(NavigateBridge, { targetRef: navigateRef }), _jsx(Popover, { open: pageBox !== null, onOpenChange: (open) => !open && !pageBusy && closePage(), children: pageBox && _jsx(PageForm, { box: pageBox, busy: pageBusy, onCreate: createPage }) }), _jsx(Popover, { open: linkBox !== null, onOpenChange: (open) => !open && closeLink(), children: linkBox && (_jsx(LinkForm, { box: linkBox, onApply: (href) => {
1410
+ : `${length.toLocaleString()} of ${maxLength.toLocaleString()} characters` })), inRouter && _jsx(NavigateBridge, { targetRef: navigateRef }), _jsx(Popover, { open: pageBox !== null, onOpenChange: (open) => !open && !pageBusy && closePage(), children: pageBox && _jsx(PageForm, { box: pageBox, busy: pageBusy, onCreate: createPage }) }), _jsx(Popover, { open: imageBox !== null, onOpenChange: (open) => !open && closeImage(), children: imageBox && (_jsx(ImageDescriptionForm, { box: imageBox, onApply: (description) => {
1411
+ editorRef.current?.action((ctx) => setImageDescription(ctx.get(editorViewCtx), imageBox.pos, description));
1412
+ closeImage();
1413
+ } })) }), _jsx(Popover, { open: linkBox !== null, onOpenChange: (open) => !open && closeLink(), children: linkBox && (_jsx(LinkForm, { box: linkBox, onApply: (href) => {
1365
1414
  const editor = editorRef.current;
1366
1415
  editor?.action((ctx) => applyLink(ctx.get(editorViewCtx), linkBox, href));
1367
1416
  closeLink();
@@ -0,0 +1,29 @@
1
+ import { type FocusEvent, type Ref } from 'react';
2
+ import type { EditorState } from '@milkdown/kit/prose/state';
3
+ import type { EditorView } from '@milkdown/kit/prose/view';
4
+ import type { BoxAnchor } from './rich-text-box-anchor.js';
5
+ import { type SelectedImage } from './rich-text-image-select.js';
6
+ export type ImageBox = SelectedImage & {
7
+ anchor: BoxAnchor;
8
+ };
9
+ export interface RichTextImageButtonProps {
10
+ view: EditorView;
11
+ /** The editor's state now, so it moves with the image. */
12
+ state: EditorState;
13
+ image: SelectedImage;
14
+ /** The field's element it's placed against (positioned: `relative`). */
15
+ field: HTMLElement | null;
16
+ /** Pressed: open the box. */
17
+ onOpen: () => void;
18
+ /** Esc or Tab: focus back to the text. */
19
+ onReturn: () => void;
20
+ onBlur: (event: FocusEvent) => void;
21
+ ref?: Ref<HTMLDivElement>;
22
+ }
23
+ /** The Description button over the selected image's top-left corner. */
24
+ export declare function RichTextImageButton({ view, state, image, field, onOpen, onReturn, onBlur, ref }: RichTextImageButtonProps): import("react").JSX.Element;
25
+ /** The box: the image's description, and Apply. */
26
+ export declare function ImageDescriptionForm({ box, onApply }: {
27
+ box: ImageBox;
28
+ onApply: (description: string) => void;
29
+ }): import("react").JSX.Element;
@@ -0,0 +1,89 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // A selected image's description in the rich-text editor: the alt text a
3
+ // screen reader reads in its place, saved as `![description](url)`. The
4
+ // editor decides when each part shows (milkdown-editor.tsx):
5
+ //
6
+ // - The Description button, on the image while it's selected (a click or
7
+ // a tap on it, or the arrow keys onto it) and the text is editable. It
8
+ // sits inside the field's own element, placed against it, as the
9
+ // floating toolbar does. A mouse press never takes focus from the text.
10
+ // - The box, opened by the button, by Enter on the selected image, or
11
+ // Alt+F10 then Enter: the description, and Apply. Enter applies it, in
12
+ // one undo step; Esc closes the box, the image left as it was. An empty
13
+ // description is saved as `![](url)`: the image only decorates.
14
+ import { useId, useLayoutEffect, useRef, useState } from 'react';
15
+ import { CaptionsIcon } from 'lucide-react';
16
+ import { cn } from 'cn';
17
+ import { Button } from '../ui/button.js';
18
+ import { Field, FieldDescription, FieldLabel } from '../ui/field.js';
19
+ import { Input } from '../ui/input.js';
20
+ import { PopoverContent } from '../ui/popover.js';
21
+ import { imageElement } from './rich-text-image-select.js';
22
+ const GAP = 8;
23
+ /** The Description button over the selected image's top-left corner. */
24
+ export function RichTextImageButton({ view, state, image, field, onOpen, onReturn, onBlur, ref }) {
25
+ const [bar, setBar] = useState(null);
26
+ const [placement, setPlacement] = useState(null);
27
+ // Over the image's corner when it's big enough to hold the button, else
28
+ // just under it; never past the field's sides.
29
+ useLayoutEffect(() => {
30
+ if (!bar || !field)
31
+ return;
32
+ const update = () => {
33
+ const element = imageElement(view, image.pos);
34
+ if (!element)
35
+ return;
36
+ const picture = element.getBoundingClientRect();
37
+ const box = field.getBoundingClientRect();
38
+ const { offsetWidth: width, offsetHeight: height } = bar;
39
+ const inside = picture.width >= width + 2 * GAP && picture.height >= height + 2 * GAP;
40
+ const top = inside ? picture.top + GAP : picture.bottom + GAP;
41
+ const left = Math.max(0, Math.min((inside ? picture.left + GAP : picture.left) - box.left, box.width - width));
42
+ setPlacement({ top: top - box.top, left });
43
+ };
44
+ update();
45
+ // An image still loading has no size yet.
46
+ const element = imageElement(view, image.pos);
47
+ element?.addEventListener('load', update);
48
+ window.addEventListener('resize', update);
49
+ return () => {
50
+ element?.removeEventListener('load', update);
51
+ window.removeEventListener('resize', update);
52
+ };
53
+ }, [view, state, image.pos, field, bar]);
54
+ const onKeyDown = (event) => {
55
+ if (event.key === 'Escape' || event.key === 'Tab') {
56
+ // Its own: not the field's (editing in place would give up the edit).
57
+ event.preventDefault();
58
+ event.stopPropagation();
59
+ onReturn();
60
+ }
61
+ };
62
+ return (_jsx("div", { ref: (element) => {
63
+ setBar(element);
64
+ if (typeof ref === 'function')
65
+ ref(element);
66
+ else if (ref)
67
+ ref.current = element;
68
+ }, "data-slot": "rich-text-image-button", "data-rich-text-menu": "", style: placement ? { top: placement.top, left: placement.left } : undefined, className: cn('absolute z-50 rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10', 'animate-in fade-in-0 zoom-in-95 duration-100', !placement && 'invisible'), onKeyDown: onKeyDown, onBlur: onBlur, children: _jsxs(Button, { size: "sm", variant: "ghost", tabIndex: 0, "aria-keyshortcuts": "Enter",
69
+ // At least a 40px tap on a touch screen, as the keyboard row's.
70
+ className: "pointer-coarse:h-11", onMouseDown: (event) => event.preventDefault(), onClick: onOpen, children: [_jsx(CaptionsIcon, { "aria-hidden": true }), image.alt ? 'Edit Description' : 'Add Description'] }) }));
71
+ }
72
+ /** The box: the image's description, and Apply. */
73
+ export function ImageDescriptionForm({ box, onApply }) {
74
+ const [typed, setTyped] = useState(box.alt);
75
+ const inputRef = useRef(null);
76
+ const inputId = useId();
77
+ const helpId = `${inputId}-help`;
78
+ // Enter (Ctrl/Cmd+Enter too) applies and stays its own: editing in place
79
+ // listens for Ctrl/Cmd+Enter through the portal, and would save the
80
+ // field without it. Esc is the popover's: it closes the box only.
81
+ const onKeyDown = (event) => {
82
+ if (event.key === 'Enter' && event.target === inputRef.current) {
83
+ event.preventDefault();
84
+ event.stopPropagation();
85
+ onApply(typed);
86
+ }
87
+ };
88
+ return (_jsxs(PopoverContent, { anchor: box.anchor, align: "start", "aria-label": box.alt ? 'Edit Description' : 'Add Description', initialFocus: inputRef, finalFocus: false, className: "w-80", onKeyDown: onKeyDown, children: [_jsxs(Field, { children: [_jsx(FieldLabel, { htmlFor: inputId, children: "Image Description" }), _jsx(Input, { ref: inputRef, id: inputId, value: typed, autoComplete: "off", "aria-describedby": helpId, onChange: (event) => setTyped(event.target.value) }), _jsx(FieldDescription, { id: helpId, children: "Read aloud in place of the picture. Leave it empty if the picture only decorates." })] }), _jsx("div", { className: "flex gap-2", children: _jsx(Button, { size: "sm", onClick: () => onApply(typed), children: "Apply" }) })] }));
89
+ }
@@ -0,0 +1,21 @@
1
+ import { type EditorState } from '@milkdown/kit/prose/state';
2
+ import type { EditorView } from '@milkdown/kit/prose/view';
3
+ import type { BoxAnchor } from './rich-text-box-anchor.js';
4
+ /** The image the selection is, with where it is and what it says now. */
5
+ export type SelectedImage = {
6
+ pos: number;
7
+ alt: string;
8
+ };
9
+ /** The selected image, when the selection is one image and nothing else. */
10
+ export declare function selectedImage(state: EditorState): SelectedImage | null;
11
+ /**
12
+ * A tap on an image selects it, as a click does. ProseMirror leaves a
13
+ * touch's selection to the browser, which puts the caret beside an image.
14
+ */
15
+ export declare function selectTappedImage(view: EditorView, event: Event): void;
16
+ /** The description set on the image at `pos`, as one step (one undo), the image kept selected. */
17
+ export declare function setImageDescription(view: Pick<EditorView, 'state' | 'dispatch'>, pos: number, description: string): boolean;
18
+ /** The image's element on screen, for the button and the box. */
19
+ export declare function imageElement(view: EditorView, pos: number): HTMLElement | null;
20
+ /** The box's anchor: the image itself (the box opens under it). */
21
+ export declare function imageAnchor(view: EditorView, pos: number): BoxAnchor;
@@ -0,0 +1,55 @@
1
+ // Which image the rich-text editor's selection is, and its description
2
+ // set (rich-text-image-box.tsx draws the button and the box). DOM-free
3
+ // but the image's element, so its rules are unit tested in node
4
+ // (tests/rich-text-image-select.test.ts).
5
+ import { NodeSelection } from '@milkdown/kit/prose/state';
6
+ /** The selected image, when the selection is one image and nothing else. */
7
+ export function selectedImage(state) {
8
+ const { selection } = state;
9
+ if (!(selection instanceof NodeSelection) || selection.node.type.name !== 'image')
10
+ return null;
11
+ return { pos: selection.from, alt: String(selection.node.attrs.alt ?? '') };
12
+ }
13
+ /**
14
+ * A tap on an image selects it, as a click does. ProseMirror leaves a
15
+ * touch's selection to the browser, which puts the caret beside an image.
16
+ */
17
+ export function selectTappedImage(view, event) {
18
+ const target = event.target;
19
+ if (!view.editable || !(target instanceof HTMLImageElement) || !view.dom.contains(target))
20
+ return;
21
+ const pos = view.posAtDOM(target, 0);
22
+ const node = view.state.doc.nodeAt(pos);
23
+ if (node?.type.name !== 'image')
24
+ return;
25
+ const { selection } = view.state;
26
+ if (selection instanceof NodeSelection && selection.from === pos)
27
+ return;
28
+ view.dispatch(view.state.tr.setSelection(NodeSelection.create(view.state.doc, pos)));
29
+ }
30
+ /** The description set on the image at `pos`, as one step (one undo), the image kept selected. */
31
+ export function setImageDescription(view, pos, description) {
32
+ const node = view.state.doc.nodeAt(pos);
33
+ if (!node || node.type.name !== 'image')
34
+ return false;
35
+ const alt = description.replace(/\s+/g, ' ').trim();
36
+ if (alt === node.attrs.alt)
37
+ return true;
38
+ view.dispatch(view.state.tr.setNodeAttribute(pos, 'alt', alt));
39
+ return true;
40
+ }
41
+ /** The image's element on screen, for the button and the box. */
42
+ export function imageElement(view, pos) {
43
+ const dom = view.nodeDOM(pos);
44
+ return dom instanceof HTMLElement ? dom : null;
45
+ }
46
+ /** The box's anchor: the image itself (the box opens under it). */
47
+ export function imageAnchor(view, pos) {
48
+ return {
49
+ getBoundingClientRect: () => {
50
+ const image = imageElement(view, pos)?.getBoundingClientRect();
51
+ return image ? new DOMRect(image.left, image.top, image.width, image.height) : new DOMRect();
52
+ },
53
+ contextElement: view.dom,
54
+ };
55
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tristan2828/ui-foundation",
3
- "version": "5.0.1",
3
+ "version": "5.1.0",
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": {