@tristan2828/ui-foundation 4.125.0 → 4.127.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +1 -1
  2. package/conventions/docs/add-an-entity.md +140 -35
  3. package/conventions/docs/cell-patterns.md +144 -56
  4. package/conventions/docs/design-language.md +45 -13
  5. package/dist/api/contracts.d.ts +8 -1
  6. package/dist/api/gateway/errors.js +4 -0
  7. package/dist/api/schema.d.ts +9 -0
  8. package/dist/api/transport/index.js +10 -1
  9. package/dist/components/app/data-table-tools.d.ts +12 -0
  10. package/dist/components/app/data-table-tools.js +2 -2
  11. package/dist/components/app/data-table.d.ts +2 -1
  12. package/dist/components/app/data-table.js +1 -1
  13. package/dist/components/app/edit-caret.d.ts +25 -0
  14. package/dist/components/app/edit-caret.js +118 -0
  15. package/dist/components/app/edit-in-place-presets.d.ts +51 -1
  16. package/dist/components/app/edit-in-place-presets.js +30 -0
  17. package/dist/components/app/edit-in-place-store.d.ts +70 -4
  18. package/dist/components/app/edit-in-place-store.js +219 -21
  19. package/dist/components/app/edit-in-place.d.ts +11 -0
  20. package/dist/components/app/editable-value.js +202 -25
  21. package/dist/components/app/entity-form.js +4 -0
  22. package/dist/components/app/entity-view.js +5 -1
  23. package/dist/components/app/equal-items.d.ts +32 -6
  24. package/dist/components/app/equal-items.js +59 -8
  25. package/dist/components/app/error-state.js +1 -0
  26. package/dist/components/app/form-leave-guard.js +7 -1
  27. package/dist/components/app/milkdown-editor.d.ts +1 -0
  28. package/dist/components/app/milkdown-editor.js +226 -64
  29. package/dist/components/app/pill-filter.d.ts +16 -0
  30. package/dist/components/app/pill-filter.js +22 -1
  31. package/dist/components/app/prose-look.d.ts +1 -1
  32. package/dist/components/app/prose-look.js +3 -1
  33. package/dist/components/app/rating-input.d.ts +22 -0
  34. package/dist/components/app/rating-input.js +65 -0
  35. package/dist/components/app/rating-score.d.ts +2 -1
  36. package/dist/components/app/rating-score.js +2 -6
  37. package/dist/components/app/rich-text-autolink.d.ts +6 -0
  38. package/dist/components/app/rich-text-autolink.js +79 -0
  39. package/dist/components/app/rich-text-edges.d.ts +8 -0
  40. package/dist/components/app/rich-text-edges.js +144 -0
  41. package/dist/components/app/rich-text-editor.d.ts +19 -4
  42. package/dist/components/app/rich-text-editor.js +19 -6
  43. package/dist/components/app/rich-text-empty-paragraph.d.ts +14 -6
  44. package/dist/components/app/rich-text-empty-paragraph.js +19 -8
  45. package/dist/components/app/rich-text-formats.js +88 -15
  46. package/dist/components/app/rich-text-full-screen.d.ts +2 -0
  47. package/dist/components/app/rich-text-full-screen.js +78 -0
  48. package/dist/components/app/rich-text-highlight-menu.d.ts +3 -1
  49. package/dist/components/app/rich-text-highlight-menu.js +3 -2
  50. package/dist/components/app/rich-text-input-rules.d.ts +7 -0
  51. package/dist/components/app/rich-text-input-rules.js +83 -0
  52. package/dist/components/app/rich-text-keyboard-bar.d.ts +24 -0
  53. package/dist/components/app/rich-text-keyboard-bar.js +215 -0
  54. package/dist/components/app/rich-text-node-views.js +2 -1
  55. package/dist/components/app/rich-text-paste.d.ts +43 -0
  56. package/dist/components/app/rich-text-paste.js +355 -0
  57. package/dist/components/app/rich-text-shortcuts.d.ts +5 -1
  58. package/dist/components/app/rich-text-shortcuts.js +132 -2
  59. package/dist/components/app/rich-text-slash-menu.js +47 -9
  60. package/dist/components/app/rich-text-slash.d.ts +7 -0
  61. package/dist/components/app/rich-text-slash.js +27 -14
  62. package/dist/components/app/rich-text-table-grips.d.ts +8 -6
  63. package/dist/components/app/rich-text-table-grips.js +11 -12
  64. package/dist/components/app/rich-text-tasks.d.ts +8 -0
  65. package/dist/components/app/rich-text-tasks.js +20 -0
  66. package/dist/components/app/rich-text-toolbar.d.ts +5 -1
  67. package/dist/components/app/rich-text-toolbar.js +14 -6
  68. package/dist/components/app/rich-text-tools-bar.d.ts +3 -1
  69. package/dist/components/app/rich-text-tools-bar.js +2 -2
  70. package/dist/components/app/rich-text-touch.d.ts +2 -0
  71. package/dist/components/app/rich-text-touch.js +18 -0
  72. package/dist/components/app/rich-text-widgets.js +1 -1
  73. package/dist/hooks/table-url-changes.d.ts +4 -0
  74. package/dist/hooks/table-url-changes.js +13 -0
  75. package/dist/hooks/use-record-update.d.ts +13 -1
  76. package/dist/hooks/use-record-update.js +17 -3
  77. package/dist/hooks/use-table-url-state.js +14 -8
  78. package/dist/index.d.ts +5 -2
  79. package/dist/index.js +8 -0
  80. package/dist/lib/markdown-merge.d.ts +38 -0
  81. package/dist/lib/markdown-merge.js +202 -17
  82. package/dist/lib/page-leaving.d.ts +8 -0
  83. package/dist/lib/page-leaving.js +30 -0
  84. package/dist/lib/pending-edits.d.ts +14 -0
  85. package/dist/lib/pending-edits.js +51 -0
  86. package/dist/lib/rating-glyphs.d.ts +3 -0
  87. package/dist/lib/rating-glyphs.js +7 -0
  88. package/dist/mocks/e2e-hooks.js +10 -0
  89. package/dist/mocks/override.d.ts +8 -0
  90. package/dist/testing/index.d.ts +40 -2
  91. package/dist/testing/index.js +101 -7
  92. package/openapi/foundation.yaml +12 -0
  93. package/package.json +1 -1
  94. package/styles/index.css +7 -0
