feat: Add onNotice callback to decouple shared editor from toast library (#13046)

* feat: Add onNotice callback to decouple shared editor from toast library

Shared editor code called sonner's toast directly. Introduce an onNotice
callback (defaulting to a toast) so the shared editor stays agnostic of the
host app's notification library.

* Add lint rule to prevent regression

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Tom MoorandClaude Opus 4.8 authored and GitHub committed 2026-07-19 08:56:35 -04:00
1 parent 24b5a0a17c
commit 7d3e6591c2
16 files changed
+123 -29

No files matched your search

+26
View File
@@ -123,6 +123,32 @@
"react/rules-of-hooks": "error"
},
"plugins": ["eslint", "oxc", "react", "typescript", "import"]
},
{
"files": ["shared/**/*.{js,jsx,ts,tsx}"],
"rules": {
"no-restricted-imports": [
"error",
{
"paths": [
{
"name": "prosemirror-tables",
"importNames": [
"addRowBefore",
"addRowAfter",
"addColumnBefore",
"addColumnAfter"
],
"message": "Use the wrappers from shared/editor/commands/table instead, which respect the target index and place the cursor in the inserted cell."
},
{
"name": "sonner",
"message": "Do not import a toast library within shared; surface notifications through the onNotice callback so shared code stays decoupled from the app's toast implementation."
}
]
}
]
}
}
]
}
+2
View File
@@ -16,6 +16,7 @@ import { AttachmentValidation } from "@shared/validations";
import ClickablePadding from "~/components/ClickablePadding";
import ErrorBoundary from "~/components/ErrorBoundary";
import type { Props as EditorProps, Editor as SharedEditor } from "~/editor";
import { toastNotice } from "~/editor/toastNotice";
import useCurrentUser from "~/hooks/useCurrentUser";
import useEditorClickHandlers from "~/hooks/useEditorClickHandlers";
import useEmbeds from "~/hooks/useEmbeds";
@@ -178,6 +179,7 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) {
onFileUploadStart: handleFileUploadStart,
onFileUploadStop: handleFileUploadStop,
onFileUploadProgress: handleFileUploadProgress,
onNotice: toastNotice,
isAttachment,
});
},
@@ -12,6 +12,7 @@ import { EmbedDescriptor } from "@shared/editor/embeds";
import filterExcessSeparators from "@shared/editor/lib/filterExcessSeparators";
import { findParentNode } from "@shared/editor/queries/findParentNode";
import type { MenuItem } from "@shared/editor/types";
import { toastNotice } from "~/editor/toastNotice";
import { s } from "@shared/styles";
import { getEventFiles } from "@shared/utils/files";
import { AttachmentValidation } from "@shared/validations";
@@ -501,6 +502,7 @@ function SuggestionsMenu<T extends MenuItem>(props: Props<T>) {
onFileUploadStart,
onFileUploadStop,
onFileUploadProgress,
onNotice: toastNotice,
isAttachment: inputRef.current?.accept === "*",
attrs,
});
+8
View File
@@ -38,6 +38,7 @@ import { basicExtensions as extensions } from "@shared/editor/nodes";
import type ReactNode from "@shared/editor/nodes/ReactNode";
import type {
ComponentProps,
EditorNotice,
SelectionToolbarMenuDescriptor,
} from "@shared/editor/types";
import type {
@@ -63,6 +64,7 @@ import type { LightboxImage } from "@shared/editor/lib/Lightbox";
import { LightboxImageFactory } from "@shared/editor/lib/Lightbox";
import Lightbox from "~/components/Lightbox";
import { anchorPlugin } from "@shared/editor/plugins/AnchorPlugin";
import { toastNotice } from "./toastNotice";
export type Props = {
/** An optional identifier for the editor context. It is used to persist local settings */
@@ -161,6 +163,11 @@ export type Props = {
) => void;
/** Callback when user presses any key with document focused */
onKeyDown?: (event: React.KeyboardEvent<HTMLDivElement>) => void;
/**
* Callback used to surface a short notice to the user. Defaults to rendering
* a toast so that shared editor code stays agnostic of the toast library.
*/
onNotice?: EditorNotice;
/** Collection of embed types to render in the document */
embeds: EmbedDescriptor[];
/** Display preferences for the logged in user, if any. */
@@ -206,6 +213,7 @@ export class Editor extends React.PureComponent<
onFileUploadStop: () => {
// no default behavior
},
onNotice: toastNotice,
embeds: [],
extensions,
};
+25
View File
@@ -0,0 +1,25 @@
import { toast } from "sonner";
import type { EditorNotice } from "@shared/editor/types";
/**
* The default editor notice handler, rendering a toast. This keeps knowledge of
* the toast library at the application layer, out of shared editor code.
*
* @param message - the message to display.
* @param type - the severity of the notice.
*/
export const toastNotice: EditorNotice = (message, type = "info") => {
switch (type) {
case "error":
toast.error(message);
return;
case "success":
toast.success(message);
return;
case "warning":
toast.warning(message);
return;
default:
toast.message(message);
}
};
+6 -3
View File
@@ -1,7 +1,7 @@
import { t } from "i18next";
import { v4 as uuidv4 } from "uuid";
import type { EditorView } from "prosemirror-view";
import { toast } from "sonner";
import type { EditorNotice } from "../types";
import FileHelper from "../lib/FileHelper";
import uploadPlaceholderPlugin, {
findPlaceholder,
@@ -26,6 +26,8 @@ export type Options = {
onFileUploadStop?: () => void;
/** Callback fired when file upload progress changes */
onFileUploadProgress?: (id: string, fractionComplete: number) => void;
/** Callback fired to surface a notice to the user */
onNotice?: EditorNotice;
/** Attributes to overwrite */
attrs?: {
/** Width to use when inserting image */
@@ -247,8 +249,9 @@ const insertFiles = async function (
})
);
toast.error(
error.message || t("Sorry, an error occurred uploading the file")
options.onNotice?.(
error.message || t("Sorry, an error occurred uploading the file"),
"error"
);
})
.finally(() => {
+11 -9
View File
@@ -5,10 +5,9 @@ import type { Command } from "prosemirror-state";
import { NodeSelection, Selection, TextSelection } from "prosemirror-state";
import type * as React from "react";
import { getMarkRange } from "../queries/getMarkRange";
import { toast } from "sonner";
import { sanitizeUrl } from "@shared/utils/urls";
import { getMarkRangeNodeSelection } from "../queries/getMarkRange";
import type { NodeAttrMark } from "@shared/editor/types";
import type { EditorNotice, NodeAttrMark } from "@shared/editor/types";
const addLinkTextSelection =
(attrs: Attrs): Command =>
@@ -59,7 +58,8 @@ const openLinkTextSelection =
| MouseEvent
| React.MouseEvent<HTMLButtonElement>
) => void)
| undefined
| undefined,
onNotice?: EditorNotice
): Command =>
(state) => {
if (!(state.selection instanceof TextSelection)) {
@@ -72,7 +72,7 @@ const openLinkTextSelection =
const event = new KeyboardEvent("keydown", { metaKey: false });
onClickLink(sanitizeUrl(range.mark.attrs.href) ?? "", event);
} catch (_err) {
toast.error(t("Sorry, that type of link is not supported"));
onNotice?.(t("Sorry, that type of link is not supported"), "error");
}
return true;
}
@@ -89,7 +89,8 @@ const openLinkNodeSelection =
| MouseEvent
| React.MouseEvent<HTMLButtonElement>
) => void)
| undefined
| undefined,
onNotice?: EditorNotice
): Command =>
(state) => {
if (!(state.selection instanceof NodeSelection)) {
@@ -110,7 +111,7 @@ const openLinkNodeSelection =
const event = new KeyboardEvent("keydown", { metaKey: false });
onClickLink(sanitizeUrl(linkMark.attrs.href) ?? "", event);
} catch (_err) {
toast.error(t("Sorry, that type of link is not supported"));
onNotice?.(t("Sorry, that type of link is not supported"), "error");
}
return true;
};
@@ -259,11 +260,12 @@ export const openLink = (
url: string,
event?: KeyboardEvent | MouseEvent | React.MouseEvent<HTMLButtonElement>
) => void)
| undefined
| undefined,
onNotice?: EditorNotice
): Command =>
chainCommands(
openLinkTextSelection(onClickLink),
openLinkNodeSelection(onClickLink)
openLinkTextSelection(onClickLink, onNotice),
openLinkNodeSelection(onClickLink, onNotice)
);
export const updateLink = (attrs: Attrs): Command =>
+6 -4
View File
@@ -2,21 +2,23 @@ import copy from "copy-to-clipboard";
import type { MouseEvent } from "react";
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import styled, { css } from "styled-components";
import type { EditorNotice } from "../types";
interface Props {
/** The CSS color the swatch represents, in its original notation. */
color: string;
/** The relative luminance of the color, used to pick an outline. */
luminance: number;
/** Callback used to surface a notice to the user. */
onNotice?: EditorNotice;
}
/**
* A small colored circle rendered after a CSS color inside inline code. Clicking
* it copies the color to the clipboard.
*/
export function ColorSwatch({ color, luminance }: Props) {
export function ColorSwatch({ color, luminance, onNotice }: Props) {
const { t } = useTranslation();
const handleMouseDown = useCallback((event: MouseEvent) => {
@@ -29,9 +31,9 @@ export function ColorSwatch({ color, luminance }: Props) {
event.preventDefault();
event.stopPropagation();
copy(color);
toast.message(t("Copied to clipboard"));
onNotice?.(t("Copied to clipboard"));
},
[color, t]
[color, onNotice, t]
);
return (
@@ -120,6 +120,7 @@ export default class ColorSwatchPreview extends Extension {
const element = this.editor.renderToPortal(ColorSwatch, {
color,
luminance,
onNotice: this.editor.props.onNotice,
});
// Keep the mount point layout-neutral; the swatch styles itself.
element.style.display = "contents";
+5 -3
View File
@@ -7,7 +7,6 @@ import type { Node } from "prosemirror-model";
import type { Transaction } from "prosemirror-state";
import { NodeSelection, Plugin, PluginKey } from "prosemirror-state";
import { Decoration, DecorationSet } from "prosemirror-view";
import { toast } from "sonner";
import { errToString } from "../../utils/error";
import { isCode, isMermaid } from "../lib/isCode";
import { isRemoteTransaction, mapDecorations } from "../lib/multiplayer";
@@ -397,7 +396,7 @@ export default function Mermaid({
isDark: boolean;
editor: Editor;
}) {
const { onClickLink } = editor.props;
const { onClickLink, onNotice } = editor.props;
return new Plugin({
key: pluginKey,
@@ -633,7 +632,10 @@ export default function Mermaid({
onClickLink(sanitizeUrl(href) ?? "");
}
} catch (_err) {
toast.error(t("Sorry, that type of link is not supported"));
onNotice?.(
t("Sorry, that type of link is not supported"),
"error"
);
}
}
+10 -4
View File
@@ -12,7 +12,6 @@ import type {
import type { Command, EditorState } from "prosemirror-state";
import { Plugin, TextSelection } from "prosemirror-state";
import type { EditorView } from "prosemirror-view";
import { toast } from "sonner";
import { isUrl, sanitizeUrl } from "../../utils/urls";
import { getMarkRange } from "../queries/getMarkRange";
import Mark from "./Mark";
@@ -126,7 +125,10 @@ export default class Link extends Mark<LinkOptions> {
keys(): Record<string, Command> {
return {
"Mod-Enter": openLink(this.options.onClickLink),
"Mod-Enter": openLink(
this.options.onClickLink,
this.editor.props.onNotice
),
};
}
@@ -135,7 +137,8 @@ export default class Link extends Mark<LinkOptions> {
link: (attrs: Attrs) => toggleLink(attrs),
addLink,
updateLink,
openLink: (): Command => openLink(this.options.onClickLink),
openLink: (): Command =>
openLink(this.options.onClickLink, this.editor.props.onNotice),
removeLink,
};
}
@@ -226,7 +229,10 @@ export default class Link extends Mark<LinkOptions> {
this.options.onClickLink(sanitized, event);
}
} catch (_err) {
toast.error(t("Sorry, that type of link is not supported"));
this.editor.props.onNotice?.(
t("Sorry, that type of link is not supported"),
"error"
);
}
return true;
+2
View File
@@ -178,6 +178,7 @@ export default class Attachment extends Node {
onFileUploadStart,
onFileUploadStop,
onFileUploadProgress,
onNotice,
} = this.editor.props;
if (!uploadFile) {
@@ -205,6 +206,7 @@ export default class Attachment extends Node {
onFileUploadStart,
onFileUploadStop,
onFileUploadProgress,
onNotice,
replaceExisting: true,
attrs: {
preview: node.attrs.preview,
+2 -3
View File
@@ -16,7 +16,6 @@ import {
TextSelection,
} from "prosemirror-state";
import { Decoration, DecorationSet, type EditorView } from "prosemirror-view";
import { toast } from "sonner";
import type { Primitive } from "utility-types";
import type { UserPreferences } from "../../types";
import { isBrowser, isMac } from "../../utils/browser";
@@ -351,7 +350,7 @@ export default class CodeFence extends Node<CodeFenceOptions> {
if (codeBlock) {
copy(codeBlock.node.textContent);
toast.message(t("Copied to clipboard"));
this.editor.props.onNotice?.(t("Copied to clipboard"));
return true;
}
@@ -372,7 +371,7 @@ export default class CodeFence extends Node<CodeFenceOptions> {
dispatch?.(tr);
copy(tr.doc.textBetween(state.selection.from, state.selection.to));
toast.message(t("Copied to clipboard"));
this.editor.props.onNotice?.(t("Copied to clipboard"));
return true;
}
+5 -3
View File
@@ -11,7 +11,6 @@ import type {
import type { Command } from "prosemirror-state";
import { Plugin, TextSelection } from "prosemirror-state";
import { Decoration, DecorationSet } from "prosemirror-view";
import { toast } from "sonner";
import type { Primitive } from "utility-types";
import { isSafari } from "../../utils/browser";
import backspaceToParagraph from "../commands/backspaceToParagraph";
@@ -131,11 +130,14 @@ export default class Heading extends Node<HeadingOptions> {
.replace("/edit", "");
try {
copy(normalizedUrl + hash);
toast.message(t("Link copied to clipboard"));
this.editor.props.onNotice?.(t("Link copied to clipboard"));
} catch (_err) {
// Some browser contexts disable the prompt() fallback used by
// copy-to-clipboard, causing it to throw – surface it rather than crash.
toast.error(t("Sorry, the link could not be copied"));
this.editor.props.onNotice?.(
t("Sorry, the link could not be copied"),
"error"
);
}
};
+2
View File
@@ -163,6 +163,7 @@ export default class SimpleImage extends Node {
onFileUploadStart,
onFileUploadStop,
onFileUploadProgress,
onNotice,
} = this.editor.props;
if (!uploadFile) {
@@ -184,6 +185,7 @@ export default class SimpleImage extends Node {
onFileUploadStart,
onFileUploadStop,
onFileUploadProgress,
onNotice,
replaceExisting: true,
attrs: {
width: node.attrs.width,
+10
View File
@@ -13,6 +13,16 @@ export type NodeWithPos = {
export type PlainTextSerializer = (node: ProsemirrorNode) => string;
/** The severity of a notice surfaced to the user from the editor. */
export type EditorNoticeType = "info" | "success" | "warning" | "error";
/**
* Callback used by the editor to surface a short notice (e.g. a toast) to the
* user. Provided by the host application so shared editor code stays agnostic
* of any specific notification library.
*/
export type EditorNotice = (message: string, type?: EditorNoticeType) => void;
export enum TableLayout {
fullWidth = "full-width",
}