Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
feat(notes): tables in the note editor, plus a formatting toolbar (#2255)
voidf7ea87216f63
diff --git a/CLAUDE.md b/CLAUDE.mdindex d4a2bbdb8..2f6fcb3f6 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -177,6 +177,10 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.- **SettingsPage.tsx**: Comprehensive settings interface- **WhisperModelPicker.tsx**: Model selection and download UI- **ui/**: Reusable UI components (buttons, cards, inputs, etc.)+- **ui/RichTextEditor.tsx**: Tiptap note editor. Note bodies (`content`, `enhanced_content`) are stored as Markdown via tiptap-markdown (`html: false`)+ - `RichTextEditorExtensions.ts` holds the extension list (`RichTextEditor` adds the mention extension in front of it); order matters: at equal priority, later extensions' keymaps and clipboard props run first+ - `RichTextEditorTable.ts` keeps every table to what a GFM pipe table can store: header first row, one single-line paragraph per cell, no merged cells, no alignment or column widths. Pasted cells are flattened while parsing, a normalizer fixes what commands and pastes leave behind, and the table serializer escapes `|` in cells. Tests: `test/components/richTextEditor.test.js` (happy-dom)+ - Floating menus: `RichTextEditorFormatMenu.tsx` shows one formatting toolbar (marks, text style, lists, quote, insert table) above selected text (Tiptap `BubbleMenu`) and beside the caret on an empty top-level line (`FloatingMenu`); `RichTextEditorTableMenu.tsx` is the table's `⋯` menu. They share `RichTextEditorMenus.ts`: a menu hides when focus leaves it, so dropdowns portal into the menu element itself, never into the editor's scroller (EditorContent moves the scroller's children when a note closes); `useHideOnFocusLeave` hides a menu when focus leaves from inside it or after a click on it, which Tiptap misses. The menus detach their element without unmounting it, so buttons use a native `title` rather than `<Tooltip>`, and a dropdown inside a menu is controlled and closed from the menu's `onHide` — otherwise it stays open over a scroll-locked page when the menu hides. Keep menu props stable, or each render dispatches an `updateOptions` transaction### React Hooks (src/hooks/)@@ -762,7 +766,7 @@ const { t } = useTranslation();Raster UI assets live in `src/assets/` (onboarding ones are named `onboarding-*`). Vector provider/brand marks live in `src/assets/icons/`.-UI icons come from `src/components/icons/` (vendored Nucleo core outline components behind lucide-style names, e.g. `import { Check, Loader2 } from "../icons"`). To add one, map a name to a Nucleo label in `src/components/icons/nucleo-map.json` and run `node scripts/sync-nucleo-icons.js`; never import from `lucide-react` or a machine-local Nucleo path.+UI icons come from `src/components/icons/` (vendored Nucleo core outline components behind lucide-style names, e.g. `import { Check, Loader2 } from "../icons"`). To add one, map a name to a Nucleo label in `src/components/icons/nucleo-map.json` and run `node scripts/sync-nucleo-icons.js`; never import from `lucide-react` or a machine-local Nucleo path. Icons outside that set — the status marks and the note toolbar's formatting glyphs — are drawn by hand in `src/components/icons/primitives.tsx`, which the generated `index.ts` re-exports.**Typography**: `--font-family-sans` is Yowza (brand, Latin only) falling back to the bundled Noto Sans; `--font-family-display` is Yowza Soft for headings. The font files are licensed and never committed — `src/brandFonts.ts` registers whatever `scripts/download-brand-fonts.js` fetched at build time, and a build without them silently uses Noto Sans.diff --git a/package-lock.json b/package-lock.jsonindex 20e0376cf..39665e777 100644--- a/package-lock.json+++ b/package-lock.json@@ -38,10 +38,15 @@"@radix-ui/react-tabs": "^1.1.12","@tanstack/react-virtual": "^3.13.2","@tiptap/core": "3.31.3",+ "@tiptap/extension-bubble-menu": "3.31.3",+ "@tiptap/extension-floating-menu": "3.31.3",+ "@tiptap/extension-horizontal-rule": "3.31.3","@tiptap/extension-mention": "3.31.3","@tiptap/extension-placeholder": "3.31.3",+ "@tiptap/extension-table": "3.31.3","@tiptap/extension-task-item": "3.31.3","@tiptap/extension-task-list": "3.31.3",+ "@tiptap/pm": "3.31.3","@tiptap/react": "3.31.3","@tiptap/starter-kit": "3.31.3","@tiptap/suggestion": "3.31.3",@@ -97,6 +102,7 @@"eslint-plugin-react-refresh": "^0.5.2","espree": "^11.2.0","globals": "17.5.0",+ "happy-dom": "^20.14.5","postcss": "^8.5.10","prettier": "^3.8.3","tailwindcss": "^4.1.10",@@ -4650,7 +4656,6 @@"resolved": "https://registry.npmjs.org/@tiptap/extension-bubble-menu/-/extension-bubble-menu-3.31.3.tgz","integrity": "sha512-EV6ZnwKc++2OM/OcD54n8s1B7C9LP7GKAtdEPwu0t3BYJf3sG8Ueoinf7SgGPO9oMPg96GneOkDNm1urMV167g==","license": "MIT",- "optional": true,"dependencies": {"@floating-ui/dom": "^1.0.0"},@@ -4734,7 +4739,6 @@"resolved": "https://registry.npmjs.org/@tiptap/extension-floating-menu/-/extension-floating-menu-3.31.3.tgz","integrity": "sha512-rd4VJ9PGSP9Eop8ZTEwaLZcMzMXLuJKe3hUNf58rq+zANpwM+9fI+vB7g9MAc3eXwUNDxNDVACFIL2oeBqpQ3A==","license": "MIT",- "optional": true,"funding": {"type": "github","url": "https://github.com/sponsors/ueberdosis"@@ -4935,6 +4939,20 @@"@tiptap/core": "3.31.3"}},+ "node_modules/@tiptap/extension-table": {+ "version": "3.31.3",+ "resolved": "https://registry.npmjs.org/@tiptap/extension-table/-/extension-table-3.31.3.tgz",+ "integrity": "sha512-7cnVPHhdiGGeauYqca6JVyPLTqZbqFEEk9nn2e2E8+fBo6zVtV07AktJBqth/XEzjZxcUmGxjoeuWYAisWjUHg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/ueberdosis"+ },+ "peerDependencies": {+ "@tiptap/core": "3.31.3",+ "@tiptap/pm": "3.31.3"+ }+ },"node_modules/@tiptap/extension-task-item": {"version": "3.31.3","resolved": "https://registry.npmjs.org/@tiptap/extension-task-item/-/extension-task-item-3.31.3.tgz",@@ -5295,6 +5313,13 @@"integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==","license": "MIT"},+ "node_modules/@types/whatwg-mimetype": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz",+ "integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/ws": {"version": "8.18.1","resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",@@ -6486,6 +6511,19 @@"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==","license": "MIT"},+ "node_modules/buffer-image-size": {+ "version": "0.6.4",+ "resolved": "https://registry.npmjs.org/buffer-image-size/-/buffer-image-size-0.6.4.tgz",+ "integrity": "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ },+ "engines": {+ "node": ">=4.0"+ }+ },"node_modules/builder-util": {"version": "26.15.3","resolved": "https://registry.npmjs.org/builder-util/-/builder-util-26.15.3.tgz",@@ -8873,6 +8911,38 @@"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==","license": "ISC"},+ "node_modules/happy-dom": {+ "version": "20.14.5",+ "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.14.5.tgz",+ "integrity": "sha512-x/RzkpWO40bTjIoT30iQtt64FLLmH/iRcUCN2X//bLx7H3ifkdfPXyqsro/OYtqzIAhiLMMA7mmiOR9C3NOKjQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": ">=20.0.0",+ "@types/whatwg-mimetype": "^3.0.2",+ "@types/ws": "^8.18.1",+ "buffer-image-size": "^0.6.4",+ "entities": "^7.0.1",+ "whatwg-mimetype": "^3.0.0",+ "ws": "^8.21.0"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/happy-dom/node_modules/entities": {+ "version": "7.0.1",+ "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",+ "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=0.12"+ },+ "funding": {+ "url": "https://github.com/fb55/entities?sponsor=1"+ }+ },"node_modules/has-flag": {"version": "4.0.0","resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",@@ -13565,6 +13635,16 @@"tslib": "^2.8.1"}},+ "node_modules/whatwg-mimetype": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz",+ "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=12"+ }+ },"node_modules/which": {"version": "2.0.2","resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",diff --git a/package.json b/package.jsonindex 53f44882f..26be1eb77 100644--- a/package.json+++ b/package.json@@ -113,6 +113,7 @@"eslint-plugin-react-refresh": "^0.5.2","espree": "^11.2.0","globals": "17.5.0",+ "happy-dom": "^20.14.5","postcss": "^8.5.10","prettier": "^3.8.3","tailwindcss": "^4.1.10",@@ -150,10 +151,15 @@"@radix-ui/react-tabs": "^1.1.12","@tanstack/react-virtual": "^3.13.2","@tiptap/core": "3.31.3",+ "@tiptap/extension-bubble-menu": "3.31.3",+ "@tiptap/extension-floating-menu": "3.31.3",+ "@tiptap/extension-horizontal-rule": "3.31.3","@tiptap/extension-mention": "3.31.3","@tiptap/extension-placeholder": "3.31.3",+ "@tiptap/extension-table": "3.31.3","@tiptap/extension-task-item": "3.31.3","@tiptap/extension-task-list": "3.31.3",+ "@tiptap/pm": "3.31.3","@tiptap/react": "3.31.3","@tiptap/starter-kit": "3.31.3","@tiptap/suggestion": "3.31.3",diff --git a/scripts/sync-nucleo-icons.js b/scripts/sync-nucleo-icons.jsindex 901aec381..25901f3f6 100644--- a/scripts/sync-nucleo-icons.js+++ b/scripts/sync-nucleo-icons.js@@ -87,7 +87,19 @@ import { createIcon } from "./createIcon";import * as Nucleo from "./nucleo";export type { IconComponent, IconProps } from "./createIcon";-export { Circle, Square } from "./primitives";+export {+ Bold,+ Circle,+ Heading,+ Italic,+ List,+ ListChecks,+ ListOrdered,+ Quote,+ Square,+ Strikethrough,+ Table,+} from "./primitives";${exportLines.join("\n")}`;diff --git a/src/components/CommandSearch.tsx b/src/components/CommandSearch.tsxindex f3be63e03..2098281a0 100644--- a/src/components/CommandSearch.tsx+++ b/src/components/CommandSearch.tsx@@ -59,12 +59,17 @@ type FlatItem =| { kind: "conversation"; conversation: ConversationResult };function stripMarkdownPreview(text: string): string {- return text- .replace(/#{1,6}\s+/g, "")- .replace(/[*_~`]+/g, "")- .replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")- .replace(/\n+/g, " ")- .trim();+ return (+ text+ .replace(/#{1,6}\s+/g, "")+ .replace(/[*_~`]+/g, "")+ .replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")+ // Table delimiter rows, then the pipes between cells.+ .replace(/^[ \t|:-]+$/gm, "")+ .replace(/\\?\|/g, " ")+ .replace(/\s+/g, " ")+ .trim()+ );}export default function CommandSearch({diff --git a/src/components/icons/index.ts b/src/components/icons/index.tsindex 23c90b83d..8d3afec80 100644--- a/src/components/icons/index.ts+++ b/src/components/icons/index.ts@@ -3,7 +3,19 @@ import { createIcon } from "./createIcon";import * as Nucleo from "./nucleo";export type { IconComponent, IconProps } from "./createIcon";-export { Circle, Square } from "./primitives";+export {+ Bold,+ Circle,+ Heading,+ Italic,+ List,+ ListChecks,+ ListOrdered,+ Quote,+ Square,+ Strikethrough,+ Table,+} from "./primitives";export const AlertCircle = createIcon("alert-circle", Nucleo.CircleWarningOutline24);export const AlertTriangle = createIcon("alert-triangle", Nucleo.TriangleWarningOutline24);diff --git a/src/components/icons/primitives.tsx b/src/components/icons/primitives.tsxindex a4b9b88fb..ce49c54db 100644--- a/src/components/icons/primitives.tsx+++ b/src/components/icons/primitives.tsx@@ -40,5 +40,119 @@ function SquareMark({ strokeWidth = 2, ...props }: MarkProps) {);}+// The note editor's formatting glyphs, drawn to the same 24px grid as the+// vendored Nucleo outline set (2px stroke, round caps, 3–21 bounds).+const glyph = (children: SVGProps<SVGSVGElement>["children"]) =>+ function Glyph({ strokeWidth = 2, ...props }: MarkProps) {+ return (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width={24}+ height={24}+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth={strokeWidth}+ strokeLinecap="round"+ strokeLinejoin="round"+ {...props}+ >+ {children}+ </svg>+ );+ };++const listRows = (x: number) => (+ <>+ <path d={`M${x} 6h11`} />+ <path d={`M${x} 12h11`} />+ <path d={`M${x} 18h11`} />+ </>+);++const BoldMark = glyph(+ <>+ <path d="M7 5h5.5a3.5 3.5 0 0 1 0 7H7z" />+ <path d="M7 12h6.5a3.5 3.5 0 0 1 0 7H7z" />+ </>+);++const ItalicMark = glyph(+ <>+ <path d="M10 5h8" />+ <path d="M6 19h8" />+ <path d="M14.5 5l-5 14" />+ </>+);++const StrikethroughMark = glyph(+ <>+ <path d="M4 12h16" />+ <path d="M16.5 8C16.5 6.2 14.5 5 12 5S7.5 6.2 7.5 8c0 1.5 1.3 2.5 3.5 3.2" />+ <path d="M7.5 16c0 1.8 2 3 4.5 3s4.5-1.2 4.5-3c0-.7-.2-1.3-.7-1.8" />+ </>+);++const HeadingMark = glyph(+ <>+ <path d="M6 5v14" />+ <path d="M18 5v14" />+ <path d="M6 12h12" />+ </>+);++const ListMark = glyph(+ <>+ {listRows(9)}+ <circle cx="4.5" cy="6" r="1.1" fill="currentColor" stroke="none" />+ <circle cx="4.5" cy="12" r="1.1" fill="currentColor" stroke="none" />+ <circle cx="4.5" cy="18" r="1.1" fill="currentColor" stroke="none" />+ </>+);++const ListOrderedMark = glyph(+ <>+ {listRows(9)}+ <path d="M3 4.5l1.5-1V8" />+ <path d="M3 14h2.5L3 18h2.5" />+ </>+);++const ListChecksMark = glyph(+ <>+ <path d="M9 7h11" />+ <path d="M9 17h11" />+ <path d="M3 7l1.5 1.5L7 6" />+ <path d="M3 17l1.5 1.5L7 15" />+ </>+);++const QuoteMark = glyph(+ <>+ <path d="M5 5v14" />+ <path d="M11 7h9" />+ <path d="M11 12h9" />+ <path d="M11 17h6" />+ </>+);++const TableMark = glyph(+ <>+ <rect x="3" y="4" width="18" height="16" rx="2" />+ <path d="M3 10h18" />+ <path d="M3 15h18" />+ <path d="M10 10v10" />+ </>+);+export const Circle = createIcon("circle", CircleMark);export const Square = createIcon("square", SquareMark);+export const Bold = createIcon("bold", BoldMark);+export const Heading = createIcon("heading", HeadingMark);+export const Italic = createIcon("italic", ItalicMark);+export const List = createIcon("list", ListMark);+export const ListChecks = createIcon("list-checks", ListChecksMark);+export const ListOrdered = createIcon("list-ordered", ListOrderedMark);+export const Quote = createIcon("quote", QuoteMark);+export const Strikethrough = createIcon("strikethrough", StrikethroughMark);+export const Table = createIcon("table", TableMark);diff --git a/src/components/ui/RichTextEditor.tsx b/src/components/ui/RichTextEditor.tsxindex 57785dce4..6951929bf 100644--- a/src/components/ui/RichTextEditor.tsx+++ b/src/components/ui/RichTextEditor.tsx@@ -1,12 +1,10 @@import { useEffect, useRef, useCallback, type MutableRefObject } from "react";import { useEditor, EditorContent, type Editor } from "@tiptap/react";-import StarterKit from "@tiptap/starter-kit";-import TaskList from "@tiptap/extension-task-list";-import TaskItem from "@tiptap/extension-task-item";-import Placeholder from "@tiptap/extension-placeholder";-import { Markdown } from "tiptap-markdown";import { cn } from "../lib/utils";import { createMentionExtension } from "./RichTextEditorMention";+import { createRichTextExtensions } from "./RichTextEditorExtensions";+import { RichTextEditorFormatMenu } from "./RichTextEditorFormatMenu";+import { RichTextEditorTableMenu } from "./RichTextEditorTableMenu";import type { MentionPerson } from "../../utils/mentionMarkdown";interface RichTextEditorProps {@@ -43,22 +41,7 @@ export function RichTextEditor({const editor = useEditor({extensions: [...(withMentions ? [createMentionExtension(() => mentionPeopleRef.current ?? [])] : []),- StarterKit.configure({- heading: { levels: [1, 2, 3] },- bulletList: { keepMarks: true },- orderedList: { keepMarks: true },- }),- TaskList,- TaskItem.configure({ nested: true }),- Placeholder.configure({- placeholder: placeholder || "",- emptyEditorClass: "is-editor-empty",- }),- Markdown.configure({- html: false,- transformPastedText: true,- transformCopiedText: true,- }),+ ...createRichTextExtensions(placeholder || ""),],content: value,editable: !disabled,@@ -122,12 +105,15 @@ export function RichTextEditor({<EditorContenteditor={editor}className={cn(- "h-full overflow-y-auto",+ // relative: the table menu positions against this scroller and scrolls with it.+ "relative h-full overflow-y-auto",disabled && "pointer-events-none opacity-70",// Reserved by an ancestor via --floating-inset; 0 elsewhere."pb-[var(--floating-inset,0px)]")}/>+ {editor && !disabled && <RichTextEditorFormatMenu editor={editor} />}+ {editor && !disabled && <RichTextEditorTableMenu editor={editor} />}</div>);}diff --git a/src/components/ui/RichTextEditorExtensions.ts b/src/components/ui/RichTextEditorExtensions.tsnew file mode 100644index 000000000..fc6cdbb5e--- /dev/null+++ b/src/components/ui/RichTextEditorExtensions.ts@@ -0,0 +1,36 @@+import StarterKit from "@tiptap/starter-kit";+import TaskList from "@tiptap/extension-task-list";+import TaskItem from "@tiptap/extension-task-item";+import Placeholder from "@tiptap/extension-placeholder";+import { Markdown } from "tiptap-markdown";+import { HorizontalRuleOutsideTables, markdownTableExtensions } from "./RichTextEditorTable";++/**+ * The note editor's schema and Markdown round-trip. Order matters: at equal+ * priority Tiptap runs later extensions' plugins first, and the table's Enter+ * handling and clipboard serializer must win over StarterKit's and+ * tiptap-markdown's.+ */+export function createRichTextExtensions(placeholder: string) {+ return [+ StarterKit.configure({+ heading: { levels: [1, 2, 3] },+ bulletList: { keepMarks: true },+ orderedList: { keepMarks: true },+ horizontalRule: false,+ }),+ HorizontalRuleOutsideTables,+ TaskList,+ TaskItem.configure({ nested: true }),+ Placeholder.configure({+ placeholder,+ emptyEditorClass: "is-editor-empty",+ }),+ Markdown.configure({+ html: false,+ transformPastedText: true,+ transformCopiedText: true,+ }),+ ...markdownTableExtensions,+ ];+}diff --git a/src/components/ui/RichTextEditorFormatMenu.tsx b/src/components/ui/RichTextEditorFormatMenu.tsxnew file mode 100644index 000000000..2fa239156--- /dev/null+++ b/src/components/ui/RichTextEditorFormatMenu.tsx@@ -0,0 +1,284 @@+import type { ReactNode } from "react";+import type { Editor } from "@tiptap/core";+import { NodeSelection, type EditorState } from "@tiptap/pm/state";+import { isInTable } from "@tiptap/pm/tables";+import { useEditorState } from "@tiptap/react";+import {+ BubbleMenu,+ FloatingMenu,+ type BubbleMenuProps,+ type FloatingMenuProps,+} from "@tiptap/react/menus";+import { useTranslation } from "react-i18next";+import {+ Bold,+ Check,+ ChevronDown,+ Code2,+ Heading,+ Italic,+ List,+ ListChecks,+ ListOrdered,+ Quote,+ Strikethrough,+ Table,+ type IconComponent,+} from "../icons";+import { cn } from "../lib/utils";+import { formatHotkeyLabel } from "../../utils/hotkeys";+import { Button } from "./button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "./dropdown-menu";+import {+ editorHasFocus,+ refocusEditor,+ runCommand,+ useHideOnFocusLeave,+ useMenuDropdown,+ type ChainCommand,+} from "./RichTextEditorMenus";+import { insertEmptyTable, isOnEmptyLine } from "./RichTextEditorTable";++interface FormatAction {+ key: string;+ icon: IconComponent;+ shortcut: string;+ run: ChainCommand;+}++const MARKS: FormatAction[] = [+ { key: "bold", icon: Bold, shortcut: "CommandOrControl+B", run: (c) => c.toggleBold() },+ { key: "italic", icon: Italic, shortcut: "CommandOrControl+I", run: (c) => c.toggleItalic() },+ {+ key: "strike",+ icon: Strikethrough,+ shortcut: "CommandOrControl+Shift+S",+ run: (c) => c.toggleStrike(),+ },+ { key: "code", icon: Code2, shortcut: "CommandOrControl+E", run: (c) => c.toggleCode() },+];++const BLOCKS: FormatAction[] = [+ {+ key: "bulletList",+ icon: List,+ shortcut: "CommandOrControl+Shift+8",+ run: (c) => c.toggleBulletList(),+ },+ {+ key: "orderedList",+ icon: ListOrdered,+ shortcut: "CommandOrControl+Shift+7",+ run: (c) => c.toggleOrderedList(),+ },+ {+ key: "taskList",+ icon: ListChecks,+ shortcut: "CommandOrControl+Shift+9",+ run: (c) => c.toggleTaskList(),+ },+ {+ key: "blockquote",+ icon: Quote,+ shortcut: "CommandOrControl+Shift+B",+ run: (c) => c.toggleBlockquote(),+ },+];++const HEADING_LEVELS = [1, 2, 3] as const;++const TEXT_STYLES: { key: string; level: number; run: ChainCommand }[] = [+ { key: "paragraph", level: 0, run: (c) => c.setParagraph() },+ ...HEADING_LEVELS.map((level) => ({+ key: `heading${level}`,+ level,+ run: (c) => c.setHeading({ level }),+ })),+];++const SELECTION_MENU = "formatSelectionMenu";+const LINE_MENU = "formatLineMenu";+const MENU_KEYS = [SELECTION_MENU, LINE_MENU];++// Tables have their own menu, and none of these actions belong in a code block:+// the marks don't apply there and a list would take the fence apart.+const canFormat = (editor: Editor, state: EditorState): boolean =>+ !editor.isDestroyed &&+ editor.isEditable &&+ editorHasFocus(editor.view) &&+ !isInTable(state) &&+ !editor.isActive("codeBlock");++// Above selected text.+const shouldShowOnSelection: BubbleMenuProps["shouldShow"] = ({ editor, state }) =>+ canFormat(editor, state) && !state.selection.empty && !(state.selection instanceof NodeSelection);++// On an empty top-level line, where a list, heading or table can start. The+// menu sits on the line itself, beside the caret, so it covers no text.+const shouldShowOnEmptyLine: FloatingMenuProps["shouldShow"] = ({ editor, state }) =>+ canFormat(editor, state) && isOnEmptyLine(state.selection);++/** A toggle when `active` is set, a plain button otherwise. */+function ToolbarButton({+ label,+ title = label,+ active,+ onClick,+ children,+}: {+ label: string;+ title?: string;+ active?: boolean;+ onClick: () => void;+ children: ReactNode;+}) {+ // A native title, not <Tooltip>: the menus detach the toolbar without+ // unmounting it, which would leave a hovered button's tooltip on screen.+ return (+ <Button+ size="icon"+ variant="ghost"+ title={title}+ aria-label={label}+ aria-pressed={active}+ onClick={onClick}+ className={cn(+ "h-7 w-7 rounded-md text-muted-foreground hover:bg-foreground/5 hover:text-foreground",+ active && "bg-foreground/10 text-foreground"+ )}+ >+ {children}+ </Button>+ );+}++const Separator = () => <div className="mx-0.5 h-4 w-px bg-border" aria-hidden="true" />;++function FormatToolbar({+ editor,+ dropdown,+}: {+ editor: Editor;+ dropdown: ReturnType<typeof useMenuDropdown>;+}) {+ const { t } = useTranslation();+ const active = useEditorState({+ editor,+ selector: ({ editor: current }) => ({+ actions: Object.fromEntries(+ [...MARKS, ...BLOCKS].map(({ key }) => [key, current.isActive(key)])+ ) as Record<string, boolean>,+ heading: HEADING_LEVELS.find((level) => current.isActive("heading", { level })) ?? 0,+ }),+ });++ const run = (command: ChainCommand) => runCommand(editor, command);+ const label = (key: string) => t(`notes.editor.format.${key}`);+ const actionButton = (action: FormatAction) => (+ <ToolbarButton+ key={action.key}+ label={label(action.key)}+ title={t("notes.editor.format.withShortcut", {+ action: label(action.key),+ shortcut: formatHotkeyLabel(action.shortcut),+ })}+ active={active.actions[action.key]}+ onClick={() => run(action.run)}+ >+ <action.icon size={15} />+ </ToolbarButton>+ );++ return (+ <div+ role="group"+ aria-label={label("toolbar")}+ className="flex items-center gap-0.5 rounded-lg border border-border bg-popover p-1 shadow-lg"+ // Keep focus and the selection in the editor: the commands apply to it.+ onMouseDown={(event) => event.preventDefault()}+ >+ {MARKS.map(actionButton)}+ <Separator />+ <DropdownMenu open={dropdown.open} onOpenChange={dropdown.setOpen}>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ title={label("textStyle")}+ aria-label={label("textStyle")}+ className={cn(+ "h-7 gap-0.5 rounded-md px-1.5 text-muted-foreground hover:bg-foreground/5 hover:text-foreground",+ active.heading > 0 && "bg-foreground/10 text-foreground"+ )}+ >+ <Heading size={15} />+ <ChevronDown size={11} />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ container={dropdown.container}+ align="start"+ className="min-w-40 p-1"+ onCloseAutoFocus={refocusEditor(editor)}+ >+ {TEXT_STYLES.map((style) => (+ <DropdownMenuItem+ key={style.key}+ className="text-xs gap-2 rounded-md px-2 py-1.5"+ onSelect={() => run(style.run)}+ >+ <span className="flex-1">{label(style.key)}</span>+ {active.heading === style.level && <Check size={12} />}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ <Separator />+ {BLOCKS.map(actionButton)}+ <Separator />+ <ToolbarButton+ label={label("table")}+ onClick={() => {+ editor.commands.focus();+ insertEmptyTable(editor);+ }}+ >+ <Table size={15} />+ </ToolbarButton>+ </div>+ );+}++/** Marks, text style, lists and tables for selected text or an empty line. */+export function RichTextEditorFormatMenu({ editor }: { editor: Editor }) {+ const onSelection = useMenuDropdown();+ const onEmptyLine = useMenuDropdown();+ useHideOnFocusLeave(editor, MENU_KEYS);+ return (+ <>+ <BubbleMenu+ ref={onSelection.menuRef}+ editor={editor}+ pluginKey={SELECTION_MENU}+ shouldShow={shouldShowOnSelection}+ options={onSelection.options}+ >+ <FormatToolbar editor={editor} dropdown={onSelection} />+ </BubbleMenu>+ <FloatingMenu+ ref={onEmptyLine.menuRef}+ className="rich-text-editor-line-menu"+ editor={editor}+ pluginKey={LINE_MENU}+ shouldShow={shouldShowOnEmptyLine}+ options={onEmptyLine.options}+ >+ <FormatToolbar editor={editor} dropdown={onEmptyLine} />+ </FloatingMenu>+ </>+ );+}diff --git a/src/components/ui/RichTextEditorMenus.ts b/src/components/ui/RichTextEditorMenus.tsnew file mode 100644index 000000000..394035093--- /dev/null+++ b/src/components/ui/RichTextEditorMenus.ts@@ -0,0 +1,74 @@+import { useEffect, useMemo, useRef, useState } from "react";+import type { ChainedCommands, Editor } from "@tiptap/core";+import type { EditorView } from "@tiptap/pm/view";+import type { BubbleMenuProps } from "@tiptap/react/menus";++// Shared by the note editor's floating menus (Tiptap BubbleMenu and FloatingMenu).++export type ChainCommand = (chain: ChainedCommands) => ChainedCommands;++/** Runs a command on the editor, which keeps the focus its menu button took. */+export const runCommand = (editor: Editor, command: ChainCommand) =>+ command(editor.chain().focus()).run();++/** Focus is in the editor or in a menu attached to it: the menus live in the editor's scroller. */+export const editorHasFocus = (view: EditorView) =>+ !!view.dom.parentElement?.contains(document.activeElement);++/**+ * Tiptap re-checks a menu only on editor changes and when the editor blurs, and a+ * click in a menu swallows the editor's next blur. So hide the menus whenever+ * focus leaves the editor and them, including from inside one (Tab).+ */+export function useHideOnFocusLeave(editor: Editor, pluginKeys: readonly string[]) {+ useEffect(() => {+ const scroller = editor.view.dom.parentElement;+ if (!scroller) return;+ const onFocusOut = (event: FocusEvent) => {+ // Switching windows leaves focus where it was, for when the window comes back.+ if (!document.hasFocus() || scroller.contains(event.relatedTarget as Node | null)) return;+ const target = event.target as Element;+ // An open dropdown holds on to focus (a dialog opened over it hands it back)+ // and returns it to the editor when it closes.+ if (target.closest('[role="menu"]')) return;+ // Chromium also fires focusout while it removes a focused element, before+ // detaching it. Whatever removes it (Tiptap hiding a menu) handles focus,+ // and a hide from here would interrupt that removal.+ queueMicrotask(() => {+ if (editor.isDestroyed || !target.isConnected) return;+ const tr = editor.state.tr;+ for (const key of pluginKeys) tr.setMeta(key, "hide");+ editor.view.dispatch(tr);+ });+ };+ scroller.addEventListener("focusout", onFocusOut);+ return () => scroller.removeEventListener("focusout", onFocusOut);+ }, [editor, pluginKeys]);+}++/**+ * A dropdown inside a menu, portaled into the menu element itself. Not into the+ * editor's scroller: EditorContent moves that element's children when a note+ * closes, and React could then no longer remove an open dropdown.+ *+ * Tiptap detaches that element to hide the menu without React unmounting what's+ * inside it, which would leave the dropdown open over a scroll-locked page. So+ * the dropdown is controlled and closes with the menu.+ */+export function useMenuDropdown(menuOptions?: BubbleMenuProps["options"]) {+ const menuRef = useRef<HTMLDivElement>(null);+ const [container, setContainer] = useState<HTMLDivElement | null>(null);+ const [open, setOpen] = useState(false);+ useEffect(() => setContainer(menuRef.current), []);+ // Stable: a menu dispatches a transaction whenever its props change.+ const options = useMemo(() => ({ ...menuOptions, onHide: () => setOpen(false) }), [menuOptions]);+ return { menuRef, container, open, setOpen, options };+}++/** Restore focus only while the note is still editable and mounted. */+export const refocusEditor =+ (editor: Editor): ((event: Event) => void) =>+ (event: Event): void => {+ event.preventDefault();+ if (!editor.isDestroyed && editor.isEditable) editor.commands.focus();+ };diff --git a/src/components/ui/RichTextEditorTable.ts b/src/components/ui/RichTextEditorTable.tsnew file mode 100644index 000000000..f86d806d4--- /dev/null+++ b/src/components/ui/RichTextEditorTable.ts@@ -0,0 +1,418 @@+import { InputRule, type Editor } from "@tiptap/core";+import HorizontalRule from "@tiptap/extension-horizontal-rule";+import { Table, TableCell, TableHeader, TableRow } from "@tiptap/extension-table";+import {+ DOMParser,+ Fragment,+ Slice,+ type Node as ProseMirrorNode,+ type Schema,+} from "@tiptap/pm/model";+import { closeHistory } from "@tiptap/pm/history";+import {+ Plugin,+ PluginKey,+ TextSelection,+ type EditorState,+ type Selection,+} from "@tiptap/pm/state";+import {+ CellSelection,+ TableMap,+ addRow,+ cellAround,+ handlePaste as pasteIntoCells,+ isInTable,+ nextCell,+ removeRow,+ selectedRect,+} from "@tiptap/pm/tables";+import { escapeTableCellPipes, parseTableHeaderRow } from "../../utils/markdownTable";++// Notes are stored as Markdown, and a GFM pipe table holds only a header row+// followed by body rows of one-line cells. These extensions keep every table in+// that shape, so the editor never shows a table that saving would change.++/** The prosemirror-markdown state tiptap-markdown passes to serializers. */+interface MarkdownSerializerState {+ nodes: unknown;+ marks: unknown;+ options: object;+ /** Everything written so far. */+ out: string;+ write(content?: string): void;+ ensureNewLine(): void;+ closeBlock(node: ProseMirrorNode): void;+ renderInline(parent: ProseMirrorNode, fromBlockStart?: boolean): void;+}++type MarkdownSerializerStateClass = new (+ nodes: unknown,+ marks: unknown,+ options: object+) => MarkdownSerializerState;++interface MarkdownStorage {+ markdown: { serializer: { serialize(content: Fragment): string } };+}++const markdownSerializer = (editor: Editor) =>+ (editor.storage as unknown as MarkdownStorage).markdown.serializer;++/** Joins any content into one paragraph; line breaks and block boundaries become spaces. */+function toSingleLine(content: Fragment, schema: Schema): ProseMirrorNode {+ const inline: ProseMirrorNode[] = [];+ let pendingSpace = false;+ const append = (node: ProseMirrorNode) => {+ if (pendingSpace && inline.length) inline.push(schema.text(" "));+ pendingSpace = false;+ inline.push(node);+ };+ const visit = (fragment: Fragment) =>+ fragment.forEach((node) => {+ if (node.isText) {+ append(schema.text(node.text.replace(/\n+/g, " "), node.marks));+ } else if (node.type === schema.linebreakReplacement) {+ append(schema.text(" ", node.marks));+ } else if (node.isInline) {+ append(node);+ } else {+ pendingSpace = true;+ visit(node.content);+ pendingSpace = true;+ }+ });+ visit(content);+ return schema.nodes.paragraph.create(null, inline);+}++/**+ * A cell holding one paragraph. Pasted cells can hold lists, headings or several+ * paragraphs, so they are flattened while parsing, before they can split the+ * table. GFM stores no alignment or column widths, so those are not read.+ */+const singleLineCell = (cell: typeof TableCell, tag: "td" | "th") =>+ cell.extend({+ content: "paragraph",+ parseHTML: () => [+ {+ tag,+ getContent: (dom: globalThis.Node, schema: Schema) =>+ Fragment.from(toSingleLine(DOMParser.fromSchema(schema).parseSlice(dom).content, schema)),+ },+ ],+ addAttributes() {+ return {+ ...this.parent?.(),+ colwidth: { default: null, parseHTML: () => null },+ align: { default: null, parseHTML: () => null },+ };+ },+ });++/** Rebuilds a table with merged cells as a plain grid; a merged cell's text stays in its first slot. */+function unmergeCells(table: ProseMirrorNode, map: TableMap, schema: Schema): ProseMirrorNode {+ const { tableRow, tableHeader, tableCell } = schema.nodes;+ const seen = new Set<number>();+ const rows: ProseMirrorNode[] = [];+ for (let row = 0; row < map.height; row++) {+ const cells: ProseMirrorNode[] = [];+ for (let col = 0; col < map.width; col++) {+ const offset = map.map[row * map.width + col];+ const content = seen.has(offset) ? undefined : table.nodeAt(offset).content;+ seen.add(offset);+ cells.push((row === 0 ? tableHeader : tableCell).createAndFill(null, content));+ }+ rows.push(tableRow.create(null, cells));+ }+ return table.type.create(table.attrs, rows);+}++function normalizeTables(state: EditorState) {+ const { schema, tr } = state;+ state.doc.descendants((node, pos) => {+ if (node.type.name !== "table") return !node.isTextblock;+ const map = TableMap.get(node);+ // prosemirror-tables repairs these in its own appendTransaction, which runs this again.+ if (map.problems) return false;+ if (new Set(map.map).size < map.map.length) {+ const from = tr.mapping.map(pos);+ tr.replaceWith(from, from + node.nodeSize, unmergeCells(node, map, schema));+ return false;+ }+ node.forEach((row, rowOffset, rowIndex) =>+ row.forEach((cell, cellOffset) => {+ const cellPos = pos + 1 + rowOffset + 1 + cellOffset;+ const type = rowIndex === 0 ? schema.nodes.tableHeader : schema.nodes.tableCell;+ if (cell.type !== type) tr.setNodeMarkup(tr.mapping.map(cellPos), type, cell.attrs);+ cell.firstChild.forEach((child, offset) => {+ if (child.type !== schema.linebreakReplacement) return;+ const at = tr.mapping.map(cellPos + 2 + offset);+ tr.replaceWith(at, at + 1, schema.text(" ", child.marks));+ });+ })+ );+ return false;+ });+ return tr.docChanged ? tr : null;+}++/**+ * A table on its own, or rows copied from one, which prosemirror-tables pastes+ * cell by cell. Bare cells don't count: several paragraphs pasted into a cell+ * arrive as bare cells, since a cell holds only one paragraph.+ */+function isCellPaste(content: Fragment): boolean {+ const roles: string[] = [];+ content.forEach((node) => roles.push(node.type.spec.tableRole));+ return (+ (roles.length === 1 && roles[0] === "table") ||+ (roles.length > 0 && roles.every((role) => role === "row"))+ );+}++const isRowEmpty = (row: ProseMirrorNode) => {+ let empty = true;+ row.forEach((cell) => {+ if (cell.firstChild.childCount) empty = false;+ });+ return empty;+};++/**+ * Enter in a cell moves to the cell below, adding a row from the last one. On an+ * empty last row it removes the row and leaves the table, like Enter on an empty+ * list item.+ */+function enterInCell({ state, view }: Editor): boolean {+ const $cell = cellAround(state.selection.$head);+ if (!$cell) return false;+ const tr = state.tr;+ const $below = nextCell($cell, "vert", 1);+ if ($below) {+ tr.setSelection(TextSelection.create(tr.doc, $below.pos + $below.nodeAfter.nodeSize - 2));+ } else {+ const rect = selectedRect(state);+ const tablePos = rect.tableStart - 1;+ const lastRow = rect.bottom - 1;+ if (lastRow > 0 && isRowEmpty(rect.table.child(lastRow))) {+ removeRow(tr, rect, lastRow);+ const after = tablePos + tr.doc.nodeAt(tablePos).nodeSize;+ const next = tr.doc.nodeAt(after);+ if (next?.type !== state.schema.nodes.paragraph || next.content.size) {+ tr.insert(after, state.schema.nodes.paragraph.create());+ }+ tr.setSelection(TextSelection.create(tr.doc, after + 1));+ } else {+ addRow(tr, rect, rect.bottom);+ const table = tr.doc.nodeAt(tablePos);+ const cellPos = TableMap.get(table).positionAt(rect.bottom, rect.left, table);+ tr.setSelection(TextSelection.create(tr.doc, rect.tableStart + cellPos + 2));+ }+ }+ view.dispatch(tr.scrollIntoView());+ return true;+}++/** Enter at the end of a typed `| Item | Cost |` line turns it into a table. */+function createTableFromHeaderRow({ state, view }: Editor): boolean {+ const { $from, empty } = state.selection;+ const { schema } = state;+ const line = $from.parent;+ if (!empty || line.type !== schema.nodes.paragraph || $from.parentOffset !== line.content.size) {+ return false;+ }+ // Line breaks and mentions read as newlines, which no header row contains.+ const labels = parseTableHeaderRow(line.textBetween(0, line.content.size, undefined, "\n"));+ const index = $from.index(-1);+ if (!labels || !$from.node(-1).canReplaceWith(index, index + 1, schema.nodes.table)) {+ return false;+ }+ const table = buildTable(schema, labels, 1);+ const from = $from.before();+ // Its own undo step, so undo gives back the typed line.+ const tr = closeHistory(state.tr).replaceWith(from, $from.after(), table);+ // Table open, header row, body row open, cell open, paragraph open.+ tr.setSelection(TextSelection.create(tr.doc, from + 1 + table.firstChild.nodeSize + 3));+ view.dispatch(tr.scrollIntoView());+ return true;+}++/** A header row with these labels, then `bodyRows` empty rows. */+function buildTable(schema: Schema, labels: string[], bodyRows: number): ProseMirrorNode {+ const { table, tableRow, tableHeader, tableCell, paragraph } = schema.nodes;+ const header = tableRow.create(+ null,+ labels.map((label) =>+ tableHeader.create(null, paragraph.create(null, label ? schema.text(label) : null))+ )+ );+ const body = Array.from({ length: bodyRows }, () =>+ tableRow.create(+ null,+ labels.map(() => tableCell.createAndFill())+ )+ );+ return table.create(null, [header, ...body]);+}++/** An empty top-level line: the formatting toolbar shows there, and Insert table replaces it. */+export const isOnEmptyLine = ({ empty, $from }: Selection) =>+ empty &&+ $from.depth === 1 &&+ $from.parent.type.name === "paragraph" &&+ !$from.parent.content.size;++/**+ * Inserts an empty three-column table in place of an empty top-level line, or+ * after the top-level block holding the selection, and puts the caret in its+ * first header cell.+ */+export function insertEmptyTable({ state, view }: Editor): void {+ const { $from, $to } = state.selection;+ const onEmptyLine = isOnEmptyLine(state.selection);+ const from = onEmptyLine ? $from.before() : $to.depth ? $to.after(1) : state.doc.content.size;+ const tr = closeHistory(state.tr).replaceWith(+ from,+ onEmptyLine ? $from.after() : from,+ buildTable(state.schema, ["", "", ""], 2)+ );+ // Table open, header row open, cell open, paragraph open.+ tr.setSelection(TextSelection.create(tr.doc, from + 4));+ view.dispatch(tr.scrollIntoView());+}++const MarkdownTable = Table.extend({+ addStorage() {+ return {+ markdown: {+ serialize(state: MarkdownSerializerState, node: ProseMirrorNode) {+ // Each cell renders in a state of its own and is escaped as a finished+ // string: rewriting the table's shared output would shift the mark+ // positions tiptap-markdown records for trimming.+ const CellState = state.constructor as MarkdownSerializerStateClass;+ const renderCell = (cell: ProseMirrorNode) => {+ const cellState = new CellState(state.nodes, state.marks, state.options);+ // Mid-line, so a leading "-", "+" or "1." is not escaped.+ cellState.renderInline(cell.firstChild, false);+ return escapeTableCellPipes(cellState.out);+ };+ node.forEach((row, _offset, rowIndex) => {+ const cells: string[] = [];+ row.forEach((cell) => cells.push(renderCell(cell)));+ state.write(`| ${cells.join(" | ")} |`);+ state.ensureNewLine();+ if (rowIndex === 0) {+ state.write(`| ${cells.map(() => "---").join(" | ")} |`);+ state.ensureNewLine();+ }+ });+ state.closeBlock(node);+ },+ parse: {},+ },+ };+ },++ addKeyboardShortcuts() {+ const insideTable = () => isInTable(this.editor.state);+ return {+ ...this.parent?.(),+ Enter: () => enterInCell(this.editor) || createTableFromHeaderRow(this.editor),+ // A GFM cell cannot hold a line break.+ "Shift-Enter": insideTable,+ "Mod-Enter": insideTable,+ };+ },++ addProseMirrorPlugins() {+ const editor = this.editor;+ return [+ new Plugin({+ key: new PluginKey("markdownTable"),+ appendTransaction: (transactions, _oldState, state) =>+ transactions.some((tr) => tr.docChanged) ? normalizeTables(state) : null,+ props: {+ // A pasted table or rows go to prosemirror-tables, which fills cells+ // from the caret. Anything else pasted into a table, such as several+ // paragraphs or a table followed by text, is flattened to one line; over+ // selected cells, prosemirror-tables then puts that line in each. This+ // is paste only: a drop lands at the pointer, not at the selection.+ handlePaste: (view, event, slice) => {+ if (!isInTable(view.state) || isCellPaste(slice.content)) return false;+ const line = new Slice(+ Fragment.from(toSingleLine(slice.content, view.state.schema)),+ 1,+ 1+ );+ // Nothing to insert, such as a screenshot or a pasted rule: leave the+ // table alone. Replacing would delete selected text, and+ // prosemirror-tables would empty selected cells.+ if (!line.size) return true;+ if (view.state.selection instanceof CellSelection) {+ return pasteIntoCells(view, event, line);+ }+ view.dispatch(+ view.state.tr+ .replaceSelection(line)+ .scrollIntoView()+ .setMeta("paste", true)+ .setMeta("uiEvent", "paste")+ );+ return true;+ },+ // Copied cells arrive as bare rows; one cell (a triple-click) copies as its+ // text, and an empty one as a space, since "" would fall through to+ // tiptap-markdown's "[tableRow]". Text copied inside one cell arrives+ // wrapped in every node around that cell. Anything else falls through+ // to tiptap-markdown.+ clipboardTextSerializer: (slice) => {+ const serializer = markdownSerializer(editor);+ const first = slice.content.firstChild;+ if (first?.type.spec.tableRole === "row") {+ return slice.content.childCount === 1 && first.childCount === 1+ ? serializer.serialize(first.firstChild.content) || " "+ : serializer.serialize(+ Fragment.from(editor.schema.nodes.table.create(null, slice.content))+ );+ }+ let content = slice.content;+ for (let depth = slice.openStart; depth > 0 && content.childCount === 1; depth--) {+ const node = content.firstChild;+ if (node.type.spec.tableRole?.endsWith("cell")) {+ return serializer.serialize(node.content);+ }+ content = node.content;+ }+ return "";+ },+ },+ }),+ ...(this.parent?.() ?? []),+ ];+ },+});++/**+ * Typing "---" inserts a rule before the current block. In a cell that splits+ * the table, so there the shortcut stays text. Replaces StarterKit's rule.+ */+export const HorizontalRuleOutsideTables = HorizontalRule.extend({+ addInputRules() {+ return (this.parent?.() ?? []).map(+ (rule) =>+ new InputRule({+ find: rule.find,+ handler: (props) => (isInTable(props.state) ? null : rule.handler(props)),+ undoable: rule.undoable,+ })+ );+ },+});++export const markdownTableExtensions = [+ MarkdownTable,+ TableRow,+ singleLineCell(TableHeader, "th"),+ singleLineCell(TableCell, "td"),+];diff --git a/src/components/ui/RichTextEditorTableMenu.tsx b/src/components/ui/RichTextEditorTableMenu.tsxnew file mode 100644index 000000000..02405fe5b--- /dev/null+++ b/src/components/ui/RichTextEditorTableMenu.tsx@@ -0,0 +1,156 @@+import { useCallback } from "react";+import { findParentNode, type Editor } from "@tiptap/core";+import { isInTable, selectedRect } from "@tiptap/pm/tables";+import { BubbleMenu, type BubbleMenuProps } from "@tiptap/react/menus";+import { useTranslation } from "react-i18next";+import { MoreHorizontal } from "../icons";+import { cn } from "../lib/utils";+import { Button } from "./button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "./dropdown-menu";+import {+ editorHasFocus,+ refocusEditor,+ runCommand,+ useHideOnFocusLeave,+ useMenuDropdown,+ type ChainCommand,+} from "./RichTextEditorMenus";++const findTable = findParentNode((node) => node.type.name === "table");++function getTableElement(editor: Editor): HTMLTableElement | null {+ const table = findTable(editor.state.selection);+ // Tiptap's TableView renders every table inside a wrapper div.+ return table ? (editor.view.nodeDOM(table.pos) as HTMLElement).querySelector("table") : null;+}++// Beside the header row, or above the table when there is no room beside it.+// Shifting on both axes keeps it inside the scroller when a wide table starts the+// note. BubbleMenu applies `offset` after `shift`, which would push it back out,+// so the gap is padding on the menu instead (pl-1.5 pb-1.5 below).+const MENU_OPTIONS: BubbleMenuProps["options"] = {+ placement: "right-start",+ offset: false,+ flip: { fallbackPlacements: ["top-end"] },+ shift: { crossAxis: true },+};++const PLUGIN_KEY = "tableMenu";+const PLUGIN_KEYS = [PLUGIN_KEY];++const shouldShowMenu: BubbleMenuProps["shouldShow"] = ({ editor, view }) =>+ editor.isEditable && editor.isActive("table") && editorHasFocus(view);++/**+ * Rendered only while the menu is open, from the current selection. The note can+ * re-render it after Delete table, when the caret has already left the table, and+ * a read-only editor offers no actions.+ */+function TableActions({ editor }: { editor: Editor }) {+ const { t } = useTranslation();+ if (!editor.isEditable || !isInTable(editor.state)) return null;+ const rect = selectedRect(editor.state);++ const run = (command: ChainCommand) => runCommand(editor, command);++ // Tables follow the note's text direction, so "left" is the next column in RTL.+ const addColumn = (side: "left" | "right") => {+ const table = getTableElement(editor);+ const rtl = !!table && getComputedStyle(table).direction === "rtl";+ run((chain) => ((side === "left") !== rtl ? chain.addColumnBefore() : chain.addColumnAfter()));+ };++ const item = (+ label: string,+ onSelect: () => void,+ { disabled = false, destructive = false } = {}+ ) => (+ <DropdownMenuItem+ className={cn(+ "text-xs rounded-md px-2 py-1.5",+ destructive && "text-destructive focus:bg-destructive/10 focus:text-destructive"+ )}+ disabled={disabled}+ onSelect={onSelect}+ >+ {label}+ </DropdownMenuItem>+ );++ return (+ <>+ {item(+ t("notes.editor.table.insertRowAbove"),+ () => run((chain) => chain.addRowBefore()),+ // A row above the header would take over as the header.+ { disabled: rect.top === 0 }+ )}+ {item(t("notes.editor.table.insertRowBelow"), () => run((chain) => chain.addRowAfter()))}+ {item(t("notes.editor.table.insertColumnLeft"), () => addColumn("left"))}+ {item(t("notes.editor.table.insertColumnRight"), () => addColumn("right"))}+ <DropdownMenuSeparator />+ {/* prosemirror-tables won't delete every row or column; Delete table does that. */}+ {item(t("notes.editor.table.deleteRow"), () => run((chain) => chain.deleteRow()), {+ disabled: rect.top === 0 && rect.bottom === rect.map.height,+ })}+ {item(t("notes.editor.table.deleteColumn"), () => run((chain) => chain.deleteColumn()), {+ disabled: rect.left === 0 && rect.right === rect.map.width,+ })}+ {item(t("notes.editor.table.deleteTable"), () => run((chain) => chain.deleteTable()), {+ destructive: true,+ })}+ </>+ );+}++/** Row and column actions for the table holding the caret. */+export function RichTextEditorTableMenu({ editor }: { editor: Editor }) {+ const { t } = useTranslation();+ const { menuRef, container, open, setOpen, options } = useMenuDropdown(MENU_OPTIONS);+ useHideOnFocusLeave(editor, PLUGIN_KEYS);++ // Stable, like the options above: BubbleMenu dispatches a transaction whenever these change.+ const getReferencedVirtualElement = useCallback(() => {+ const table = getTableElement(editor);+ return table && { getBoundingClientRect: () => table.getBoundingClientRect() };+ }, [editor]);++ return (+ <BubbleMenu+ ref={menuRef}+ editor={editor}+ pluginKey={PLUGIN_KEY}+ shouldShow={shouldShowMenu}+ getReferencedVirtualElement={getReferencedVirtualElement}+ options={options}+ className="pl-1.5 pb-1.5"+ >+ <DropdownMenu open={open} onOpenChange={setOpen}>+ <DropdownMenuTrigger asChild>+ <Button+ size="icon"+ variant="ghost"+ aria-label={t("notes.editor.table.actions")}+ className="h-6 w-6 rounded-md border border-border bg-popover text-muted-foreground shadow-sm hover:text-foreground hover:bg-foreground/5"+ >+ <MoreHorizontal size={14} />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ container={container}+ align="end"+ className="min-w-44 p-1"+ onCloseAutoFocus={refocusEditor(editor)}+ >+ <TableActions editor={editor} />+ </DropdownMenuContent>+ </DropdownMenu>+ </BubbleMenu>+ );+}diff --git a/src/components/ui/dropdown-menu.tsx b/src/components/ui/dropdown-menu.tsxindex 7b0390ae0..d59337dec 100644--- a/src/components/ui/dropdown-menu.tsx+++ b/src/components/ui/dropdown-menu.tsx@@ -54,9 +54,12 @@ DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayNamconst DropdownMenuContent = React.forwardRef<React.ElementRef<typeof DropdownMenuPrimitive.Content>,- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>->(({ className, sideOffset = 4, ...props }, ref) => (- <DropdownMenuPrimitive.Portal>+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content> & {+ /** Where the menu is portaled; defaults to document.body. */+ container?: HTMLElement | null;+ }+>(({ className, sideOffset = 4, container, ...props }, ref) => (+ <DropdownMenuPrimitive.Portal container={container}><DropdownMenuPrimitive.Contentref={ref}sideOffset={sideOffset}diff --git a/src/helpers/builtinActions.js b/src/helpers/builtinActions.jsindex 377133752..bd60c9ae4 100644--- a/src/helpers/builtinActions.js+++ b/src/helpers/builtinActions.js@@ -156,7 +156,7 @@ export const BASE_SYSTEM_PROMPT = `You are a note enhancement assistant. The useFORMAT RULES (strict):- Do NOT include any preamble: no title, no date/time/location, no attendee list, no topic header. Start directly with the content.-- Do NOT use tables, horizontal rules, or block quotes.+- Do NOT use horizontal rules or block quotes. Use a table only when the instructions ask for one.- Do NOT list or guess participant names/roles.- Keep the tone professional and concise. Bias toward brevity.@@ -169,7 +169,7 @@ Your job is to produce clean, actionable meeting notes in markdown. Follow theseFORMAT RULES (strict):- Do NOT include any preamble: no title, no "# Meeting Notes", no date/time/location, no attendee list, no topic header. Start directly with the summary.- Do NOT reproduce the Meeting Context block in the output.-- Do NOT use tables, horizontal rules, or block quotes.+- Do NOT use horizontal rules or block quotes. Use a table only when the instructions ask for one.- Refer to people only by the speaker labels used in the transcript. NEVER guess or invent an identity: the note owner is who the Meeting Context says they are — never a name mentioned in conversation. Keep unnamed speakers as "Them" or "Speaker N".- Start with a concise 1–2 sentence summary of what the meeting was about.- Use clear section headings: ## Key Discussion Points, ## Decisions Made, ## Action Items, ## Follow-ups (omit any section that has no content).diff --git a/src/index.css b/src/index.cssindex 7c2a42bce..01aa72d33 100644--- a/src/index.css+++ b/src/index.css@@ -1812,6 +1812,47 @@ a:hover {color: oklch(0.5 0 0 / 0.4);}+/* Tables (GFM: a header row, then one-line cells) */+.rich-text-editor-content .tableWrapper {+ overflow-x: auto;+ margin: 0.5rem 0;+}++.rich-text-editor-content table {+ border-collapse: collapse;+}++.rich-text-editor-content th,+.rich-text-editor-content td {+ min-width: 5rem;+ padding: 0.25rem 0.625rem;+ border: 1px solid var(--color-border);+ text-align: start;+ vertical-align: top;+}++.rich-text-editor-content th {+ font-weight: 600;+ background: oklch(0.5 0 0 / 0.04);+}++.rich-text-editor-content th p,+.rich-text-editor-content td p {+ margin: 0;+}++/* prosemirror-tables marks each cell of a cell selection. The .dark selector+ wins over the dark header background below. */+.rich-text-editor-content .selectedCell,+.dark .rich-text-editor-content .selectedCell {+ background: oklch(0.62 0.22 260 / 0.15);+}++/* Tiptap draws the gap cursor (e.g. above a table that starts the note) in black. */+.rich-text-editor-content .ProseMirror-gapcursor:after {+ border-top-color: var(--color-foreground);+}+/* Placeholder */.rich-text-editor-content p.is-editor-empty:first-child::before {content: attr(data-placeholder);@@ -1821,6 +1862,11 @@ a:hover {height: 0;}+/* The empty-line format toolbar sits where the placeholder would show. */+.rich-text-editor-content:has(~ .rich-text-editor-line-menu) p.is-editor-empty:first-child::before {+ content: none;+}+/* Dark mode adjustments */.dark .rich-text-editor-content li::marker {color: oklch(0.7 0 0 / 0.4);@@ -1843,6 +1889,10 @@ a:hover {color: oklch(0.7 0 0 / 0.4);}+.dark .rich-text-editor-content th {+ background: oklch(0.8 0 0 / 0.06);+}+.dark .rich-text-editor-content p.is-editor-empty:first-child::before {color: oklch(0.7 0 0 / 0.2);}diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.jsonindex 89ed6e37b..bc805a7d0 100644--- a/src/locales/ar/translation.json+++ b/src/locales/ar/translation.json@@ -1647,7 +1647,35 @@"conversationWillAppear": "ستظهر المحادثة هنا...","linkedEvent": "الحدث المرتبط","noFolder": "بدون مجلد",- "participants": "المشاركون"+ "participants": "المشاركون",+ "table": {+ "actions": "إجراءات الجدول",+ "insertRowAbove": "إدراج صف أعلى",+ "insertRowBelow": "إدراج صف أسفل",+ "insertColumnLeft": "إدراج عمود إلى اليسار",+ "insertColumnRight": "إدراج عمود إلى اليمين",+ "deleteRow": "حذف الصف",+ "deleteColumn": "حذف العمود",+ "deleteTable": "حذف الجدول"+ },+ "format": {+ "toolbar": "التنسيق",+ "withShortcut": "{{action}} ({{shortcut}})",+ "bold": "غامق",+ "italic": "مائل",+ "strike": "يتوسطه خط",+ "code": "تعليمات برمجية",+ "textStyle": "نمط النص",+ "paragraph": "نص عادي",+ "heading1": "عنوان 1",+ "heading2": "عنوان 2",+ "heading3": "عنوان 3",+ "bulletList": "قائمة نقطية",+ "orderedList": "قائمة مرقمة",+ "taskList": "قائمة مهام",+ "blockquote": "اقتباس",+ "table": "إدراج جدول"+ }},"participants": {"attendee": "حاضر",diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 5141eb50e..85147b4ab 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -3311,7 +3311,35 @@"conversationWillAppear": "Gespräch wird hier angezeigt...","linkedEvent": "Verknüpftes Ereignis","noFolder": "Kein Ordner",- "participants": "Teilnehmer"+ "participants": "Teilnehmer",+ "table": {+ "actions": "Tabellenaktionen",+ "insertRowAbove": "Zeile oberhalb einfügen",+ "insertRowBelow": "Zeile unterhalb einfügen",+ "insertColumnLeft": "Spalte links einfügen",+ "insertColumnRight": "Spalte rechts einfügen",+ "deleteRow": "Zeile löschen",+ "deleteColumn": "Spalte löschen",+ "deleteTable": "Tabelle löschen"+ },+ "format": {+ "toolbar": "Formatierung",+ "withShortcut": "{{action}} ({{shortcut}})",+ "bold": "Fett",+ "italic": "Kursiv",+ "strike": "Durchgestrichen",+ "code": "Code",+ "textStyle": "Textstil",+ "paragraph": "Normaler Text",+ "heading1": "Überschrift 1",+ "heading2": "Überschrift 2",+ "heading3": "Überschrift 3",+ "bulletList": "Aufzählung",+ "orderedList": "Nummerierte Liste",+ "taskList": "Checkliste",+ "blockquote": "Zitat",+ "table": "Tabelle einfügen"+ }},"participants": {"attendee": "Teilnehmer",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex ae051e337..2a4c14e66 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -3311,7 +3311,35 @@"conversationWillAppear": "Conversation will appear here...","linkedEvent": "Linked event","noFolder": "No folder",- "participants": "Participants"+ "participants": "Participants",+ "table": {+ "actions": "Table actions",+ "insertRowAbove": "Insert row above",+ "insertRowBelow": "Insert row below",+ "insertColumnLeft": "Insert column left",+ "insertColumnRight": "Insert column right",+ "deleteRow": "Delete row",+ "deleteColumn": "Delete column",+ "deleteTable": "Delete table"+ },+ "format": {+ "toolbar": "Formatting",+ "withShortcut": "{{action}} ({{shortcut}})",+ "bold": "Bold",+ "italic": "Italic",+ "strike": "Strikethrough",+ "code": "Code",+ "textStyle": "Text style",+ "paragraph": "Normal text",+ "heading1": "Heading 1",+ "heading2": "Heading 2",+ "heading3": "Heading 3",+ "bulletList": "Bulleted list",+ "orderedList": "Numbered list",+ "taskList": "Checklist",+ "blockquote": "Quote",+ "table": "Insert table"+ }},"participants": {"attendee": "attendee",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex bcf7e1778..d249f83d0 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -3021,7 +3021,35 @@"conversationWillAppear": "La conversación aparecerá aquí...","linkedEvent": "Evento vinculado","noFolder": "Sin carpeta",- "participants": "Participantes"+ "participants": "Participantes",+ "table": {+ "actions": "Acciones de tabla",+ "insertRowAbove": "Insertar fila arriba",+ "insertRowBelow": "Insertar fila abajo",+ "insertColumnLeft": "Insertar columna a la izquierda",+ "insertColumnRight": "Insertar columna a la derecha",+ "deleteRow": "Eliminar fila",+ "deleteColumn": "Eliminar columna",+ "deleteTable": "Eliminar tabla"+ },+ "format": {+ "toolbar": "Formato",+ "withShortcut": "{{action}} ({{shortcut}})",+ "bold": "Negrita",+ "italic": "Cursiva",+ "strike": "Tachado",+ "code": "Código",+ "textStyle": "Estilo de texto",+ "paragraph": "Texto normal",+ "heading1": "Encabezado 1",+ "heading2": "Encabezado 2",+ "heading3": "Encabezado 3",+ "bulletList": "Lista con viñetas",+ "orderedList": "Lista numerada",+ "taskList": "Lista de verificación",+ "blockquote": "Cita",+ "table": "Insertar tabla"+ }},"participants": {"attendee": "asistente",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 6b802c424..0847eb034 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -3311,7 +3311,35 @@"conversationWillAppear": "La conversation apparaîtra ici...","linkedEvent": "Événement lié","noFolder": "Aucun dossier",- "participants": "Participants"+ "participants": "Participants",+ "table": {+ "actions": "Actions du tableau",+ "insertRowAbove": "Insérer une ligne au-dessus",+ "insertRowBelow": "Insérer une ligne en dessous",+ "insertColumnLeft": "Insérer une colonne à gauche",+ "insertColumnRight": "Insérer une colonne à droite",+ "deleteRow": "Supprimer la ligne",+ "deleteColumn": "Supprimer la colonne",+ "deleteTable": "Supprimer le tableau"+ },+ "format": {+ "toolbar": "Mise en forme",+ "withShortcut": "{{action}} ({{shortcut}})",+ "bold": "Gras",+ "italic": "Italique",+ "strike": "Barré",+ "code": "Code",+ "textStyle": "Style de texte",+ "paragraph": "Texte normal",+ "heading1": "Titre 1",+ "heading2": "Titre 2",+ "heading3": "Titre 3",+ "bulletList": "Liste à puces",+ "orderedList": "Liste numérotée",+ "taskList": "Liste de tâches",+ "blockquote": "Citation",+ "table": "Insérer un tableau"+ }},"participants": {"attendee": "participant",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 2534d2093..4767df3ca 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -2968,7 +2968,35 @@"conversationWillAppear": "La conversazione apparirà qui...","linkedEvent": "Evento collegato","noFolder": "Nessuna cartella",- "participants": "Partecipanti"+ "participants": "Partecipanti",+ "table": {+ "actions": "Azioni tabella",+ "insertRowAbove": "Inserisci riga sopra",+ "insertRowBelow": "Inserisci riga sotto",+ "insertColumnLeft": "Inserisci colonna a sinistra",+ "insertColumnRight": "Inserisci colonna a destra",+ "deleteRow": "Elimina riga",+ "deleteColumn": "Elimina colonna",+ "deleteTable": "Elimina tabella"+ },+ "format": {+ "toolbar": "Formattazione",+ "withShortcut": "{{action}} ({{shortcut}})",+ "bold": "Grassetto",+ "italic": "Corsivo",+ "strike": "Barrato",+ "code": "Codice",+ "textStyle": "Stile testo",+ "paragraph": "Testo normale",+ "heading1": "Titolo 1",+ "heading2": "Titolo 2",+ "heading3": "Titolo 3",+ "bulletList": "Elenco puntato",+ "orderedList": "Elenco numerato",+ "taskList": "Elenco di controllo",+ "blockquote": "Citazione",+ "table": "Inserisci tabella"+ }},"participants": {"attendee": "partecipante",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex 6fc47fef0..cbe87b35b 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -2862,7 +2862,35 @@"transcriptEmptyDescription": "録音ボタンを押すと文字起こしが始まります。話した内容がここにリアルタイムで表示されます。","startRecording": "録音を開始","generateSummary": "AI要約を生成",- "startWriting": "書き始める..."+ "startWriting": "書き始める...",+ "table": {+ "actions": "表の操作",+ "insertRowAbove": "上に行を挿入",+ "insertRowBelow": "下に行を挿入",+ "insertColumnLeft": "左に列を挿入",+ "insertColumnRight": "右に列を挿入",+ "deleteRow": "行を削除",+ "deleteColumn": "列を削除",+ "deleteTable": "表を削除"+ },+ "format": {+ "toolbar": "書式",+ "withShortcut": "{{action}}({{shortcut}})",+ "bold": "太字",+ "italic": "斜体",+ "strike": "取り消し線",+ "code": "コード",+ "textStyle": "テキストスタイル",+ "paragraph": "標準テキスト",+ "heading1": "見出し 1",+ "heading2": "見出し 2",+ "heading3": "見出し 3",+ "bulletList": "箇条書き",+ "orderedList": "番号付きリスト",+ "taskList": "チェックリスト",+ "blockquote": "引用",+ "table": "表を挿入"+ }},"participants": {"attendee": "名の参加者",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex 7c3f2eb8e..25d220411 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -2968,7 +2968,35 @@"conversationWillAppear": "A conversa aparecerá aqui...","linkedEvent": "Evento vinculado","noFolder": "Sem pasta",- "participants": "Participantes"+ "participants": "Participantes",+ "table": {+ "actions": "Ações da tabela",+ "insertRowAbove": "Inserir linha acima",+ "insertRowBelow": "Inserir linha abaixo",+ "insertColumnLeft": "Inserir coluna à esquerda",+ "insertColumnRight": "Inserir coluna à direita",+ "deleteRow": "Excluir linha",+ "deleteColumn": "Excluir coluna",+ "deleteTable": "Excluir tabela"+ },+ "format": {+ "toolbar": "Formatação",+ "withShortcut": "{{action}} ({{shortcut}})",+ "bold": "Negrito",+ "italic": "Itálico",+ "strike": "Tachado",+ "code": "Código",+ "textStyle": "Estilo de texto",+ "paragraph": "Texto normal",+ "heading1": "Título 1",+ "heading2": "Título 2",+ "heading3": "Título 3",+ "bulletList": "Lista com marcadores",+ "orderedList": "Lista numerada",+ "taskList": "Lista de verificação",+ "blockquote": "Citação",+ "table": "Inserir tabela"+ }},"participants": {"attendee": "participante",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex f8d81b5ab..b06994531 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -2988,7 +2988,35 @@"conversationWillAppear": "Разговор появится здесь...","linkedEvent": "Связанное событие","noFolder": "Без папки",- "participants": "Участники"+ "participants": "Участники",+ "table": {+ "actions": "Действия с таблицей",+ "insertRowAbove": "Вставить строку выше",+ "insertRowBelow": "Вставить строку ниже",+ "insertColumnLeft": "Вставить столбец слева",+ "insertColumnRight": "Вставить столбец справа",+ "deleteRow": "Удалить строку",+ "deleteColumn": "Удалить столбец",+ "deleteTable": "Удалить таблицу"+ },+ "format": {+ "toolbar": "Форматирование",+ "withShortcut": "{{action}} ({{shortcut}})",+ "bold": "Жирный",+ "italic": "Курсив",+ "strike": "Зачёркнутый",+ "code": "Код",+ "textStyle": "Стиль текста",+ "paragraph": "Обычный текст",+ "heading1": "Заголовок 1",+ "heading2": "Заголовок 2",+ "heading3": "Заголовок 3",+ "bulletList": "Маркированный список",+ "orderedList": "Нумерованный список",+ "taskList": "Список задач",+ "blockquote": "Цитата",+ "table": "Вставить таблицу"+ }},"participants": {"attendee": "участник",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex e2954a673..cef35a093 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -2968,7 +2968,35 @@"conversationWillAppear": "对话将显示在这里...","linkedEvent": "关联日程","noFolder": "无文件夹",- "participants": "参与者"+ "participants": "参与者",+ "table": {+ "actions": "表格操作",+ "insertRowAbove": "在上方插入行",+ "insertRowBelow": "在下方插入行",+ "insertColumnLeft": "在左侧插入列",+ "insertColumnRight": "在右侧插入列",+ "deleteRow": "删除行",+ "deleteColumn": "删除列",+ "deleteTable": "删除表格"+ },+ "format": {+ "toolbar": "格式",+ "withShortcut": "{{action}}({{shortcut}})",+ "bold": "粗体",+ "italic": "斜体",+ "strike": "删除线",+ "code": "代码",+ "textStyle": "文本样式",+ "paragraph": "正文",+ "heading1": "标题 1",+ "heading2": "标题 2",+ "heading3": "标题 3",+ "bulletList": "项目符号列表",+ "orderedList": "编号列表",+ "taskList": "清单",+ "blockquote": "引用",+ "table": "插入表格"+ }},"participants": {"attendee": "位参会者",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex fee4c7ace..7fa2afa2a 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -2968,7 +2968,35 @@"conversationWillAppear": "對話將顯示在這裡...","linkedEvent": "關聯行程","noFolder": "無資料夾",- "participants": "參與者"+ "participants": "參與者",+ "table": {+ "actions": "表格操作",+ "insertRowAbove": "在上方插入列",+ "insertRowBelow": "在下方插入列",+ "insertColumnLeft": "在左側插入欄",+ "insertColumnRight": "在右側插入欄",+ "deleteRow": "刪除列",+ "deleteColumn": "刪除欄",+ "deleteTable": "刪除表格"+ },+ "format": {+ "toolbar": "格式",+ "withShortcut": "{{action}}({{shortcut}})",+ "bold": "粗體",+ "italic": "斜體",+ "strike": "刪除線",+ "code": "程式碼",+ "textStyle": "文字樣式",+ "paragraph": "內文",+ "heading1": "標題 1",+ "heading2": "標題 2",+ "heading3": "標題 3",+ "bulletList": "項目符號清單",+ "orderedList": "編號清單",+ "taskList": "核取清單",+ "blockquote": "引用",+ "table": "插入表格"+ }},"participants": {"attendee": "位與會者",diff --git a/src/utils/markdownTable.ts b/src/utils/markdownTable.tsnew file mode 100644index 000000000..0ac006a53--- /dev/null+++ b/src/utils/markdownTable.ts@@ -0,0 +1,36 @@+const UNESCAPED_PIPE = /(?<!\\)\|/;+const DELIMITER_CELL = /^:?-+:?$/;++/**+ * GFM splits a table row on every unescaped pipe, even inside code spans.+ *+ * Backslashes are deliberately left alone, which CodeQL flags as incomplete+ * escaping (js/incomplete-sanitization). Doubling them would lose content+ * instead: markdown-it, which reads these notes back, takes `\|` as a pipe+ * wherever it appears, so `\\|` round-trips as backslash-pipe and `\\\|` gains a+ * backslash on every save. cmark-gfm reads `\\|` as an escaped backslash and+ * splits the cell there, so a literal `\|` inside a code span renders+ * differently on GitHub. That's the rarer half of the trade.+ */+export function escapeTableCellPipes(markdown: string): string {+ return markdown.replace(/\|/g, "\\|");+}++/**+ * Header labels of a typed `| Item | Cost |` line, or null when the line is not+ * one. A delimiter row, a row with no text, or more than one line is not a header.+ */+export function parseTableHeaderRow(line: string): string[] | null {+ const row = line.trim();+ if (row.includes("\n") || !row.startsWith("|") || !row.endsWith("|") || row.endsWith("\\|")) {+ return null;+ }+ const labels = row+ .slice(1, -1)+ .split(UNESCAPED_PIPE)+ .map((label) => label.trim().replace(/\\\|/g, "|"));+ if (labels.every((label) => !label) || labels.every((label) => DELIMITER_CELL.test(label))) {+ return null;+ }+ return labels;+}diff --git a/test/components/richTextEditor.test.js b/test/components/richTextEditor.test.jsnew file mode 100644index 000000000..7ad7931d6--- /dev/null+++ b/test/components/richTextEditor.test.js@@ -0,0 +1,967 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { createRendererServer } = require("../lib/rendererTestHarness");++// Runs the note editor's real extension list in happy-dom. Tables have to leave+// the editor as GFM pipe tables, and the editor must not show anything a pipe+// table can't store. The last tests render the real RichTextEditor with its+// table and formatting menus.++const DOM_GLOBALS = [+ "document",+ "navigator",+ "Node",+ "Element",+ "HTMLElement",+ "DOMParser",+ "MutationObserver",+ "getComputedStyle",+ "KeyboardEvent",+ "ClipboardEvent",+ "DataTransfer",+ "DragEvent",+ // For the menus (React + Radix).+ "Event",+ "CustomEvent",+ "MouseEvent",+ "PointerEvent",+ "FocusEvent",+ "HTMLInputElement",+ "ResizeObserver",+ "DOMRect",+];+// tiptap-markdown's placeholder for a node it can't write as Markdown.+const LOST_NODE = /\[(table|tableRow|tableHeader|tableCell|hardBreak)\]/;+const TABLE = "| Name | Owner |\n| --- | --- |\n| Budget | Ana |\n| Hiring | Raj |";++let happyWindow;+let Editor;+let CellSelection;+let Selection;+let createRichTextExtensions;+let insertEmptyTable;+let restoreRemoval;++/**+ * Chromium removes a focused element in two steps: it blurs it, firing focusout+ * (where a handler can run and move it), then detaches it from the parent it had,+ * throwing if a handler already moved it. happy-dom does neither. Its+ * Element.remove() goes through removeChild, so patching that covers both.+ */+function emulateChromiumRemoval() {+ let proto = happyWindow.document.body;+ while (!Object.hasOwn(proto, "removeChild")) proto = Object.getPrototypeOf(proto);+ const { removeChild } = proto;+ proto.removeChild = function (child) {+ const active = happyWindow.document.activeElement;+ if (active && child.contains(active)) active.blur();+ return removeChild.call(this, child);+ };+ return () => {+ proto.removeChild = removeChild;+ };+}++test.before(async () => {+ const { Window } = await import("happy-dom");+ happyWindow = new Window();+ const define = (name, value) =>+ Object.defineProperty(globalThis, name, { value, configurable: true, writable: true });+ define("window", happyWindow);+ for (const name of DOM_GLOBALS) define(name, happyWindow[name]);+ for (const name of ["requestAnimationFrame", "cancelAnimationFrame"]) {+ define(name, happyWindow[name].bind(happyWindow));+ }+ restoreRemoval = emulateChromiumRemoval();+ ({ createRichTextExtensions } =+ await import("../../src/components/ui/RichTextEditorExtensions.ts"));+ ({ insertEmptyTable } = await import("../../src/components/ui/RichTextEditorTable.ts"));+ // Same CommonJS builds the extensions load, so ProseMirror stays one instance.+ ({ Editor } = require("@tiptap/core"));+ ({ CellSelection } = require("@tiptap/pm/tables"));+ ({ Selection } = require("@tiptap/pm/state"));+});++test.after(async () => {+ restoreRemoval();+ await happyWindow.happyDOM.close();+});++const createEditor = (markdown) =>+ new Editor({+ element: happyWindow.document.createElement("div"),+ extensions: createRichTextExtensions(""),+ content: markdown,+ });++function markdownOf(editor) {+ const markdown = editor.storage.markdown.getMarkdown();+ assert.doesNotMatch(markdown, LOST_NODE);+ return markdown.trim();+}++/** Asserts the output and that loading it back gives the same Markdown. */+function assertSaves(editor, expected) {+ const markdown = markdownOf(editor);+ assert.equal(markdown, expected);+ assert.equal(markdownOf(createEditor(markdown)), markdown);+}++const pressKey = (editor, key, modifiers = {}) =>+ editor.view.someProp("handleKeyDown", (handler) =>+ handler(editor.view, new happyWindow.KeyboardEvent("keydown", { key, ...modifiers }))+ );++/** Types through the input rules, like a keyboard does. */+function type(editor, text) {+ const { view } = editor;+ for (const char of text) {+ const { from, to } = view.state.selection;+ const insert = () => view.state.tr.insertText(char, from, to);+ const handled = view.someProp("handleTextInput", (handler) =>+ handler(view, from, to, char, insert)+ );+ if (!handled) view.dispatch(insert());+ }+}++function paste(editor, { text = "", html = "" }) {+ const clipboardData = new happyWindow.DataTransfer();+ clipboardData.setData("text/plain", text);+ if (html) clipboardData.setData("text/html", html);+ editor.view.dom.dispatchEvent(new happyWindow.ClipboardEvent("paste", { clipboardData }));+}++/** Puts the caret `offset` characters into the cell whose text is `text`. */+function caretInCell(editor, text, offset = 0) {+ let target;+ editor.state.doc.descendants((node, pos) => {+ if (+ target === undefined &&+ node.type.spec.tableRole?.includes("cell") &&+ node.textContent === text+ ) {+ target = pos + 2 + offset;+ }+ });+ assert.notEqual(target, undefined, `no cell "${text}"`);+ editor.commands.setTextSelection(target);+}++const caretText = (editor) => {+ const { $head } = editor.state.selection;+ return `${$head.parent.textContent.slice(0, $head.parentOffset)}|${$head.parent.textContent.slice($head.parentOffset)} in ${$head.node(-1).type.name}`;+};++test("a GFM table loads and saves unchanged, between paragraphs and inside a list", () => {+ assertSaves(createEditor(`Before\n\n${TABLE}\n\nAfter`), `Before\n\n${TABLE}\n\nAfter`);+ const listed = "- item\n\n | A | B |\n | --- | --- |\n | 1 | 2 |";+ assertSaves(createEditor(listed), listed);+ assertSaves(createEditor("| A | B |\n| --- | --- |"), "| A | B |\n| --- | --- |");+});++test("ragged rows are padded and alignment is neither shown nor saved", () => {+ const editor = createEditor("| A | B | C |\n| :-- | :-: | --: |\n| 1 |\n| 1 | 2 | 3 | 4 |");+ assert.doesNotMatch(editor.getHTML(), /text-align/);+ assertSaves(editor, "| A | B | C |\n| --- | --- | --- |\n| 1 | | |\n| 1 | 2 | 3 |");+});++test("editing a cell keeps the table (#1948)", () => {+ const editor = createEditor(TABLE);+ caretInCell(editor, "Ana", 3);+ type(editor, "!");+ assertSaves(editor, TABLE.replace("Ana", "Ana!"));+});++test("pipes in a cell are escaped, including inside code", () => {+ const editor = createEditor(TABLE);+ caretInCell(editor, "Budget");+ type(editor, "a|b ");+ assertSaves(editor, TABLE.replace("Budget", "a\\|b Budget"));+ const code = "| A | B |\n| --- | --- |\n| `x\\|y` | z |";+ assertSaves(createEditor(code), code);+});++test("formatting after a pipe in the same cell survives saving", () => {+ for (const cell of [+ "x \\| y **b**",+ "x \\| y *i*",+ "x \\| y ~~s~~",+ "**a** \\| `c\\|d` [l](https://x.y)",+ ]) {+ const markdown = `| A \\| B **h** |\n| --- |\n| ${cell} |`;+ const editor = createEditor(markdown);+ caretInCell(editor, "A | B h");+ type(editor, "!");+ assertSaves(editor, markdown.replace("| A", "| !A"));+ }+});++test("cell text starting with a list or number marker is saved without escapes", () => {+ const markdown = "| A | B |\n| --- | --- |\n| -5% | 1. Plan |\n| + 3 | # tag |";+ const editor = createEditor(markdown);+ caretInCell(editor, "A", 1);+ type(editor, "!");+ assertSaves(editor, markdown.replace("| A |", "| A! |"));+});++test("Enter moves to the end of the cell below", () => {+ const editor = createEditor(TABLE);+ caretInCell(editor, "Budget", 3);+ assert.equal(pressKey(editor, "Enter"), true);+ assert.equal(caretText(editor), "Hiring| in tableCell");+ assertSaves(editor, TABLE);+});++test("Enter on the last row adds a row and moves into it", () => {+ const editor = createEditor(TABLE);+ caretInCell(editor, "Raj", 1);+ pressKey(editor, "Enter");+ type(editor, "new");+ assertSaves(editor, `${TABLE}\n| | new |`);+});++test("Enter on an empty last row removes it and leaves the table", () => {+ const editor = createEditor(`${TABLE}\n\nAfter`);+ caretInCell(editor, "Raj", 3);+ pressKey(editor, "Enter");+ pressKey(editor, "Enter");+ assert.equal(caretText(editor), "| in doc");+ type(editor, "Next");+ assertSaves(editor, `${TABLE}\n\nNext\n\nAfter`);++ // An empty paragraph already below the table (here the trailing one) takes the caret instead.+ const trailing = createEditor(TABLE);+ caretInCell(trailing, "Raj", 3);+ pressKey(trailing, "Enter");+ assert.equal(trailing.state.doc.childCount, 2);+ pressKey(trailing, "Enter");+ assert.equal(trailing.state.doc.childCount, 2);+ assert.equal(caretText(trailing), "| in doc");+});++test("Enter in the header row of a header-only table adds a body row", () => {+ const editor = createEditor("| A | B |\n| --- | --- |");+ caretInCell(editor, "A", 1);+ pressKey(editor, "Enter");+ type(editor, "1");+ assertSaves(editor, "| A | B |\n| --- | --- |\n| 1 | |");+});++test("Shift-Enter and Mod-Enter never put a line break in a cell", () => {+ const editor = createEditor(TABLE);+ caretInCell(editor, "Budget", 3);+ const mod = /Mac|iP(hone|[oa]d)/.test(happyWindow.navigator.platform)+ ? { metaKey: true }+ : { ctrlKey: true };+ assert.equal(pressKey(editor, "Enter", { shiftKey: true }), true);+ assert.equal(pressKey(editor, "Enter", mod), true);+ assertSaves(editor, TABLE);+});++test("Enter outside a table keeps its usual behavior", () => {+ const paragraph = createEditor("plain text");+ paragraph.commands.setTextSelection(11);+ pressKey(paragraph, "Enter");+ type(paragraph, "ok");+ assertSaves(paragraph, "plain text\n\nok");++ const list = createEditor("- a\n- b");+ list.commands.setTextSelection(4);+ pressKey(list, "Enter");+ type(list, "c");+ assertSaves(list, "- a\n- c\n- b");++ const code = createEditor("```\ncode\n```");+ code.commands.setTextSelection(5);+ pressKey(code, "Enter");+ type(code, "x");+ assertSaves(code, "```\ncode\nx\n```");++ const lineBreak = createEditor("line");+ lineBreak.commands.setTextSelection(5);+ pressKey(lineBreak, "Enter", { shiftKey: true });+ type(lineBreak, "two");+ assertSaves(lineBreak, "line\\\ntwo");+});++test("a typed header row turns into a table on Enter", () => {+ const editor = createEditor("Intro");+ editor.commands.setTextSelection(6);+ pressKey(editor, "Enter");+ type(editor, "| Item | Cost |");+ pressKey(editor, "Enter");+ assert.equal(caretText(editor), "| in tableCell");+ type(editor, "Pens");+ assertSaves(editor, "Intro\n\n| Item | Cost |\n| --- | --- |\n| Pens | |");+});++test("undo after a typed header row gives back the typed line", () => {+ const editor = createEditor("Intro");+ editor.commands.setTextSelection(6);+ pressKey(editor, "Enter");+ type(editor, "| Item | Cost |");+ pressKey(editor, "Enter");+ editor.commands.undo();+ assertSaves(editor, "Intro\n\n| Item | Cost |");+});++test("a header row inside a list item stays text", () => {+ const editor = createEditor("- | a | b |");+ editor.commands.setTextSelection(Selection.atEnd(editor.state.doc).from);+ pressKey(editor, "Enter");+ let hasTable = false;+ editor.state.doc.descendants((node) => {+ if (node.type.name === "table") hasTable = true;+ });+ assert.equal(hasTable, false);+});++test("block Markdown shortcuts typed at the start of a cell stay text", () => {+ // The same helper does trigger them outside a table.+ const outside = createEditor("");+ type(outside, "- x");+ assertSaves(outside, "- x");+ assert.equal(outside.state.doc.firstChild.type.name, "bulletList");+ const rule = createEditor("");+ type(rule, "---");+ assert.equal(rule.state.doc.firstChild.type.name, "horizontalRule");++ for (const shortcut of ["- ", "1. ", "# ", "> ", "[ ] ", "---"]) {+ const editor = createEditor("| A |\n| --- |\n| x |");+ caretInCell(editor, "x");+ type(editor, shortcut);+ let cellText;+ editor.state.doc.descendants((node) => {+ if (node.type.name === "tableCell") cellText = node.textContent;+ });+ assert.equal(cellText, `${shortcut}x`, shortcut);+ markdownOf(editor);+ }+});++test("a pasted table without a header row gets one; line breaks become spaces", () => {+ const editor = createEditor("x");+ paste(editor, {+ html: "<table><tbody><tr><td><p>Q</p></td><td><p>Rev</p></td></tr><tr><td><p>Q1</p></td><td><p>10<br>est.</p></td></tr></tbody></table>",+ });+ assertSaves(editor, "| Q | Rev |\n| --- | --- |\n| Q1 | 10 est. |\n\nx");+});++test("pasted merged cells keep their columns aligned", () => {+ const editor = createEditor("x");+ paste(editor, {+ html: '<table><tr><th>A</th><th>B</th><th>C</th></tr><tr><td colspan="2">wide</td><td>c</td></tr><tr><td rowspan="2">tall</td><td>1</td><td>2</td></tr><tr><td>3</td><td>4</td></tr></table>',+ });+ assertSaves(+ editor,+ "| A | B | C |\n| --- | --- | --- |\n| wide | | c |\n| tall | 1 | 2 |\n| | 3 | 4 |\n\nx"+ );+});++test("pasted column widths are ignored and bold survives a line break", () => {+ const editor = createEditor("x");+ paste(editor, {+ html: '<table><colgroup><col width="420"><col width="80"></colgroup><tr><th>A</th><th>B</th></tr><tr><td><b>a<br>b</b></td><td>c</td></tr></table>',+ });+ assert.doesNotMatch(editor.getHTML(), /colwidth|420px/);+ assertSaves(editor, "| A | B |\n| --- | --- |\n| **a b** | c |\n\nx");+});++test("a pasted table with a short row is padded", () => {+ const editor = createEditor("x");+ paste(editor, {+ html: "<table><tr><th>A</th><th>B</th><th>C</th></tr><tr><td>only</td></tr><tr><td>1</td><td>2</td><td>3</td></tr></table>",+ });+ assertSaves(editor, "| A | B | C |\n| --- | --- | --- |\n| only | | |\n| 1 | 2 | 3 |\n\nx");+});++test("pasted cells holding blocks or a nested table are flattened to one line", () => {+ const editor = createEditor("x");+ paste(editor, {+ html: "<table><tr><th><h3>Topic</h3></th><th>Notes</th></tr><tr><td><p>one</p><p>two</p></td><td><ul><li>i1</li><li><b>i2</b></li></ul></td></tr><tr><td><pre>a\nb</pre></td><td><table><tr><td>nested</td><td>cells</td></tr></table></td></tr></table>",+ });+ assertSaves(+ editor,+ "| Topic | Notes |\n| --- | --- |\n| one two | i1 **i2** |\n| a b | nested cells |\n\nx"+ );+});++test("multi-line text pasted into a cell joins into one line and keeps the caret after it", () => {+ const editor = createEditor(TABLE);+ caretInCell(editor, "Budget", 2);+ paste(editor, { text: "line1\nline2" });+ assert.equal(caretText(editor), "Buline1 line2|dget in tableCell");+ paste(editor, { html: "<p>a<br>b</p><ul><li>c</li></ul>" });+ assertSaves(editor, TABLE.replace("Budget", "Buline1 line2a b cdget"));+});++test("several paragraphs pasted into a cell join into it without touching other cells", () => {+ for (const clipboard of [+ { text: "p1\n\np2" },+ { html: "<p>p1</p><p>p2</p>" },+ { html: "<div>p1</div><div>p2</div>" },+ ]) {+ const editor = createEditor(TABLE);+ caretInCell(editor, "Budget", 3);+ paste(editor, clipboard);+ assertSaves(editor, TABLE.replace("Budget", "Budp1 p2get"));+ }+ const plain = createEditor(TABLE);+ caretInCell(plain, "Budget", 3);+ plain.view.pasteText("p1\np2");+ assertSaves(plain, TABLE.replace("Budget", "Budp1 p2get"));+});++/** Selects every body cell of TABLE. */+function selectBodyCells(editor) {+ const cells = [];+ editor.state.doc.descendants((node, pos) => {+ if (node.type.name === "tableCell") cells.push(pos);+ });+ editor.view.dispatch(+ editor.state.tr.setSelection(CellSelection.create(editor.state.doc, cells[0], cells.at(-1)))+ );+}++test("several paragraphs pasted over selected cells go into each as one line", () => {+ const editor = createEditor(TABLE);+ selectBodyCells(editor);+ paste(editor, { text: "p1\n\np2" });+ assertSaves(editor, "| Name | Owner |\n| --- | --- |\n| p1 p2 | p1 p2 |\n| p1 p2 | p1 p2 |");+});++test("a paste with nothing to insert, such as a screenshot or a rule, leaves cells alone", () => {+ for (const clipboard of [{}, { text: "---" }, { html: "<hr>" }]) {+ const overCells = createEditor(TABLE);+ selectBodyCells(overCells);+ paste(overCells, clipboard);+ assertSaves(overCells, TABLE);++ const overText = createEditor(TABLE);+ caretInCell(overText, "Budget");+ overText.commands.setTextSelection({+ from: overText.state.selection.from,+ to: overText.state.selection.from + 3,+ });+ paste(overText, clipboard);+ assertSaves(overText, TABLE);+ }+});++test("a table followed by text, pasted into a cell, is flattened into it", () => {+ const editor = createEditor(TABLE);+ caretInCell(editor, "Ana", 3);+ paste(editor, { text: "| K | V |\n| --- | --- |\n| a | 1 |\n\nafter" });+ assertSaves(editor, TABLE.replace("Ana", "AnaK V a 1 after"));+});++test("two tables pasted into a cell are flattened into it", () => {+ const editor = createEditor(TABLE);+ caretInCell(editor, "Ana", 3);+ paste(editor, { text: "| K |\n| --- |\n| a |\n\n| L |\n| --- |\n| b |" });+ assertSaves(editor, TABLE.replace("Ana", "AnaK a L b"));+});++test("a table on its own pasted into a cell fills cells from the caret", () => {+ const editor = createEditor(TABLE);+ caretInCell(editor, "Ana");+ paste(editor, { html: "<table><tr><th>K</th></tr><tr><td>v</td></tr></table>" });+ assertSaves(editor, TABLE.replace("Ana", "K").replace("Raj", "v"));+});++test("a drop below a table lands the same whether or not the caret was in a cell", () => {+ const dropList = (placeCaret) => {+ const editor = createEditor(`${TABLE}\n\nEnd`);+ placeCaret(editor);+ editor.view.posAtCoords = () => ({ pos: editor.state.doc.content.size - 1, inside: -1 });+ const dataTransfer = new happyWindow.DataTransfer();+ dataTransfer.setData("text/html", "<ul><li>first</li><li>second</li></ul>");+ const drop = new happyWindow.DragEvent("drop", { bubbles: true, cancelable: true });+ // happy-dom ignores dataTransfer in the event init.+ Object.defineProperty(drop, "dataTransfer", { value: dataTransfer });+ editor.view.dom.dispatchEvent(drop);+ return markdownOf(editor);+ };+ const fromCell = dropList((editor) => caretInCell(editor, "Ana", 1));+ assert.match(fromCell, /\n- second$/);+ assert.equal(+ fromCell,+ dropList((editor) => editor.commands.setTextSelection(editor.state.doc.content.size - 1))+ );+});++test("a line break dropped into a cell becomes a space", () => {+ const editor = createEditor(TABLE);+ caretInCell(editor, "Budget", 3);+ editor.view.posAtCoords = () => ({ pos: editor.state.selection.from, inside: -1 });+ const dataTransfer = new happyWindow.DataTransfer();+ dataTransfer.setData("text/html", "<p>a<br>b</p>");+ const drop = new happyWindow.DragEvent("drop", { bubbles: true, cancelable: true });+ Object.defineProperty(drop, "dataTransfer", { value: dataTransfer });+ editor.view.dom.dispatchEvent(drop);+ assertSaves(editor, TABLE.replace("Budget", "Buda bget"));+});++test("a Markdown table pasted as text becomes a table", () => {+ const editor = createEditor("");+ paste(editor, { text: "Header\n\n| K | V |\n| --- | --- |\n| a | 1 |" });+ assertSaves(editor, "Header\n\n| K | V |\n| --- | --- |\n| a | 1 |");+});++test("row and column commands keep a header row", () => {+ const above = createEditor(TABLE);+ caretInCell(above, "Name");+ above.commands.addRowBefore();+ assertSaves(+ above,+ "| | |\n| --- | --- |\n| Name | Owner |\n| Budget | Ana |\n| Hiring | Raj |"+ );++ const deleted = createEditor(TABLE);+ caretInCell(deleted, "Name");+ deleted.commands.deleteRow();+ assertSaves(deleted, "| Budget | Ana |\n| --- | --- |\n| Hiring | Raj |");++ const columns = createEditor(TABLE);+ caretInCell(columns, "Name");+ columns.commands.addColumnAfter();+ caretInCell(columns, "Ana");+ columns.commands.deleteColumn();+ assertSaves(columns, "| Name | |\n| --- | --- |\n| Budget | |\n| Hiring | |");+});++test("copying cells puts a GFM table on the text clipboard", () => {+ const editor = createEditor(TABLE);+ const cells = [];+ editor.state.doc.descendants((node, pos) => {+ if (node.type.name === "tableCell") cells.push(pos);+ });+ editor.view.dispatch(+ editor.state.tr.setSelection(CellSelection.create(editor.state.doc, cells[0], cells.at(-1)))+ );+ const serialize = (view) =>+ view.someProp("clipboardTextSerializer", (serializer) =>+ serializer(view.state.selection.content(), view)+ );+ assert.equal(serialize(editor.view).trim(), "| Budget | Ana |\n| --- | --- |\n| Hiring | Raj |");++ for (const nestedTable of [+ `- item\n\n ${TABLE.replaceAll("\n", "\n ")}`,+ `> ${TABLE.replaceAll("\n", "\n> ")}`,+ ]) {+ const nested = createEditor(nestedTable);+ caretInCell(nested, "Budget");+ nested.commands.setTextSelection({+ from: nested.state.selection.from,+ to: nested.state.selection.from + 3,+ });+ assert.equal(serialize(nested.view), "Bud", nestedTable);+ }++ // A triple-click selects the whole cell as a one-cell selection.+ const oneCell = createEditor(TABLE);+ caretInCell(oneCell, "Ana");+ oneCell.view.dispatch(+ oneCell.state.tr.setSelection(+ CellSelection.create(oneCell.state.doc, oneCell.state.selection.$from.before(-1))+ )+ );+ assert.equal(serialize(oneCell.view), "Ana");+ const emptyCell = createEditor("| A |\n| --- |\n| |");+ let emptyPos;+ emptyCell.state.doc.descendants((node, pos) => {+ if (node.type.name === "tableCell") emptyPos = pos;+ });+ emptyCell.view.dispatch(+ emptyCell.state.tr.setSelection(CellSelection.create(emptyCell.state.doc, emptyPos))+ );+ assert.equal(serialize(emptyCell.view), " ");++ const inCell = createEditor(TABLE);+ caretInCell(inCell, "Budget");+ inCell.commands.setTextSelection({+ from: inCell.state.selection.from,+ to: inCell.state.selection.from + 3,+ });+ assert.equal(serialize(inCell.view), "Bud");++ const text = createEditor("**bold** text");+ text.commands.selectAll();+ assert.equal(serialize(text.view), "**bold** text");+});++test("undo reverts a change together with the header fix it caused", () => {+ const editor = createEditor(TABLE);+ caretInCell(editor, "Name");+ editor.commands.addRowBefore();+ assert.notEqual(markdownOf(editor), TABLE);+ editor.commands.undo();+ assert.equal(markdownOf(editor), TABLE);+});++const EMPTY_ROW = "| | | |";+const EMPTY_TABLE = `${EMPTY_ROW}\n| --- | --- | --- |\n${EMPTY_ROW}\n${EMPTY_ROW}`;++test("Insert table replaces an empty line and puts the caret in the first header cell", () => {+ const editor = createEditor("Intro");+ editor.commands.setTextSelection(6);+ pressKey(editor, "Enter");+ insertEmptyTable(editor);+ assert.equal(caretText(editor), "| in tableHeader");+ assertSaves(editor, `Intro\n\n${EMPTY_TABLE}`);+ editor.commands.undo();+ assert.equal(editor.state.doc.childCount, 2, "undo keeps the empty line");+});++test("Insert table with text selected adds the table after that block", () => {+ const editor = createEditor("- first\n- second\n\nAfter");+ editor.commands.setTextSelection({ from: 3, to: 8 });+ insertEmptyTable(editor);+ assert.equal(markdownOf(editor), `- first\n- second\n\n${EMPTY_TABLE}\n\nAfter`);+});++test("Insert table over a selection spanning two lines adds the table after the last", () => {+ const editor = createEditor("First line\n\nSecond line\n\nAfter");+ editor.commands.setTextSelection({ from: 3, to: 16 });+ insertEmptyTable(editor);+ assert.equal(markdownOf(editor), `First line\n\nSecond line\n\n${EMPTY_TABLE}\n\nAfter`);+});++/**+ * Renders the real RichTextEditor, menus included, the way NoteEditor uses it:+ * the note is state, and switching notes remounts the editor.+ */+async function mountNotes(t, markdown = `Intro\n\n${TABLE}\n\nAfter`) {+ globalThis.IS_REACT_ACT_ENVIRONMENT = true;+ const React = require("react");+ const { createRoot } = require("react-dom/client");+ const vite = await createRendererServer(t);+ const { RichTextEditor } = await vite.ssrLoadModule("/components/ui/RichTextEditor.tsx");+ const errors = [];+ class Boundary extends React.Component {+ state = { failed: false };+ static getDerivedStateFromError() {+ return { failed: true };+ }+ componentDidCatch(error) {+ errors.push(error.message);+ }+ render() {+ return this.state.failed ? null : this.props.children;+ }+ }+ const editorRef = { current: null };+ let showOtherNote;+ let setDisabled;+ let saved;+ function Note({ initial }) {+ const [value, setValue] = React.useState(initial);+ const [disabled, updateDisabled] = React.useState(false);+ setDisabled = updateDisabled;+ return React.createElement(RichTextEditor, {+ value,+ disabled,+ onChange: (markdown) => {+ saved = markdown;+ setValue(markdown);+ },+ editorRef,+ mentionPeople: [],+ });+ }+ function Notes() {+ const [other, setOther] = React.useState(false);+ showOtherNote = () => setOther(true);+ return React.createElement(Note, {+ key: String(other),+ initial: other ? "Other note" : markdown,+ });+ }+ // happy-dom reports errors thrown in event listeners and timers on window,+ // where no error boundary sees them.+ const onWindowError = (event) => errors.push(event.error?.message ?? event.message);+ happyWindow.addEventListener("error", onWindowError);+ const host = happyWindow.document.createElement("div");+ happyWindow.document.body.appendChild(host);+ const root = createRoot(host);+ t.after(async () => {+ await React.act(async () => root.unmount());+ host.remove();+ happyWindow.removeEventListener("error", onWindowError);+ });+ const settle = (ms) => new Promise((resolve) => setTimeout(resolve, ms));+ // Waits inside act for timers the editor and menus set, then again after it:+ // effects that React flushes when act ends (unmounts) set timers too. The+ // bubble menus wait 250 ms before showing for a text selection.+ const act = async (callback, wait = 30) => {+ await React.act(async () => {+ await callback();+ await settle(wait);+ });+ await settle(30);+ };+ await act(() => root.render(React.createElement(Boundary, null, React.createElement(Notes))));+ await act(() => editorRef.current.commands.focus());+ return {+ act,+ editor: () => editorRef.current,+ errors,+ host,+ /** The Markdown the note last saved through onChange. */+ saved: () => saved,+ setDisabled: (disabled) => setDisabled(disabled),+ showOtherNote: () => showOtherNote(),+ };+}++const pointerDown = (element) =>+ element.dispatchEvent(+ new happyWindow.PointerEvent("pointerdown", { bubbles: true, button: 0, pointerType: "mouse" })+ );+const clickButton = (element) => {+ element.dispatchEvent(+ new happyWindow.MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0 })+ );+ element.click();+};+const addEmptyLastLine = (editor) => {+ editor.commands.insertContentAt(editor.state.doc.content.size, { type: "paragraph" });+ editor.commands.setTextSelection(editor.state.doc.content.size - 1);+};++// Without an i18next instance, t() returns the key.+const byLabel = (label) => happyWindow.document.querySelector(`[aria-label="${label}"]`);+// A boolean, never the element: a failing assert that prints a happy-dom element+// runs the test process out of memory.+const isShown = (label) => !!byLabel(label);+const TOOLBAR = "notes.editor.format.toolbar";+const toolbarCount = () =>+ happyWindow.document.querySelectorAll(`[aria-label="${TOOLBAR}"]`).length;+const menuItem = (key) =>+ [...happyWindow.document.querySelectorAll('[role="menuitem"]')].find(+ (item) => item.textContent === key+ );++async function openTableMenu(notes, caretCell = "Ana") {+ await notes.act(() => caretInCell(notes.editor(), caretCell, 1));+ await notes.act(() => pointerDown(byLabel("notes.editor.table.actions")));+}++test("Delete table from the menu works in a note that re-renders on every change", async (t) => {+ const notes = await mountNotes(t);+ await openTableMenu(notes);+ await notes.act(() => menuItem("notes.editor.table.deleteTable").click());+ assert.deepEqual(notes.errors, []);+ assert.equal(markdownOf(notes.editor()), "Intro\n\nAfter");+ assert.equal(notes.saved().trim(), "Intro\n\nAfter");+});++test("the table menu disables actions that would break or empty the table", async (t) => {+ const isDisabled = (key) => menuItem(`notes.editor.table.${key}`).hasAttribute("data-disabled");+ const notes = await mountNotes(t, "Intro\n\n| A | B |\n| --- | --- |\n\nAfter");+ await openTableMenu(notes, "A");+ assert.equal(isDisabled("insertRowAbove"), true);+ assert.equal(isDisabled("deleteRow"), true);+ assert.equal(isDisabled("deleteColumn"), false);+});++test("switching notes while the table menu is open", async (t) => {+ const notes = await mountNotes(t);+ await openTableMenu(notes);+ assert.ok(menuItem("notes.editor.table.deleteTable"), "menu is open");+ await notes.act(notes.showOtherNote);+ assert.deepEqual(notes.errors, []);+ assert.match(notes.host.textContent, /Other note/);+});++test("the formatting toolbar shows on selected text and empty lines only", async (t) => {+ const notes = await mountNotes(t, `Intro text\n\n${TABLE}`);+ await notes.act(() => notes.editor().commands.setTextSelection({ from: 1, to: 6 }), 300);+ assert.ok(isShown(TOOLBAR), "on selected text");+ assert.equal(toolbarCount(), 1);+ await notes.act(() => notes.editor().commands.setTextSelection(3));+ assert.equal(isShown(TOOLBAR), false, "mid-line");+ await notes.act(() => {+ caretInCell(notes.editor(), "Ana", 1);+ const { from } = notes.editor().state.selection;+ notes.editor().commands.setTextSelection({ from, to: from + 2 });+ }, 300);+ assert.equal(isShown(TOOLBAR), false, "over text in a table");+ assert.ok(isShown("notes.editor.table.actions"), "the table menu instead");+ await notes.act(() => addEmptyLastLine(notes.editor()));+ assert.ok(isShown(TOOLBAR), "on an empty line");+ assert.equal(toolbarCount(), 1);+ await notes.act(() => {+ notes.editor().commands.blur();+ notes.editor().commands.setTextSelection({ from: 1, to: 6 });+ }, 300);+ assert.equal(isShown(TOOLBAR), false, "over a selection the editor doesn't hold focus for");+ assert.deepEqual(notes.errors, []);+});++test("the formatting toolbar stays away from code blocks, list items and nodes", async (t) => {+ const notes = await mountNotes(t, "```js\nconst a = 1;\n```\n\n- item\n\n---\n\nAfter");+ const editor = () => notes.editor();+ const selectIn = (text, length) => {+ let from;+ editor().state.doc.descendants((node, pos) => {+ if (from === undefined && node.isText && node.text.includes(text)) from = pos;+ });+ editor().commands.setTextSelection({ from, to: from + length });+ };+ await notes.act(() => selectIn("const a", 5), 300);+ assert.equal(isShown(TOOLBAR), false, "over code in a code block");+ await notes.act(() => selectIn("item", 4), 300);+ assert.ok(isShown(TOOLBAR), "over text in a list item");+ await notes.act(() => {+ // An empty list item is a line the toolbar's blocks and tables can't go on.+ selectIn("item", 4);+ editor().commands.deleteSelection();+ }, 300);+ assert.equal(isShown(TOOLBAR), false, "on an empty list item");+ await notes.act(() => {+ let rule;+ editor().state.doc.descendants((node, pos) => {+ if (rule === undefined && node.type.name === "horizontalRule") rule = pos;+ });+ editor().commands.setNodeSelection(rule);+ }, 300);+ assert.equal(isShown(TOOLBAR), false, "on a selected rule");+ assert.deepEqual(notes.errors, []);+});++test("the formatting toolbar formats the selection and inserts a table", async (t) => {+ const notes = await mountNotes(t, "Intro text\n\nSecond");+ const editor = () => notes.editor();+ await notes.act(() => editor().commands.setTextSelection({ from: 1, to: 6 }), 300);+ await notes.act(() => clickButton(byLabel("notes.editor.format.bold")));+ assert.equal(byLabel("notes.editor.format.bold").getAttribute("aria-pressed"), "true");+ await notes.act(() => clickButton(byLabel("notes.editor.format.bulletList")));+ assert.equal(markdownOf(editor()), "- **Intro** text\n\nSecond");++ await notes.act(() => editor().commands.setTextSelection({ from: 17, to: 23 }), 300);+ await notes.act(() => pointerDown(byLabel("notes.editor.format.textStyle")));+ await notes.act(() => menuItem("notes.editor.format.heading2").click());+ assert.equal(markdownOf(editor()), "- **Intro** text\n\n## Second");++ await notes.act(() => addEmptyLastLine(editor()));+ const insertTable = byLabel("notes.editor.format.table");+ assert.equal(insertTable.hasAttribute("aria-pressed"), false, "not a toggle");+ // Enter on the focused button, as from the keyboard.+ await notes.act(() => {+ insertTable.focus();+ insertTable.click();+ });+ assert.equal(markdownOf(editor()), `- **Intro** text\n\n## Second\n\n${EMPTY_TABLE}`);+ assert.equal(notes.saved().trim(), markdownOf(editor()));+ assert.ok(editor().isFocused, "the caret is back in the note");+ assert.deepEqual(notes.errors, []);+});++test("switching notes while a formatting toolbar's dropdown is open", async (t) => {+ const onSelection = (editor) => editor.commands.setTextSelection({ from: 1, to: 6 });+ for (const select of [onSelection, addEmptyLastLine]) {+ const notes = await mountNotes(t, "Intro text");+ await notes.act(() => select(notes.editor()), 300);+ await notes.act(() => pointerDown(byLabel("notes.editor.format.textStyle")));+ assert.ok(menuItem("notes.editor.format.heading1"), `dropdown open (${select.name})`);+ await notes.act(notes.showOtherNote);+ assert.deepEqual(notes.errors, [], select.name);+ }+});++test("the menus hide when focus leaves them, also after a click on them", async (t) => {+ const notes = await mountNotes(t, `Intro text\n\n${TABLE}`);+ const outside = happyWindow.document.createElement("input");+ happyWindow.document.body.appendChild(outside);+ t.after(() => outside.remove());+ const refocus = () => notes.act(() => notes.editor().commands.focus(), 300);++ // A click on a button keeps focus in the editor, and Tiptap then misses the next blur.+ await notes.act(() => notes.editor().commands.setTextSelection({ from: 1, to: 6 }), 300);+ await notes.act(() => clickButton(byLabel("notes.editor.format.bold")));+ await notes.act(() => outside.focus());+ assert.equal(isShown(TOOLBAR), false, "after a click on the toolbar");+ await refocus();+ assert.ok(isShown(TOOLBAR), "back when the editor is focused again");++ // Leaving a menu with Tab never blurs the editor: it lost focus to the menu.+ await notes.act(() => byLabel("notes.editor.format.italic").focus());+ await notes.act(() => outside.focus());+ assert.equal(isShown(TOOLBAR), false, "tabbing out of the toolbar");++ await refocus();+ await notes.act(() => caretInCell(notes.editor(), "Ana", 1));+ await notes.act(() => byLabel("notes.editor.table.actions").focus());+ await notes.act(() => outside.focus());+ assert.equal(isShown("notes.editor.table.actions"), false, "tabbing out of the table menu");++ // An open dropdown takes focus back, as from a dialog opened over it.+ await refocus();+ await notes.act(() => pointerDown(byLabel("notes.editor.table.actions")));+ await notes.act(() => outside.focus());+ assert.ok(menuItem("notes.editor.table.deleteTable"), "the dropdown stays open");+ assert.equal(isShown("notes.editor.table.actions"), true, "and so does its menu");+ assert.deepEqual(notes.errors, []);+});++test("a dropdown closes with the menu it lives in", async (t) => {+ const notes = await mountNotes(t);+ await openTableMenu(notes);+ assert.ok(menuItem("notes.editor.table.deleteTable"), "menu is open");+ // A change from outside the editor, as dictation or a note action makes.+ await notes.act(() => notes.editor().commands.insertContentAt(0, "Dictated. "));+ assert.equal(menuItem("notes.editor.table.deleteTable"), undefined, "the dropdown is gone");+ assert.notEqual(+ happyWindow.document.body.style.pointerEvents,+ "none",+ "the page takes clicks again"+ );+ assert.deepEqual(notes.errors, []);+});++for (const menu of ["selection", "empty line", "table"]) {+ test(`disabling the editor closes the ${menu} dropdown and re-enabling restores it`, async (t) => {+ const notes = await mountNotes(t);+ const openMenu = async () => {+ if (menu === "table") {+ await notes.act(() => notes.editor().commands.focus());+ await openTableMenu(notes);+ } else {+ await notes.act(() => {+ notes.editor().commands.focus();+ notes+ .editor()+ .commands.setTextSelection(+ menu === "selection" ? { from: 1, to: 6 } : notes.editor().state.doc.content.size - 1+ );+ }, 300);+ await notes.act(() => pointerDown(byLabel("notes.editor.format.textStyle")));+ }+ };+ if (menu === "empty line") await notes.act(() => addEmptyLastLine(notes.editor()));+ await openMenu();+ const actionKey =+ menu === "table" ? "notes.editor.table.deleteTable" : "notes.editor.format.heading1";+ assert.ok(menuItem(actionKey), "dropdown starts open");+ const originalMarkdown = markdownOf(notes.editor());+ const originalSaved = notes.saved();++ await notes.act(() => notes.setDisabled(true));+ assert.equal(notes.editor().isEditable, false);+ assert.equal(!!menuItem(actionKey), false, "read-only notes offer no menu action");+ assert.equal(toolbarCount(), 0);+ assert.equal(isShown("notes.editor.table.actions"), false);+ assert.notEqual(happyWindow.document.body.style.pointerEvents, "none");+ assert.equal(markdownOf(notes.editor()), originalMarkdown);+ assert.equal(notes.saved(), originalSaved, "disabling does not save a content change");++ await notes.act(() => notes.setDisabled(false));+ await openMenu();+ await notes.act(() => menuItem(actionKey).click());+ assert.notEqual(markdownOf(notes.editor()), originalMarkdown);+ assert.equal(notes.saved().trim(), markdownOf(notes.editor()));+ assert.deepEqual(notes.errors, []);+ });+}diff --git a/test/utils/markdownTable.test.js b/test/utils/markdownTable.test.jsnew file mode 100644index 000000000..3c5731008--- /dev/null+++ b/test/utils/markdownTable.test.js@@ -0,0 +1,40 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/utils/markdownTable.ts");++test("escapeTableCellPipes escapes every pipe, including one after a backslash or in code", async () => {+ const { escapeTableCellPipes } = await load();+ assert.equal(escapeTableCellPipes("a|b"), "a\\|b");+ assert.equal(escapeTableCellPipes("`x|y`"), "`x\\|y`");+ // A serialized literal backslash is already doubled; the pipe still needs its own escape.+ assert.equal(escapeTableCellPipes("a\\\\|b"), "a\\\\\\|b");+ assert.equal(escapeTableCellPipes("no pipes"), "no pipes");+});++test("parseTableHeaderRow reads the labels of a typed header row", async () => {+ const { parseTableHeaderRow } = await load();+ assert.deepEqual(parseTableHeaderRow("| Item | Cost |"), ["Item", "Cost"]);+ assert.deepEqual(parseTableHeaderRow(" |Item|Cost| "), ["Item", "Cost"]);+ assert.deepEqual(parseTableHeaderRow("| Single |"), ["Single"]);+ assert.deepEqual(parseTableHeaderRow("| Name | |"), ["Name", ""]);+ assert.deepEqual(parseTableHeaderRow("| a \\| b | c |"), ["a | b", "c"]);+});++test("parseTableHeaderRow rejects lines that are not a header row", async () => {+ const { parseTableHeaderRow } = await load();+ for (const line of [+ "",+ "|",+ "||",+ "| |",+ "plain text",+ "a | b",+ "| a | b",+ "| a \\|",+ "| --- | :-: |",+ "| a |\n| b |",+ ]) {+ assert.equal(parseTableHeaderRow(line), null, line);+ }+});