@@ -12,6 +12,7 @@ import { jsx as _jsx } from "react/jsx-runtime";
12
12
  // button with aria-pressed.
13
13
  import { cn } from 'cn';
14
14
  import { ToggleGroup, ToggleGroupItem } from '../ui/toggle-group.js';
15
+ import { navCountText } from './app-shell-nav.js';
15
16
  // The All pill's value inside the group: Base UI's toggles need one that
16
17
  // isn't empty, and '' is what the app's filter calls All.
17
18
  const ALL = '__all__';
@@ -20,6 +21,16 @@ const ALL = '__all__';
20
21
  const PILL_CLASS = 'rounded-full px-3 aria-pressed:border-primary aria-pressed:bg-primary aria-pressed:text-primary-foreground ' +
21
22
  'aria-pressed:hover:bg-primary/90 aria-pressed:hover:text-primary-foreground';
22
23
  export function PillFilter({ label, options, value, onValueChange, allLabel = 'All', className }) {
24
+ return (_jsx(PillGroup, { label: label, options: options, value: value, onValueChange: onValueChange, allLabel: allLabel, className: className }));
25
+ }
26
+ // The count as drawn: navCountText's rules (nothing at 0 or while loading,
27
+ // "99+" past 99), shared with the sidebar's counts.
28
+ function countText(count) {
29
+ return navCountText(count ?? undefined);
30
+ }
31
+ // PillFilter's pills, with an optional count per pill. Internal: DataTable's
32
+ // views draw theirs with it (data-table-tools.tsx's ViewPills).
33
+ export function PillGroup({ label, options, value, onValueChange, allLabel = 'All', className, }) {
23
34
  const pills = allLabel === null ? options : [{ value: ALL, label: allLabel }, ...options];
24
35
  const pressed = value === '' && allLabel !== null ? ALL : value;
25
36
  return (_jsx(ToggleGroup, { "aria-label": label, variant: "outline", size: "sm", spacing: 1, className: cn('flex-wrap', className), value: [pressed], onValueChange: (next) => {
@@ -28,5 +39,15 @@ export function PillFilter({ label, options, value, onValueChange, allLabel = 'A
28
39
  if (chosen === undefined || chosen === pressed)
29
40
  return;
30
41
  onValueChange(chosen === ALL ? '' : chosen);
31
- }, children: pills.map((option) => (_jsx(ToggleGroupItem, { value: option.value, className: PILL_CLASS, children: option.label }, option.value))) }));
42
+ }, children: pills.map((option) => {
43
+ const count = countText(option.count);
44
+ return (_jsx(ToggleGroupItem, { value: option.value, "aria-label": count !== undefined ? `${option.label}, ${count}` : undefined, className: PILL_CLASS, children: option.counted || count !== undefined ? _jsx(CountedLabel, { label: option.label, count: count, counted: option.counted }) : option.label }, option.value));
45
+ }) }));
46
+ }
47
+ // "Needs a Look · 3". A hidden copy with a two-digit count (::after, not in
48
+ // the DOM's text or the name) holds the pill at that width while the count
49
+ // loads, is 0 or is one digit, the way EntityView's tab names hold their
50
+ // bold width; the label sits centred in it.
51
+ function CountedLabel({ label, count, counted }) {
52
+ return (_jsx("span", { "data-slot": "pill-label", "data-reserve": counted ? `${label} · 00` : undefined, className: "inline-grid after:invisible after:col-start-1 after:row-start-1 after:h-0 after:tabular-nums after:content-[attr(data-reserve)]", children: _jsx("span", { "data-slot": "pill-text", className: "col-start-1 row-start-1 justify-self-center tabular-nums", children: count !== undefined ? `${label} · ${count}` : label }) }));
32
53
  }
