Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* Shared types between the API and UI packages.
|
||||
*/
|
||||
export type Message = {
|
||||
id: string;
|
||||
createdAt?: Date;
|
||||
content: string;
|
||||
role: "system" | "user" | "assistant";
|
||||
};
|
||||
|
||||
export type CreateMessage = {
|
||||
id?: string;
|
||||
createdAt?: Date;
|
||||
content: string;
|
||||
role: "system" | "user" | "assistant";
|
||||
};
|
||||
|
||||
export type RequestOptions = {
|
||||
headers?: Record<string, string> | Headers;
|
||||
body?: object;
|
||||
};
|
||||
|
||||
export type UseChatOptions = {
|
||||
/**
|
||||
* The API endpoint that accepts a `{ messages: Message[] }` object and returns
|
||||
* a stream of tokens of the AI chat response. Defaults to `/api/chat`.
|
||||
*/
|
||||
api?: string;
|
||||
|
||||
/**
|
||||
* An unique identifier for the chat. If not provided, a random one will be
|
||||
* generated. When provided, the `useChat` hook with the same `id` will
|
||||
* have shared states across components.
|
||||
*/
|
||||
id?: string;
|
||||
|
||||
/**
|
||||
* Initial messages of the chat. Useful to load an existing chat history.
|
||||
*/
|
||||
initialMessages?: Message[];
|
||||
|
||||
/**
|
||||
* Initial input of the chat.
|
||||
*/
|
||||
initialInput?: string;
|
||||
|
||||
/**
|
||||
* Callback function to be called when the API response is received.
|
||||
*/
|
||||
onResponse?: (response: Response) => void | Promise<void>;
|
||||
|
||||
/**
|
||||
* Callback function to be called when the chat is finished streaming.
|
||||
*/
|
||||
onFinish?: (message: Message) => void;
|
||||
|
||||
/**
|
||||
* Callback function to be called when an error is encountered.
|
||||
*/
|
||||
onError?: (error: Error) => void;
|
||||
|
||||
/**
|
||||
* HTTP headers to be sent with the API request.
|
||||
*/
|
||||
headers?: Record<string, string> | Headers;
|
||||
|
||||
/**
|
||||
* Extra body object to be sent with the API request.
|
||||
* @example
|
||||
* Send a `sessionId` to the API along with the messages.
|
||||
* ```js
|
||||
* useChat({
|
||||
* body: {
|
||||
* sessionId: '123',
|
||||
* }
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
body?: object;
|
||||
|
||||
/**
|
||||
* Whether to send extra message fields such as `message.id` and `message.createdAt` to the API.
|
||||
* Defaults to `false`. When set to `true`, the API endpoint might need to
|
||||
* handle the extra fields before forwarding the request to the AI service.
|
||||
*/
|
||||
sendExtraMessageFields?: boolean;
|
||||
};
|
||||
|
||||
export type UseCompletionOptions = {
|
||||
/**
|
||||
* The API endpoint that accepts a `{ prompt: string }` object and returns
|
||||
* a stream of tokens of the AI completion response. Defaults to `/api/completion`.
|
||||
*/
|
||||
api: string;
|
||||
/**
|
||||
* An unique identifier for the chat. If not provided, a random one will be
|
||||
* generated. When provided, the `useChat` hook with the same `id` will
|
||||
* have shared states across components.
|
||||
*/
|
||||
id: string;
|
||||
|
||||
/**
|
||||
* Initial prompt input of the completion.
|
||||
*/
|
||||
initialInput?: string;
|
||||
|
||||
/**
|
||||
* Initial completion result. Useful to load an existing history.
|
||||
*/
|
||||
initialCompletion?: string;
|
||||
|
||||
/**
|
||||
* Callback function to be called when the API response is received.
|
||||
*/
|
||||
onResponse?: (response: Response) => void | Promise<void>;
|
||||
|
||||
/**
|
||||
* Callback function to be called when the completion is finished streaming.
|
||||
*/
|
||||
onFinish?: (prompt: string, completion: string) => void;
|
||||
|
||||
/**
|
||||
* Callback function to be called when an error is encountered.
|
||||
*/
|
||||
onError?: (error: Error) => void;
|
||||
|
||||
/**
|
||||
* HTTP headers to be sent with the API request.
|
||||
*/
|
||||
headers?: Record<string, string> | Headers;
|
||||
|
||||
/**
|
||||
* Extra body object to be sent with the API request.
|
||||
* @example
|
||||
* Send a `sessionId` to the API along with the prompt.
|
||||
* ```js
|
||||
* useChat({
|
||||
* body: {
|
||||
* sessionId: '123',
|
||||
* }
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
body?: object;
|
||||
};
|
||||
@@ -0,0 +1,238 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { t as i18nT } from "i18next";
|
||||
import useSWRMutation from "swr/mutation";
|
||||
import useSWR from "swr";
|
||||
|
||||
import { createChunkDecoder } from "./utils";
|
||||
import { UseCompletionOptions, RequestOptions } from "./types";
|
||||
|
||||
export type UseCompletionHelpers = {
|
||||
/** The current completion result */
|
||||
completion: string;
|
||||
/**
|
||||
* Send a new prompt to the API endpoint and update the completion state.
|
||||
*/
|
||||
complete: (prompt: string, options?: RequestOptions) => Promise<string | null | undefined>;
|
||||
/** The error object of the API request */
|
||||
error: undefined | Error;
|
||||
/**
|
||||
* Abort the current API request but keep the generated tokens.
|
||||
*/
|
||||
stop: () => void;
|
||||
/**
|
||||
* Update the `completion` state locally.
|
||||
*/
|
||||
setCompletion: (completion: string) => void;
|
||||
/** The current value of the input */
|
||||
input: string;
|
||||
/** setState-powered method to update the input value */
|
||||
setInput: React.Dispatch<React.SetStateAction<string>>;
|
||||
/**
|
||||
* An input/textarea-ready onChange handler to control the value of the input
|
||||
* @example
|
||||
* ```jsx
|
||||
* <input onChange={handleInputChange} value={input} />
|
||||
* ```
|
||||
*/
|
||||
handleInputChange: (e: React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLTextAreaElement>) => void;
|
||||
/**
|
||||
* Form submission handler to automattically reset input and append a user message
|
||||
* @example
|
||||
* ```jsx
|
||||
* <form onSubmit={handleSubmit}>
|
||||
* <input onChange={handleInputChange} value={input} />
|
||||
* </form>
|
||||
* ```
|
||||
*/
|
||||
handleSubmit: (e: React.FormEvent<HTMLFormElement>) => void;
|
||||
/** Whether the API request is in progress */
|
||||
isLoading: boolean;
|
||||
};
|
||||
|
||||
export function useCompletion({
|
||||
api,
|
||||
id,
|
||||
initialCompletion = "",
|
||||
initialInput = "",
|
||||
headers,
|
||||
body,
|
||||
onResponse,
|
||||
onFinish,
|
||||
onError,
|
||||
}: UseCompletionOptions): UseCompletionHelpers {
|
||||
// Generate an unique id for the completion if not provided.
|
||||
const completionId = id;
|
||||
|
||||
// Store the completion state in SWR, using the completionId as the key to share states.
|
||||
const { data, mutate } = useSWR<string>([api, completionId], null, {
|
||||
fallbackData: initialCompletion,
|
||||
});
|
||||
const completion = data!;
|
||||
|
||||
// Abort controller to cancel the current API call.
|
||||
const [abortController, setAbortController] = useState<AbortController | null>(null);
|
||||
|
||||
const extraMetadataRef = useRef<any>({
|
||||
headers,
|
||||
body,
|
||||
});
|
||||
useEffect(() => {
|
||||
extraMetadataRef.current = {
|
||||
headers,
|
||||
body,
|
||||
};
|
||||
}, [headers, body]);
|
||||
|
||||
// Actual mutation hook to send messages to the API endpoint and update the
|
||||
// chat state.
|
||||
const { error, trigger, isMutating } = useSWRMutation<
|
||||
string | null,
|
||||
any,
|
||||
[string, string],
|
||||
{
|
||||
prompt: string;
|
||||
options?: RequestOptions;
|
||||
}
|
||||
>(
|
||||
[api, completionId],
|
||||
async (_, { arg }) => {
|
||||
try {
|
||||
const { prompt, options } = arg;
|
||||
|
||||
const abortController = new AbortController();
|
||||
setAbortController(abortController);
|
||||
|
||||
// Empty the completion immediately.
|
||||
mutate("", false);
|
||||
|
||||
const res = await fetch(api, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
prompt,
|
||||
...extraMetadataRef.current.body,
|
||||
...options?.body,
|
||||
}),
|
||||
headers: {
|
||||
...extraMetadataRef.current.headers,
|
||||
...options?.headers,
|
||||
},
|
||||
signal: abortController.signal,
|
||||
}).catch((err) => {
|
||||
throw err;
|
||||
});
|
||||
|
||||
if (onResponse) {
|
||||
try {
|
||||
await onResponse(res);
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error((await res.text()) || i18nT("novel.editor.errors.fetchFailed"));
|
||||
}
|
||||
|
||||
if (!res.body) {
|
||||
throw new Error(i18nT("novel.editor.errors.emptyResponse"));
|
||||
}
|
||||
|
||||
let result = "";
|
||||
const reader = res.body.getReader();
|
||||
const decoder = createChunkDecoder();
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Update the completion state with the new message tokens.
|
||||
result += decoder(value);
|
||||
mutate(result, false);
|
||||
|
||||
// The request has been aborted, stop reading the stream.
|
||||
if (abortController === null) {
|
||||
reader.cancel();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (onFinish) {
|
||||
onFinish(prompt, result);
|
||||
}
|
||||
|
||||
setAbortController(null);
|
||||
return result;
|
||||
} catch (err) {
|
||||
// Ignore abort errors as they are expected.
|
||||
if ((err as any).name === "AbortError") {
|
||||
setAbortController(null);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (onError && err instanceof Error) {
|
||||
onError(err);
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
{
|
||||
populateCache: false,
|
||||
revalidate: false,
|
||||
}
|
||||
);
|
||||
|
||||
const stop = useCallback(() => {
|
||||
if (abortController) {
|
||||
abortController.abort();
|
||||
setAbortController(null);
|
||||
}
|
||||
}, [abortController]);
|
||||
|
||||
const setCompletion = useCallback(
|
||||
(completion: string) => {
|
||||
mutate(completion, false);
|
||||
},
|
||||
[mutate]
|
||||
);
|
||||
|
||||
const complete = useCallback<UseCompletionHelpers["complete"]>(
|
||||
async (prompt, options) => {
|
||||
return trigger({
|
||||
prompt,
|
||||
options,
|
||||
});
|
||||
},
|
||||
[trigger]
|
||||
);
|
||||
|
||||
const [input, setInput] = useState(initialInput);
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
(e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (!input) return;
|
||||
return complete(input);
|
||||
},
|
||||
[input, complete]
|
||||
);
|
||||
|
||||
const handleInputChange = (e: any) => {
|
||||
setInput(e.target.value);
|
||||
};
|
||||
|
||||
return {
|
||||
completion,
|
||||
complete,
|
||||
error,
|
||||
setCompletion,
|
||||
stop,
|
||||
input,
|
||||
setInput,
|
||||
handleInputChange,
|
||||
handleSubmit,
|
||||
isLoading: isMutating,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { customAlphabet } from "nanoid";
|
||||
|
||||
// 7-character random string
|
||||
export const nanoid = customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 7);
|
||||
|
||||
export function createChunkDecoder() {
|
||||
const decoder = new TextDecoder();
|
||||
return function (chunk: Uint8Array | undefined): string {
|
||||
if (!chunk) return "";
|
||||
return decoder.decode(chunk, { stream: true });
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { EditorView } from "@tiptap/pm/view";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { toast } from "sonner";
|
||||
import { apiPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
|
||||
export type ImageUploadOptions = {
|
||||
apiBaseUrl?: string;
|
||||
tenantSlug?: string | null;
|
||||
tenantId?: string | null;
|
||||
};
|
||||
|
||||
export const handleImageUpload = (file: File, view: EditorView, event: ClipboardEvent | DragEvent | Event, options: ImageUploadOptions = {}) => {
|
||||
// check if the file is an image
|
||||
if (!file.type.includes("image/")) {
|
||||
toast.error(i18nT("novel.editor.upload.unsupportedType"));
|
||||
|
||||
// check if the file size is less than 50MB
|
||||
} else if (file.size / 1024 / 1024 > 50) {
|
||||
toast.error(i18nT("novel.editor.upload.tooLarge"));
|
||||
} else {
|
||||
// const reader = new FileReader();
|
||||
// reader.onload = (e) => {
|
||||
// const { schema } = view.state;
|
||||
// const node = schema.nodes.image.create({
|
||||
// src: e.target?.result,
|
||||
// alt: file,
|
||||
// title: file.name,
|
||||
// }); // creates the image element
|
||||
// const transaction = view.state.tr.replaceSelectionWith(node);
|
||||
// view.dispatch(transaction);
|
||||
// };
|
||||
// reader.readAsDataURL(file);
|
||||
|
||||
const tenantId = options.tenantId ?? "";
|
||||
const uploadUrl = options.apiBaseUrl && tenantId ? new URL(apiPath("ai/upload", { mode: "host-aware" }), options.apiBaseUrl).toString() : null;
|
||||
if (!uploadUrl) {
|
||||
toast.error(i18nT("novel.editor.upload.unavailable"));
|
||||
return;
|
||||
}
|
||||
|
||||
toast.promise(
|
||||
fetch(uploadUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": file?.type || "application/octet-stream",
|
||||
"x-filename": file?.name || "image.png",
|
||||
"x-tenant-id": tenantId,
|
||||
},
|
||||
body: file,
|
||||
}).then(async (res) => {
|
||||
// Successfully uploaded image
|
||||
if (res.status === 200) {
|
||||
const { url } = await res.json();
|
||||
// preload the image
|
||||
let image = new Image();
|
||||
image.src = url;
|
||||
image.onload = () => {
|
||||
insertImage(url);
|
||||
};
|
||||
|
||||
// No blob store configured
|
||||
} else if (res.status === 401) {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
insertImage(e.target?.result as string);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
throw new Error(i18nT("novel.editor.upload.localFallback"));
|
||||
|
||||
// Unknown error
|
||||
} else {
|
||||
throw new Error(i18nT("novel.editor.upload.error"));
|
||||
}
|
||||
}),
|
||||
{
|
||||
loading: i18nT("novel.editor.upload.loading"),
|
||||
success: i18nT("novel.editor.upload.success"),
|
||||
error: (e) => e.message,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const insertImage = (url: string) => {
|
||||
// for paste events
|
||||
if (event instanceof ClipboardEvent) {
|
||||
return view.dispatch(
|
||||
view.state.tr.replaceSelectionWith(
|
||||
view.state.schema.nodes.image.create({
|
||||
src: url,
|
||||
alt: file.name,
|
||||
title: file.name,
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
// for drag and drop events
|
||||
} else if (event instanceof DragEvent) {
|
||||
const { schema } = view.state;
|
||||
const coordinates = view.posAtCoords({
|
||||
left: event.clientX,
|
||||
top: event.clientY,
|
||||
});
|
||||
const node = schema.nodes.image.create({
|
||||
src: url,
|
||||
alt: file.name,
|
||||
title: file.name,
|
||||
}); // creates the image element
|
||||
const transaction = view.state.tr.insert(coordinates?.pos || 0, node); // places it in the correct position
|
||||
return view.dispatch(transaction);
|
||||
|
||||
// for input upload events
|
||||
} else if (event instanceof Event) {
|
||||
return view.dispatch(
|
||||
view.state.tr.replaceSelectionWith(
|
||||
view.state.schema.nodes.image.create({
|
||||
src: url,
|
||||
alt: file.name,
|
||||
title: file.name,
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,42 @@
|
||||
// @vitest-environment node
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
||||
const editorSource = readFileSync(path.join(moduleDir, "ui/editor/index.tsx"), "utf8");
|
||||
const extensionsSource = readFileSync(path.join(moduleDir, "ui/editor/extensions/index.tsx"), "utf8");
|
||||
const hookSource = readFileSync(path.join(moduleDir, "ui/editor/useHocuspocusProvider.ts"), "utf8");
|
||||
|
||||
describe("Novel editor — Hocuspocus integration", () => {
|
||||
it("disables StarterKit history when collab is active to avoid clashing with Y.js history", () => {
|
||||
expect(extensionsSource).toContain("history: starterKitHistory");
|
||||
// ensure history option is conditional on `collab`
|
||||
expect(extensionsSource).toMatch(/collab\s*\?\s*false\s*:/);
|
||||
});
|
||||
|
||||
it("only appends Collaboration + CollaborationCursor extensions when collab is provided", () => {
|
||||
expect(extensionsSource).toContain("Collaboration.configure");
|
||||
expect(extensionsSource).toContain("CollaborationCursor.configure");
|
||||
expect(extensionsSource).toMatch(/\.\.\.\(collab[\s\S]+?Collaboration\.configure/);
|
||||
});
|
||||
|
||||
it("exposes a typed collab prop on NovelEditor", () => {
|
||||
expect(editorSource).toContain("collab?: NovelEditorCollabOptions");
|
||||
expect(editorSource).toContain("export type NovelEditorCollabOptions");
|
||||
});
|
||||
|
||||
it("skips localStorage hydration when collab is active (Y.Doc is source of truth)", () => {
|
||||
expect(editorSource).toContain("if (collaborationConfig) {");
|
||||
});
|
||||
|
||||
it("renders a status banner while the provider is connecting / disconnected", () => {
|
||||
expect(editorSource).toContain("data-testid=\"novel-collab-status\"");
|
||||
});
|
||||
|
||||
it("provider hook returns null when url or token are missing — graceful degradation", () => {
|
||||
expect(hookSource).toContain("Boolean(url && token && documentName)");
|
||||
expect(hookSource).toContain("if (!enabled");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
// @vitest-environment node
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
||||
const editorSource = readFileSync(path.join(moduleDir, "ui/editor/index.tsx"), "utf8");
|
||||
const slashCommandSource = readFileSync(path.join(moduleDir, "ui/editor/extensions/slash-command.tsx"), "utf8");
|
||||
const uploadSource = readFileSync(path.join(moduleDir, "lib/utils/editor.ts"), "utf8");
|
||||
|
||||
describe("Novel editor routing", () => {
|
||||
it("does not target disabled internal AI routes from active editor UI", () => {
|
||||
expect(editorSource).not.toContain("internal/ai/generate");
|
||||
expect(slashCommandSource).not.toContain("internal/ai/generate");
|
||||
expect(uploadSource).not.toContain("internal/ai/upload");
|
||||
});
|
||||
|
||||
it("uploads through the canonical API host with tenant scope", () => {
|
||||
expect(uploadSource).toContain('apiPath("ai/upload"');
|
||||
expect(uploadSource).toContain('"x-tenant-id": tenantId');
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
+22
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
export default function Github({ className }: { className?: string }) {
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="20"
|
||||
height="20"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
className={className}
|
||||
>
|
||||
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
export default function LoadingCircle({ dimensions }: { dimensions?: string }) {
|
||||
return (
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
className={`${
|
||||
dimensions || "h-4 w-4"
|
||||
} animate-spin fill-stone-600 text-stone-200`}
|
||||
viewBox="0 0 100 101"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
<path
|
||||
d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
|
||||
fill="currentFill"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
export default function Magic({ className }: { className: string }) {
|
||||
return (
|
||||
<svg
|
||||
width="469"
|
||||
height="469"
|
||||
viewBox="0 0 469 469"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
shapeRendering="geometricPrecision"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="1.5"
|
||||
className={className}
|
||||
>
|
||||
<path
|
||||
d="M237.092 62.3004L266.754 71.4198C267.156 71.5285 267.51 71.765 267.765 72.0934C268.02 72.4218 268.161 72.8243 268.166 73.2399C268.172 73.6555 268.042 74.0616 267.796 74.3967C267.55 74.7318 267.201 74.9777 266.803 75.097L237.141 84.3145C236.84 84.4058 236.566 84.5699 236.344 84.7922C236.121 85.0146 235.957 85.2883 235.866 85.5893L226.747 115.252C226.638 115.653 226.401 116.008 226.073 116.263C225.745 116.517 225.342 116.658 224.926 116.664C224.511 116.669 224.105 116.539 223.77 116.293C223.435 116.047 223.189 115.699 223.069 115.301L213.852 85.6383C213.761 85.3374 213.597 85.0636 213.374 84.8412C213.152 84.6189 212.878 84.4548 212.577 84.3635L182.914 75.2441C182.513 75.1354 182.158 74.8989 181.904 74.5705C181.649 74.2421 181.508 73.8396 181.503 73.424C181.497 73.0084 181.627 72.6023 181.873 72.2672C182.119 71.9321 182.467 71.6863 182.865 71.5669L212.528 62.3494C212.829 62.2582 213.103 62.0941 213.325 61.8717C213.547 61.6494 213.712 61.3756 213.803 61.0747L222.922 31.4121C223.031 31.0109 223.267 30.656 223.596 30.4013C223.924 30.1465 224.327 30.0057 224.742 30.0002C225.158 29.9946 225.564 30.1247 225.899 30.3706C226.234 30.6165 226.48 30.9649 226.599 31.363L235.817 61.0257C235.908 61.3266 236.072 61.6003 236.295 61.8227C236.517 62.0451 236.791 62.2091 237.092 62.3004Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
<path
|
||||
d="M155.948 155.848L202.771 168.939C203.449 169.131 204.045 169.539 204.47 170.101C204.895 170.663 205.125 171.348 205.125 172.052C205.125 172.757 204.895 173.442 204.47 174.004C204.045 174.566 203.449 174.974 202.771 175.166L155.899 188.06C155.361 188.209 154.87 188.496 154.475 188.891C154.079 189.286 153.793 189.777 153.644 190.316L140.553 237.138C140.361 237.816 139.953 238.413 139.391 238.838C138.829 239.262 138.144 239.492 137.44 239.492C136.735 239.492 136.05 239.262 135.488 238.838C134.927 238.413 134.519 237.816 134.327 237.138L121.432 190.267C121.283 189.728 120.997 189.237 120.601 188.842C120.206 188.446 119.715 188.16 119.177 188.011L72.3537 174.92C71.676 174.728 71.0795 174.32 70.6547 173.759C70.2299 173.197 70 172.512 70 171.807C70 171.103 70.2299 170.418 70.6547 169.856C71.0795 169.294 71.676 168.886 72.3537 168.694L119.226 155.799C119.764 155.65 120.255 155.364 120.65 154.969C121.046 154.573 121.332 154.082 121.481 153.544L134.572 106.721C134.764 106.043 135.172 105.447 135.734 105.022C136.295 104.597 136.981 104.367 137.685 104.367C138.389 104.367 139.075 104.597 139.637 105.022C140.198 105.447 140.606 106.043 140.798 106.721L153.693 153.593C153.842 154.131 154.128 154.622 154.524 155.018C154.919 155.413 155.41 155.699 155.948 155.848Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
<path
|
||||
d="M386.827 289.992C404.33 292.149 403.84 305.828 386.876 307.299C346.623 310.829 298.869 316.271 282.199 360.005C274.844 379.192 269.942 403.2 267.49 432.029C267.427 432.846 267.211 433.626 266.856 434.319C266.501 435.012 266.015 435.602 265.431 436.05C254.988 444.041 251.212 434.186 250.183 425.606C239.2 332.353 214.588 316.909 124.668 306.122C123.892 306.031 123.151 305.767 122.504 305.35C121.857 304.933 121.322 304.375 120.942 303.72C116.399 295.679 119.324 291.038 129.718 289.796C224.688 278.47 236.062 262.83 250.183 169.331C252.177 156.355 257.259 154.083 265.431 162.516C266.51 163.593 267.202 165.099 267.392 166.782C279.257 258.564 293.328 278.617 386.827 289.992Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user