@ignite-ember/ui-react 0.0.0-stage → 0.2.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.
Files changed (134) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +260 -2
  4. package/dist/CopySource.d.ts +4 -0
  5. package/dist/CopySource.d.ts.map +1 -0
  6. package/dist/CopySource.js +50 -0
  7. package/dist/CopySource.js.map +1 -0
  8. package/dist/DataTable.d.ts +77 -0
  9. package/dist/DataTable.d.ts.map +1 -0
  10. package/dist/DataTable.js +45 -0
  11. package/dist/DataTable.js.map +1 -0
  12. package/dist/Dialog.d.ts +41 -0
  13. package/dist/Dialog.d.ts.map +1 -0
  14. package/dist/Dialog.js +94 -0
  15. package/dist/Dialog.js.map +1 -0
  16. package/dist/ErrorBoundary.d.ts +97 -0
  17. package/dist/ErrorBoundary.d.ts.map +1 -0
  18. package/dist/ErrorBoundary.js +97 -0
  19. package/dist/ErrorBoundary.js.map +1 -0
  20. package/dist/LiveRegion.d.ts +41 -0
  21. package/dist/LiveRegion.d.ts.map +1 -0
  22. package/dist/LiveRegion.js +76 -0
  23. package/dist/LiveRegion.js.map +1 -0
  24. package/dist/Markdown.d.ts +22 -0
  25. package/dist/Markdown.d.ts.map +1 -0
  26. package/dist/Markdown.js +56 -0
  27. package/dist/Markdown.js.map +1 -0
  28. package/dist/MarkdownInline.d.ts +53 -0
  29. package/dist/MarkdownInline.d.ts.map +1 -0
  30. package/dist/MarkdownInline.js +159 -0
  31. package/dist/MarkdownInline.js.map +1 -0
  32. package/dist/MenuIcon.d.ts +60 -0
  33. package/dist/MenuIcon.d.ts.map +1 -0
  34. package/dist/MenuIcon.js +102 -0
  35. package/dist/MenuIcon.js.map +1 -0
  36. package/dist/Mermaid.d.ts +40 -0
  37. package/dist/Mermaid.d.ts.map +1 -0
  38. package/dist/Mermaid.js +121 -0
  39. package/dist/Mermaid.js.map +1 -0
  40. package/dist/Monogram.d.ts +46 -0
  41. package/dist/Monogram.d.ts.map +1 -0
  42. package/dist/Monogram.js +96 -0
  43. package/dist/Monogram.js.map +1 -0
  44. package/dist/OverflowMenu.d.ts +60 -0
  45. package/dist/OverflowMenu.d.ts.map +1 -0
  46. package/dist/OverflowMenu.js +149 -0
  47. package/dist/OverflowMenu.js.map +1 -0
  48. package/dist/Shell.d.ts +67 -0
  49. package/dist/Shell.d.ts.map +1 -0
  50. package/dist/Shell.js +44 -0
  51. package/dist/Shell.js.map +1 -0
  52. package/dist/Skeleton.d.ts +62 -0
  53. package/dist/Skeleton.d.ts.map +1 -0
  54. package/dist/Skeleton.js +56 -0
  55. package/dist/Skeleton.js.map +1 -0
  56. package/dist/Split.d.ts +85 -0
  57. package/dist/Split.d.ts.map +1 -0
  58. package/dist/Split.js +156 -0
  59. package/dist/Split.js.map +1 -0
  60. package/dist/Tabs.d.ts +77 -0
  61. package/dist/Tabs.d.ts.map +1 -0
  62. package/dist/Tabs.js +91 -0
  63. package/dist/Tabs.js.map +1 -0
  64. package/dist/Toast.d.ts +98 -0
  65. package/dist/Toast.d.ts.map +1 -0
  66. package/dist/Toast.js +129 -0
  67. package/dist/Toast.js.map +1 -0
  68. package/dist/Tooltip.d.ts +24 -0
  69. package/dist/Tooltip.d.ts.map +1 -0
  70. package/dist/Tooltip.js +166 -0
  71. package/dist/Tooltip.js.map +1 -0
  72. package/dist/controls.d.ts +117 -0
  73. package/dist/controls.d.ts.map +1 -0
  74. package/dist/controls.js +59 -0
  75. package/dist/controls.js.map +1 -0
  76. package/dist/cx.d.ts +3 -0
  77. package/dist/cx.d.ts.map +1 -0
  78. package/dist/cx.js +5 -0
  79. package/dist/cx.js.map +1 -0
  80. package/dist/fenceInfo.d.ts +26 -0
  81. package/dist/fenceInfo.d.ts.map +1 -0
  82. package/dist/fenceInfo.js +22 -0
  83. package/dist/fenceInfo.js.map +1 -0
  84. package/dist/formControls.d.ts +143 -0
  85. package/dist/formControls.d.ts.map +1 -0
  86. package/dist/formControls.js +108 -0
  87. package/dist/formControls.js.map +1 -0
  88. package/dist/index.d.ts +78 -0
  89. package/dist/index.d.ts.map +1 -0
  90. package/dist/index.js +78 -0
  91. package/dist/index.js.map +1 -0
  92. package/dist/layout.d.ts +95 -0
  93. package/dist/layout.d.ts.map +1 -0
  94. package/dist/layout.js +93 -0
  95. package/dist/layout.js.map +1 -0
  96. package/dist/primitives.d.ts +33 -0
  97. package/dist/primitives.d.ts.map +1 -0
  98. package/dist/primitives.js +33 -0
  99. package/dist/primitives.js.map +1 -0
  100. package/dist/progress.d.ts +64 -0
  101. package/dist/progress.d.ts.map +1 -0
  102. package/dist/progress.js +51 -0
  103. package/dist/progress.js.map +1 -0
  104. package/dist/text.d.ts +63 -0
  105. package/dist/text.d.ts.map +1 -0
  106. package/dist/text.js +61 -0
  107. package/dist/text.js.map +1 -0
  108. package/package.json +56 -4
  109. package/src/CopySource.tsx +67 -0
  110. package/src/DataTable.tsx +120 -0
  111. package/src/Dialog.tsx +158 -0
  112. package/src/ErrorBoundary.tsx +137 -0
  113. package/src/LiveRegion.tsx +127 -0
  114. package/src/Markdown.tsx +75 -0
  115. package/src/MarkdownInline.tsx +177 -0
  116. package/src/MenuIcon.tsx +209 -0
  117. package/src/Mermaid.tsx +144 -0
  118. package/src/Monogram.tsx +112 -0
  119. package/src/OverflowMenu.tsx +359 -0
  120. package/src/Shell.tsx +99 -0
  121. package/src/Skeleton.tsx +98 -0
  122. package/src/Split.tsx +267 -0
  123. package/src/Tabs.tsx +194 -0
  124. package/src/Toast.tsx +269 -0
  125. package/src/Tooltip.tsx +213 -0
  126. package/src/controls.tsx +159 -0
  127. package/src/cx.ts +4 -0
  128. package/src/fenceInfo.ts +36 -0
  129. package/src/formControls.tsx +249 -0
  130. package/src/index.ts +149 -0
  131. package/src/layout.tsx +141 -0
  132. package/src/primitives.tsx +33 -0
  133. package/src/progress.tsx +129 -0
  134. package/src/text.tsx +99 -0