@@ -31,7 +31,7 @@ export declare const PROSE: {
31
31
  * so it sits on the first line of a heading that wraps. Its chevron points
32
32
  * down while the section shows and right while it's folded.
33
33
  */
34
- export declare const FOLD_BUTTON = "-ml-1 flex h-[1lh] w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground outline-none hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50";
34
+ export declare const FOLD_BUTTON: string;
35
35
  /** A heading with a fold button: the button and the words side by side, the look on both. */
36
36
  export declare const FOLD_HEADING = "flex items-start gap-1";
37
37
  /**
@@ -37,7 +37,9 @@ export const PROSE = {
37
37
  * so it sits on the first line of a heading that wraps. Its chevron points
38
38
  * down while the section shows and right while it's folded.
39
39
  */
40
- export const FOLD_BUTTON = '-ml-1 flex h-[1lh] w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground outline-none hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50';
40
+ export const FOLD_BUTTON = '-ml-1 flex h-[1lh] w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground outline-none hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50' +
41
+ // On a touch screen, an invisible 40px square round it takes the tap (review F11).
42
+ " relative pointer-coarse:before:absolute pointer-coarse:before:top-1/2 pointer-coarse:before:left-1/2 pointer-coarse:before:size-10 pointer-coarse:before:-translate-1/2 pointer-coarse:before:content-['']";
41
43
  /** A heading with a fold button: the button and the words side by side, the look on both. */
42
44
  export const FOLD_HEADING = 'flex items-start gap-1';
43
45
  /**
@@ -0,0 +1,22 @@
1
+ import type { RatingScoreGlyph } from './rating-score.js';
2
+ /** How a RatingInput's value was set: a click or tap, or the keyboard. */
3
+ export type RatingInputSource = 'pointer' | 'keyboard';
4
+ export type RatingInputProps = {
5
+ /** How many stars are set, 1…max, or `null` for none (rounded, clamped). */
6
+ value: number | null;
7
+ /** How many stars it has. Defaults to 5. */
8
+ max?: number;
9
+ /** Stars (the default) or hearts. */
10
+ glyph?: RatingScoreGlyph;
11
+ /** The new value: a star's number, or `null` when the set one was pressed again. */
12
+ onChange: (value: number | null, source: RatingInputSource) => void;
13
+ /** The group's accessible name: the field's label ("My Rating"). */
14
+ label: string;
15
+ disabled?: boolean;
16
+ /** The line describing it (a field's error or hint). */
17
+ 'aria-describedby'?: string;
18
+ invalid?: boolean;
19
+ id?: string;
20
+ className?: string;
21
+ };
22
+ export declare function RatingInput({ value, max, glyph, onChange, label, disabled, invalid, id, className, 'aria-describedby': describedBy, }: RatingInputProps): import("react").JSX.Element;
@@ -0,0 +1,65 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ // A score out of a few, set by clicking a star (cell pattern 9, 4.127):
3
+ // RatingScore's glyphs and tokens, as a control. "My Rating" as ★★★★☆,
4
+ // where a click on the second star makes it 2.
5
+ //
6
+ // - One radio group named by `label` (shadcn's RadioGroup on Base UI): one
7
+ // tab stop, the arrow keys move along the stars and set the value, Space
8
+ // or a click sets the star it's on. Each star is a radio named "2 of 5".
9
+ // - Pressing the star that's already set clears it (`null`): a click, or
10
+ // Space on it. Nothing else can clear it, so a slip of the arrow keys
11
+ // never empties a score.
12
+ // - Hovering previews: the stars up to the pointer fill as they would on a
13
+ // click, and leaving puts the value back. A mouse's only: a finger has
14
+ // no hover, and a tap's preview would stick.
15
+ // - Drawn as RatingScore draws: the filled glyphs in `foreground`, the
16
+ // rest outlines in `muted-foreground` (3:1 on the page in both themes),
17
+ // so the count carries the value and survives greyscale.
18
+ // - Compact on a mouse's screen (24px targets, the glyphs RatingScore's
19
+ // 16px), 44px targets on a touch screen (`pointer-coarse`), the glyphs
20
+ // 20px. Fixed-size: as wide at 1 as at 5, so setting it moves nothing.
21
+ // - `onChange`'s second argument says how it was set: `pointer` (a click
22
+ // or a tap, a deliberate pick) or `keyboard` (an arrow, which may be one
23
+ // of several on the way). `inPlace.rating` saves a pick at once and an
24
+ // arrow's value a pause after the last one.
25
+ import { Radio } from '@base-ui/react/radio';
26
+ import { useRef, useState } from 'react';
27
+ import { cn } from 'cn';
28
+ import { RadioGroup } from '../ui/radio-group.js';
29
+ import { RATING_GLYPH_PATHS } from '../../lib/rating-glyphs.js';
30
+ const clamp = (value, max) => (value == null ? null : Math.min(Math.max(0, Math.round(value)), max) || null);
31
+ export function RatingInput({ value, max = 5, glyph = 'star', onChange, label, disabled = false, invalid = false, id, className, 'aria-describedby': describedBy, }) {
32
+ const set = clamp(value, max);
33
+ const [preview, setPreview] = useState(null);
34
+ // What started the change Base UI reports: a key (an arrow, Space) or a pointer.
35
+ const source = useRef('pointer');
36
+ const filled = disabled ? (set ?? 0) : (preview ?? set ?? 0);
37
+ const path = RATING_GLYPH_PATHS[glyph];
38
+ const onKeyDown = () => {
39
+ source.current = 'keyboard';
40
+ };
41
+ const onPointerDown = () => {
42
+ source.current = 'pointer';
43
+ };
44
+ const hover = (star) => (event) => {
45
+ if (event.pointerType === 'mouse')
46
+ setPreview(star);
47
+ };
48
+ return (_jsx(RadioGroup, { id: id, "data-slot": "rating-input", "data-value": set ?? undefined, "data-glyph": glyph, "aria-label": label, "aria-describedby": describedBy, "aria-invalid": invalid || undefined, value: set, onValueChange: (next) => {
49
+ if (next != null && next !== set)
50
+ onChange(next, source.current);
51
+ }, disabled: disabled, onKeyDown: onKeyDown, onPointerDown: onPointerDown, onPointerLeave: hover(null), className: cn('inline-flex w-fit shrink-0 items-center gap-0 align-middle text-foreground', invalid && 'rounded-md ring-3 ring-destructive/20 dark:ring-destructive/40', className), children: Array.from({ length: max }, (_, at) => {
52
+ const star = at + 1;
53
+ const on = star <= filled;
54
+ return (_jsx(Radio.Root, { value: star, "data-star": star, "aria-label": `${star} of ${max}`, onPointerEnter: hover(star),
55
+ // Pressing the set star again clears it (a click, a tap or
56
+ // Space, which Base UI turns into a click). Base UI reports no
57
+ // change for it. The arrow keys check a radio by focusing it,
58
+ // never by a click, so they never clear.
59
+ onClick: () => {
60
+ if (disabled || star !== set)
61
+ return;
62
+ onChange(null, source.current);
63
+ }, className: cn('inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-sm outline-none', 'focus-visible:ring-3 focus-visible:ring-ring/50', 'pointer-coarse:size-11', 'data-disabled:cursor-not-allowed data-disabled:opacity-50'), children: _jsx("svg", { viewBox: "0 0 24 24", "aria-hidden": "true", "data-filled": on ? '' : undefined, className: cn('size-4 shrink-0 pointer-coarse:size-5', on ? 'text-current' : 'text-muted-foreground'), children: _jsx("path", { d: path, className: on ? 'fill-current stroke-current' : 'fill-none stroke-current', strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }) }) }, star));
64
+ }) }));
65
+ }
@@ -1,4 +1,5 @@
1
- export type RatingScoreGlyph = 'star' | 'heart';
1
+ import { type RatingGlyph } from '../../lib/rating-glyphs.js';
2
+ export type RatingScoreGlyph = RatingGlyph;
2
3
  export type RatingScoreProps = {
3
4
  /** How many glyphs are filled, 0…max (rounded). */
4
5
  value: number;
@@ -12,11 +12,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
12
12
  // Fixed-size glyphs: the score is as wide at 1 as at 5, so a value edited
13
13
  // in place never moves what's beside it.
14
14
  import { cn } from 'cn';
15
- // Lucide's star and heart (24×24), so they match the icons around them.
16
- const PATHS = {
17
- star: 'M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z',
18
- heart: 'M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5',
19
- };
15
+ import { RATING_GLYPH_PATHS } from '../../lib/rating-glyphs.js';
20
16
  /** A score's spoken words: "4 of 5", or "Loved, 4 of 5" with a word. */
21
17
  function ratingScoreName(value, max = 5, word) {
22
18
  const filled = Math.min(Math.max(0, Math.round(value)), max);
@@ -24,6 +20,6 @@ function ratingScoreName(value, max = 5, word) {
24
20
  }
25
21
  export function RatingScore({ value, max = 5, glyph = 'star', word, label, className }) {
26
22
  const filled = Math.min(Math.max(0, Math.round(value)), max);
27
- const path = PATHS[glyph];
23
+ const path = RATING_GLYPH_PATHS[glyph];
28
24
  return (_jsxs("span", { role: "img", "aria-label": label ?? ratingScoreName(filled, max, word), "data-slot": "rating-score", "data-value": filled, "data-glyph": glyph, className: cn('inline-flex shrink-0 items-center gap-1.5 align-middle text-foreground', className), children: [_jsx("span", { "aria-hidden": "true", className: "inline-flex shrink-0 items-center gap-0.5", children: Array.from({ length: max }, (_, at) => (_jsx("svg", { viewBox: "0 0 24 24", "data-filled": at < filled ? '' : undefined, className: cn('size-4 shrink-0', at < filled ? 'text-current' : 'text-muted-foreground'), children: _jsx("path", { d: path, className: at < filled ? 'fill-current stroke-current' : 'fill-none stroke-current', strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }) }, at))) }), word && (_jsx("span", { "aria-hidden": "true", className: "text-muted-foreground", children: word }))] }));
29
25
  }
@@ -0,0 +1,6 @@
1
+ import { Plugin } from '@milkdown/kit/prose/state';
2
+ import type { EditorView } from '@milkdown/kit/prose/view';
3
+ /** Links the address that ends at the caret, if there is one: for Enter, before the line splits. */
4
+ export declare function linkWordBefore(view: EditorView): void;
5
+ /** A space typed after an address links it. */
6
+ export declare function autolinkPlugin(): Plugin;
@@ -0,0 +1,79 @@
1
+ // A web or email address typed into the rich-text editor becomes a link
2
+ // as the word ends: on a space (autolinkPlugin) or on Enter (linkWordBefore,
3
+ // which the editor's Enter calls before the line splits). Web and email
4
+ // addresses only (`https://…`, `www.…`, `name@example.com`), through
5
+ // linkHref: `www.` gains https://, an email mailto:. Punctuation that ends
6
+ // a sentence after it (`.`, `,`, `)`) stays outside the link. Not in code,
7
+ // and not in words already linked. One undo takes the link off, the
8
+ // typing kept.
9
+ //
10
+ // The link's words are the address as typed, so the Markdown saves it as
11
+ // an address (`<https://…>` or `[www.x.org](https://www.x.org)`), never
12
+ // as escaped text (`https\://`).
13
+ import { Plugin, PluginKey } from '@milkdown/kit/prose/state';
14
+ import { addressOf } from './rich-text-paste.js';
15
+ const TRAILING = /[.,;:!?'")\]}]+$/;
16
+ // The address ending at `pos` in its textblock, and its span; `null` when
17
+ // the word before `pos` isn't one, or can't be linked there.
18
+ function addressBefore(state, pos) {
19
+ const $pos = state.doc.resolve(pos);
20
+ const parent = $pos.parent;
21
+ if (!parent.isTextblock || parent.type.spec.code)
22
+ return null;
23
+ const link = state.schema.marks.link;
24
+ if (!link)
25
+ return null;
26
+ const before = parent.textBetween(0, $pos.parentOffset, undefined, '');
27
+ const word = /\S+$/.exec(before)?.[0];
28
+ if (!word)
29
+ return null;
30
+ const trimmed = word.replace(TRAILING, '');
31
+ // An opening bracket before the address stays outside it too.
32
+ const lead = /^[(['"<]+/.exec(trimmed)?.[0] ?? '';
33
+ const address = trimmed.slice(lead.length);
34
+ const href = addressOf(address);
35
+ if (!href)
36
+ return null;
37
+ const from = pos - word.length + lead.length;
38
+ const to = from + address.length;
39
+ let blocked = false;
40
+ state.doc.nodesBetween(from, to, (node) => {
41
+ if (node.isText && node.marks.some((mark) => mark.type === link || mark.type.spec.code))
42
+ blocked = true;
43
+ if (node.isInline && !node.isText)
44
+ blocked = true;
45
+ });
46
+ return blocked ? null : { from, to, href };
47
+ }
48
+ function linkAt(tr, state, span) {
49
+ return tr.addMark(span.from, span.to, state.schema.marks.link.create({ href: span.href }));
50
+ }
51
+ /** Links the address that ends at the caret, if there is one: for Enter, before the line splits. */
52
+ export function linkWordBefore(view) {
53
+ const { selection } = view.state;
54
+ if (!selection.empty || !view.editable)
55
+ return;
56
+ const span = addressBefore(view.state, selection.from);
57
+ if (span)
58
+ view.dispatch(linkAt(view.state.tr, view.state, span));
59
+ }
60
+ const autolinkKey = new PluginKey('rich-text-autolink');
61
+ /** A space typed after an address links it. */
62
+ export function autolinkPlugin() {
63
+ return new Plugin({
64
+ key: autolinkKey,
65
+ props: {
66
+ handleTextInput: (view, from, to, text) => {
67
+ if (text !== ' ' || from !== to || view.composing)
68
+ return false;
69
+ const span = addressBefore(view.state, from);
70
+ if (!span)
71
+ return false;
72
+ // The space first, so it takes the words' marks and not the link's.
73
+ const tr = linkAt(view.state.tr.insertText(text, from, to), view.state, span);
74
+ view.dispatch(tr);
75
+ return true;
76
+ },
77
+ },
78
+ });
79
+ }
@@ -0,0 +1,8 @@
1
+ import { Plugin } from '@milkdown/kit/prose/state';
2
+ import type { EditorView } from '@milkdown/kit/prose/view';
3
+ /** Whether a key press leads out of the block at the note's edge, and does it if so. */
4
+ export declare function handleEdgeKey(view: EditorView, event: KeyboardEvent): boolean;
5
+ /** The plugin: the keys at the edges, a click past them, and focus kept on a ticked box. */
6
+ export declare function edgesPlugin(): Plugin;
7
+ /** The plugin, for the editor's `.use()`. */
8
+ export declare const edges: import("@milkdown/utils").$Prose;
@@ -0,0 +1,144 @@
1
+ // The note's two edges (4.126, the RichTextEditor review's F10): a code
2
+ // block, a table, a quote, a callout or a divider that ends a note had no
3
+ // way past it (Ctrl+Enter, shown nowhere, and none on a phone), and one
4
+ // that starts it nothing above it.
5
+ // - ArrowDown at the end of such a last block, or ArrowRight at its very
6
+ // end, puts a line under it and the caret there; ArrowUp (ArrowLeft) at
7
+ // the start of such a first block, a line above it. Anywhere else the
8
+ // keys are left alone.
9
+ // - A click under the last block (in the text's padding or the space under
10
+ // a short note) puts the caret on a line under it: a new one, unless the
11
+ // last block is already a paragraph. A click above the first block, a
12
+ // line above it when that block isn't one.
13
+ // - Ticking a task's box keeps focus in the text (the review's F24), so
14
+ // Ctrl+Z takes the tick back: from outside, the caret lands in that item.
15
+ // No trailing-paragraph rule: a note isn't given a line nobody typed, so
16
+ // nothing is saved until one is asked for. And no gap cursor, which can't
17
+ // stand by a code block (a textblock).
18
+ import { Plugin, Selection, TextSelection } from '@milkdown/kit/prose/state';
19
+ import { $prose } from '@milkdown/kit/utils';
20
+ // The blocks the keys lead out of: those Enter doesn't (a code block keeps
21
+ // its lines, a table's last row has its own Enter), or does only twice.
22
+ const BOXED = new Set(['code_block', 'table', 'blockquote', 'callout', 'hr']);
23
+ // Whether the selection is at the note's edge, in the block there that the
24
+ // keys lead out of: on its last (first) line, or its table's last (first)
25
+ // row; for `whole`, at its very end (start), as ArrowRight needs.
26
+ function atEdge(view, side, whole) {
27
+ const { doc, selection } = view.state;
28
+ const block = side === 'end' ? doc.lastChild : doc.firstChild;
29
+ if (!block || !BOXED.has(block.type.name))
30
+ return false;
31
+ const edge = side === 'end' ? Selection.atEnd(doc) : Selection.atStart(doc);
32
+ if (selection.eq(edge))
33
+ return true;
34
+ if (!selection.empty || whole)
35
+ return false;
36
+ const $head = selection.$head;
37
+ if ($head.index(0) !== (side === 'end' ? doc.childCount - 1 : 0))
38
+ return false;
39
+ if (!view.endOfTextblock(side === 'end' ? 'down' : 'up'))
40
+ return false;
41
+ if ($head.parent === edge.$head.parent)
42
+ return true;
43
+ // In a table: any cell of its last (first) row.
44
+ return block.type.name === 'table' && $head.depth >= 2 && $head.index(1) === (side === 'end' ? block.childCount - 1 : 0);
45
+ }
46
+ // A paragraph at the note's edge, the caret in it, scrolled to.
47
+ function addLine(view, side) {
48
+ const { state } = view;
49
+ const at = side === 'end' ? state.doc.content.size : 0;
50
+ const tr = state.tr.insert(at, state.schema.nodes.paragraph.create());
51
+ view.dispatch(tr.setSelection(TextSelection.create(tr.doc, at + 1)).scrollIntoView());
52
+ }
53
+ // The caret at the note's edge (a paragraph there), or a new line past the
54
+ // block that's there.
55
+ function toEdge(view, side) {
56
+ const { doc } = view.state;
57
+ const block = (side === 'end' ? doc.lastChild : doc.firstChild);
58
+ if (block.type.name === 'paragraph') {
59
+ const selection = side === 'end' ? Selection.atEnd(doc) : Selection.atStart(doc);
60
+ view.dispatch(view.state.tr.setSelection(selection).scrollIntoView());
61
+ }
62
+ else
63
+ addLine(view, side);
64
+ view.focus();
65
+ }
66
+ /** Whether a key press leads out of the block at the note's edge, and does it if so. */
67
+ export function handleEdgeKey(view, event) {
68
+ if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey || event.isComposing)
69
+ return false;
70
+ const side = event.key === 'ArrowDown' || event.key === 'ArrowRight' ? 'end' : event.key === 'ArrowUp' || event.key === 'ArrowLeft' ? 'start' : null;
71
+ if (!side || !atEdge(view, side, event.key === 'ArrowRight' || event.key === 'ArrowLeft'))
72
+ return false;
73
+ event.preventDefault();
74
+ addLine(view, side);
75
+ return true;
76
+ }
77
+ // Which edge a click is past: under the last block's box or above the
78
+ // first's, or neither.
79
+ function clickedPast(view, event) {
80
+ const first = view.dom.firstElementChild;
81
+ const last = view.dom.lastElementChild;
82
+ if (!first || !last)
83
+ return null;
84
+ if (event.clientY > last.getBoundingClientRect().bottom)
85
+ return 'end';
86
+ if (event.clientY < first.getBoundingClientRect().top)
87
+ return 'start';
88
+ return null;
89
+ }
90
+ // What a press below or above the text is for: the element the text sits
91
+ // in, padding and all (Milkdown's root, around its own wrapper).
92
+ function frameOf(view) {
93
+ return view.dom.parentElement?.parentElement ?? view.dom;
94
+ }
95
+ function isTaskBox(target) {
96
+ return target instanceof HTMLInputElement && target.type === 'checkbox' && target.closest('li')?.dataset.itemType === 'task';
97
+ }
98
+ /** The plugin: the keys at the edges, a click past them, and focus kept on a ticked box. */
99
+ export function edgesPlugin() {
100
+ return new Plugin({
101
+ props: {
102
+ handleKeyDown: (view, event) => view.editable && handleEdgeKey(view, event),
103
+ },
104
+ view: (view) => {
105
+ const frame = frameOf(view);
106
+ const press = (event) => {
107
+ if (event.button !== 0 || event.shiftKey || event.metaKey || event.ctrlKey || !view.editable)
108
+ return;
109
+ // Only presses on the text's own surface: not a node view's
110
+ // control, a menu or a toolbar in the frame.
111
+ const target = event.target;
112
+ if (target !== frame && target !== view.dom && target !== view.dom.parentElement)
113
+ return;
114
+ const side = clickedPast(view, event);
115
+ if (!side)
116
+ return;
117
+ event.preventDefault();
118
+ toEdge(view, side);
119
+ };
120
+ // The box's own click (milkdown-editor.tsx) ticks it; this brings focus
121
+ // back to the text after, the caret in that item when it was elsewhere.
122
+ const ticked = (event) => {
123
+ if (!isTaskBox(event.target) || !view.editable)
124
+ return;
125
+ const text = event.target.nextElementSibling;
126
+ if (!view.hasFocus() && text) {
127
+ const $at = view.state.doc.resolve(view.posAtDOM(text, 0));
128
+ view.dispatch(view.state.tr.setSelection(Selection.near($at)));
129
+ }
130
+ view.focus();
131
+ };
132
+ frame.addEventListener('mousedown', press);
133
+ view.dom.addEventListener('click', ticked);
134
+ return {
135
+ destroy: () => {
136
+ frame.removeEventListener('mousedown', press);
137
+ view.dom.removeEventListener('click', ticked);
138
+ },
139
+ };
140
+ },
141
+ });
142
+ }
143
+ /** The plugin, for the editor's `.use()`. */
144
+ export const edges = $prose(() => edgesPlugin());
@@ -10,9 +10,22 @@ export type RichTextEditorProps = {
10
10
  * value it reported, passed back, changes nothing.
11
11
  */
12
12
  defaultValue: string;
13
- /** The Markdown to save, after every edit: untouched blocks as originally written. */
13
+ /**
14
+ * The Markdown to save, untouched blocks as originally written. Called a
15
+ * short pause after typing stops (300 ms), not on every
16
+ * key: turning a long note back into Markdown costs time in proportion
17
+ * to its length. Always called first, synchronously, when the
18
+ * text loses focus, on Esc and Ctrl/Cmd+Enter, when the page is hidden,
19
+ * when it unmounts, and when anything calls `flushPendingEdits()`
20
+ * (EntityForm's submit, the edit-in-place store's saves, the leave
21
+ * guards), so a save never reads a value from before the last key.
22
+ */
14
23
  onChange: (markdown: string) => void;
15
- /** Why the edit can't be saved as it stands, or `null` once it can. */
24
+ /**
25
+ * Why the edit can't be saved as it stands, or `null` once it can. A form
26
+ * sets it as the field's error and refuses submit while it stands. Left
27
+ * out, the editor shows the message inside the field instead.
28
+ */
16
29
  onProblem?: (message: string | null) => void;
17
30
  /** Shown but not editable (while a save is in flight). */
18
31
  readOnly?: boolean;
@@ -45,8 +58,10 @@ export type RichTextEditorProps = {
45
58
  inline?: boolean;
46
59
  /**
47
60
  * Images uploaded into the text: pasted, dropped, or picked with an
48
- * Image button on the fixed toolbar or the slash menu's Image ("/image",
49
- * 4.123, the way to pick one with only the floating toolbar). Each file goes through this (the
61
+ * Image button (on the fixed toolbar; with `toolbar="floating"`, on the
62
+ * "Editor tools" strip shown while the field has focus; on a phone, in
63
+ * the row pinned to the keyboard) or the slash menu's Image ("/image",
64
+ * 4.123). Each file goes through this (the
50
65
  * app's own storage: the package knows no endpoint) and goes in as
51
66
  * `![](url)`, from the result's `url`, else its `thumbUrl`. A
52
67
  * placeholder shows where it will go while it uploads (it isn't saved);
@@ -7,8 +7,12 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
7
7
  // and saving round-trip exactly: an untouched document comes back byte for
8
8
  // byte, and an edited one keeps every block the person didn't change as it
9
9
  // was written (src/lib/markdown-merge.ts). If an edit can't be saved
10
- // without rewriting another block, `onProblem` says so and `onChange`
11
- // isn't called: the draft stays on screen, nothing is saved in its place.
10
+ // without rewriting another block, `onChange` isn't called (the draft
11
+ // stays on screen, nothing is saved in its place), the editor marks itself
12
+ // invalid, and `onProblem` says why; with no `onProblem`, the editor says
13
+ // it itself, inside the field. A form gives `onProblem` and holds its
14
+ // submit on it (add-an-entity.md "The form"), or Save would send the last
15
+ // text that could be saved and say it worked.
12
16
  //
13
17
  // Raw HTML in the text shows as its characters, as <Markdown> shows it,
14
18
  // and nothing pasted or typed can add markup.
@@ -19,8 +23,9 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
19
23
  // keys scroll.
20
24
  //
21
25
  // Images in the text (`![alt](url)`) show, at most the field's width.
22
- // With `upload`, an image pasted, dropped or picked with the toolbar's
23
- // Image button is uploaded through the app's own storage and goes in as
26
+ // With `upload`, an image pasted, dropped or picked with an Image button
27
+ // (the fixed toolbar's, or the tools strip's with `toolbar="floating"`) is
28
+ // uploaded through the app's own storage and goes in as
24
29
  // `![](url)`; while it uploads, a placeholder shows where it will go.
25
30
  //
26
31
  // A table's columns fit their words. Grips on its column and row (or a
@@ -53,7 +58,7 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
53
58
  // Markdown never downloads it. Until it arrives the text shows as
54
59
  // <Markdown> draws it (4.123), the field's size, so nothing moves when the
55
60
  // editor takes its place; an empty one shows skeleton lines.
56
- import { lazy, Suspense, useState } from 'react';
61
+ import { lazy, Suspense, useLayoutEffect, useRef, useState } from 'react';
57
62
  import { cn } from 'cn';
58
63
  import { Skeleton } from '../ui/skeleton.js';
59
64
  import { Markdown } from './markdown.js';
@@ -78,9 +83,17 @@ function useOpenings(defaultValue) {
78
83
  export function RichTextEditor(props) {
79
84
  const { opening, report } = useOpenings(props.defaultValue);
80
85
  const { onChange } = props;
81
- return (_jsx(Suspense, { fallback: _jsxs("div", { "data-slot": "rich-text-editor", "data-state": "loading", className: cn('flex w-full flex-col', !props.inline && 'rounded-lg border border-input', props.className), children: [(props.toolbar ?? true) === true && _jsx("div", { className: "h-9 border-b border-input" }), _jsx("div", { "aria-busy": "true", className: cn('flex flex-col gap-2', props.inline ? 'py-0.5' : 'min-h-24 px-2.5 py-2',
86
+ // The editor reports what was typed as it unmounts (F6); one replaced
87
+ // by a new value (a reset) has nothing left to say.
88
+ const live = useRef(opening);
89
+ useLayoutEffect(() => {
90
+ live.current = opening;
91
+ });
92
+ return (_jsx(Suspense, { fallback: _jsxs("div", { "data-slot": "rich-text-editor", "data-state": "loading", className: cn('flex w-full flex-col', !props.inline && 'rounded-lg border border-input', props.className), children: [(props.toolbar ?? true) === true && _jsx("div", { className: "h-9 border-b border-input pointer-coarse:hidden" }), _jsx("div", { "aria-busy": "true", className: cn('flex flex-col gap-2', props.inline ? 'py-0.5' : 'min-h-24 px-2.5 py-2',
82
93
  // The room of the add-row bar the editor draws under a table.
83
94
  !props.readOnly && '[&_table]:mb-5'), children: props.defaultValue.trim() ? (_jsx(Markdown, { headingLevel: props.headingLevel, headingFrom: props.headingFrom, foldKey: props.foldable === false ? undefined : props.foldKey, children: props.defaultValue })) : (_jsxs(_Fragment, { children: [_jsx(Skeleton, { className: "h-4 w-3/4" }), _jsx(Skeleton, { className: "h-4 w-1/2" })] })) })] }), children: _jsx(MilkdownEditor, { ...props, onChange: (markdown) => {
95
+ if (live.current !== opening)
96
+ return;
84
97
  report(markdown);
85
98
  onChange(markdown);
86
99
  }, foldKey: props.foldable === false ? undefined : props.foldKey }, opening) }));
@@ -1,10 +1,18 @@
1
1
  import type { NodeSchema } from '@milkdown/kit/transformer';
2
2
  /**
3
- * An empty paragraph goes to Markdown with `children: []`. Milkdown's own
4
- * runner opens and closes the node with nothing in it, and its serializer
5
- * then leaves `children` out. mdast says a paragraph always has the
6
- * array, and mdast-util-gfm-task-list-item 2.0.1 reads its length: an
7
- * empty task item ("- [ ] ", Enter at a list's end) threw there, and the
8
- * edit was never saved.
3
+ * How a paragraph goes to Markdown, past Milkdown's own:
4
+ *
5
+ * An empty paragraph goes with `children: []`. Milkdown's own runner opens
6
+ * and closes the node with nothing in it, and its serializer then leaves
7
+ * `children` out. mdast says a paragraph always has the array, and
8
+ * mdast-util-gfm-task-list-item 2.0.1 reads its length: an empty task item
9
+ * ("- [ ] ", Enter at a list's end) threw there, and the edit was never
10
+ * saved.
11
+ *
12
+ * And a paragraph's spaces at its end are left out (4.126, the
13
+ * RichTextEditor review's F22). Markdown drops them on reading, so a pause
14
+ * after a space saved a note that read back without it (and remark-stringify
15
+ * sometimes wrote it as `&#x20;`). A hard break's spaces aren't these: it is
16
+ * a node of its own.
9
17
  */
10
18
  export declare function withEmptyParagraphChildren<Ctx>(previous: (ctx: Ctx) => NodeSchema): (ctx: Ctx) => NodeSchema;
@@ -1,10 +1,18 @@
1
1
  /**
2
- * An empty paragraph goes to Markdown with `children: []`. Milkdown's own
3
- * runner opens and closes the node with nothing in it, and its serializer
4
- * then leaves `children` out. mdast says a paragraph always has the
5
- * array, and mdast-util-gfm-task-list-item 2.0.1 reads its length: an
6
- * empty task item ("- [ ] ", Enter at a list's end) threw there, and the
7
- * edit was never saved.
2
+ * How a paragraph goes to Markdown, past Milkdown's own:
3
+ *
4
+ * An empty paragraph goes with `children: []`. Milkdown's own runner opens
5
+ * and closes the node with nothing in it, and its serializer then leaves
6
+ * `children` out. mdast says a paragraph always has the array, and
7
+ * mdast-util-gfm-task-list-item 2.0.1 reads its length: an empty task item
8
+ * ("- [ ] ", Enter at a list's end) threw there, and the edit was never
9
+ * saved.
10
+ *
11
+ * And a paragraph's spaces at its end are left out (4.126, the
12
+ * RichTextEditor review's F22). Markdown drops them on reading, so a pause
13
+ * after a space saved a note that read back without it (and remark-stringify
14
+ * sometimes wrote it as `&#x20;`). A hard break's spaces aren't these: it is
15
+ * a node of its own.
8
16
  */
9
17
  export function withEmptyParagraphChildren(previous) {
10
18
  return (ctx) => {
@@ -15,10 +23,13 @@ export function withEmptyParagraphChildren(previous) {
15
23
  toMarkdown: {
16
24
  ...base.toMarkdown,
17
25
  runner: (state, node) => {
18
- if (node.content.size === 0)
26
+ const last = node.lastChild;
27
+ const spaces = last?.isText ? (/[ \t]+$/.exec(last.text ?? '')?.[0].length ?? 0) : 0;
28
+ const kept = spaces ? node.copy(node.content.cut(0, node.content.size - spaces)) : node;
29
+ if (kept.content.size === 0)
19
30
  state.addNode('paragraph', []);
20
31
  else
21
- runner(state, node);
32
+ runner(state, kept);
22
33
  },
23
34
  },
24
35
  };