@open-elements/ui 0.8.0 → 0.10.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 (37) hide show
  1. package/README.md +153 -18
  2. package/dist/components/capability-status.d.ts +10 -0
  3. package/dist/components/capability-status.d.ts.map +1 -0
  4. package/dist/components/capability-status.js +12 -0
  5. package/dist/components/capability-status.js.map +1 -0
  6. package/dist/components/markdown-editor.d.ts +1 -1
  7. package/dist/components/markdown-editor.d.ts.map +1 -1
  8. package/dist/components/markdown-editor.js +131 -44
  9. package/dist/components/markdown-editor.js.map +1 -1
  10. package/dist/components/markdown-view.d.ts +1 -1
  11. package/dist/components/markdown-view.d.ts.map +1 -1
  12. package/dist/components/markdown-view.js +110 -27
  13. package/dist/components/markdown-view.js.map +1 -1
  14. package/dist/index.d.ts +3 -1
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +1 -0
  17. package/dist/index.js.map +1 -1
  18. package/dist/lib/markdown-extensions.d.ts +48 -0
  19. package/dist/lib/markdown-extensions.d.ts.map +1 -0
  20. package/dist/lib/markdown-extensions.js +73 -0
  21. package/dist/lib/markdown-extensions.js.map +1 -0
  22. package/dist/tsconfig.build.tsbuildinfo +1 -1
  23. package/dist/types/index.d.ts +17 -0
  24. package/dist/types/index.d.ts.map +1 -1
  25. package/package.json +41 -24
  26. package/src/components/__tests__/capability-status.test.tsx +82 -0
  27. package/src/components/__tests__/markdown-editor.test.tsx +226 -22
  28. package/src/components/__tests__/markdown-view.test.tsx +274 -21
  29. package/src/components/capability-status.tsx +63 -0
  30. package/src/components/markdown-editor.tsx +185 -79
  31. package/src/components/markdown-view.tsx +133 -28
  32. package/src/index.ts +3 -0
  33. package/src/lib/__tests__/markdown-extensions.test.ts +290 -0
  34. package/src/lib/markdown-extensions.ts +107 -0
  35. package/src/test/setup.ts +29 -0
  36. package/src/types/__tests__/markdown-toolbar-action.test.ts +34 -0
  37. package/src/types/index.ts +32 -0
@@ -1,32 +1,285 @@
1
1
  import { describe, it, expect, vi, afterEach } from "vitest";
2
- import { render, cleanup } from "@testing-library/react";
3
-
4
- // Mock TipTap before importing the component
5
- vi.mock("@tiptap/react", () => ({
6
- useEditor: () => null,
7
- EditorContent: () => <div data-testid="editor-content" />,
8
- }));
9
- vi.mock("@tiptap/starter-kit", () => ({ default: { configure: () => ({}) } }));
10
- vi.mock("@tiptap/extension-link", () => ({ default: { configure: () => ({}) } }));
11
- vi.mock("tiptap-markdown", () => ({ Markdown: {} }));
12
-
2
+ import { render, cleanup, waitFor, fireEvent } from "@testing-library/react";
3
+ import type { Editor } from "@tiptap/core";
13
4
  import { MarkdownView } from "../markdown-view.tsx";
14
5
 
15
6
  afterEach(cleanup);
16
7
 
