"use client"; import * as React from "react"; import { Button, Card, Input, ToolbarButton, ToolbarRoot } from "@uifn/components-react"; import { captureMarkdownInsertion, createAuthoringModel, createToolbarModel, insertUploadedMarkdown, runToolbarAction, type AuthoringVersion, type MarkdownUploadResult, type SlashCommand, type ToolbarCommandTarget, type ToolbarGroup } from "@mdfn/components"; import { Transaction, canTransitionReview, createCommentThread, createSuggestion, decideSuggestion, replyToComment, setCommentResolved, transitionReview, type EditorController, type EditorialActor, type ReviewState } from "@mdfn/core"; import { MdfnEditor, useMdfn, type MdfnEditorHandle, type MdfnEditorProps } from "@mdfn/react"; export interface MdfnToolbarProps extends Omit, "children"> { readonly controller: EditorController; readonly groups?: readonly ToolbarGroup[]; readonly ariaLabel?: string; readonly commandTarget?: ToolbarCommandTarget | null; } export function MdfnToolbar({ controller, groups, ariaLabel, commandTarget, ...props }: MdfnToolbarProps): React.ReactElement { useMdfn(controller); const model = createToolbarModel(controller, groups, ariaLabel, commandTarget); return ( {model.groups.map((group) => ( {group.actions.map((action) => ( runToolbarAction(controller, action, commandTarget)}> {action.label} ))} ))} ); } export interface MdfnEditorShellProps extends MdfnEditorProps { readonly toolbarGroups?: readonly ToolbarGroup[]; readonly hideToolbar?: boolean; readonly hideAuthoringChrome?: boolean; readonly actor?: EditorialActor; readonly onSelectFiles?: (files: readonly File[]) => Promise; readonly onModeChange?: (mode: MdfnEditorProps["mode"]) => void; readonly versions?: readonly AuthoringVersion[]; readonly onRestoreVersion?: (version: number) => void | Promise; } export const MdfnEditorShell = React.forwardRef, MdfnEditorShellProps>(function MdfnEditorShell( { toolbarGroups, hideToolbar, hideAuthoringChrome, actor, onSelectFiles, onModeChange, versions, onRestoreVersion, className, onReady, ...props }, forwardedRef, ) { const readOnly = props.readOnly === true || props.mode === "read-only"; const insertionLifecycle = React.useRef(null); React.useEffect(() => { const lifecycle = new AbortController(); insertionLifecycle.current = lifecycle; return () => { lifecycle.abort(); if (insertionLifecycle.current === lifecycle) insertionLifecycle.current = null; }; }, [props.controller]); const [commandTarget, setCommandTarget] = React.useState(null); const [editorHandle, setEditorHandle] = React.useState(null); const editorHandleRef = React.useRef(null); const setEditorRef = React.useCallback((handle: MdfnEditorHandle | null) => { editorHandleRef.current = handle; setEditorHandle(handle); setCommandTarget(handle ? { can: (command) => handle.can(command as Parameters[0]), run: (command) => handle.run(command as Parameters[0]), } : null); if (typeof forwardedRef === "function") forwardedRef(handle); else if (forwardedRef) forwardedRef.current = handle; }, [forwardedRef]); const editorReady = React.useCallback((handle: MdfnEditorHandle) => { setCommandTarget({ can: (command) => handle.can(command as Parameters[0]), run: (command) => handle.run(command as Parameters[0]), }); onReady?.(handle); }, [onReady]); const handleFiles = React.useCallback(async (files: readonly File[]) => { const insertion = captureMarkdownInsertion(props.controller, insertionLifecycle.current?.signal); try { await insertUploadedMarkdown(insertion, Promise.resolve(onSelectFiles?.(files))); await props.onFiles?.(files); } catch (error) { insertion.cancel(); throw error; } }, [onSelectFiles, props.controller, props.onFiles]); return (
{!hideToolbar && !readOnly && } {!hideAuthoringChrome && }
); }); export interface MdfnAuthoringChromeProps { readonly controller: EditorController; readonly editor?: MdfnEditorHandle | null; readonly mode?: MdfnEditorProps["mode"]; readonly readOnly?: boolean; readonly compact?: boolean; readonly actor?: EditorialActor; readonly onSelectFiles?: (files: readonly File[]) => Promise; readonly onModeChange?: (mode: MdfnEditorProps["mode"]) => void; readonly versions?: readonly AuthoringVersion[]; readonly onRestoreVersion?: (version: number) => void | Promise; } const modes = ["visual", "source", "split", "preview", "read-only"] as const; export function MdfnAuthoringChrome({ controller, editor, mode = "visual", readOnly, compact, actor, onSelectFiles, onModeChange, versions = [], onRestoreVersion }: MdfnAuthoringChromeProps): React.ReactElement { const isReadOnly = readOnly === true || mode === "read-only"; useMdfn(controller); const insertionLifecycle = React.useRef(null); React.useEffect(() => { const lifecycle = new AbortController(); insertionLifecycle.current = lifecycle; return () => { lifecycle.abort(); if (insertionLifecycle.current === lifecycle) insertionLifecycle.current = null; }; }, [controller]); const [slashQuery, setSlashQuery] = React.useState(""); const [link, setLink] = React.useState(""); const [rows, setRows] = React.useState(2); const [columns, setColumns] = React.useState(2); const [comment, setComment] = React.useState(""); const [suggestion, setSuggestion] = React.useState(""); const [replies, setReplies] = React.useState>({}); const [slashOpen, setSlashOpen] = React.useState(false); const model = createAuthoringModel(controller, { mode, compact, slashQuery, slashOpen }); const runSlash = (item: SlashCommand): void => { if (item.kind === "command" && item.command) editor?.run(item.command as Parameters[0]); if (item.kind === "table") editor?.insertTable(rows, columns); if (item.kind === "link" && link) editor?.setLink(link); setSlashOpen(false); }; const currentActor = actor ?? { id: "local-author" }; const updateSidecar = (sidecar: NonNullable["sidecar"]>, source: string): void => { controller.dispatch(new Transaction().setSidecar(sidecar).withSource(source)); }; const setReview = (next: ReviewState): void => updateSidecar(transitionReview({ sidecar: controller.getState().sidecar, to: next, actor: currentActor }), "editorial:review"); const addComment = (): void => { const state = controller.getState(); const selection = state.selection?.kind === "text" ? state.selection : { anchor: 0, head: 0 }; const result = createCommentThread({ sidecar: state.sidecar, anchor: { from: Math.min(selection.anchor, selection.head), to: Math.max(selection.anchor, selection.head) }, body: comment, actor: currentActor, markdownLength: state.markdown.length }); updateSidecar(result.sidecar, "editorial:comment"); setComment(""); }; const selectionRange = (): { from: number; to: number } => { const selection = controller.getState().selection; return selection?.kind === "text" ? { from: Math.min(selection.anchor, selection.head), to: Math.max(selection.anchor, selection.head) } : { from: 0, to: 0 }; }; const addSuggestion = (): void => { const state = controller.getState(); const result = createSuggestion({ sidecar: state.sidecar, anchor: selectionRange(), replacement: suggestion, actor: currentActor, markdownLength: state.markdown.length }); updateSidecar(result.sidecar, "editorial:suggestion"); setSuggestion(""); }; return (
{!isReadOnly && model.bubbleVisible && editor.can(command as Parameters[0]), run: (command) => editor.run(command as Parameters[0]) } : null} ariaLabel="Selection formatting" data-mdfn-surface="bubble-toolbar" />} {!isReadOnly && model.floatingVisible &&
editor.can(command as Parameters[0]), run: (command) => editor.run(command as Parameters[0]) } : null} ariaLabel="Block formatting" />
} {!isReadOnly && } {!isReadOnly && model.slashOpen && Insert ) => setSlashQuery(event.currentTarget.value)} />
{model.slashCommands.map((item) => )}
} {!isReadOnly && Link ) => setLink(event.currentTarget.value)} /> } {!isReadOnly && Table ) => setRows(Number(event.currentTarget.value))} />) => setColumns(Number(event.currentTarget.value))} /> } {!isReadOnly && Files ) => { const files = [...(event.currentTarget.files ?? [])]; const insertion = captureMarkdownInsertion(controller, insertionLifecycle.current?.signal); const upload = onSelectFiles?.(files); if (!upload) { insertion.cancel(); return; } void insertUploadedMarkdown(insertion, upload).catch(() => insertion.cancel()); }} /> } Review

