Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

refactor(editor): share extensions and editor lifecycle

Tinecf0f41b3038
diff --git a/apps/web/src/components/activity/comment-editor.tsx b/apps/web/src/components/activity/comment-editor.tsx
index 4b0cc2f8e..bded5cf77 100644
--- a/apps/web/src/components/activity/comment-editor.tsx
+++ b/apps/web/src/components/activity/comment-editor.tsx
@@ -1,53 +1,37 @@
+import {
+ richTextCommands,
+ type SlashCommand,
+ type SlashRange,
+} from "@/components/editor/slash-commands";
+import { TableToolbar } from "@/components/editor/table-toolbar";
+import { createEditorExtensions } from "@/components/editor/extensions";
+import { insertUploadedAsset as insertEditorAsset } from "@/components/editor/insert-uploaded-asset";
+import { useEditorHighlighter } from "@/components/editor/use-editor-highlighter";
import type { Editor } from "@tiptap/core";
import Image from "@tiptap/extension-image";
-import Placeholder from "@tiptap/extension-placeholder";
-import { Table } from "@tiptap/extension-table";
-import TableCell from "@tiptap/extension-table-cell";
-import TableHeader from "@tiptap/extension-table-header";
-import TableRow from "@tiptap/extension-table-row";
-import TaskList from "@tiptap/extension-task-list";
-import { Markdown } from "@tiptap/markdown";
import { TextSelection } from "@tiptap/pm/state";
import { EditorContent, useEditor } from "@tiptap/react";
import { BubbleMenu } from "@tiptap/react/menus";
-import StarterKit from "@tiptap/starter-kit";
import {
- BetweenHorizontalEnd,
- BetweenHorizontalStart,
- BetweenVerticalEnd,
- BetweenVerticalStart,
Bold,
Check,
ChevronDown,
- Columns3,
Copy,
- Grid2x2X,
Italic,
Link2,
List,
ListOrdered,
ListTodo,
Paperclip,
- Rows3,
UnderlineIcon,
} from "lucide-react";
import type { MouseEvent as ReactMouseEvent } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
-import type { Highlighter } from "shiki";
-import { AttachmentCard } from "@/components/task/extensions/attachment-card";
-import { EmbedBlock } from "@/components/task/extensions/embed-block";
-import { KaneoIssueLink } from "@/components/task/extensions/kaneo-issue-link";
import { KaneoMention } from "@/components/task/extensions/kaneo-mention";
import type { MentionMember } from "@/components/task/extensions/mention-list";
import { MentionSuggestion } from "@/components/task/extensions/mention-suggestion";
-import { MermaidBlock } from "@/components/task/extensions/mermaid-block";
-import { SafeHardBreak } from "@/components/task/extensions/safe-hard-break";
-import {
- SHIKI_CODEBLOCK_REFRESH_META,
- ShikiCodeBlock,
-} from "@/components/task/extensions/shiki-code-block";
-import { TaskItemWithCheckbox } from "@/components/task/extensions/task-item-with-checkbox";
+import { SHIKI_CODEBLOCK_REFRESH_META } from "@/components/task/extensions/shiki-code-block";
import { Button } from "@/components/ui/button";
import { Dialog, DialogPopup } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
@@ -98,17 +82,6 @@ type CommentEditorProps = {
onAttachActionChange?: (attach: (() => void) | null) => void;
};
-type SlashRange = { from: number; to: number };
-
-type SlashCommand = {
- id: string;
- label: string;
- group: "text" | "lists" | "insert";
- shortcut?: string;
- search: string;
- run: (editor: Editor, range: SlashRange) => void;
-};
-
type SlashMenuState = {
from: number;
to: number;
@@ -230,10 +203,11 @@ export default function CommentEditor({
range?: SlashRange;
} | null>(null);
const [slashMenu, setSlashMenu] = useState<SlashMenuState | null>(null);
- const [shikiHighlighter, setShikiHighlighter] = useState<Highlighter | null>(
- null,
- );
- const shikiHighlighterRef = useRef<Highlighter | null>(null);
+ const {
+ highlighter: shikiHighlighter,
+ highlighterRef: shikiHighlighterRef,
+ languages: availableShikiLanguages,
+ } = useEditorHighlighter();
const [hoveredCodeBlock, setHoveredCodeBlock] =
useState<HoveredCodeBlock | null>(null);
const hoveredCodeBlockElementRef = useRef<HTMLElement | null>(null);
@@ -259,9 +233,6 @@ export default function CommentEditor({
})),
[t],
);
- const [availableShikiLanguages, setAvailableShikiLanguages] = useState(
- () => new Set<string>(),
- );
const toShikiLanguage = useCallback(
(language: string) => {
const normalized = language.toLowerCase();
@@ -297,50 +268,16 @@ export default function CommentEditor({
const insertUploadedAsset = useCallback(
(
- activeEditor: Editor,
+ editor: Editor,
asset: Awaited<ReturnType<typeof uploadTaskImage>>,
range?: SlashRange,
) => {
- const chain = activeEditor.chain().focus();
-
- if (range) {
- chain.deleteRange(range);
- } else {
- const { selection } = activeEditor.state;
- if (!selection.empty) {
- chain.setTextSelection(selection.to);
- }
- }
-
- if (asset.kind === "image") {
- const ran = chain
- .setImage({
- src: asset.url,
- alt: asset.alt,
- })
- .run();
- // Chain commands report silent failure via false rather than
- // throwing; convert it so the caller's catch reports it.
- if (!ran) {
- throw new Error(t("activity:comment.editor.failedToUploadFile"));
- }
- return;
- }
-
- const ran = chain
- .insertContent({
- type: "attachmentCard",
- attrs: {
- url: asset.url,
- filename: asset.filename,
- mimeType: asset.mimeType,
- size: asset.size,
- },
- })
- .run();
- if (!ran) {
- throw new Error(t("activity:comment.editor.failedToUploadFile"));
- }
+ insertEditorAsset(
+ editor,
+ asset,
+ t("activity:comment.editor.failedToUploadFile"),
+ range,
+ );
},
[t],
);
@@ -486,9 +423,8 @@ export default function CommentEditor({
label: t("activity:comment.editor.slashParagraph"),
group: "text",
search: t("activity:comment.editor.searchParagraph"),
- run: (activeEditor, range) => {
- activeEditor.chain().focus().deleteRange(range).setParagraph().run();
- },
+ run: richTextCommands.find((command) => command.id === "paragraph")!
+ .run,
},
{
id: "heading-2",
@@ -496,14 +432,8 @@ export default function CommentEditor({
group: "text",
shortcut: "Ctrl Alt 2",
search: t("activity:comment.editor.searchHeading"),
- run: (activeEditor, range) => {
- activeEditor
- .chain()
- .focus()
- .deleteRange(range)
- .toggleHeading({ level: 2 })
- .run();
- },
+ run: richTextCommands.find((command) => command.id === "heading-2")!
+ .run,
},
{
id: "bullet-list",
@@ -511,28 +441,16 @@ export default function CommentEditor({
group: "lists",
shortcut: "Ctrl Alt 8",
search: t("activity:comment.editor.searchBulletList"),
- run: (activeEditor, range) => {
- activeEditor
- .chain()
- .focus()
- .deleteRange(range)
- .toggleBulletList()
- .run();
- },
+ run: richTextCommands.find((command) => command.id === "bullet-list")!
+ .run,
},
{
id: "task-list",
label: t("activity:comment.editor.slashTaskList"),
group: "lists",
search: t("activity:comment.editor.searchTaskList"),
- run: (activeEditor, range) => {
- activeEditor
- .chain()
- .focus()
- .deleteRange(range)
- .toggleTaskList()
- .run();
- },
+ run: richTextCommands.find((command) => command.id === "task-list")!
+ .run,
},
{
id: "ordered-list",
@@ -540,28 +458,16 @@ export default function CommentEditor({
group: "lists",
shortcut: "Ctrl Alt 9",
search: t("activity:comment.editor.searchOrderedList"),
- run: (activeEditor, range) => {
- activeEditor
- .chain()
- .focus()
- .deleteRange(range)
- .toggleOrderedList()
- .run();
- },
+ run: richTextCommands.find((command) => command.id === "ordered-list")!
+ .run,
},
{
id: "blockquote",
label: t("activity:comment.editor.slashQuote"),
group: "insert",
search: t("activity:comment.editor.searchQuote"),
- run: (activeEditor, range) => {
- activeEditor
- .chain()
- .focus()
- .deleteRange(range)
- .toggleBlockquote()
- .run();
- },
+ run: richTextCommands.find((command) => command.id === "blockquote")!
+ .run,
},
{
id: "code-block",
@@ -569,28 +475,15 @@ export default function CommentEditor({
group: "insert",
shortcut: "Ctrl Alt \\",
search: t("activity:comment.editor.searchCodeBlock"),
- run: (activeEditor, range) => {
- activeEditor
- .chain()
- .focus()
- .deleteRange(range)
- .toggleCodeBlock()
- .run();
- },
+ run: richTextCommands.find((command) => command.id === "code-block")!
+ .run,
},
{
id: "table",
label: t("activity:comment.editor.slashTable"),
group: "insert",
search: t("activity:comment.editor.searchTable"),
- run: (activeEditor, range) => {
- activeEditor
- .chain()
- .focus()
- .deleteRange(range)
- .insertTable({ cols: 3, rows: 3 })
- .run();
- },
+ run: richTextCommands.find((command) => command.id === "table")!.run,
},
{
id: "file",
@@ -606,32 +499,6 @@ export default function CommentEditor({
[openImagePicker, t],
);
- useEffect(() => {
- let mounted = true;
-
- void Promise.all([
- import("@/lib/shiki-highlighter").then(({ getSharedShikiHighlighter }) =>
- getSharedShikiHighlighter(),
- ),
- import("shiki"),
- ])
- .then(([instance, { bundledLanguages: languages }]) => {
- if (!mounted) return;
- shikiHighlighterRef.current = instance;
- setShikiHighlighter(instance);
- setAvailableShikiLanguages(new Set(Object.keys(languages)));
- })
- .catch((err) => {
- // Shared initializer resets its cached promise on rejection so a
- // later attempt can retry. If this attempt also fails, swallow it
- // and render without syntax highlighting.
- console.error("Failed to initialize Shiki highlighter:", err);
- });
-
- return () => {
- mounted = false;
- };
- }, []);
const filteredSlashCommands = useMemo(() => {
const query = slashMenu?.query.trim().toLowerCase() || "";
if (!query) return slashCommands;
@@ -647,58 +514,19 @@ export default function CommentEditor({
immediatelyRender: false,
autofocus: autoFocus,
editable: !readOnly && !disabled,
- extensions: [
- StarterKit.configure({
- heading: { levels: [1, 2, 3] },
- trailingNode: false,
- codeBlock: {
- HTMLAttributes: { class: "kaneo-tiptap-codeblock" },
- },
- hardBreak: false,
- }),
- SafeHardBreak,
- Markdown.configure({
- markedOptions: {
- breaks: true,
- gfm: true,
- },
- }),
- ShikiCodeBlock.configure({
- highlighter: () => shikiHighlighterRef.current,
- resolveLanguage: toShikiLanguage,
- themeDark: "github-dark",
- themeLight: "github-light",
- }),
- MermaidBlock.configure({
- errorKey: "activity:comment.editor.mermaid.renderFailed",
- }),
- EmbedBlock,
- AttachmentCard,
- KaneoIssueLink,
- KaneoMention,
- MentionSuggestion.configure({
- getMembers: () => mentionMembersRef.current,
- }),
- TaskList,
- Image.configure({
- HTMLAttributes: {
- class: "kaneo-editor-image",
- loading: "lazy",
- },
- }),
- TaskItemWithCheckbox.configure({
- nested: true,
- }),
- Placeholder.configure({
- placeholder: resolvedPlaceholder,
- }),
- Table.configure({
- resizable: true,
- }),
- TableRow,
- TableHeader,
- TableCell,
- ],
+ extensions: createEditorExtensions({
+ placeholder: resolvedPlaceholder,
+ highlighter: () => shikiHighlighterRef.current,
+ resolveLanguage: toShikiLanguage,
+ image: Image,
+ mermaidErrorKey: "activity:comment.editor.mermaid.renderFailed",
+ extra: [
+ KaneoMention,
+ MentionSuggestion.configure({
+ getMembers: () => mentionMembersRef.current,
+ }),
+ ],
+ }),
editorProps: {
attributes: {
class: cn(
@@ -1701,101 +1529,35 @@ export default function CommentEditor({
activeEditor.isActive("table") && from === to
}
>
- <Button
- type="button"
- variant="ghost"
- size="xs"
+ <TableToolbar
+ editor={editor}
className="kaneo-comment-editor-bubble-btn"
- title={t("activity:comment.editor.table.addColumnBefore", {
- defaultValue: "Insert column left",
- })}
- onClick={() => editor.chain().focus().addColumnBefore().run()}
- >
- <BetweenVerticalStart className="size-3.5" />
- </Button>
- <Button
- type="button"
- variant="ghost"
- size="xs"
- className="kaneo-comment-editor-bubble-btn"
- title={t("activity:comment.editor.table.addColumnAfter", {
- defaultValue: "Insert column right",
- })}
- onClick={() => editor.chain().focus().addColumnAfter().run()}
- >
- <BetweenVerticalEnd className="size-3.5" />
- </Button>
- <Button
- type="button"
- variant="ghost"
- size="xs"
- className={cn(
- "kaneo-comment-editor-bubble-btn",
- "text-destructive",
- )}
- title={t("activity:comment.editor.table.deleteColumn", {
- defaultValue: "Delete column",
- })}
- onClick={() => editor.chain().focus().deleteColumn().run()}
- >
- <Columns3 className="size-3.5" />
- </Button>
- <span className="kaneo-tiptap-bubble-separator" />
- <Button
- type="button"
- variant="ghost"
- size="xs"
- className="kaneo-comment-editor-bubble-btn"
- title={t("activity:comment.editor.table.addRowBefore", {
- defaultValue: "Insert row above",
- })}
- onClick={() => editor.chain().focus().addRowBefore().run()}
- >
- <BetweenHorizontalStart className="size-3.5" />
- </Button>
- <Button
- type="button"
- variant="ghost"
- size="xs"
- className="kaneo-comment-editor-bubble-btn"
- title={t("activity:comment.editor.table.addRowAfter", {
- defaultValue: "Insert row below",
- })}
- onClick={() => editor.chain().focus().addRowAfter().run()}
- >
- <BetweenHorizontalEnd className="size-3.5" />
- </Button>
- <Button
- type="button"
- variant="ghost"
- size="xs"
- className={cn(
- "kaneo-comment-editor-bubble-btn",
- "text-destructive",
- )}
- title={t("activity:comment.editor.table.deleteRow", {
- defaultValue: "Delete row",
- })}
- onClick={() => editor.chain().focus().deleteRow().run()}
- >
- <Rows3 className="size-3.5" />
- </Button>
- <span className="kaneo-tiptap-bubble-separator" />
- <Button
- type="button"
- variant="ghost"
- size="xs"
- className={cn(
- "kaneo-comment-editor-bubble-btn",
- "text-destructive",
- )}
- title={t("activity:comment.editor.table.deleteTable", {
- defaultValue: "Delete table",
- })}
- onClick={() => editor.chain().focus().deleteTable().run()}
- >
- <Grid2x2X className="size-3.5" />
- </Button>
+ labels={{
+ addColumnBefore: t(
+ "activity:comment.editor.table.addColumnBefore",
+ { defaultValue: "Insert column left" },
+ ),
+ addColumnAfter: t(
+ "activity:comment.editor.table.addColumnAfter",
+ { defaultValue: "Insert column right" },
+ ),
+ deleteColumn: t("activity:comment.editor.table.deleteColumn", {
+ defaultValue: "Delete column",
+ }),
+ addRowBefore: t("activity:comment.editor.table.addRowBefore", {
+ defaultValue: "Insert row above",
+ }),
+ addRowAfter: t("activity:comment.editor.table.addRowAfter", {
+ defaultValue: "Insert row below",
+ }),
+ deleteRow: t("activity:comment.editor.table.deleteRow", {
+ defaultValue: "Delete row",
+ }),
+ deleteTable: t("activity:comment.editor.table.deleteTable", {
+ defaultValue: "Delete table",
+ }),
+ }}
+ />
</BubbleMenu>
)}
{slashMenu && !readOnly && !disabled && (
diff --git a/apps/web/src/components/editor/extensions.ts b/apps/web/src/components/editor/extensions.ts
new file mode 100644
index 000000000..32e1d6f22
--- /dev/null
+++ b/apps/web/src/components/editor/extensions.ts
@@ -0,0 +1,67 @@
+import type { AnyExtension } from "@tiptap/core";
+import Placeholder from "@tiptap/extension-placeholder";
+import { Table } from "@tiptap/extension-table";
+import TableCell from "@tiptap/extension-table-cell";
+import TableHeader from "@tiptap/extension-table-header";
+import TableRow from "@tiptap/extension-table-row";
+import TaskList from "@tiptap/extension-task-list";
+import { Markdown } from "@tiptap/markdown";
+import StarterKit from "@tiptap/starter-kit";
+import type { Highlighter } from "shiki";
+import { AttachmentCard } from "@/components/task/extensions/attachment-card";
+import { EmbedBlock } from "@/components/task/extensions/embed-block";
+import { KaneoIssueLink } from "@/components/task/extensions/kaneo-issue-link";
+import { MermaidBlock } from "@/components/task/extensions/mermaid-block";
+import { SafeHardBreak } from "@/components/task/extensions/safe-hard-break";
+import { ShikiCodeBlock } from "@/components/task/extensions/shiki-code-block";
+import { TaskItemWithCheckbox } from "@/components/task/extensions/task-item-with-checkbox";
+
+export function createEditorExtensions({
+ placeholder,
+ highlighter,
+ resolveLanguage,
+ image,
+ extra = [],
+ mermaidErrorKey,
+}: {
+ placeholder: string;
+ highlighter: () => Highlighter | null;
+ resolveLanguage: (language: string) => string;
+ image: AnyExtension;
+ extra?: AnyExtension[];
+ mermaidErrorKey?: string;
+}) {
+ return [
+ StarterKit.configure({
+ codeBlock: { HTMLAttributes: { class: "kaneo-tiptap-codeblock" } },
+ trailingNode: false,
+ heading: { levels: [1, 2, 3] },
+ hardBreak: false,
+ }),
+ SafeHardBreak,
+ Markdown.configure({ markedOptions: { breaks: true, gfm: true } }),
+ ShikiCodeBlock.configure({
+ highlighter,
+ resolveLanguage,
+ themeDark: "github-dark",
+ themeLight: "github-light",
+ }),
+ mermaidErrorKey
+ ? MermaidBlock.configure({ errorKey: mermaidErrorKey })
+ : MermaidBlock,
+ EmbedBlock,
+ AttachmentCard,
+ KaneoIssueLink,
+ ...extra,
+ TaskList,
+ image.configure({
+ HTMLAttributes: { class: "kaneo-editor-image", loading: "lazy" },
+ }),
+ TaskItemWithCheckbox.configure({ nested: true }),
+ Placeholder.configure({ placeholder }),
+ Table.configure({ resizable: true }),
+ TableRow,
+ TableHeader,
+ TableCell,
+ ];
+}
diff --git a/apps/web/src/components/editor/insert-uploaded-asset.ts b/apps/web/src/components/editor/insert-uploaded-asset.ts
new file mode 100644
index 000000000..a4bb7584f
--- /dev/null
+++ b/apps/web/src/components/editor/insert-uploaded-asset.ts
@@ -0,0 +1,29 @@
+import type { Editor } from "@tiptap/core";
+import type { uploadTaskImage } from "@/lib/upload-task-image";
+
+export function insertUploadedAsset(
+ editor: Editor,
+ asset: Awaited<ReturnType<typeof uploadTaskImage>>,
+ errorMessage: string,
+ range?: { from: number; to: number },
+) {
+ const chain = editor.chain().focus();
+ if (range) chain.deleteRange(range);
+ else if (!editor.state.selection.empty)
+ chain.setTextSelection(editor.state.selection.to);
+ const ran =
+ asset.kind === "image"
+ ? chain.setImage({ src: asset.url, alt: asset.alt }).run()
+ : chain
+ .insertContent({
+ type: "attachmentCard",
+ attrs: {
+ url: asset.url,
+ filename: asset.filename,
+ mimeType: asset.mimeType,
+ size: asset.size,
+ },
+ })
+ .run();
+ if (!ran) throw new Error(errorMessage);
+}
diff --git a/apps/web/src/components/editor/slash-commands.ts b/apps/web/src/components/editor/slash-commands.ts
new file mode 100644
index 000000000..e301ba337
--- /dev/null
+++ b/apps/web/src/components/editor/slash-commands.ts
@@ -0,0 +1,100 @@
+import type { Editor } from "@tiptap/core";
+
+export type SlashRange = { from: number; to: number };
+export type SlashCommand = {
+ id: string;
+ label: string;
+ group: "text" | "lists" | "insert";
+ shortcut?: string;
+ search: string;
+ run: (editor: Editor, range: SlashRange) => void;
+};
+
+export const richTextCommands: SlashCommand[] = [
+ {
+ id: "paragraph",
+ label: "Text",
+ group: "text",
+ search: "text paragraph normal",
+ run: (editor, range) => {
+ editor.chain().focus().deleteRange(range).setParagraph().run();
+ },
+ },
+ {
+ id: "heading-2",
+ label: "Heading",
+ group: "text",
+ shortcut: "Ctrl Alt 2",
+ search: "heading title h2",
+ run: (editor, range) => {
+ editor
+ .chain()
+ .focus()
+ .deleteRange(range)
+ .toggleHeading({ level: 2 })
+ .run();
+ },
+ },
+ {
+ id: "bullet-list",
+ label: "Bulleted list",
+ group: "lists",
+ shortcut: "Ctrl Alt 8",
+ search: "list bullet unordered",
+ run: (editor, range) => {
+ editor.chain().focus().deleteRange(range).toggleBulletList().run();
+ },
+ },
+ {
+ id: "task-list",
+ label: "To-do list",
+ group: "lists",
+ search: "todo to-do checklist checkbox task list",
+ run: (editor, range) => {
+ editor.chain().focus().deleteRange(range).toggleTaskList().run();
+ },
+ },
+ {
+ id: "ordered-list",
+ label: "Numbered list",
+ group: "lists",
+ shortcut: "Ctrl Alt 9",
+ search: "list ordered numbered",
+ run: (editor, range) => {
+ editor.chain().focus().deleteRange(range).toggleOrderedList().run();
+ },
+ },
+ {
+ id: "blockquote",
+ label: "Quote",
+ group: "insert",
+ search: "quote blockquote",
+ run: (editor, range) => {
+ editor.chain().focus().deleteRange(range).toggleBlockquote().run();
+ },
+ },
+ {
+ id: "code-block",
+ label: "Code block",
+ group: "insert",
+ shortcut: "Ctrl Alt \\",
+ search: "code snippet",
+ run: (editor, range) => {
+ editor.chain().focus().deleteRange(range).toggleCodeBlock().run();
+ },
+ },
+ {
+ id: "table",
+ label: "Table",
+ group: "insert",
+ search: "table grid",
+ run: (editor, range) => {
+ editor
+ .chain()
+ .focus()
+ .deleteRange(range)
+ .insertTable({ cols: 3, rows: 3 })
+ .run();
+ },
+ },
+];
diff --git a/apps/web/src/components/editor/table-toolbar.tsx b/apps/web/src/components/editor/table-toolbar.tsx
new file mode 100644
index 000000000..a942fda39
--- /dev/null
+++ b/apps/web/src/components/editor/table-toolbar.tsx
@@ -0,0 +1,63 @@
+import type { Editor } from "@tiptap/core";
+import {
+ BetweenHorizontalEnd,
+ BetweenHorizontalStart,
+ BetweenVerticalEnd,
+ BetweenVerticalStart,
+ Columns3,
+ Grid2x2X,
+ Rows3,
+} from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/cn";
+
+export function TableToolbar({
+ editor,
+ className,
+ labels,
+}: {
+ editor: Editor;
+ className: string;
+ labels: {
+ addColumnBefore: string;
+ addColumnAfter: string;
+ deleteColumn: string;
+ addRowBefore: string;
+ addRowAfter: string;
+ deleteRow: string;
+ deleteTable: string;
+ };
+}) {
+ const actions = [
+ { command: "addColumnBefore", icon: BetweenVerticalStart },
+ { command: "addColumnAfter", icon: BetweenVerticalEnd },
+ {
+ command: "deleteColumn",
+ icon: Columns3,
+ destructive: true,
+ separator: true,
+ },
+ { command: "addRowBefore", icon: BetweenHorizontalStart },
+ { command: "addRowAfter", icon: BetweenHorizontalEnd },
+ { command: "deleteRow", icon: Rows3, destructive: true, separator: true },
+ { command: "deleteTable", icon: Grid2x2X, destructive: true },
+ ] as const;
+ return actions.map((action) => (
+ <span key={action.command} className="contents">
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ className={cn(className, "destructive" in action && "text-destructive")}
+ title={labels[action.command]}
+ aria-label={labels[action.command]}
+ onClick={() => editor.chain().focus()[action.command]().run()}
+ >
+ <action.icon className="size-3.5" />
+ </Button>
+ {"separator" in action && (
+ <span className="kaneo-tiptap-bubble-separator" />
+ )}
+ </span>
+ ));
+}
diff --git a/apps/web/src/components/editor/use-editor-highlighter.ts b/apps/web/src/components/editor/use-editor-highlighter.ts
new file mode 100644
index 000000000..b11923c0b
--- /dev/null
+++ b/apps/web/src/components/editor/use-editor-highlighter.ts
@@ -0,0 +1,30 @@
+import { useEffect, useRef, useState } from "react";
+import type { Highlighter } from "shiki";
+
+export function useEditorHighlighter() {
+ const [highlighter, setHighlighter] = useState<Highlighter | null>(null);
+ const highlighterRef = useRef<Highlighter | null>(null);
+ const [languages, setLanguages] = useState(() => new Set<string>(["text"]));
+ useEffect(() => {
+ let disposed = false;
+ void Promise.all([
+ import("@/lib/shiki-highlighter").then(({ getSharedShikiHighlighter }) =>
+ getSharedShikiHighlighter(),
+ ),
+ import("shiki"),
+ ])
+ .then(([instance, { bundledLanguages }]) => {
+ if (disposed) return;
+ highlighterRef.current = instance;
+ setHighlighter(instance);
+ setLanguages(new Set([...Object.keys(bundledLanguages), "text"]));
+ })
+ .catch((error) =>
+ console.error("Failed to initialize Shiki highlighter:", error),
+ );
+ return () => {
+ disposed = true;
+ };
+ }, []);
+ return { highlighter, highlighterRef, languages };
+}
diff --git a/apps/web/src/components/task/task-description.tsx b/apps/web/src/components/task/task-description.tsx
index 09cb6abff..4204cf8e6 100644
--- a/apps/web/src/components/task/task-description.tsx
+++ b/apps/web/src/components/task/task-description.tsx
@@ -1,28 +1,23 @@
+import {
+ richTextCommands,
+ type SlashCommand,
+ type SlashRange,
+} from "@/components/editor/slash-commands";
+import { TableToolbar } from "@/components/editor/table-toolbar";
+import { createEditorExtensions } from "@/components/editor/extensions";
+import { insertUploadedAsset as insertEditorAsset } from "@/components/editor/insert-uploaded-asset";
+import { useEditorHighlighter } from "@/components/editor/use-editor-highlighter";
import type { Editor } from "@tiptap/core";
-import Placeholder from "@tiptap/extension-placeholder";
-import { Table } from "@tiptap/extension-table";
-import TableCell from "@tiptap/extension-table-cell";
-import TableHeader from "@tiptap/extension-table-header";
-import TableRow from "@tiptap/extension-table-row";
-import TaskList from "@tiptap/extension-task-list";
-import { Markdown } from "@tiptap/markdown";
import { EditorState, TextSelection } from "@tiptap/pm/state";
import { EditorContent, useEditor } from "@tiptap/react";
import { BubbleMenu } from "@tiptap/react/menus";
-import StarterKit from "@tiptap/starter-kit";
import {
- BetweenHorizontalEnd,
- BetweenHorizontalStart,
- BetweenVerticalEnd,
- BetweenVerticalStart,
Bold,
Braces,
Check,
ChevronDown,
Code,
- Columns3,
Copy,
- Grid2x2X,
Heading2,
Italic,
Link2,
@@ -31,7 +26,6 @@ import {
ListTodo,
Paperclip,
Quote,
- Rows3,
Strikethrough,
Table2,
Underline as UnderlineIcon,
@@ -47,7 +41,6 @@ import {
useSyncExternalStore,
} from "react";
import { useTranslation } from "react-i18next";
-import type { Highlighter } from "shiki";
import { Button } from "@/components/ui/button";
import { Dialog, DialogPopup } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
@@ -74,17 +67,8 @@ import { isInCodeBlockLanguagePicker } from "@/lib/is-in-codeblock-language-pick
import { pasteMarkdown } from "@/lib/paste-markdown";
import { toast } from "@/lib/toast";
import { uploadTaskImage } from "@/lib/upload-task-image";
-import { AttachmentCard } from "./extensions/attachment-card";
-import { EmbedBlock } from "./extensions/embed-block";
-import { KaneoIssueLink } from "./extensions/kaneo-issue-link";
-import { MermaidBlock } from "./extensions/mermaid-block";
import { ResizableImage } from "./extensions/resizable-image";
-import { SafeHardBreak } from "./extensions/safe-hard-break";
-import {
- SHIKI_CODEBLOCK_REFRESH_META,
- ShikiCodeBlock,
-} from "./extensions/shiki-code-block";
-import { TaskItemWithCheckbox } from "./extensions/task-item-with-checkbox";
+import { SHIKI_CODEBLOCK_REFRESH_META } from "./extensions/shiki-code-block";
import "tippy.js/dist/tippy.css";
type TaskDescriptionProps = {
@@ -98,17 +82,6 @@ type HoveredCodeBlock = {
left: number;
};
-type SlashRange = { from: number; to: number };
-
-type SlashCommand = {
- id: string;
- label: string;
- group: "text" | "lists" | "insert";
- shortcut?: string;
- search: string;
- run: (editor: Editor, range: SlashRange) => void;
-};
-
type SlashMenuState = {
from: number;
to: number;
@@ -205,95 +178,6 @@ const SHIKI_LANGUAGE_ALIASES: Record<string, string> = {
reasonml: "ocaml",
};
-const SLASH_COMMANDS: SlashCommand[] = [
- {
- id: "paragraph",
- label: "Text",
- group: "text",
- search: "text paragraph normal",
- run: (editor, range) => {
- editor.chain().focus().deleteRange(range).setParagraph().run();
- },
- },
- {
- id: "heading-2",
- label: "Heading",
- group: "text",
- shortcut: "Ctrl Alt 2",
- search: "heading title h2",
- run: (editor, range) => {
- editor
- .chain()
- .focus()
- .deleteRange(range)
- .toggleHeading({ level: 2 })
- .run();
- },
- },
- {
- id: "bullet-list",
- label: "Bulleted list",
- group: "lists",
- shortcut: "Ctrl Alt 8",
- search: "list bullet unordered",
- run: (editor, range) => {
- editor.chain().focus().deleteRange(range).toggleBulletList().run();
- },
- },
- {
- id: "task-list",
- label: "To-do list",
- group: "lists",
- search: "todo to-do checklist checkbox task list",
- run: (editor, range) => {
- editor.chain().focus().deleteRange(range).toggleTaskList().run();
- },
- },
- {
- id: "ordered-list",
- label: "Numbered list",
- group: "lists",
- shortcut: "Ctrl Alt 9",
- search: "list ordered numbered",
- run: (editor, range) => {
- editor.chain().focus().deleteRange(range).toggleOrderedList().run();
- },
- },
- {
- id: "blockquote",
- label: "Quote",
- group: "insert",
- search: "quote blockquote",
- run: (editor, range) => {
- editor.chain().focus().deleteRange(range).toggleBlockquote().run();
- },
- },
- {
- id: "code-block",
- label: "Code block",
- group: "insert",
- shortcut: "Ctrl Alt \\",
- search: "code snippet",
- run: (editor, range) => {
- editor.chain().focus().deleteRange(range).toggleCodeBlock().run();
- },
- },
- {
- id: "table",
- label: "Table",
- group: "insert",
- search: "table grid",
- run: (editor, range) => {
- editor
- .chain()
- .focus()
- .deleteRange(range)
- .insertTable({ cols: 3, rows: 3 })
- .run();
- },
- },
-];
-
export default function TaskDescription({ taskId }: TaskDescriptionProps) {
const { t } = useTranslation();
const { data: task } = useGetTask(taskId);
@@ -332,10 +216,11 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
const [isCodeLanguageMenuOpen, setIsCodeLanguageMenuOpen] = useState(false);
const codeCopyResetTimeoutRef = useRef<number | null>(null);
const [isCodeCopied, setIsCodeCopied] = useState(false);
- const [shikiHighlighter, setShikiHighlighter] = useState<Highlighter | null>(
- null,
- );
- const shikiHighlighterRef = useRef<Highlighter | null>(null);
+ const {
+ highlighter: shikiHighlighter,
+ highlighterRef: shikiHighlighterRef,
+ languages: shikiSupportedLanguages,
+ } = useEditorHighlighter();
const [slashMenu, setSlashMenu] = useState<SlashMenuState | null>(null);
const [embedComposer, setEmbedComposer] = useState<EmbedComposerState | null>(
null,
@@ -354,9 +239,6 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
updateTaskRef.current = updateTaskDescription;
}, [task, taskId, updateTaskDescription]);
- const [shikiSupportedLanguages, setShikiSupportedLanguages] = useState(
- () => new Set<string>(["text"]),
- );
const toShikiLanguage = useCallback(
(language: string) => SHIKI_LANGUAGE_ALIASES[language] || language,
[],
@@ -392,50 +274,16 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
const insertUploadedAsset = useCallback(
(
- activeEditor: Editor,
+ editor: Editor,
asset: Awaited<ReturnType<typeof uploadTaskImage>>,
range?: SlashRange,
) => {
- const chain = activeEditor.chain().focus();
-
- if (range) {
- chain.deleteRange(range);
- } else {
- const { selection } = activeEditor.state;
- if (!selection.empty) {
- chain.setTextSelection(selection.to);
- }
- }
-
- if (asset.kind === "image") {
- const ran = chain
- .setImage({
- src: asset.url,
- alt: asset.alt,
- })
- .run();
- // Chain commands report silent failure via false rather than
- // throwing; convert it so the caller's catch reports it.
- if (!ran) {
- throw new Error(t("tasks:detail.editor.upload.failed"));
- }
- return;
- }
-
- const ran = chain
- .insertContent({
- type: "attachmentCard",
- attrs: {
- url: asset.url,
- filename: asset.filename,
- mimeType: asset.mimeType,
- size: asset.size,
- },
- })
- .run();
- if (!ran) {
- throw new Error(t("tasks:detail.editor.upload.failed"));
- }
+ insertEditorAsset(
+ editor,
+ asset,
+ t("tasks:detail.editor.upload.failed"),
+ range,
+ );
},
[t],
);
@@ -559,7 +407,7 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
const slashCommands = useMemo(
() => [
- ...SLASH_COMMANDS.map((command) => ({
+ ...richTextCommands.map((command) => ({
...command,
label: t(`tasks:detail.editor.slash.commands.${command.id}`, {
defaultValue: command.label,
@@ -579,33 +427,6 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
[openImagePicker, t],
);
- useEffect(() => {
- let isDisposed = false;
-
- void Promise.all([
- import("@/lib/shiki-highlighter").then(({ getSharedShikiHighlighter }) =>
- getSharedShikiHighlighter(),
- ),
- import("shiki"),
- ])
- .then(([nextHighlighter, { bundledLanguages: languages }]) => {
- shikiHighlighterRef.current = nextHighlighter;
- if (!isDisposed) {
- setShikiHighlighter(nextHighlighter);
- setShikiSupportedLanguages(
- new Set([...Object.keys(languages), "text"]),
- );
- }
- })
- .catch((error) => {
- console.error("Failed to initialize Shiki highlighter:", error);
- });
-
- return () => {
- isDisposed = true;
- };
- }, []);
-
const saveState = useSyncExternalStore(
descriptionSaveQueue.subscribe,
() => descriptionSaveQueue.get(taskId)?.state ?? "saved",
@@ -622,52 +443,12 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
const editor = useEditor(
{
immediatelyRender: false,
- extensions: [
- StarterKit.configure({
- codeBlock: {
- HTMLAttributes: { class: "kaneo-tiptap-codeblock" },
- },
- trailingNode: false,
- heading: { levels: [1, 2, 3] },
- hardBreak: false,
- }),
- SafeHardBreak,
- Markdown.configure({
- markedOptions: {
- breaks: true,
- gfm: true,
- },
- }),
- ShikiCodeBlock.configure({
- highlighter: () => shikiHighlighterRef.current,
- resolveLanguage: toShikiLanguage,
- themeDark: "github-dark",
- themeLight: "github-light",
- }),
- MermaidBlock,
- EmbedBlock,
- AttachmentCard,
- KaneoIssueLink,
- TaskList,
- ResizableImage.configure({
- HTMLAttributes: {
- class: "kaneo-editor-image",
- loading: "lazy",
- },
- }),
- TaskItemWithCheckbox.configure({
- nested: true,
- }),
- Placeholder.configure({
- placeholder: t("tasks:detail.editor.placeholder"),
- }),
- Table.configure({
- resizable: true,
- }),
- TableRow,
- TableHeader,
- TableCell,
- ],
+ extensions: createEditorExtensions({
+ placeholder: t("tasks:detail.editor.placeholder"),
+ highlighter: () => shikiHighlighterRef.current,
+ resolveLanguage: toShikiLanguage,
+ image: ResizableImage,
+ }),
editorProps: {
attributes: {
class: "kaneo-tiptap-prose",
@@ -1722,92 +1503,33 @@ export default function TaskDescription({ taskId }: TaskDescriptionProps) {
activeEditor.isActive("table") && from === to
}
>
- <Button
- type="button"
- variant="ghost"
- size="xs"
- className="kaneo-tiptap-bubble-btn"
- title={t("tasks:editor.table.addColumnBefore", {
- defaultValue: "Insert column left",
- })}
- onClick={() => editor.chain().focus().addColumnBefore().run()}
- >
- <BetweenVerticalStart className="size-3.5" />
- </Button>
- <Button
- type="button"
- variant="ghost"
- size="xs"
- className="kaneo-tiptap-bubble-btn"
- title={t("tasks:editor.table.addColumnAfter", {
- defaultValue: "Insert column right",
- })}
- onClick={() => editor.chain().focus().addColumnAfter().run()}
- >
- <BetweenVerticalEnd className="size-3.5" />
- </Button>
- <Button
- type="button"
- variant="ghost"
- size="xs"
- className={cn("kaneo-tiptap-bubble-btn", "text-destructive")}
- title={t("tasks:editor.table.deleteColumn", {
- defaultValue: "Delete column",
- })}
- onClick={() => editor.chain().focus().deleteColumn().run()}
- >
- <Columns3 className="size-3.5" />
- </Button>
- <span className="kaneo-tiptap-bubble-separator" />
- <Button
- type="button"
- variant="ghost"
- size="xs"
+ <TableToolbar
+ editor={editor}
className="kaneo-tiptap-bubble-btn"
- title={t("tasks:editor.table.addRowBefore", {
- defaultValue: "Insert row above",
- })}
- onClick={() => editor.chain().focus().addRowBefore().run()}
- >
- <BetweenHorizontalStart className="size-3.5" />
- </Button>
- <Button
- type="button"
- variant="ghost"
- size="xs"
- className="kaneo-tiptap-bubble-btn"
- title={t("tasks:editor.table.addRowAfter", {
- defaultValue: "Insert row below",
- })}
- onClick={() => editor.chain().focus().addRowAfter().run()}
- >
- <BetweenHorizontalEnd className="size-3.5" />
- </Button>
- <Button
- type="button"
- variant="ghost"
- size="xs"
- className={cn("kaneo-tiptap-bubble-btn", "text-destructive")}
- title={t("tasks:editor.table.deleteRow", {
- defaultValue: "Delete row",
- })}
- onClick={() => editor.chain().focus().deleteRow().run()}
- >
- <Rows3 className="size-3.5" />
- </Button>
- <span className="kaneo-tiptap-bubble-separator" />
- <Button
- type="button"
- variant="ghost"
- size="xs"
- className={cn("kaneo-tiptap-bubble-btn", "text-destructive")}
- title={t("tasks:editor.table.deleteTable", {
- defaultValue: "Delete table",
- })}
- onClick={() => editor.chain().focus().deleteTable().run()}
- >
- <Grid2x2X className="size-3.5" />
- </Button>
+ labels={{
+ addColumnBefore: t("tasks:editor.table.addColumnBefore", {
+ defaultValue: "Insert column left",
+ }),
+ addColumnAfter: t("tasks:editor.table.addColumnAfter", {
+ defaultValue: "Insert column right",
+ }),
+ deleteColumn: t("tasks:editor.table.deleteColumn", {
+ defaultValue: "Delete column",
+ }),
+ addRowBefore: t("tasks:editor.table.addRowBefore", {
+ defaultValue: "Insert row above",
+ }),
+ addRowAfter: t("tasks:editor.table.addRowAfter", {
+ defaultValue: "Insert row below",
+ }),
+ deleteRow: t("tasks:editor.table.deleteRow", {
+ defaultValue: "Delete row",
+ }),
+ deleteTable: t("tasks:editor.table.deleteTable", {
+ defaultValue: "Delete table",
+ }),
+ }}
+ />
</BubbleMenu>
)}