17
- describe("MarkdownView", () => {
18
- it("mounts without error", () => {
19
- const { container } = render(<MarkdownView content="" />);
20
- expect(container).toBeTruthy();
8
+ async function renderView(content: string, onChange?: (md: string) => void | Promise<void>) {
9
+ const result = render(<MarkdownView content={content} onChange={onChange} />);
10
+ await waitFor(() => expect(result.container.querySelector(".ProseMirror")).toBeTruthy());
11
+ return result;
12
+ }
13
+
14
+ function checkboxes(container: HTMLElement): HTMLInputElement[] {
15
+ return Array.from(container.querySelectorAll<HTMLInputElement>("input[type=checkbox]"));
16
+ }
17
+
18
+ /** Toggle a checkbox to `to` and fire the change event the node view listens for. */
19
+ function toggle(input: HTMLInputElement, to: boolean): void {
20
+ input.checked = to;
21
+ fireEvent.change(input);
22
+ }
23
+
24
+ function getEditor(container: HTMLElement): Editor {
25
+ const dom = container.querySelector(".ProseMirror") as (HTMLElement & { editor?: Editor }) | null;
26
+ if (!dom?.editor) throw new Error("editor not mounted");
27
+ return dom.editor;
28
+ }
29
+
30
+ /** A promise whose settlement is controlled by the test. */
31
+ function deferred(): { promise: Promise<void>; resolve: () => void; reject: () => void } {
32
+ let resolve!: () => void;
33
+ let reject!: () => void;
34
+ const promise = new Promise<void>((res, rej) => {
35
+ resolve = res;
36
+ reject = () => rej(new Error("save failed"));
37
+ });
38
+ return { promise, resolve, reject };
39
+ }
40
+
41
+ describe("MarkdownView — rendering (read-only)", () => {
42
+ it("renders structural Markdown as structure, not plain paragraphs", async () => {
43
+ const { container } = await renderView("# Title\n\n- a\n- b\n\n> quote");
44
+ expect(container.querySelector("h1")).toBeTruthy();
45
+ expect(container.querySelector("ul")).toBeTruthy();
46
+ expect(container.querySelector("blockquote")).toBeTruthy();
47
+ });
48
+
49
+ it("reflects the stored checked state without an onChange prop", async () => {
50
+ const { container } = await renderView("- [x] Done\n- [ ] Open");
51
+ const boxes = checkboxes(container);
52
+ expect(boxes).toHaveLength(2);
53
+ expect(boxes[0].checked).toBe(true);
54
+ expect(boxes[1].checked).toBe(false);
55
+ });
56
+
57
+ it("reverts a click and leaves the document unchanged without onChange", async () => {
58
+ const { container } = await renderView("- [ ] Open item");
59
+ const before = getEditor(container).storage.markdown.getMarkdown();
60
+ toggle(checkboxes(container)[0], true);
61
+ await waitFor(() => expect(checkboxes(container)[0].checked).toBe(false));
62
+ expect(getEditor(container).storage.markdown.getMarkdown()).toBe(before);
63
+ });
64
+
65
+ it("suppresses the prose bullet on the task list", async () => {
66
+ const { container } = await renderView("- [x] Done\n- [ ] Open");
67
+ const list = container.querySelector('[data-type="taskList"]');
68
+ expect(list?.classList.contains("list-none")).toBe(true);
69
+ expect(list?.classList.contains("pl-0")).toBe(true);
70
+ });
71
+ });
72
+
73
+ describe("MarkdownView — toggling with onChange", () => {
74
+ it("reports the full updated Markdown when ticking", async () => {
75
+ const onChange = vi.fn();
76
+ const { container } = await renderView("- [ ] Call Anna\n- [ ] Send offer", onChange);
77
+ toggle(checkboxes(container)[0], true);
78
+ await waitFor(() => expect(onChange).toHaveBeenCalledTimes(1));
79
+ expect(onChange).toHaveBeenCalledWith("- [x] Call Anna\n- [ ] Send offer");
80
+ });
81
+
82
+ it("reports the full updated Markdown when unticking", async () => {
83
+ const onChange = vi.fn();
84
+ const { container } = await renderView("- [x] Call Anna", onChange);
85
+ toggle(checkboxes(container)[0], false);
86
+ await waitFor(() => expect(onChange).toHaveBeenCalledTimes(1));
87
+ expect(onChange).toHaveBeenCalledWith("- [ ] Call Anna");
88
+ });
89
+
90
+ it("flips the checkbox immediately, before the Promise settles", async () => {
91
+ const gate = deferred();
92
+ const { container } = await renderView("- [ ] Task", () => gate.promise);
93
+ toggle(checkboxes(container)[0], true);
94
+ await waitFor(() => expect(checkboxes(container)[0].checked).toBe(true));
95
+ gate.resolve();
96
+ });
97
+
98
+ it("changes only the clicked item in a mixed document", async () => {
99
+ const onChange = vi.fn();
100
+ // A paragraph separates the bullet list from the task list: a bullet list
101
+ // directly adjacent to a task list serializes with a phantom empty task
102
+ // item (a pre-existing round-trip quirk unrelated to this spec).
103
+ const content = "# Title\n\nSome text\n\n- one\n- two\n\nMore\n\n- [ ] a\n- [ ] b\n- [ ] c";
104
+ const { container } = await renderView(content, onChange);
105
+ const before = getEditor(container).storage.markdown.getMarkdown();
106
+ // The three task checkboxes are the only ones in the document.
107
+ toggle(checkboxes(container)[1], true);
108
+ await waitFor(() => expect(onChange).toHaveBeenCalledTimes(1));
109
+ const reported = onChange.mock.calls[0][0] as string;
110
+ expect(reported).not.toBe(before);
111
+ expect(reported).toContain("- [x] b");
112
+ expect(reported).toContain("- [ ] a");
113
+ expect(reported).toContain("- [ ] c");
114
+ expect(reported.match(/\[x\]/g)).toHaveLength(1);
115
+ expect(reported).toContain("# Title");
116
+ expect(reported).toContain("- one");
117
+ });
118
+
119
+ it("changes only the nested item, keeping indentation", async () => {
120
+ const onChange = vi.fn();
121
+ const { container } = await renderView("- [ ] parent\n - [ ] child", onChange);
122
+ toggle(checkboxes(container)[1], true);
123
+ await waitFor(() => expect(onChange).toHaveBeenCalledTimes(1));
124
+ expect(onChange).toHaveBeenCalledWith("- [ ] parent\n - [x] child");
125
+ });
126
+ });
127
+
128
+ describe("MarkdownView — busy state", () => {
129
+ it("disables and mutes every checkbox while a save is pending", async () => {
130
+ const gate = deferred();
131
+ const { container } = await renderView("- [ ] a\n- [ ] b", () => gate.promise);
132
+ toggle(checkboxes(container)[0], true);
133
+ await waitFor(() => {
134
+ const boxes = checkboxes(container);
135
+ expect(boxes.every((b) => b.disabled)).toBe(true);
136
+ });
137
+ expect(container.querySelector('[aria-busy="true"]')).toBeTruthy();
138
+ gate.resolve();
139
+ });
140
+
141
+ it("ignores a second click during a pending save", async () => {
142
+ const gate = deferred();
143
+ const onChange = vi.fn(() => gate.promise);
144
+ const { container } = await renderView("- [ ] a\n- [ ] b", onChange);
145
+ toggle(checkboxes(container)[0], true);
146
+ await waitFor(() => expect(onChange).toHaveBeenCalledTimes(1));
147
+ // Second click while busy.
148
+ toggle(checkboxes(container)[1], true);
149
+ await waitFor(() => expect(checkboxes(container)[1].checked).toBe(false));
150
+ expect(onChange).toHaveBeenCalledTimes(1);
151
+ gate.resolve();
152
+ });
153
+
154
+ it("re-enables interaction after the Promise resolves", async () => {
155
+ const gate = deferred();
156
+ const { container } = await renderView("- [ ] a\n- [ ] b", () => gate.promise);
157
+ toggle(checkboxes(container)[0], true);
158
+ await waitFor(() => expect(checkboxes(container).every((b) => b.disabled)).toBe(true));
159
+ gate.resolve();
160
+ await waitFor(() => expect(checkboxes(container).some((b) => b.disabled)).toBe(false));
161
+ expect(checkboxes(container)[0].checked).toBe(true);
162
+ });
163
+
164
+ it("stays interactive when onChange returns void", async () => {
165
+ const onChange = vi.fn(() => undefined);
166
+ const { container } = await renderView("- [ ] a\n- [ ] b", onChange);
167
+ toggle(checkboxes(container)[0], true);
168
+ await waitFor(() => expect(onChange).toHaveBeenCalledTimes(1));
169
+ expect(checkboxes(container).every((b) => b.disabled)).toBe(false);
170
+ toggle(checkboxes(container)[1], true);
171
+ await waitFor(() => expect(onChange).toHaveBeenCalledTimes(2));
172
+ });
173
+ });
174
+
175
+ describe("MarkdownView — failure and rollback", () => {
176
+ it("reverts the document when the save rejects", async () => {
177
+ const gate = deferred();
178
+ const { container } = await renderView("- [ ] Call Anna", () => gate.promise);
179
+ toggle(checkboxes(container)[0], true);
180
+ await waitFor(() => expect(checkboxes(container)[0].checked).toBe(true));
181
+ gate.reject();
182
+ await waitFor(() => expect(checkboxes(container)[0].checked).toBe(false));
183
+ expect(getEditor(container).storage.markdown.getMarkdown()).toBe("- [ ] Call Anna");
184
+ });
185
+
186
+ it("re-enables interaction after a rejection", async () => {
187
+ const first = deferred();
188
+ const onChange = vi.fn(() => first.promise);
189
+ const { container } = await renderView("- [ ] a", onChange);
190
+ toggle(checkboxes(container)[0], true);
191
+ await waitFor(() => expect(onChange).toHaveBeenCalledTimes(1));
192
+ first.reject();
193
+ await waitFor(() => expect(checkboxes(container)[0].disabled).toBe(false));
194
+ // A fresh click is accepted.
195
+ toggle(checkboxes(container)[0], true);
196
+ await waitFor(() => expect(onChange).toHaveBeenCalledTimes(2));
197
+ });
198
+
199
+ it("reverts only the failed change after a prior success", async () => {
200
+ const gates = [deferred(), deferred()];
201
+ let call = 0;
202
+ const onChange = vi.fn(() => gates[call++].promise);
203
+ const { container } = await renderView("- [ ] a\n- [ ] b", onChange);
204
+
205
+ toggle(checkboxes(container)[0], true);
206
+ await waitFor(() => expect(onChange).toHaveBeenCalledTimes(1));
207
+ gates[0].resolve();
208
+ await waitFor(() => expect(checkboxes(container)[0].disabled).toBe(false));
209
+
210
+ toggle(checkboxes(container)[1], true);
211
+ await waitFor(() => expect(onChange).toHaveBeenCalledTimes(2));
212
+ gates[1].reject();
213
+ // Reverts to the state after the first toggle: a checked, b unchecked.
214
+ await waitFor(() =>
215
+ expect(getEditor(container).storage.markdown.getMarkdown()).toBe("- [x] a\n- [ ] b"),
216
+ );
217
+ });
218
+ });
219
+
220
+ describe("MarkdownView — content prop interaction", () => {
221
+ it("does not rebuild the document when content merely echoes the report", async () => {
222
+ const onChange = vi.fn();
223
+ const { container, rerender } = render(
224
+ <MarkdownView content={"- [ ] a"} onChange={onChange} />,
225
+ );
226
+ await waitFor(() => expect(container.querySelector(".ProseMirror")).toBeTruthy());
227
+ toggle(checkboxes(container)[0], true);
228
+ await waitFor(() => expect(onChange).toHaveBeenCalledWith("- [x] a"));
229
+ const domBefore = container.querySelector(".ProseMirror");
230
+ // Parent echoes exactly what was reported.
231
+ rerender(<MarkdownView content={"- [x] a"} onChange={onChange} />);
232
+ await waitFor(() => expect(checkboxes(container)[0].checked).toBe(true));
233
+ // Same editor DOM node — not torn down and rebuilt.
234
+ expect(container.querySelector(".ProseMirror")).toBe(domBefore);
235
+ });
236
+
237
+ it("replaces the document when content genuinely differs", async () => {
238
+ const { container, rerender } = render(<MarkdownView content={"# First"} />);
239
+ await waitFor(() => expect(container.querySelector(".ProseMirror")).toBeTruthy());
240
+ const editor = getEditor(container);
241
+ rerender(<MarkdownView content={"# Second"} />);
242
+ await waitFor(() => expect(editor.storage.markdown.getMarkdown()).toBe("# Second"));
243
+ });
244
+
245
+ it("lets a content change during a pending save win over the rollback", async () => {
246
+ const gate = deferred();
247
+ const { container, rerender } = render(
248
+ <MarkdownView content={"- [ ] a"} onChange={() => gate.promise} />,
249
+ );
250
+ await waitFor(() => expect(container.querySelector(".ProseMirror")).toBeTruthy());
251
+ const editor = getEditor(container);
252
+ toggle(checkboxes(container)[0], true);
253
+ await waitFor(() => expect(checkboxes(container)[0].checked).toBe(true));
254
+ // A genuinely different value arrives while the save is pending.
255
+ rerender(<MarkdownView content={"- [ ] a\n- [ ] c"} onChange={() => gate.promise} />);
256
+ await waitFor(() => expect(editor.storage.markdown.getMarkdown()).toBe("- [ ] a\n- [ ] c"));
257
+ gate.reject();
258
+ await waitFor(() => expect(editor.storage.markdown.getMarkdown()).toBe("- [ ] a\n- [ ] c"));
259
+ });
260
+ });
261
+
262
+ describe("MarkdownView — edge cases", () => {
263
+ it("never calls onChange for content without a task list", async () => {
264
+ const onChange = vi.fn();
265
+ const { container } = await renderView("# Heading\n\nJust text", onChange);
266
+ expect(checkboxes(container)).toHaveLength(0);
267
+ fireEvent.click(container.querySelector("h1") as HTMLElement);
268
+ expect(onChange).not.toHaveBeenCalled();
21
269
  });
22
270
 
23
- it("renders editor content area", () => {
24
- const { container } = render(<MarkdownView content="Hello world" />);
25
- expect(container.querySelector("[data-testid='editor-content']")).toBeTruthy();
271
+ it("renders nothing interactive for empty content", async () => {
272
+ const onChange = vi.fn();
273
+ const { container } = await renderView("", onChange);
274
+ expect(checkboxes(container)).toHaveLength(0);
275
+ expect(onChange).not.toHaveBeenCalled();
26
276
  });
27
277
 
28
- it("accepts markdown content without error", () => {
29
- const { container } = render(<MarkdownView content="Hello **bold** and *italic*" />);
30
- expect(container).toBeTruthy();
278
+ it("keeps text non-editable", async () => {
279
+ const onChange = vi.fn();
280
+ const { container } = await renderView("Just a paragraph", onChange);
281
+ const pm = container.querySelector(".ProseMirror") as HTMLElement;
282
+ expect(pm.getAttribute("contenteditable")).toBe("false");
283
+ expect(onChange).not.toHaveBeenCalled();
31
284
  });
32
285
  });
@@ -0,0 +1,63 @@
1
+ "use client";
2
+
3
+ import { CircleCheck, TriangleAlert } from "lucide-react";
4
+ import { Card, CardContent } from "./card.tsx";
5
+ import { Tooltip, TooltipContent, TooltipTrigger } from "./tooltip.tsx";
6
+
7
+ interface CapabilityStatusProps {
8
+ readonly available: boolean;
9
+ readonly label: string;
10
+ readonly availableText: string;
11
+ readonly unavailableText: string;
12
+ readonly hint?: string;
13
+ }
14
+
15
+ export function CapabilityStatus({
16
+ available,
17
+ label,
18
+ availableText,
19
+ unavailableText,
20
+ hint,
21
+ }: CapabilityStatusProps) {
22
+ const statusText = available ? availableText : unavailableText;
23
+ const Icon = available ? CircleCheck : TriangleAlert;
24
+
25
+ const row = (
26
+ <div className="flex items-center gap-3">
27
+ <Icon
28
+ className={`h-5 w-5 shrink-0 ${available ? "text-oe-green" : "text-oe-red"}`}
29
+ aria-hidden="true"
30
+ />
31
+ <div className="flex flex-col">
32
+ <span className="text-base font-medium text-oe-dark">{label}</span>
33
+ <span className="text-sm text-oe-gray-mid">{statusText}</span>
34
+ </div>
35
+ </div>
36
+ );
37
+
38
+ return (
39
+ <Card className="border-oe-gray-light">
40
+ <CardContent>
41
+ {hint ? (
42
+ <Tooltip>
43
+ <TooltipTrigger asChild>
44
+ <div
45
+ tabIndex={0}
46
+ role="note"
47
+ aria-label={`${label}: ${statusText}. ${hint}`}
48
+ className="cursor-help outline-none"
49
+ >
50
+ {row}
51
+ </div>
52
+ </TooltipTrigger>
53
+ <TooltipContent>{hint}</TooltipContent>
54
+ </Tooltip>
55
+ ) : (
56
+ row
57
+ )}
58
+ </CardContent>
59
+ </Card>
60
+ );
61
+ }
62
+
63
+ export type { CapabilityStatusProps };
@@ -1,119 +1,225 @@
1
1
  "use client";
2
2
 
3
3
  import { useEditor, EditorContent, type Editor } from "@tiptap/react";
4
- import StarterKit from "@tiptap/starter-kit";
5
- import Link from "@tiptap/extension-link";
6
- import Placeholder from "@tiptap/extension-placeholder";
7
- import { Markdown } from "tiptap-markdown";
8
- import { Bold, Italic, Strikethrough, Link as LinkIcon, Unlink } from "lucide-react";
9
- import { useEffect, useCallback } from "react";
4
+ import {
5
+ Bold,
6
+ Italic,
7
+ Strikethrough,
8
+ Code,
9
+ Link as LinkIcon,
10
+ Unlink,
11
+ Heading1,
12
+ Heading2,
13
+ Heading3,
14
+ List,
15
+ ListOrdered,
16
+ ListChecks,
17
+ Quote,
18
+ SquareCode,
19
+ Minus,
20
+ type LucideIcon,
21
+ } from "lucide-react";
22
+ import { useEffect } from "react";
10
23
  import { cn } from "../lib/utils.ts";
11
- import type { MarkdownEditorProps } from "../types/index.ts";
24
+ import { createMarkdownExtensions } from "../lib/markdown-extensions.ts";
25
+ import type { MarkdownEditorProps, MarkdownToolbarAction } from "../types/index.ts";
26
+
27
+ const DEFAULT_TOOLBAR: readonly MarkdownToolbarAction[] = ["bold", "italic"];
28
+
29
+ /** Opens a prompt to set, change or clear the link on the current selection. */
30
+ function editLink(editor: Editor): void {
31
+ const previousUrl = (editor.getAttributes("link").href as string | undefined) ?? "";
32
+ const url = window.prompt("URL", previousUrl);
33
+ if (url === null) return;
34
+ if (url === "") {
35
+ editor.chain().focus().extendMarkRange("link").unsetLink().run();
36
+ return;
37
+ }
38
+ editor.chain().focus().extendMarkRange("link").setLink({ href: url }).run();
39
+ }
40
+
41
+ interface ActionSpec {
42
+ readonly icon: LucideIcon;
43
+ readonly label: string;
44
+ readonly isActive: (editor: Editor) => boolean;
45
+ readonly run: (editor: Editor) => void;
46
+ }
47
+
48
+ /**
49
+ * Single mapping from a toolbar action to its icon, accessible label, active-state
50
+ * predicate and command. Adding an action later touches only this record.
51
+ */
52
+ const ACTIONS: Record<MarkdownToolbarAction, ActionSpec> = {
53
+ bold: {
54
+ icon: Bold,
55
+ label: "Bold",
56
+ isActive: (e) => e.isActive("bold"),
57
+ run: (e) => e.chain().focus().toggleBold().run(),
58
+ },
59
+ italic: {
60
+ icon: Italic,
61
+ label: "Italic",
62
+ isActive: (e) => e.isActive("italic"),
63
+ run: (e) => e.chain().focus().toggleItalic().run(),
64
+ },
65
+ strike: {
66
+ icon: Strikethrough,
67
+ label: "Strikethrough",
68
+ isActive: (e) => e.isActive("strike"),
69
+ run: (e) => e.chain().focus().toggleStrike().run(),
70
+ },
71
+ code: {
72
+ icon: Code,
73
+ label: "Code",
74
+ isActive: (e) => e.isActive("code"),
75
+ run: (e) => e.chain().focus().toggleCode().run(),
76
+ },
77
+ link: {
78
+ icon: LinkIcon,
79
+ label: "Link",
80
+ isActive: (e) => e.isActive("link"),
81
+ run: editLink,
82
+ },
83
+ h1: {
84
+ icon: Heading1,
85
+ label: "Heading 1",
86
+ isActive: (e) => e.isActive("heading", { level: 1 }),
87
+ run: (e) => e.chain().focus().toggleHeading({ level: 1 }).run(),
88
+ },
89
+ h2: {
90
+ icon: Heading2,
91
+ label: "Heading 2",
92
+ isActive: (e) => e.isActive("heading", { level: 2 }),
93
+ run: (e) => e.chain().focus().toggleHeading({ level: 2 }).run(),
94
+ },
95
+ h3: {
96
+ icon: Heading3,
97
+ label: "Heading 3",
98
+ isActive: (e) => e.isActive("heading", { level: 3 }),
99
+ run: (e) => e.chain().focus().toggleHeading({ level: 3 }).run(),
100
+ },
101
+ bulletList: {
102
+ icon: List,
103
+ label: "Bullet list",
104
+ isActive: (e) => e.isActive("bulletList"),
105
+ run: (e) => e.chain().focus().toggleBulletList().run(),
106
+ },
107
+ orderedList: {
108
+ icon: ListOrdered,
109
+ label: "Numbered list",
110
+ isActive: (e) => e.isActive("orderedList"),
111
+ run: (e) => e.chain().focus().toggleOrderedList().run(),
112
+ },
113
+ taskList: {
114
+ icon: ListChecks,
115
+ label: "Task list",
116
+ isActive: (e) => e.isActive("taskList"),
117
+ run: (e) => e.chain().focus().toggleTaskList().run(),
118
+ },
119
+ blockquote: {
120
+ icon: Quote,
121
+ label: "Blockquote",
122
+ isActive: (e) => e.isActive("blockquote"),
123
+ run: (e) => e.chain().focus().toggleBlockquote().run(),
124
+ },
125
+ codeBlock: {
126
+ icon: SquareCode,
127
+ label: "Code block",
128
+ isActive: (e) => e.isActive("codeBlock"),
129
+ run: (e) => e.chain().focus().toggleCodeBlock().run(),
130
+ },
131
+ horizontalRule: {
132
+ icon: Minus,
133
+ label: "Horizontal rule",
134
+ isActive: () => false,
135
+ run: (e) => e.chain().focus().setHorizontalRule().run(),
136
+ },
137
+ };
12
138
 
13
139
  function ToolbarButton({
14
140
  active,
15
- disabled,
16
141
  onClick,
17
- children,
18
- title,
142
+ icon: Icon,
143
+ label,
19
144
  }: {
20
145
  readonly active?: boolean;
21
- readonly disabled?: boolean;
22
146
  readonly onClick: () => void;
23
- readonly children: React.ReactNode;
24
- readonly title: string;
147
+ readonly icon: LucideIcon;
148
+ readonly label: string;
25
149
  }) {
26
150
  return (
27
151
  <button
28
152
  type="button"
29
- title={title}
30
- disabled={disabled}
153
+ title={label}
154
+ aria-label={label}
155
+ aria-pressed={active}
31
156
  onClick={onClick}
32
157
  className={cn(
33
158
  "rounded p-1.5 transition-colors",
34
159
  active
35
160
  ? "bg-oe-dark/10 text-oe-dark"
36
161
  : "text-muted-foreground hover:bg-muted hover:text-foreground",
37
- disabled && "cursor-not-allowed opacity-40",
38
162
  )}
39
163
  >
40
- {children}
164
+ <Icon className="h-4 w-4" />
41
165
  </button>
42
166
  );
43
167
  }
44
168
 
45
- function Toolbar({ editor }: { readonly editor: Editor | null }) {
46
- const setLink = useCallback(() => {
47
- if (!editor) return;
48
- const previousUrl = editor.getAttributes("link").href ?? "";
49
- const url = window.prompt("URL", previousUrl);
50
- if (url === null) return;
51
- if (url === "") {
52
- editor.chain().focus().extendMarkRange("link").unsetLink().run();
53
- return;
54
- }
55
- editor.chain().focus().extendMarkRange("link").setLink({ href: url }).run();
56
- }, [editor]);
57
-
169
+ function Toolbar({
170
+ editor,
171
+ actions,
172
+ }: {
173
+ readonly editor: Editor | null;
174
+ readonly actions: readonly MarkdownToolbarAction[];
175
+ }) {
58
176
  if (!editor) return null;
59
177
 
178
+ // Preserve declaration order, drop duplicates (first occurrence wins).
179
+ const uniqueActions = actions.filter((action, index) => actions.indexOf(action) === index);
180
+ if (uniqueActions.length === 0) return null;
181
+
60
182
  return (
61
183
  <div className="flex items-center gap-0.5 border-b px-2 py-1.5">
62
- <ToolbarButton
63
- title="Bold"
64
- active={editor.isActive("bold")}
65
- onClick={() => editor.chain().focus().toggleBold().run()}
66
- >
67
- <Bold className="h-4 w-4" />
68
- </ToolbarButton>
69
- <ToolbarButton
70
- title="Italic"
71
- active={editor.isActive("italic")}
72
- onClick={() => editor.chain().focus().toggleItalic().run()}
73
- >
74
- <Italic className="h-4 w-4" />
75
- </ToolbarButton>
76
- <ToolbarButton
77
- title="Strikethrough"
78
- active={editor.isActive("strike")}
79
- onClick={() => editor.chain().focus().toggleStrike().run()}
80
- >
81
- <Strikethrough className="h-4 w-4" />
82
- </ToolbarButton>
83
- <div className="bg-border mx-1 h-5 w-px" />
84
- <ToolbarButton title="Link" active={editor.isActive("link")} onClick={setLink}>
85
- <LinkIcon className="h-4 w-4" />
86
- </ToolbarButton>
87
- {editor.isActive("link") && (
88
- <ToolbarButton title="Remove link" onClick={() => editor.chain().focus().unsetLink().run()}>
89
- <Unlink className="h-4 w-4" />
90
- </ToolbarButton>
91
- )}
184
+ {uniqueActions.map((action) => {
185
+ const spec = ACTIONS[action];
186
+ return (
187
+ <span key={action} className="flex items-center gap-0.5">
188
+ <ToolbarButton
189
+ icon={spec.icon}
190
+ label={spec.label}
191
+ active={spec.isActive(editor)}
192
+ onClick={() => spec.run(editor)}
193
+ />
194
+ {action === "link" && editor.isActive("link") && (
195
+ <ToolbarButton
196
+ icon={Unlink}
197
+ label="Remove link"
198
+ onClick={() => editor.chain().focus().unsetLink().run()}
199
+ />
200
+ )}
201
+ </span>
202
+ );
203
+ })}
92
204
  </div>
93
205
  );
94
206
  }
95
207
 
96
- export function MarkdownEditor({ value, onChange, placeholder }: MarkdownEditorProps) {
208
+ export function MarkdownEditor({ value, onChange, placeholder, toolbar }: MarkdownEditorProps) {
209
+ const actions = toolbar ?? DEFAULT_TOOLBAR;
210
+
97
211
  const editor = useEditor({
98
- extensions: [
99
- StarterKit.configure({
100
- heading: false,
101
- codeBlock: false,
102
- blockquote: false,
103
- horizontalRule: false,
104
- bulletList: false,
105
- orderedList: false,
106
- listItem: false,
107
- }),
108
- Link.configure({
109
- openOnClick: false,
110
- HTMLAttributes: { class: "text-blue-600 underline" },
111
- }),
112
- Placeholder.configure({ placeholder: placeholder ?? "" }),
113
- Markdown,
114
- ],
212
+ extensions: createMarkdownExtensions({
213
+ placeholder,
214
+ openLinksOnClick: false,
215
+ allowedActions: actions,
216
+ }),
115
217
  content: value,
116
218
  immediatelyRender: false,
219
+ // Re-render the toolbar on every transaction so active states and the
220
+ // contextual Unlink button track the cursor. TipTap v3 defaults this to
221
+ // false, which would freeze the toolbar's active styling as the user moves.
222
+ shouldRerenderOnTransaction: true,
117
223
  onUpdate: ({ editor: ed }) => {
118
224
  onChange(ed.storage.markdown.getMarkdown());
119
225
  },
@@ -134,7 +240,7 @@ export function MarkdownEditor({ value, onChange, placeholder }: MarkdownEditorP
134
240
 
135
241
  return (
136
242
  <div className="bg-background rounded-md border">
137
- <Toolbar editor={editor} />
243
+ <Toolbar editor={editor} actions={actions} />
138
244
  <EditorContent editor={editor} />
139
245
  </div>
140
246
  );