Track HiveGrid Cloud planning reference

This commit is contained in:
david committed 2026-06-26 20:48:01 +02:00
1 parent b3d5ea6764
commit e341c5938a
5784 files changed
+1104929 -3

No files matched your search

@@ -0,0 +1,95 @@
import { Editor } from "@tiptap/core";
import clsx from "clsx";
import { Check, ChevronDown } from "~/components/ui/icons/vendor";
import { useTranslation } from "react-i18next";
export interface BubbleColorMenuItem {
name: string;
color: string;
}
interface ColorSelectorProps {
editor: Editor;
isOpen: boolean;
setIsOpen: (isOpen: boolean) => void;
}
export default function ColorSelector({ editor, isOpen, setIsOpen }: ColorSelectorProps) {
const { t } = useTranslation();
const items: BubbleColorMenuItem[] = [
{
name: t("novel.editor.colors.default"),
color: "#000000",
},
{
name: t("novel.editor.colors.purple"),
color: "#9333EA",
},
{
name: t("novel.editor.colors.red"),
color: "#E00000",
},
{
name: t("novel.editor.colors.blue"),
color: "#2563EB",
},
{
name: t("novel.editor.colors.green"),
color: "#008A00",
},
{
name: t("novel.editor.colors.orange"),
color: "#FFA500",
},
{
name: t("novel.editor.colors.pink"),
color: "#BA4081",
},
{
name: t("novel.editor.colors.gray"),
color: "#A8A29E",
},
];
const activeItem = items.find(({ color }) => editor.isActive("textStyle", { color }));
return (
<div className="relative h-full">
<button
type="button"
className="text-muted-foreground hover:bg-secondary flex h-full items-center gap-1 p-2 text-sm font-medium"
onClick={() => setIsOpen(!isOpen)}
>
<span style={{ color: activeItem?.color || "#000000" }}>{t("novel.editor.colors.label")}</span>
<ChevronDown className="h-4 w-4 " />
</button>
{isOpen && (
<section className="animate-in fade-in slide-in-from-top-1 bg-background fixed top-full z-99999 mt-1 flex w-48 flex-col overflow-hidden rounded border border-stone-200 p-1 shadow-xl">
{items.map(({ name, color }, index) => (
<button
type="button"
key={index}
onClick={() => {
editor.chain().focus().setColor(color).run();
setIsOpen(false);
}}
className={clsx("flex items-center justify-between rounded-sm px-2 py-1 text-sm text-stone-600 hover:bg-stone-100", {
"text-blue-600": editor.isActive("textStyle", { color }),
})}
>
<div className="flex items-center space-x-2">
<div className="rounded-sm border border-stone-200 px-1 py-px font-medium" style={{ color }}>
A
</div>
<span>{name}</span>
</div>
{editor.isActive("textStyle", { color }) && <Check className="h-4 w-4" />}
</button>
))}
</section>
)}
</div>
);
}
@@ -0,0 +1,124 @@
import { BubbleMenu, BubbleMenuProps } from "@tiptap/react";
import clsx from "clsx";
import { Fragment, useState } from "react";
import { BoldIcon, ItalicIcon, UnderlineIcon, CodeIcon } from "~/components/ui/icons/vendor";
import { NodeSelector } from "./NodeSelector";
import ColorSelector from "./ColorSelector";
// million-ignore
export interface BubbleMenuItem {
name: string;
isActive: () => boolean;
command: () => void;
icon: typeof BoldIcon;
}
type EditorBubbleMenuProps = Omit<BubbleMenuProps, "children">;
export const EditorBubbleMenu: React.FC<EditorBubbleMenuProps> = (props) => {
const items: BubbleMenuItem[] = [
{
name: "bold",
isActive: () => props.editor?.isActive("bold") ?? false,
command: () => props.editor?.chain().focus().toggleBold().run(),
icon: BoldIcon,
},
{
name: "italic",
isActive: () => props.editor?.isActive("italic") ?? false,
command: () => props.editor?.chain().focus().toggleItalic().run(),
icon: ItalicIcon,
},
{
name: "underline",
isActive: () => props.editor?.isActive("underline") ?? false,
command: () => props.editor?.chain().focus().toggleUnderline().run(),
icon: UnderlineIcon,
},
// {
// name: "strike",
// isActive: () => props.editor?.isActive("strike") ?? false,
// command: () => props.editor?.chain().focus().toggleStrike().run(),
// icon: StrikethroughIcon,
// },
{
name: "code",
isActive: () => props.editor?.isActive("code") ?? false,
command: () => props.editor?.chain().focus().toggleCode().run(),
icon: CodeIcon,
},
];
const bubbleMenuProps: EditorBubbleMenuProps = {
...props,
shouldShow: ({ editor }) => {
// don't show if image is selected
if (editor?.isActive("image")) {
return false;
}
return editor.view.state.selection.content().size > 0;
},
tippyOptions: {
moveTransition: "transform 0.15s ease-out",
onHidden: () => {
setIsNodeSelectorOpen(false);
setIsColorSelectorOpen(false);
},
},
};
const [isNodeSelectorOpen, setIsNodeSelectorOpen] = useState(false);
const [isColorSelectorOpen, setIsColorSelectorOpen] = useState(false);
return (
<BubbleMenu {...bubbleMenuProps} className="bg-background flex overflow-hidden rounded border border-stone-200 shadow-xl">
{props.editor && (
<Fragment>
<NodeSelector
editor={props.editor}
isOpen={isNodeSelectorOpen}
setIsOpen={() => {
setIsNodeSelectorOpen(!isNodeSelectorOpen);
setIsColorSelectorOpen(false);
}}
/>
{items.map((item, index) => (
<button
key={index}
onClick={item.command}
type="button"
aria-label={item.name}
aria-pressed={item.isActive()}
className="min-h-10 min-w-10 p-2 text-stone-600 hover:bg-stone-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 active:bg-stone-200"
>
<item.icon
aria-hidden="true"
className={clsx("h-4 w-4", {
"text-blue-500": item.isActive(),
})}
/>
</button>
))}
<ColorSelector
editor={props.editor}
isOpen={isColorSelectorOpen}
setIsOpen={() => {
setIsColorSelectorOpen(!isColorSelectorOpen);
setIsNodeSelectorOpen(false);
}}
/>
{/* <ColorSelector
editor={props.editor}
isOpen={isColorSelectorOpen}
setIsOpen={() => {
setIsColorSelectorOpen(!isColorSelectorOpen);
setIsNodeSelectorOpen(false);
}}
/> */}
</Fragment>
)}
</BubbleMenu>
);
};
@@ -0,0 +1,110 @@
import { Editor } from "@tiptap/core";
import clsx from "clsx";
import { Check, ChevronDown, Heading1, Heading2, Heading3, TextQuote, ListOrdered, TextIcon, Code } from "~/components/ui/icons/vendor";
import { useTranslation } from "react-i18next";
import { BubbleMenuItem } from "./EditorBubbleMenu";
interface NodeSelectorProps {
editor: Editor;
isOpen: boolean;
setIsOpen: (isOpen: boolean) => void;
}
export const NodeSelector: React.FC<NodeSelectorProps> = ({ editor, isOpen, setIsOpen }) => {
const { t } = useTranslation();
const items: BubbleMenuItem[] = [
{
name: t("novel.editor.commands.text"),
icon: TextIcon,
command: () => editor.chain().focus().toggleNode("paragraph", "paragraph").run(),
// I feel like there has to be a more efficient way to do this – feel free to PR if you know how!
isActive: () => editor.isActive("paragraph") && !editor.isActive("bulletList") && !editor.isActive("orderedList"),
},
{
name: t("novel.editor.commands.heading1"),
icon: Heading1,
command: () => editor.chain().focus().toggleHeading({ level: 1 }).run(),
isActive: () => editor.isActive("heading", { level: 1 }),
},
{
name: t("novel.editor.commands.heading2"),
icon: Heading2,
command: () => editor.chain().focus().toggleHeading({ level: 2 }).run(),
isActive: () => editor.isActive("heading", { level: 2 }),
},
{
name: t("novel.editor.commands.heading3"),
icon: Heading3,
command: () => editor.chain().focus().toggleHeading({ level: 3 }).run(),
isActive: () => editor.isActive("heading", { level: 3 }),
},
{
name: t("novel.editor.commands.bulletList"),
icon: ListOrdered,
command: () => editor.chain().focus().toggleBulletList().run(),
isActive: () => editor.isActive("bulletList"),
},
{
name: t("novel.editor.commands.orderedList"),
icon: ListOrdered,
command: () => editor.chain().focus().toggleOrderedList().run(),
isActive: () => editor.isActive("orderedList"),
},
{
name: t("novel.editor.commands.quote"),
icon: TextQuote,
command: () => editor.chain().focus().toggleNode("paragraph", "paragraph").toggleBlockquote().run(),
isActive: () => editor.isActive("blockquote"),
},
{
name: t("novel.editor.commands.code"),
icon: Code,
command: () => editor.chain().focus().toggleCodeBlock().run(),
isActive: () => editor.isActive("codeBlock"),
},
];
const activeItem = items.filter((item) => item.isActive()).pop() ?? {
name: t("novel.editor.commands.multiple"),
};
return (
<div className="relative h-full">
<button
className="flex h-full items-center gap-1 p-2 text-sm font-medium text-stone-600 hover:bg-stone-100 active:bg-stone-200"
type="button"
onClick={() => setIsOpen(!isOpen)}
>
<span>{activeItem?.name}</span>
<ChevronDown className="h-4 w-4" />
</button>
{isOpen && (
<section className="animate-in fade-in slide-in-from-top-1 bg-background fixed top-full z-99999 mt-1 flex w-48 flex-col overflow-hidden rounded border border-stone-200 p-1 shadow-xl">
{items.map((item, index) => (
<button
type="button"
key={index}
onClick={() => {
item.command();
setIsOpen(false);
}}
className={clsx("flex items-center justify-between rounded-sm px-2 py-1 text-sm text-stone-600 hover:bg-stone-100", {
"text-blue-600": item.isActive(),
})}
>
<div className="flex items-center space-x-2">
<div className="rounded-sm border border-stone-200 p-1">
<item.icon className="h-3 w-3" />
</div>
<span>{item.name}</span>
</div>
{activeItem.name === item.name && <Check className="h-4 w-4" />}
</button>
))}
</section>
)}
</div>
);
};
@@ -0,0 +1 @@
export * from "./EditorBubbleMenu";
@@ -0,0 +1,159 @@
import { JSONContent } from "@tiptap/core";
import { t as i18nT } from "i18next";
const DEFAULT_EDITOR_CONTENT: JSONContent = {
type: "doc",
content: [
{
type: "heading",
attrs: { level: 2 },
content: [{ type: "text", text: i18nT("novel.editor.defaultContent.title") }],
},
{
type: "paragraph",
content: [
{
type: "text",
text: i18nT("novel.editor.defaultContent.introLead"),
},
{
type: "text",
marks: [
{
type: "link",
attrs: {
href: "https://tiptap.dev/",
target: "_blank",
class: "text-stone-400 underline underline-offset-[3px] hover:text-stone-600 transition-colors cursor-pointer",
},
},
],
text: "Tiptap",
},
{ type: "text", text: i18nT("novel.editor.defaultContent.commaSeparator") },
{
type: "text",
marks: [
{
type: "link",
attrs: {
href: "https://sdk.vercel.ai/docs",
target: "_blank",
class: "text-stone-400 underline underline-offset-[3px] hover:text-stone-600 transition-colors cursor-pointer",
},
},
],
text: "AI SDK",
},
{ type: "text", text: i18nT("novel.editor.defaultContent.andThe") },
{
type: "text",
marks: [
{
type: "link",
attrs: {
href: "https://sdk.vercel.ai/docs",
target: "_blank",
class: "text-stone-400 underline underline-offset-[3px] hover:text-stone-600 transition-colors cursor-pointer",
},
},
],
text: "Vercel AI SDK",
},
{ type: "text", text: i18nT("novel.editor.defaultContent.arrowSeparator") },
{ type: "text", marks: [{ type: "code" }], text: "npm i ai" },
],
},
{
type: "heading",
attrs: { level: 3 },
content: [{ type: "text", text: i18nT("novel.editor.defaultContent.learnMore") }],
},
{
type: "orderedList",
attrs: { start: 1 },
content: [
{
type: "listItem",
content: [
{
type: "paragraph",
content: [
{ type: "text", text: i18nT("novel.editor.defaultContent.checkOutThe") },
{
type: "text",
marks: [
{
type: "link",
attrs: {
href: "https://twitter.com/steventey/status/1669762868416512000",
target: "_blank",
class: "text-stone-400 underline underline-offset-[3px] hover:text-stone-600 transition-colors cursor-pointer",
},
},
],
text: i18nT("novel.editor.defaultContent.launchVideo"),
},
{ type: "text", text: i18nT("novel.editor.defaultContent.period") },
],
},
],
},
{
type: "listItem",
content: [
{
type: "paragraph",
content: [
{ type: "text", text: i18nT("novel.editor.defaultContent.starUsOn") },
{
type: "text",
marks: [
{
type: "link",
attrs: {
href: "https://github.com/steven-tey/novel",
target: "_blank",
class: "text-stone-400 underline underline-offset-[3px] hover:text-stone-600 transition-colors cursor-pointer",
},
},
],
text: "GitHub",
},
{ type: "text", text: i18nT("novel.editor.defaultContent.period") },
],
},
],
},
{
type: "listItem",
content: [
{
type: "paragraph",
content: [
{
type: "text",
marks: [
{
type: "link",
attrs: {
href: "https://vercel.com/templates/next.js/novel",
target: "_blank",
class: "text-stone-400 underline underline-offset-[3px] hover:text-stone-600 transition-colors cursor-pointer",
},
},
],
text: i18nT("novel.editor.defaultContent.deploy"),
},
{ type: "text", text: i18nT("novel.editor.defaultContent.yourOwn") },
],
},
],
},
],
},
{ type: "paragraph" },
],
};
export default DEFAULT_EDITOR_CONTENT;
@@ -0,0 +1,145 @@
import StarterKit from "@tiptap/starter-kit";
import HorizontalRule from "@tiptap/extension-horizontal-rule";
import TiptapLink from "@tiptap/extension-link";
import TiptapImage from "@tiptap/extension-image";
import Placeholder from "@tiptap/extension-placeholder";
import TiptapUnderline from "@tiptap/extension-underline";
import TextStyle from "@tiptap/extension-text-style";
import { Color } from "@tiptap/extension-color";
import HighlightExtension from "@tiptap/extension-highlight";
import Collaboration from "@tiptap/extension-collaboration";
import CollaborationCursor from "@tiptap/extension-collaboration-cursor";
import type { HocuspocusProvider } from "@hocuspocus/provider";
import type * as Y from "yjs";
import { t as i18nT, type TFunction } from "i18next";
import SlashCommand, { createSlashCommand } from "./slash-command";
import { InputRule } from "@tiptap/core";
import type { ImageUploadOptions } from "~/modules/novel/lib/utils/editor";
export type CollaborationConfig = {
/** Y.Doc instance shared between Collaboration + HocuspocusProvider. */
readonly document: Y.Doc;
/** Live provider; only its `awareness` field is used here. */
readonly provider: HocuspocusProvider;
/** Identity rendered as the live cursor label. */
readonly user: {
readonly name: string;
readonly color: string;
readonly avatarUrl?: string | null;
};
};
export function createTiptapExtensions(options: ImageUploadOptions = {}, collab: CollaborationConfig | null = null, t: TFunction = i18nT) {
// When collab is enabled we must remove StarterKit.history — Collaboration
// ships its own Y.js-aware history extension, and having two history
// implementations registered raises a Tiptap warning + breaks undo/redo.
const starterKitHistory: false | undefined = collab ? false : undefined;
return [
StarterKit.configure({
history: starterKitHistory,
bulletList: {
HTMLAttributes: {
class: "list-disc list-outside leading-3",
},
},
orderedList: {
HTMLAttributes: {
class: "list-decimal list-outside leading-3",
},
},
listItem: {
HTMLAttributes: {
class: "leading-normal",
},
},
blockquote: {
HTMLAttributes: {
class: "border-l-4 border-border",
},
},
codeBlock: {
HTMLAttributes: {
class: "rounded-sm bg-secondary text-secondary-foreground p-5 font-mono font-medium",
},
},
code: {
HTMLAttributes: {
class: "rounded-md bg-secondary text-secondary-foreground px-1.5 py-1 font-mono font-medium",
},
},
horizontalRule: false,
dropcursor: {
color: "#DBEAFE",
width: 4,
},
gapcursor: false,
}),
// patch to fix horizontal rule bug: https://github.com/ueberdosis/tiptap/pull/3859#issuecomment-1536799740
HorizontalRule.extend({
addInputRules() {
return [
new InputRule({
find: /^(?:---|—-|___\s|\*\*\*\s)$/,
handler: ({ state, range, match }) => {
const attributes = {};
const { tr } = state;
const start = range.from;
let end = range.to;
tr.insert(start - 1, this.type.create(attributes)).delete(tr.mapping.map(start), tr.mapping.map(end));
},
}),
];
},
}).configure({
HTMLAttributes: {
class: "mt-4 mb-6 border-t border-border",
},
}),
TiptapLink.configure({
autolink: true,
HTMLAttributes: {
rel: "noopener noreferrer",
target: "_blank",
class: "text-muted-foreground underline underline-offset-[3px] hover:text-foreground transition-colors cursor-pointer",
},
}),
TiptapImage.configure({
allowBase64: true,
HTMLAttributes: {
class: "rounded-lg border border-border",
},
}),
Placeholder.configure({
placeholder: ({ node }) => {
if (node.type.name === "heading") {
return t("novel.editor.placeholder.heading", { level: node.attrs.level });
}
return t("novel.editor.placeholder.commands");
},
includeChildren: true,
}),
options.apiBaseUrl ? createSlashCommand(options) : SlashCommand,
TiptapUnderline,
TextStyle,
Color,
HighlightExtension.configure({ multicolor: true }),
...(collab
? [
Collaboration.configure({ document: collab.document }),
CollaborationCursor.configure({
provider: collab.provider,
user: {
name: collab.user.name,
color: collab.user.color,
avatarUrl: collab.user.avatarUrl ?? null,
},
}),
]
: []),
];
}
export const TiptapExtensions = createTiptapExtensions();
@@ -0,0 +1,22 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
const sourcePath = path.resolve(process.cwd(), "apps/web/app/modules/novel/ui/editor/extensions/slash-command.tsx");
describe("novel slash command i18n", () => {
it("keeps visible command copy behind semantic translation keys", () => {
const source = fs.readFileSync(sourcePath, "utf8");
expect(source).toContain("novel.editor.commands.continueWriting");
expect(source).toContain("novel.editor.commands.heading1");
expect(source).toContain("novel.editor.commands.orderedList");
expect(source).toContain("novel.editor.commandDescriptions.continueWriting");
expect(source).toContain("novel.editor.commandDescriptions.text");
expect(source).toContain("novel.editor.commandDescriptions.image");
expect(source).not.toContain("ui.autogenerated");
expect(source).not.toContain("Continue writing");
expect(source).not.toContain("Use AI to expand your thoughts");
expect(source).not.toContain("Just start typing with plain text");
});
});
@@ -0,0 +1,356 @@
import React, { useState, useEffect, useCallback, ReactNode, useRef, useLayoutEffect } from "react";
import { t as i18nT } from "i18next";
import { Editor, Range, Extension } from "@tiptap/core";
import Suggestion from "@tiptap/suggestion";
import { ReactRenderer } from "@tiptap/react";
import { useCompletion } from "../../../lib/ai/react/useCompletion";
import tippy from "tippy.js";
import { Heading1, Heading2, Heading3, List, ListOrdered, Text, TextQuote, Image as ImageIcon, Code } from "~/components/ui/icons/vendor";
import LoadingCircle from "~/modules/novel/ui/shared/loading-circle";
import { toast } from "sonner";
import Magic from "~/modules/novel/ui/shared/magic";
import { handleImageUpload, type ImageUploadOptions } from "~/modules/novel/lib/utils/editor";
interface CommandItemProps {
id: string;
title: string;
description: string;
icon: ReactNode;
}
interface Command {
editor: Editor;
range: Range;
}
const CommandExtension = Extension.create({
name: "slash-command",
addOptions() {
return {
suggestion: {
char: "/",
command: ({ editor, range, props }: { editor: Editor; range: Range; props: any }) => {
props.command({ editor, range });
},
},
};
},
addProseMirrorPlugins() {
return [
Suggestion({
editor: this.editor,
...this.options.suggestion,
}),
];
},
});
const getSuggestionItems = ({ query, options = {} }: { query: string; options?: ImageUploadOptions }) => {
const apiBaseUrl = options.apiBaseUrl;
return [
{
id: "continue-writing",
title: i18nT("novel.editor.commands.continueWriting"),
description: i18nT("novel.editor.commandDescriptions.continueWriting"),
icon: <Magic className="w-7 text-black" />,
},
// {
// title: "Send Feedback",
// description: "Let us know how we can improve.",
// icon: <MessageSquarePlus size={18} />,
// command: ({ editor, range }: Command) => {
// editor.chain().focus().deleteRange(range).run();
// window.open("/feedback", "_blank");
// },
// },
{
id: "text",
title: i18nT("novel.editor.commands.text"),
description: i18nT("novel.editor.commandDescriptions.text"),
icon: <Text size={18} />,
command: ({ editor, range }: Command) => {
editor.chain().focus().deleteRange(range).toggleNode("paragraph", "paragraph").run();
},
},
{
id: "heading-1",
title: i18nT("novel.editor.commands.heading1"),
description: i18nT("novel.editor.commandDescriptions.heading1"),
icon: <Heading1 size={18} />,
command: ({ editor, range }: Command) => {
editor.chain().focus().deleteRange(range).setNode("heading", { level: 1 }).run();
},
},
{
id: "heading-2",
title: i18nT("novel.editor.commands.heading2"),
description: i18nT("novel.editor.commandDescriptions.heading2"),
icon: <Heading2 size={18} />,
command: ({ editor, range }: Command) => {
editor.chain().focus().deleteRange(range).setNode("heading", { level: 2 }).run();
},
},
{
id: "heading-3",
title: i18nT("novel.editor.commands.heading3"),
description: i18nT("novel.editor.commandDescriptions.heading3"),
icon: <Heading3 size={18} />,
command: ({ editor, range }: Command) => {
editor.chain().focus().deleteRange(range).setNode("heading", { level: 3 }).run();
},
},
{
id: "bullet-list",
title: i18nT("novel.editor.commands.bulletList"),
description: i18nT("novel.editor.commandDescriptions.bulletList"),
icon: <List size={18} />,
command: ({ editor, range }: Command) => {
editor.chain().focus().deleteRange(range).toggleBulletList().run();
},
},
{
id: "ordered-list",
title: i18nT("novel.editor.commands.orderedList"),
description: i18nT("novel.editor.commandDescriptions.orderedList"),
icon: <ListOrdered size={18} />,
command: ({ editor, range }: Command) => {
editor.chain().focus().deleteRange(range).toggleOrderedList().run();
},
},
{
id: "quote",
title: i18nT("novel.editor.commands.quote"),
description: i18nT("novel.editor.commandDescriptions.quote"),
icon: <TextQuote size={18} />,
command: ({ editor, range }: Command) => editor.chain().focus().deleteRange(range).toggleNode("paragraph", "paragraph").toggleBlockquote().run(),
},
{
id: "code",
title: i18nT("novel.editor.commands.code"),
description: i18nT("novel.editor.commandDescriptions.code"),
icon: <Code size={18} />,
command: ({ editor, range }: Command) => editor.chain().focus().deleteRange(range).toggleCodeBlock().run(),
},
{
id: "image",
title: i18nT("novel.editor.commands.image"),
description: i18nT("novel.editor.commandDescriptions.image"),
icon: <ImageIcon size={18} />,
command: ({ editor, range }: Command) => {
editor.chain().focus().deleteRange(range).run();
// upload image
const input = document.createElement("input");
input.type = "file";
input.accept = "image/*";
input.onchange = async (event) => {
if (input.files?.length) {
const file = input.files[0];
return handleImageUpload(file, editor.view, event, { ...options, apiBaseUrl });
}
};
input.click();
},
},
{
id: "divider",
title: i18nT("novel.editor.commands.divider"),
description: i18nT("novel.editor.commandDescriptions.divider"),
icon: <hr className="h-1 w-5" />,
command: ({ editor, range }: Command) => {
editor.chain().focus().deleteRange(range).setHorizontalRule().run();
},
},
].filter((item) => {
if (typeof query === "string" && query.length > 0) {
return item.title.toLowerCase().includes(query.toLowerCase());
}
return true;
});
};
export const updateScrollView = (container: HTMLElement, item: HTMLElement) => {
const containerHeight = container.offsetHeight;
const itemHeight = item ? item.offsetHeight : 0;
const top = item.offsetTop;
const bottom = top + itemHeight;
if (top < container.scrollTop) {
container.scrollTop -= container.scrollTop - top + 5;
} else if (bottom > containerHeight + container.scrollTop) {
container.scrollTop += bottom - containerHeight - container.scrollTop + 5;
}
};
const CommandList = ({ items, command, editor, range }: { items: CommandItemProps[]; command: any; editor: any; range: any }) => {
const [selectedIndex, setSelectedIndex] = useState(0);
const { complete, isLoading } = useCompletion({
id: "novel",
api: "",
onResponse: (response) => {
if (response.status === 429) {
toast.error(i18nT("novel.editor.errors.requestLimit"));
// va.track("Rate Limit Reached");
return;
}
editor.chain().focus().deleteRange(range).run();
},
onFinish: (_prompt, completion) => {
// highlight the generated text
editor.commands.setTextSelection({
from: range.from,
to: range.from + completion.length,
});
},
onError: (e) => {
toast.error(e?.message ?? i18nT("novel.editor.errors.generic"));
},
});
const selectItem = useCallback(
(index: number) => {
const item = items[index];
// va.track("Slash Command Used", {
// command: item.title,
// });
if (item) {
if (item.id === "continue-writing") {
toast.error(i18nT("novel.editor.errors.aiWritingDisabled"));
} else {
command(item);
}
}
},
[complete, command, editor, items]
);
useEffect(() => {
const navigationKeys = ["ArrowUp", "ArrowDown", "Enter"];
const onKeyDown = (e: KeyboardEvent) => {
if (navigationKeys.includes(e.key)) {
e.preventDefault();
if (e.key === "ArrowUp") {
setSelectedIndex((selectedIndex + items.length - 1) % items.length);
return true;
}
if (e.key === "ArrowDown") {
setSelectedIndex((selectedIndex + 1) % items.length);
return true;
}
if (e.key === "Enter") {
selectItem(selectedIndex);
return true;
}
return false;
}
};
document.addEventListener("keydown", onKeyDown);
return () => {
document.removeEventListener("keydown", onKeyDown);
};
}, [items, selectedIndex, setSelectedIndex, selectItem]);
useEffect(() => {
setSelectedIndex(0);
}, [items]);
const commandListContainer = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const container = commandListContainer?.current;
const item = container?.children[selectedIndex] as HTMLElement;
if (item && container) updateScrollView(container, item);
}, [selectedIndex]);
return items.length > 0 ? (
<div
id="slash-command"
ref={commandListContainer}
className="bg-background z-50 h-auto max-h-[330px] w-72 overflow-y-auto scroll-smooth rounded-md border border-stone-200 px-1 py-2 shadow-md transition-all"
>
{items.map((item: CommandItemProps, index: number) => {
return (
<button
type="button"
className={`flex w-full items-center space-x-2 rounded-md px-2 py-1 text-left text-sm text-stone-900 hover:bg-stone-100 ${
index === selectedIndex ? "bg-stone-100 text-stone-900" : ""
}`}
key={index}
onClick={() => selectItem(index)}
>
<div className="bg-background flex h-10 w-10 items-center justify-center rounded-md border border-stone-200">
{item.id === "continue-writing" && isLoading ? <LoadingCircle /> : item.icon}
</div>
<div>
<p className="font-medium">{item.title}</p>
<p className="text-xs text-stone-500">{item.description}</p>
</div>
</button>
);
})}
</div>
) : null;
};
const renderItems = () => {
let component: ReactRenderer | null = null;
let popup: any | null = null;
return {
onStart: (props: { editor: Editor; clientRect: DOMRect }) => {
component = new ReactRenderer(CommandList, {
props,
editor: props.editor,
});
// @ts-ignore
popup = tippy("body", {
getReferenceClientRect: props.clientRect,
appendTo: () => document.body,
content: component.element,
showOnCreate: true,
interactive: true,
trigger: "manual",
placement: "bottom-start",
});
},
onUpdate: (props: { editor: Editor; clientRect: DOMRect }) => {
component?.updateProps(props);
popup &&
popup[0].setProps({
getReferenceClientRect: props.clientRect,
});
},
onKeyDown: (props: { event: KeyboardEvent }) => {
if (props.event.key === "Escape") {
popup?.[0].hide();
return true;
}
// @ts-ignore
return component?.ref?.onKeyDown(props);
},
onExit: () => {
popup?.[0].destroy();
component?.destroy();
},
};
};
export function createSlashCommand(options: ImageUploadOptions = {}) {
return CommandExtension.configure({
suggestion: {
items: ({ query }: { query: string }) => getSuggestionItems({ query, options }),
render: renderItems,
},
});
}
const SlashCommand = createSlashCommand();
export default SlashCommand;
@@ -0,0 +1,267 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useEditor, EditorContent, UseEditorOptions } from "@tiptap/react";
import { createTiptapEditorProps } from "./props";
import { createTiptapExtensions, type CollaborationConfig } from "./extensions";
import { useHocuspocusProvider } from "./useHocuspocusProvider";
import { useCompletion } from "../../lib/ai/react/useCompletion";
import { toast } from "sonner";
import { EditorBubbleMenu } from "./components";
import { Editor, EditorOptions, JSONContent } from "@tiptap/core";
import clsx from "clsx";
import { useRootData } from "~/utils/data/useRootData";
import { useTranslation } from "react-i18next";
type ValueDto = {
html?: string;
json?: JSONContent;
text?: string;
};
export type NovelEditorCollabOptions = {
/** WebSocket URL, e.g. `wss://collab.example.com`. */
readonly url: string | null | undefined;
/** Short-lived JWT from `/api/collab/token`. */
readonly token: string | null | undefined;
/** `tenantId:resourceType:resourceId` triple matching the JWT claims. */
readonly documentName: string;
/** Cursor label + colour shown on collaborators' tabs. */
readonly user: {
readonly name: string;
readonly color: string;
readonly avatarUrl?: string | null;
};
};
interface Props {
content: string | JSONContent | undefined;
onChange: (value: ValueDto) => void;
readOnly?: boolean;
disabled?: boolean;
className?: string;
autoFocus?: boolean;
darkMode?: boolean;
usingLocalStorage?: boolean;
/**
* Optional realtime-collab settings. When `undefined` (or `url` / `token`
* are blank), the editor mounts as before — no Y.js, no Hocuspocus.
*/
collab?: NovelEditorCollabOptions;
}
export default function NovelEditor({
content,
onChange,
readOnly,
disabled,
className = "min-h-[500px]",
autoFocus = true,
darkMode = true,
usingLocalStorage,
collab,
}: Props) {
const { t } = useTranslation();
const rootData = useRootData();
const [saveStatusKey, setSaveStatusKey] = useState("novel.editor.status.saved");
const [hydrated, setHydrated] = useState(false);
const imageUploadOptions = useMemo(
() => ({ apiBaseUrl: rootData.apiBaseUrl, tenantId: rootData.currentTenant?.id ?? null, tenantSlug: rootData.currentTenant?.slug ?? null }),
[rootData.apiBaseUrl, rootData.currentTenant?.id, rootData.currentTenant?.slug]
);
const hocuspocus = useHocuspocusProvider({
url: collab?.url ?? null,
token: collab?.token ?? null,
documentName: collab?.documentName ?? "",
});
const collaborationConfig: CollaborationConfig | null = useMemo(() => {
if (!hocuspocus || !collab) return null;
return {
document: hocuspocus.doc,
provider: hocuspocus.provider,
user: collab.user,
};
}, [collab, hocuspocus]);
const extensions = useMemo(() => createTiptapExtensions(imageUploadOptions, collaborationConfig, t), [collaborationConfig, imageUploadOptions, t]);
const editorProps = useMemo(() => createTiptapEditorProps(imageUploadOptions), [imageUploadOptions]);
const collabStatus = hocuspocus?.status ?? null;
const collabSynced = hocuspocus?.synced ?? false;
const debouncedUpdates = useCallback(
({ editor }: { editor: Editor }) => {
const json = editor.getJSON();
const html = editor.getHTML();
const text = editor.getText();
setSaveStatusKey("novel.editor.status.saving");
// onChange(json);
onChange({
json,
html,
text,
});
// Simulate a delay in saving.
// setTimeout(() => {
setSaveStatusKey("novel.editor.status.saved");
// }, 500);
},
[onChange]
);
let options: UseEditorOptions = {
immediatelyRender: false,
extensions,
editorProps,
onUpdate: (e) => {
setSaveStatusKey("novel.editor.status.saving");
const selection = e.editor.state.selection;
const lastTwo = e.editor.state.doc.textBetween(selection.from - 2, selection.from, "\n");
if (lastTwo === "++" && !isLoading) {
e.editor.commands.deleteRange({
from: selection.from - 2,
to: selection.from,
});
toast.error(t("novel.editor.errors.aiWritingDisabled"));
// va.track("Autocomplete Shortcut Used");
} else {
debouncedUpdates(e);
}
},
};
if (autoFocus) {
options.autofocus = "start";
} else {
options.autofocus = false;
}
const editor = useEditor(options);
const { complete, completion, isLoading, stop } = useCompletion({
id: "novel",
api: "",
onResponse: (response) => {
if (response.status === 429) {
toast.error(t("novel.editor.errors.requestLimit"));
// va.track("Rate Limit Reached");
return;
}
},
onFinish: (_prompt, completion) => {
editor?.commands.setTextSelection({
from: editor.state.selection.from - completion.length,
to: editor.state.selection.from,
});
},
onError: () => {
toast.error(t("novel.editor.errors.generic"));
},
});
const prev = useRef("");
// Insert chunks of the generated text
useEffect(() => {
const diff = completion.slice(prev.current.length);
prev.current = completion;
editor?.commands.insertContent(diff, {
parseOptions: {
preserveWhitespace: "full",
},
});
}, [isLoading, editor, completion]);
useEffect(() => {
// if user presses escape or cmd + z and it's loading,
// stop the request, delete the completion, and insert back the "++"
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape" || (e.metaKey && e.key === "z")) {
stop();
if (e.key === "Escape") {
editor?.commands.deleteRange({
from: editor.state.selection.from - completion.length,
to: editor.state.selection.from,
});
}
editor?.commands.insertContent("++");
}
};
const mousedownHandler = (e: MouseEvent) => {
e.preventDefault();
e.stopPropagation();
stop();
if (window.confirm(t("novel.editor.confirm.aiWritingPaused"))) {
toast.error(t("novel.editor.errors.aiWritingDisabled"));
}
};
if (isLoading) {
document.addEventListener("keydown", onKeyDown);
window.addEventListener("mousedown", mousedownHandler);
} else {
document.removeEventListener("keydown", onKeyDown);
window.removeEventListener("mousedown", mousedownHandler);
}
return () => {
document.removeEventListener("keydown", onKeyDown);
window.removeEventListener("mousedown", mousedownHandler);
};
}, [stop, isLoading, editor, complete, completion.length, t]);
// Hydrate the editor with the content from localStorage.
//
// When realtime-collab is active, the Y.Doc is the canonical source of
// truth — Hocuspocus's `synced` event hydrates the doc from Postgres on
// connect, and any local `setContent` here would race with that and
// either duplicate or wipe out persisted content. Skip hydration once
// we're connected via Hocuspocus.
useEffect(() => {
if (collaborationConfig) {
// Mark hydrated so the legacy localStorage path doesn't re-fire later.
if (!hydrated) setHydrated(true);
return;
}
if (editor && content && !hydrated) {
editor.commands.setContent(content);
setHydrated(true);
}
}, [collaborationConfig, editor, content, hydrated]);
return (
// Mouse-only hit-area enhancement: clicking the editor chrome focuses the
// editor. The editing surface is itself keyboard focusable, so this wrapper
// must not become a focusable/role-bearing element (redundant tab stop).
// eslint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events
<div
onClick={() => {
editor?.chain().focus().run();
}}
className={clsx(
"border-border bg-background relative w-full max-w-(--breakpoint-lg) border p-12 px-8 sm:rounded-lg sm:border sm:px-12 sm:shadow-lg",
className
// darkMode && "dark:border-gray-800 dark:bg-gray-900 dark:text-slate-200"
)}
>
{usingLocalStorage && (
<div
className={clsx(
"bg-secondary text-secondary-foreground absolute top-5 right-5 mb-5 rounded-lg px-2 py-1 text-sm",
darkMode && "dark:bg-gray-800 dark:text-slate-200"
)}
>
{t(saveStatusKey)}
</div>
)}
{collabStatus && collabStatus !== "connected" && (
<div
data-testid="novel-collab-status"
className="bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-200 absolute top-5 left-5 mb-5 rounded-lg px-2 py-1 text-sm"
>
{collabStatus === "connecting" ? t("novel.editor.collab.connecting") : t("novel.editor.collab.offline")}
</div>
)}
{collabSynced ? null : null}
{/* value: {JSON.stringify(value)} */}
{editor ? (
<>
<EditorContent editor={editor} readOnly={readOnly} disabled={disabled} />
<EditorBubbleMenu editor={editor} />
</>
) : (
<></>
)}
</div>
);
}
@@ -0,0 +1,39 @@
import { handleImageUpload, type ImageUploadOptions } from "~/modules/novel/lib/utils/editor";
import { EditorProps } from "@tiptap/pm/view";
export function createTiptapEditorProps(options: ImageUploadOptions = {}): EditorProps {
return {
attributes: {
class: "prose-lg prose-headings:font-display focus:outline-hidden",
},
handleDOMEvents: {
keydown: (_view, event) => {
// prevent default event listeners from firing when slash command is active
if (["ArrowUp", "ArrowDown", "Enter"].includes(event.key)) {
const slashCommand = document.querySelector("#slash-command");
if (slashCommand) {
return true;
}
}
},
},
handlePaste: (view, event, _slice) => {
if (event.clipboardData && event.clipboardData.files && event.clipboardData.files[0]) {
event.preventDefault();
const file = event.clipboardData.files[0];
return handleImageUpload(file, view, event, options);
}
return false;
},
handleDrop: (view, event, _slice, moved) => {
if (!moved && event.dataTransfer && event.dataTransfer.files && event.dataTransfer.files[0]) {
event.preventDefault();
const file = event.dataTransfer.files[0];
return handleImageUpload(file, view, event, options);
}
return false;
},
};
}
export const TiptapEditorProps: EditorProps = createTiptapEditorProps();
@@ -0,0 +1,94 @@
/**
* `useHocuspocusProvider` — opens a Hocuspocus WebSocket connection bound to
* a Y.Doc and tears it down on unmount. Returns `null` until the connection
* is established or when collab is intentionally disabled (no URL / no
* token) so the Novel-Editor falls back to its single-user REST-save path.
*
* Refs: docs/improvement-plan/05-business-features/realtime-collab.md
*/
import { useEffect, useMemo, useRef, useState } from "react";
import * as Y from "yjs";
import { HocuspocusProvider, HocuspocusProviderWebsocket } from "@hocuspocus/provider";
export type HocuspocusBinding = {
/** Stable Y.Doc instance bound to the provider. */
readonly doc: Y.Doc;
/** Live HocuspocusProvider — wire into Collaboration / Awareness extensions. */
readonly provider: HocuspocusProvider;
/** Current connection status (driven by the provider's status events). */
readonly status: "connecting" | "connected" | "disconnected";
/** True once the initial sync handshake completed. */
readonly synced: boolean;
};
export type UseHocuspocusOptions = {
/** WebSocket URL — typically `wss://collab.example.com`. */
readonly url: string | null | undefined;
/** Short-lived JWT issued by the web app's collab-token endpoint. */
readonly token: string | null | undefined;
/** `tenantId:resourceType:resourceId` triple matching the JWT claims. */
readonly documentName: string;
};
/**
* The hook intentionally returns `null` until BOTH `url` and `token` are
* present — this is the graceful-degradation entry point. Callers that
* receive `null` should mount the editor without Collaboration extensions.
*/
export function useHocuspocusProvider(options: UseHocuspocusOptions): HocuspocusBinding | null {
const { url, token, documentName } = options;
const docRef = useRef<Y.Doc | null>(null);
const providerRef = useRef<HocuspocusProvider | null>(null);
const socketRef = useRef<HocuspocusProviderWebsocket | null>(null);
const [status, setStatus] = useState<"connecting" | "connected" | "disconnected">("connecting");
const [synced, setSynced] = useState(false);
const enabled = useMemo(() => Boolean(url && token && documentName), [url, token, documentName]);
useEffect(() => {
if (!enabled || !url || !token) return;
const doc = new Y.Doc();
const socket = new HocuspocusProviderWebsocket({ url });
const provider = new HocuspocusProvider({
websocketProvider: socket,
name: documentName,
document: doc,
token,
});
docRef.current = doc;
providerRef.current = provider;
socketRef.current = socket;
const onStatus = ({ status: next }: { status: "connecting" | "connected" | "disconnected" }) => {
setStatus(next);
};
const onSynced = ({ state }: { state: boolean }) => {
setSynced(state);
};
provider.on("status", onStatus);
provider.on("synced", onSynced);
return () => {
provider.off("status", onStatus);
provider.off("synced", onSynced);
provider.destroy();
socket.destroy();
doc.destroy();
docRef.current = null;
providerRef.current = null;
socketRef.current = null;
setSynced(false);
setStatus("disconnected");
};
}, [documentName, enabled, token, url]);
if (!enabled || !docRef.current || !providerRef.current) return null;
return {
doc: docRef.current,
provider: providerRef.current,
status,
synced,
};
}