State: {model.reviewState}

{!isReadOnly && <>) => setComment(event.currentTarget.value)} />} {!isReadOnly && <>) => setSuggestion(event.currentTarget.value)} />}
    {(model.comments ?? []).map((thread) =>
  • {thread.messages.map((message) =>

    {message.body}

    )} {thread.resolved ? "Resolved" : "Open"} {!isReadOnly && <>) => setReplies((current) => ({ ...current, [thread.id]: event.currentTarget.value }))} />}
  • )}
    {(model.suggestions ?? []).map((suggestion) =>
  • {suggestion.replacement} ({suggestion.status}) {suggestion.status === "pending" && !isReadOnly && <>}
  • )}
{!isReadOnly &&
{(["draft", "in-review", "changes-requested", "approved"] as const).map((state) => )}
}
Version history
    {versions.map((entry) =>
  1. Version {entry.version}{entry.authorId ? ` by ${entry.authorId}` : ""} {onRestoreVersion && !isReadOnly && }
  2. )}
    {(model.audit ?? []).map((entry) =>
  1. {entry.action} by {entry.actorId}
  2. )}
); } export function MdfnOutline({ controller }: { readonly controller: EditorController }): React.ReactElement { useMdfn(controller); const outline = createAuthoringModel(controller).outline; return ; } export function MdfnDiagnostics({ controller }: { readonly controller: EditorController }): React.ReactElement { useMdfn(controller); const diagnostics = controller.getState().diagnostics; return ; } export { MdfnEditor } from "@mdfn/react"; export const MDFN_COMPONENTS_REACT_VERSION = "0.1.1" as const;