package/src/Dialog.tsx ADDED
@@ -0,0 +1,158 @@
1
+ /**
2
+ * The dialog: the one primitive that is behaviour rather than a box.
3
+ *
4
+ * Part of the primitives; see `primitives.tsx`. **Under the
5
+ * compatibility floor.**
6
+ */
7
+
8
+ import type { HTMLAttributes, KeyboardEvent, ReactNode } from "react";
9
+ import { useCallback, useEffect, useId, useRef } from "react";
10
+
11
+ import { cx } from "./cx.js";
12
+ import { Actions } from "./layout.js";
13
+
14
+ /** What a {@link Dialog} takes. */
15
+ export interface DialogProps extends Omit<
16
+ HTMLAttributes<HTMLDivElement>,
17
+ "title"
18
+ > {
19
+ /** Its title. Also the accessible name of the dialog. */
20
+ title: ReactNode;
21
+ /** Shown under the title. A sentence, not a paragraph. */
22
+ sub?: ReactNode;
23
+ /** The body. */
24
+ children?: ReactNode;
25
+ /** The buttons. Rendered in an `Actions` row at the foot. */
26
+ actions?: ReactNode;
27
+ /** Escape, or a click on the backdrop. */
28
+ onClose: () => void;
29
+ }
30
+
31
+ /**
32
+ * The one primitive here that is behaviour rather than a box.
33
+ *
34
+ * A dialog has to trap focus, close on Escape, restore focus to
35
+ * whatever opened it, and not let a click inside the panel count as a
36
+ * click on the backdrop. Every extension that built its own would get
37
+ * some of that wrong, and the ones they get wrong are the ones only
38
+ * keyboard and screen-reader users notice.
39
+ *
40
+ * @param title — its title, also the accessible name of the dialog.
41
+ * @param sub — shown under the title: a sentence, not a paragraph.
42
+ * @param children — the body.
43
+ * @param actions — the buttons, rendered in an `Actions` row at the
44
+ * foot.
45
+ * @param onClose — escape, or a click on the backdrop.
46
+ * @param className — added to the element's classes, beside the one the
47
+ * theme gives it.
48
+ * @param rest — the remaining props, spread onto the dialog panel.
49
+ */
50
+ export function Dialog({
51
+ title,
52
+ sub,
53
+ children,
54
+ actions,
55
+ onClose,
56
+ className,
57
+ ...rest
58
+ }: DialogProps) {
59
+ const panel = useRef<HTMLDivElement | null>(null);
60
+ const opener = useRef<Element | null>(null);
61
+ const titleId = useId();
62
+
63
+ useEffect(() => {
64
+ opener.current = document.activeElement;
65
+ // Focus the panel itself rather than the first control: reading
66
+ // the title before the buttons is the point of having one.
67
+ panel.current?.focus();
68
+ return () => {
69
+ // Only if it is still in the document: an opener that has
70
+ // unmounted drops focus to <body> silently, which is worse than
71
+ // leaving it where the closing action put it.
72
+ const back = opener.current;
73
+ if (back instanceof HTMLElement && back.isConnected) back.focus();
74
+ };
75
+ }, []);
76
+
77
+ const onKeyDown = useCallback(
78
+ (event: KeyboardEvent) => {
79
+ if (event.key === "Escape") {
80
+ event.stopPropagation();
81
+ onClose();
82
+ return;
83
+ }
84
+ if (event.key !== "Tab") return;
85
+ // `:not([disabled])` matters more than it looks: a modal whose
86
+ // confirm button is disabled until a field is typed is the
87
+ // commonest pattern there is, and without this the wrap targets
88
+ // a disabled element, preventDefault fires, focus() is a no-op
89
+ // and Tab appears dead. Dead Tab is worse than escaping Tab.
90
+ // `iframe` is here because an extension *is* one.
91
+ const focusable = panel.current?.querySelectorAll<HTMLElement>(
92
+ [
93
+ "button:not([disabled])",
94
+ "a[href]",
95
+ "input:not([disabled]):not([type=hidden])",
96
+ "select:not([disabled])",
97
+ "textarea:not([disabled])",
98
+ "iframe",
99
+ "summary",
100
+ "[contenteditable]",
101
+ '[tabindex]:not([tabindex="-1"])',
102
+ ].join(", "),
103
+ );
104
+ if (!focusable || focusable.length === 0) {
105
+ // Nothing to move to, so hold the focus here rather than let
106
+ // Tab walk into the page behind a modal with no way back.
107
+ event.preventDefault();
108
+ return;
109
+ }
110
+ const first = focusable[0];
111
+ const last = focusable[focusable.length - 1];
112
+ if (event.shiftKey && document.activeElement === first) {
113
+ event.preventDefault();
114
+ last.focus();
115
+ } else if (!event.shiftKey && document.activeElement === last) {
116
+ event.preventDefault();
117
+ first.focus();
118
+ }
119
+ },
120
+ [onClose],
121
+ );
122
+
123
+ return (
124
+ <div
125
+ className="overlay"
126
+ onMouseDown={(e) => {
127
+ // Primary button only, and only on the backdrop itself, so a
128
+ // right-click raising a context menu leaves the modal open.
129
+ if (e.button === 0 && e.target === e.currentTarget) onClose();
130
+ }}
131
+ >
132
+ <div
133
+ {...rest}
134
+ ref={panel}
135
+ className={cx("dialog", className)}
136
+ role="dialog"
137
+ aria-modal="true"
138
+ // The title is the dialog's accessible name; without it a
139
+ // screen reader announces "dialog" and nothing else.
140
+ aria-labelledby={titleId}
141
+ tabIndex={-1}
142
+ onKeyDown={onKeyDown}
143
+ // Without this a drag that starts inside and ends outside
144
+ // closes the dialog, which eats a selection.
145
+ onMouseDown={(e) => e.stopPropagation()}
146
+ >
147
+ <h2 className="dialog-title" id={titleId}>
148
+ {title}
149
+ </h2>
150
+ {sub ? <p className="dialog-sub">{sub}</p> : null}
151
+ {children}
152
+ {actions ? (
153
+ <Actions className="dialog-actions">{actions}</Actions>
154
+ ) : null}
155
+ </div>
156
+ </div>
157
+ );
158
+ }
@@ -0,0 +1,137 @@
1
+ /**
2
+ * What is shown where a subtree threw.
3
+ *
4
+ * EXTENSIBILITY §7 promises "UI throws → its own error boundary" and
5
+ * nothing provided one. The iframe does protect the *host*: igni's
6
+ * shell survives whatever an extension does. It does not protect the
7
+ * extension from itself. A React tree that throws unmounts, so what
8
+ * an author actually shipped was a blank frame inside a working app —
9
+ * the worst-looking failure available, and the one a partner demo
10
+ * finds.
11
+ *
12
+ * A class, because `componentDidCatch` and
13
+ * `getDerivedStateFromError` have no hook equivalent. This is the
14
+ * only class component under the floor and it is not a style
15
+ * preference.
16
+ *
17
+ * **It catches less than people expect**, and saying so is part of
18
+ * the contract: render, lifecycle and constructor throws, in the
19
+ * subtree below it. Not event handlers, not `setTimeout`, not
20
+ * promise rejections, not anything during SSR. An extension still
21
+ * needs to handle its own async failures — the reference extension's
22
+ * `ScannerClient` is what that looks like.
23
+ */
24
+ import { Component, type ErrorInfo, type ReactNode } from "react";
25
+
26
+ /** What an {@link ErrorBoundary} takes. */
27
+ export interface ErrorBoundaryProps {
28
+ /** The subtree this boundary guards. */
29
+ children: ReactNode;
30
+ /**
31
+ * Shown instead of the subtree. Receives the error and a function
32
+ * that clears the boundary and remounts the children.
33
+ *
34
+ * The default is deliberately plain and deliberately shows the
35
+ * message: the reader is an extension's user, and "something went
36
+ * wrong" has never once helped anybody report a bug.
37
+ */
38
+ fallback?: (error: Error, reset: () => void) => ReactNode;
39
+ /** Somewhere to send this — a logger, telemetry, a toast. */
40
+ onError?: (error: Error, info: ErrorInfo) => void;
41
+ /**
42
+ * Changing any of these clears the boundary.
43
+ *
44
+ * Without it a boundary that has caught once stays caught forever,
45
+ * so navigating away from the thing that broke shows the error
46
+ * page for the thing that works. Compared by identity, in order,
47
+ * like a hook dependency array.
48
+ */
49
+ resetKeys?: readonly unknown[];
50
+ }
51
+
52
+ interface State {
53
+ error: Error | null;
54
+ }
55
+
56
+ // Anything can be thrown. The fallback and `onError` are typed to get an
57
+ // Error, and `null` held as the error would read as "nothing thrown".
58
+ function toError(thrown: unknown): Error {
59
+ return thrown instanceof Error ? thrown : new Error(String(thrown));
60
+ }
61
+
62
+ function changed(a: readonly unknown[], b: readonly unknown[]): boolean {
63
+ return a.length !== b.length || a.some((value, i) => !Object.is(value, b[i]));
64
+ }
65
+
66
+ /**
67
+ * What is shown where a subtree threw.
68
+ *
69
+ * It catches less than people expect: render, lifecycle and
70
+ * constructor throws in the subtree below it, and not event handlers,
71
+ * `setTimeout`, promise rejections or anything during SSR. The default
72
+ * fallback shows the error's message on purpose.
73
+ */
74
+ export class ErrorBoundary extends Component<ErrorBoundaryProps, State> {
75
+ /**
76
+ * The error the subtree threw, or null while nothing has thrown.
77
+ */
78
+ state: State = { error: null };
79
+
80
+ /**
81
+ * The state the boundary holds after a throw.
82
+ *
83
+ * @param error — the error the subtree threw.
84
+ */
85
+ static getDerivedStateFromError(error: Error): State {
86
+ return { error: toError(error) };
87
+ }
88
+
89
+ /**
90
+ * Reports the error to whoever asked for it.
91
+ *
92
+ * @param error — the error the subtree threw.
93
+ * @param info — React's account of where it was thrown: the component
94
+ * stack.
95
+ */
96
+ componentDidCatch(error: Error, info: ErrorInfo): void {
97
+ this.props.onError?.(toError(error), info);
98
+ }
99
+
100
+ /**
101
+ * Clears the boundary when the reset keys change.
102
+ *
103
+ * @param previous — the props from the previous render, whose
104
+ * `resetKeys` are compared with the new ones.
105
+ */
106
+ componentDidUpdate(previous: ErrorBoundaryProps): void {
107
+ if (this.state.error === null) return;
108
+ const before = previous.resetKeys ?? [];
109
+ const now = this.props.resetKeys ?? [];
110
+ if (changed(before, now)) this.reset();
111
+ }
112
+
113
+ /**
114
+ * Clears the error and renders the children again.
115
+ */
116
+ reset = (): void => {
117
+ this.setState({ error: null });
118
+ };
119
+
120
+ /**
121
+ * The children, or the error page when the subtree threw.
122
+ */
123
+ render(): ReactNode {
124
+ const { error } = this.state;
125
+ if (error === null) return this.props.children;
126
+ if (this.props.fallback) return this.props.fallback(error, this.reset);
127
+ return (
128
+ <div className="ui-crash" role="alert">
129
+ <p className="ui-text">Something in this view stopped working.</p>
130
+ <pre className="ui-crash-detail">{error.message}</pre>
131
+ <button type="button" className="btn" onClick={this.reset}>
132
+ Try again
133
+ </button>
134
+ </div>
135
+ );
136
+ }
137
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Saying what changed, to somebody who cannot see it change.
3
+ *
4
+ * A filtered count, a finished scan, a saved draft: all of them move
5
+ * nothing and focus nothing, so a screen reader is told none of it.
6
+ * The reference extension hand-rolled an `aria-live` paragraph with
7
+ * `ui-visually-hidden`, which is the right shape and the wrong place
8
+ * — every extension would write it, and most would get one of the
9
+ * three details wrong.
10
+ *
11
+ * The three details:
12
+ *
13
+ * 1. **The region must exist before the text does.** A live region
14
+ * added to the DOM with its message already in it is frequently
15
+ * not announced at all — the assistive technology has nothing to
16
+ * observe a change against. So this renders an empty element and
17
+ * fills it afterwards.
18
+ * 2. **The same message twice is not a change.** Scanning 40 files
19
+ * and then scanning 40 files again is silence, because the text
20
+ * never differed. A zero-width space is toggled on repeats.
21
+ * 3. **Polite waits, assertive interrupts.** Almost everything is
22
+ * polite. Assertive is for something the user must act on, and
23
+ * using it for a count makes the product unusable by the people
24
+ * it is meant to help.
25
+ */
26
+ import { useCallback, useEffect, useRef, useState } from "react";
27
+
28
+ /** Which way to say it. */
29
+ export type Urgency = "polite" | "assertive";
30
+
31
+ /** A live region and the function that speaks into it. */
32
+ export interface Announcer {
33
+ /** Say something. Re-saying the same thing still announces. */
34
+ announce: (message: string, urgency?: Urgency) => void;
35
+ /** Render this. It must be in the tree before anything is said. */
36
+ region: React.ReactElement;
37
+ }
38
+
39
+ /**
40
+ * A live region and the function that speaks into it.
41
+ *
42
+ * Two regions are rendered, not one. A single region whose
43
+ * `aria-live` value changes is unreliable: the attribute is read
44
+ * when the region is observed, so flipping it at the same moment the
45
+ * text changes races, and the announcement comes out at whichever
46
+ * urgency the implementation noticed first.
47
+ */
48
+ export function useAnnounce(): Announcer {
49
+ const [polite, setPolite] = useState("");
50
+ const [assertive, setAssertive] = useState("");
51
+ const last = useRef({ polite: "", assertive: "" });
52
+
53
+ const announce = useCallback(
54
+ (message: string, urgency: Urgency = "polite") => {
55
+ // Identical consecutive text is not a mutation, so nothing is
56
+ // announced. A zero-width space makes it one, and is not read
57
+ // aloud.
58
+ const previous = last.current[urgency];
59
+ const text = message === previous ? `${message}​` : message;
60
+ last.current[urgency] = text;
61
+ if (urgency === "assertive") setAssertive(text);
62
+ else setPolite(text);
63
+ },
64
+ [],
65
+ );
66
+
67
+ const region = (
68
+ <>
69
+ <div
70
+ className="ui-visually-hidden"
71
+ role="status"
72
+ aria-live="polite"
73
+ aria-atomic="true"
74
+ >
75
+ {polite}
76
+ </div>
77
+ <div
78
+ className="ui-visually-hidden"
79
+ role="alert"
80
+ aria-live="assertive"
81
+ aria-atomic="true"
82
+ >
83
+ {assertive}
84
+ </div>
85
+ </>
86
+ );
87
+
88
+ return { announce, region };
89
+ }
90
+
91
+ /** What a {@link LiveRegion} takes. */
92
+ export interface LiveRegionProps {
93
+ /** What to say. Changing it announces; clearing it says nothing. */
94
+ children?: string;
95
+ /** How insistently it is announced: politely, or assertively. */
96
+ urgency?: Urgency;
97
+ }
98
+
99
+ /**
100
+ * The declarative form, for a value that already lives in state.
101
+ *
102
+ * `<LiveRegion>{`${n} results`}</LiveRegion>` is the whole usage.
103
+ * Mounted empty on the first render so the region exists before it
104
+ * has anything to say: a live region added to the page with its
105
+ * message already in it is frequently not announced.
106
+ *
107
+ * @param children — what to say; changing it announces, and clearing it
108
+ * says nothing.
109
+ * @param urgency — how insistently it is announced: politely, or
110
+ * assertively.
111
+ */
112
+ export function LiveRegion({ children = "", urgency = "polite" }: LiveRegionProps) {
113
+ const [text, setText] = useState("");
114
+ useEffect(() => {
115
+ setText(children);
116
+ }, [children]);
117
+ return (
118
+ <div
119
+ className="ui-visually-hidden"
120
+ role={urgency === "assertive" ? "alert" : "status"}
121
+ aria-live={urgency}
122
+ aria-atomic="true"
123
+ >
124
+ {text}
125
+ </div>
126
+ );
127
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Markdown with its block structure intact.
3
+ *
4
+ * The floor published exactly one markdown component and it was
5
+ * `MarkdownInline`, which is *designed* to destroy block structure:
6
+ * headings lose their size, lists become middots, images return
7
+ * null. That is right for a two-line preview and exactly wrong for a
8
+ * document, so an extension with prose in it bundled its own
9
+ * renderer — and then had nothing to style it against, because
10
+ * igni's prose rules live in `theme.css` and were not published
11
+ * either.
12
+ *
13
+ * `examples/release-notes` hand-rolls a deliberately small subset
14
+ * and says so. This is what that was missing.
15
+ *
16
+ * **Not a configurable pipeline.** No plugin prop, no component
17
+ * overrides. The value here is that prose in an extension looks like
18
+ * prose in igni, and every escape hatch is a way for that to stop
19
+ * being true. An extension that needs a different pipeline should
20
+ * bundle react-markdown directly — it is a peer dependency it
21
+ * already has — and wrap the result in `.ui-prose`.
22
+ */
23
+ import ReactMarkdown, { type Components } from "react-markdown";
24
+ import remarkGfm from "remark-gfm";
25
+
26
+ function cx(...parts: (string | false | null | undefined)[]): string {
27
+ return parts.filter(Boolean).join(" ");
28
+ }
29
+
30
+ /**
31
+ * Links open where they point, safely.
32
+ *
33
+ * A document can arrive from a colleague, so the href is somebody
34
+ * else's. `noopener` is the one that matters: without it the opened
35
+ * page gets a handle on this frame through `window.opener` and can
36
+ * navigate it somewhere else.
37
+ */
38
+ const COMPONENTS: Components = {
39
+ a: ({ href, children, ...rest }) => (
40
+ <a {...rest} href={href} target="_blank" rel="noopener noreferrer">
41
+ {children}
42
+ </a>
43
+ ),
44
+ };
45
+
46
+ /** What a {@link Markdown} takes. */
47
+ export interface MarkdownProps {
48
+ /** The source. Rendered as a document, not flattened. */
49
+ children: string;
50
+ /** Added to the element's classes, beside the one the theme gives it. */
51
+ className?: string;
52
+ }
53
+
54
+ /**
55
+ * Render markdown as prose.
56
+ *
57
+ * GitHub-flavoured, because that is what people write: tables,
58
+ * strikethrough, task lists and autolinks. Raw HTML is **not**
59
+ * enabled and will not be — `rehype-raw` in a surface that renders
60
+ * text somebody else wrote is a script tag waiting to happen, and an
61
+ * extension's frame has a CSP precisely so that it cannot.
62
+ *
63
+ * @param children — the source; rendered as a document, not flattened.
64
+ * @param className — added to the element's classes, beside the one the
65
+ * theme gives it.
66
+ */
67
+ export function Markdown({ children, className }: MarkdownProps) {
68
+ return (
69
+ <div className={cx("ui-prose", className)}>
70
+ <ReactMarkdown remarkPlugins={[remarkGfm]} components={COMPONENTS}>
71
+ {children}
72
+ </ReactMarkdown>
73
+ </div>
74
+ );
75
+ }
@@ -0,0 +1,177 @@
1
+ import { useMemo } from "react";
2
+ import ReactMarkdown, { type Components } from "react-markdown";
3
+ import remarkGfm from "remark-gfm";
4
+
5
+ /**
6
+ * Markdown rendered as one flowing line of text.
7
+ *
8
+ * For previews: a list row, a snippet, anywhere a document has to be
9
+ * recognisable in two lines. Showing the raw source there leaks `##`
10
+ * and `**` into prose; rendering it normally is worse, because a
11
+ * heading at heading size in a 11.5px row is a heading, and a bullet
12
+ * list becomes four lines where there was room for two.
13
+ *
14
+ * So every block becomes inline. Headings keep their emphasis but not
15
+ * their size, list items are separated by middots rather than laid
16
+ * out, and code keeps its face. The result reads as the sentence the
17
+ * author wrote, which is what a preview is for.
18
+ *
19
+ * Two constraints are load-bearing, both from where this gets used:
20
+ *
21
+ * - **Nothing interactive.** These previews sit inside a `<button>`
22
+ * that opens the document. A link inside a button is invalid, and
23
+ * worse, it is a second click target inside the first.
24
+ * - **Nothing that loads.** An image in a preview is a network
25
+ * request to render two lines of text, and a broken one is an icon
26
+ * where a sentence should be.
27
+ */
28
+
29
+ /** Blocks flow inline, so a preview is one sentence rather than a page. */
30
+ const INLINE_COMPONENTS: Components = {
31
+ // Emphasis without the size. A document whose first line is a
32
+ // heading should read as its first line, not as a title.
33
+ h1: ({ children }) => <strong className="mdi-heading">{children}</strong>,
34
+ h2: ({ children }) => <strong className="mdi-heading">{children}</strong>,
35
+ h3: ({ children }) => <strong className="mdi-heading">{children}</strong>,
36
+ h4: ({ children }) => <strong className="mdi-heading">{children}</strong>,
37
+ h5: ({ children }) => <strong className="mdi-heading">{children}</strong>,
38
+ h6: ({ children }) => <strong className="mdi-heading">{children}</strong>,
39
+
40
+ p: ({ children }) => <span className="mdi-block">{children}</span>,
41
+ blockquote: ({ children }) => <span className="mdi-block">{children}</span>,
42
+
43
+ ul: ({ children }) => <span className="mdi-block">{children}</span>,
44
+ ol: ({ children }) => <span className="mdi-block">{children}</span>,
45
+ li: ({ children }) => <span className="mdi-item">{children}</span>,
46
+
47
+ // A fenced block and an inline span both become inline code: the
48
+ // point of showing code in a preview is that it is code.
49
+ pre: ({ children }) => <span className="mdi-block">{children}</span>,
50
+ code: ({ children }) => <code className="mdi-code">{children}</code>,
51
+
52
+ // Text only. The row itself is the link.
53
+ a: ({ children }) => <span>{children}</span>,
54
+
55
+ img: () => null,
56
+ hr: () => null,
57
+ br: () => <span> </span>,
58
+
59
+ // Tables flatten to their cells. A preview of a table is not a
60
+ // table, and rendering one inside two clamped lines produces a
61
+ // column of single characters.
62
+ table: ({ children }) => <span className="mdi-block">{children}</span>,
63
+ thead: () => null,
64
+ tbody: ({ children }) => <span>{children}</span>,
65
+ tr: ({ children }) => <span className="mdi-item">{children}</span>,
66
+ td: ({ children }) => <span className="mdi-cell">{children}</span>,
67
+ th: ({ children }) => <span className="mdi-cell">{children}</span>,
68
+ };
69
+
70
+ /**
71
+ * Repair markdown cut mid-syntax.
72
+ *
73
+ * Previews arrive pre-truncated, and the cut lands wherever it lands
74
+ * — often inside `**bold` or an unclosed backtick. Rendered as-is the
75
+ * marker shows up literally, which is the thing this component
76
+ * exists to stop. Closing what was left open is cheaper than asking
77
+ * every producer of a preview to cut carefully.
78
+ */
79
+ export function closeOpenMarks(text: string): string {
80
+ let out = text;
81
+ // Fences first: an unclosed one swallows everything after it.
82
+ if ((out.match(/^```/gm) ?? []).length % 2 === 1) out += "\n```";
83
+ // Then inline runs, longest marker first so `**` is not read as two
84
+ // single `*`.
85
+ for (const mark of ["**", "`", "*", "_"]) {
86
+ const count = out.split(mark).length - 1;
87
+ if (count % 2 === 1) out += mark;
88
+ }
89
+ return out;
90
+ }
91
+
92
+ /**
93
+ * Drop a leading line that only repeats the document's name.
94
+ *
95
+ * Most documents open with their own title. In a list the name is
96
+ * already the row's first line, so rendering it again spends the
97
+ * preview — the two lines somebody reads to tell this document from
98
+ * the next one — saying what they just read.
99
+ *
100
+ * Heading or plain line: the duplication is the same either way, and
101
+ * whether the author marked it up is not the reader's problem. The
102
+ * line has to *be* the name, though, not merely open with it —
103
+ * "Session handling is a signed JWT flow" is the first sentence of
104
+ * the document and belongs in the preview.
105
+ */
106
+ export function dropEchoedTitle(text: string, name: string): string {
107
+ const title = name.trim().toLowerCase();
108
+ if (!title) return text;
109
+ const lines = text.split("\n");
110
+ let i = 0;
111
+ while (i < lines.length && !lines[i].trim()) i++;
112
+ const first = lines[i]?.trim() ?? "";
113
+ const heading = first.replace(/^#{1,6}\s+/, "").trim();
114
+ // Only when it *is* the title, not when it merely starts with it —
115
+ // "Session handling in detail" is a different heading.
116
+ if (heading.toLowerCase() !== title) return text;
117
+ return lines
118
+ .slice(i + 1)
119
+ .join("\n")
120
+ .trimStart();
121
+ }
122
+
123
+ /**
124
+ * Markdown rendered as one flowing line of text.
125
+ *
126
+ * Every block becomes inline: headings keep their emphasis but not
127
+ * their size, list items are separated by middots, tables flatten to
128
+ * their cells, and links and images are dropped to their text or to
129
+ * nothing. `limit` bounds the work, not the appearance: the clamp is
130
+ * visual, and a document longer than `limit` is cut with an ellipsis,
131
+ * back to a word boundary when one falls in the last 40% of it.
132
+ *
133
+ * @param text — the markdown to render as one flowing line.
134
+ * @param name — the document's name, so a title echo can be dropped.
135
+ * @param limit — characters to keep; the clamp is visual, and this
136
+ * bounds the work.
137
+ * @param className — added to the element's classes, beside the one the
138
+ * theme gives it.
139
+ */
140
+ export function MarkdownInline({
141
+ text,
142
+ /** The document's name, so a title echo can be dropped. */
143
+ name = "",
144
+ /** Characters to keep. The clamp is visual; this bounds the work. */
145
+ limit = 320,
146
+ className = "",
147
+ }: {
148
+ text: string;
149
+ name?: string;
150
+ limit?: number;
151
+ className?: string;
152
+ }) {
153
+ const source = useMemo(() => {
154
+ const body = dropEchoedTitle(String(text || ""), name);
155
+ if (body.length <= limit) return closeOpenMarks(body);
156
+ // Cut back to a space so the preview does not end mid-word.
157
+ const cut = body.slice(0, limit);
158
+ const space = cut.lastIndexOf(" ");
159
+ const kept = space > limit * 0.6 ? cut.slice(0, space) : cut;
160
+ // Inside an unclosed fence the ellipsis goes in before the repair:
161
+ // after it, the closing fence would read "```…", which is not one.
162
+ if ((kept.match(/^```/gm) ?? []).length % 2 === 1) {
163
+ return closeOpenMarks(kept + "…");
164
+ }
165
+ return closeOpenMarks(kept) + "…";
166
+ }, [text, name, limit]);
167
+
168
+ if (!source.trim()) return null;
169
+
170
+ return (
171
+ <span className={className ? `mdi ${className}` : "mdi"}>
172
+ <ReactMarkdown remarkPlugins={[remarkGfm]} components={INLINE_COMPONENTS}>
173
+ {source}
174
+ </ReactMarkdown>
175
+ </span>
176
+ );
177
+ }