Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

feat: improve toolbar performance

thecodrr52ae30527443
diff --git a/packages/editor/bugs.md b/packages/editor/bugs.md
new file mode 100644
index 000000000..a85467b29
--- /dev/null
+++ b/packages/editor/bugs.md
@@ -0,0 +1,5 @@
+1. Color tool is not updated on selection
+2. Cached colors not working
+3. ~Font size cannot be changed after a single change~
+4. ~Setting font size and then changing text to heading has no effect~
+5. List cannot be inserted from the dropdown
diff --git a/packages/editor/dist/components/button.d.ts b/packages/editor/dist/components/button.d.ts
index feeca8fb8..ccd1c4605 100644
--- a/packages/editor/dist/components/button.d.ts
+++ b/packages/editor/dist/components/button.d.ts
@@ -1,3 +1,3 @@
/// <reference types="react" />
import { ButtonProps } from "rebass";
-export declare const Button: import("react").ForwardRefExoticComponent<Pick<ButtonProps, "cite" | "data" | "dir" | "form" | "label" | "p" | "slot" | "span" | "style" | "summary" | "title" | "pattern" | "children" | "className" | "start" | "sizes" | "content" | "variant" | "tx" | "as" | "css" | "key" | "m" | "margin" | "mt" | "marginTop" | "mr" | "marginRight" | "mb" | "marginBottom" | "ml" | "marginLeft" | "mx" | "marginX" | "my" | "marginY" | "padding" | "pt" | "paddingTop" | "pr" | "paddingRight" | "pb" | "paddingBottom" | "pl" | "paddingLeft" | "px" | "paddingX" | "py" | "paddingY" | "width" | "height" | "minWidth" | "minHeight" | "maxWidth" | "maxHeight" | "display" | "verticalAlign" | "size" | "overflow" | "overflowX" | "overflowY" | "fontFamily" | "fontSize" | "fontWeight" | "lineHeight" | "letterSpacing" | "fontStyle" | "textAlign" | "color" | "bg" | "backgroundColor" | "opacity" | "alignItems" | "alignContent" | "justifyItems" | "justifyContent" | "flexWrap" | "flexDirection" | "flex" | "flexGrow" | "flexShrink" | "flexBasis" | "justifySelf" | "alignSelf" | "order" | "sx" | "accept" | "acceptCharset" | "action" | "allowFullScreen" | "allowTransparency" | "alt" | "async" | "autoComplete" | "autoFocus" | "autoPlay" | "capture" | "cellPadding" | "cellSpacing" | "charSet" | "challenge" | "checked" | "classID" | "cols" | "colSpan" | "controls" | "coords" | "crossOrigin" | "dateTime" | "default" | "defer" | "disabled" | "download" | "encType" | "formAction" | "formEncType" | "formMethod" | "formNoValidate" | "formTarget" | "frameBorder" | "headers" | "high" | "href" | "hrefLang" | "htmlFor" | "httpEquiv" | "integrity" | "keyParams" | "keyType" | "kind" | "list" | "loop" | "low" | "manifest" | "marginHeight" | "marginWidth" | "max" | "maxLength" | "media" | "mediaGroup" | "method" | "min" | "minLength" | "multiple" | "muted" | "name" | "nonce" | "noValidate" | "open" | "optimum" | "placeholder" | "playsInline" | "poster" | "preload" | "readOnly" | "rel" | "required" | "reversed" | "rows" | "rowSpan" | "sandbox" | "scope" | "scoped" | "scrolling" | "seamless" | "selected" | "shape" | "src" | "srcDoc" | "srcLang" | "srcSet" | "step" | "target" | "type" | "useMap" | "value" | "wmode" | "wrap" | "defaultChecked" | "defaultValue" | "suppressContentEditableWarning" | "suppressHydrationWarning" | "accessKey" | "contentEditable" | "contextMenu" | "draggable" | "hidden" | "id" | "lang" | "spellCheck" | "tabIndex" | "translate" | "radioGroup" | "role" | "about" | "datatype" | "inlist" | "prefix" | "property" | "resource" | "typeof" | "vocab" | "autoCapitalize" | "autoCorrect" | "autoSave" | "itemProp" | "itemScope" | "itemType" | "itemID" | "itemRef" | "results" | "security" | "unselectable" | "inputMode" | "is" | "aria-activedescendant" | "aria-atomic" | "aria-autocomplete" | "aria-busy" | "aria-checked" | "aria-colcount" | "aria-colindex" | "aria-colspan" | "aria-controls" | "aria-current" | "aria-describedby" | "aria-details" | "aria-disabled" | "aria-dropeffect" | "aria-errormessage" | "aria-expanded" | "aria-flowto" | "aria-grabbed" | "aria-haspopup" | "aria-hidden" | "aria-invalid" | "aria-keyshortcuts" | "aria-label" | "aria-labelledby" | "aria-level" | "aria-live" | "aria-modal" | "aria-multiline" | "aria-multiselectable" | "aria-orientation" | "aria-owns" | "aria-placeholder" | "aria-posinset" | "aria-pressed" | "aria-readonly" | "aria-relevant" | "aria-required" | "aria-roledescription" | "aria-rowcount" | "aria-rowindex" | "aria-rowspan" | "aria-selected" | "aria-setsize" | "aria-sort" | "aria-valuemax" | "aria-valuemin" | "aria-valuenow" | "aria-valuetext" | "dangerouslySetInnerHTML" | "onCopy" | "onCopyCapture" | "onCut" | "onCutCapture" | "onPaste" | "onPasteCapture" | "onCompositionEnd" | "onCompositionEndCapture" | "onCompositionStart" | "onCompositionStartCapture" | "onCompositionUpdate" | "onCompositionUpdateCapture" | "onFocus" | "onFocusCapture" | "onBlur" | "onBlurCapture" | "onChange" | "onChangeCapture" | "onBeforeInput" | "onBeforeInputCapture" | "onInput" | "onInputCapture" | "onReset" | "onResetCapture" | "onSubmit" | "onSubmitCapture" | "onInvalid" | "onInvalidCapture" | "onLoad" | "onLoadCapture" | "onError" | "onErrorCapture" | "onKeyDown" | "onKeyDownCapture" | "onKeyPress" | "onKeyPressCapture" | "onKeyUp" | "onKeyUpCapture" | "onAbort" | "onAbortCapture" | "onCanPlay" | "onCanPlayCapture" | "onCanPlayThrough" | "onCanPlayThroughCapture" | "onDurationChange" | "onDurationChangeCapture" | "onEmptied" | "onEmptiedCapture" | "onEncrypted" | "onEncryptedCapture" | "onEnded" | "onEndedCapture" | "onLoadedData" | "onLoadedDataCapture" | "onLoadedMetadata" | "onLoadedMetadataCapture" | "onLoadStart" | "onLoadStartCapture" | "onPause" | "onPauseCapture" | "onPlay" | "onPlayCapture" | "onPlaying" | "onPlayingCapture" | "onProgress" | "onProgressCapture" | "onRateChange" | "onRateChangeCapture" | "onSeeked" | "onSeekedCapture" | "onSeeking" | "onSeekingCapture" | "onStalled" | "onStalledCapture" | "onSuspend" | "onSuspendCapture" | "onTimeUpdate" | "onTimeUpdateCapture" | "onVolumeChange" | "onVolumeChangeCapture" | "onWaiting" | "onWaitingCapture" | "onAuxClick" | "onAuxClickCapture" | "onClick" | "onClickCapture" | "onContextMenu" | "onContextMenuCapture" | "onDoubleClick" | "onDoubleClickCapture" | "onDrag" | "onDragCapture" | "onDragEnd" | "onDragEndCapture" | "onDragEnter" | "onDragEnterCapture" | "onDragExit" | "onDragExitCapture" | "onDragLeave" | "onDragLeaveCapture" | "onDragOver" | "onDragOverCapture" | "onDragStart" | "onDragStartCapture" | "onDrop" | "onDropCapture" | "onMouseDown" | "onMouseDownCapture" | "onMouseEnter" | "onMouseLeave" | "onMouseMove" | "onMouseMoveCapture" | "onMouseOut" | "onMouseOutCapture" | "onMouseOver" | "onMouseOverCapture" | "onMouseUp" | "onMouseUpCapture" | "onSelect" | "onSelectCapture" | "onTouchCancel" | "onTouchCancelCapture" | "onTouchEnd" | "onTouchEndCapture" | "onTouchMove" | "onTouchMoveCapture" | "onTouchStart" | "onTouchStartCapture" | "onPointerDown" | "onPointerDownCapture" | "onPointerMove" | "onPointerMoveCapture" | "onPointerUp" | "onPointerUpCapture" | "onPointerCancel" | "onPointerCancelCapture" | "onPointerEnter" | "onPointerEnterCapture" | "onPointerLeave" | "onPointerLeaveCapture" | "onPointerOver" | "onPointerOverCapture" | "onPointerOut" | "onPointerOutCapture" | "onGotPointerCapture" | "onGotPointerCaptureCapture" | "onLostPointerCapture" | "onLostPointerCaptureCapture" | "onScroll" | "onScrollCapture" | "onWheel" | "onWheelCapture" | "onAnimationStart" | "onAnimationStartCapture" | "onAnimationEnd" | "onAnimationEndCapture" | "onAnimationIteration" | "onAnimationIterationCapture" | "onTransitionEnd" | "onTransitionEndCapture"> & import("react").RefAttributes<HTMLButtonElement>>;
+export declare const Button: import("react").ForwardRefExoticComponent<Pick<ButtonProps, "name" | "onFocus" | "onBlur" | "fontSize" | "style" | "textAlign" | "fontFamily" | "color" | "dir" | "content" | "draggable" | "alignContent" | "alignItems" | "alignSelf" | "backgroundColor" | "display" | "flex" | "flexBasis" | "flexDirection" | "flexGrow" | "flexShrink" | "flexWrap" | "fontStyle" | "fontWeight" | "height" | "justifyContent" | "justifyItems" | "justifySelf" | "letterSpacing" | "lineHeight" | "margin" | "marginBottom" | "marginLeft" | "marginRight" | "marginTop" | "maxHeight" | "maxWidth" | "minHeight" | "minWidth" | "opacity" | "order" | "overflow" | "overflowX" | "overflowY" | "padding" | "paddingBottom" | "paddingLeft" | "paddingRight" | "paddingTop" | "translate" | "verticalAlign" | "width" | "default" | "px" | "cite" | "data" | "form" | "label" | "p" | "slot" | "span" | "summary" | "title" | "pattern" | "children" | "sizes" | "key" | "selected" | "value" | "id" | "variant" | "tx" | "as" | "css" | "m" | "mt" | "mr" | "mb" | "ml" | "mx" | "marginX" | "my" | "marginY" | "pt" | "pr" | "pb" | "pl" | "paddingX" | "py" | "paddingY" | "size" | "bg" | "sx" | "accept" | "acceptCharset" | "action" | "allowFullScreen" | "allowTransparency" | "alt" | "async" | "autoComplete" | "autoFocus" | "autoPlay" | "capture" | "cellPadding" | "cellSpacing" | "charSet" | "challenge" | "checked" | "classID" | "cols" | "colSpan" | "controls" | "coords" | "crossOrigin" | "dateTime" | "defer" | "disabled" | "download" | "encType" | "formAction" | "formEncType" | "formMethod" | "formNoValidate" | "formTarget" | "frameBorder" | "headers" | "high" | "href" | "hrefLang" | "htmlFor" | "httpEquiv" | "integrity" | "keyParams" | "keyType" | "kind" | "list" | "loop" | "low" | "manifest" | "marginHeight" | "marginWidth" | "max" | "maxLength" | "media" | "mediaGroup" | "method" | "min" | "minLength" | "multiple" | "muted" | "nonce" | "noValidate" | "open" | "optimum" | "placeholder" | "playsInline" | "poster" | "preload" | "readOnly" | "rel" | "required" | "reversed" | "rows" | "rowSpan" | "sandbox" | "scope" | "scoped" | "scrolling" | "seamless" | "shape" | "src" | "srcDoc" | "srcLang" | "srcSet" | "start" | "step" | "target" | "type" | "useMap" | "wmode" | "wrap" | "defaultChecked" | "defaultValue" | "suppressContentEditableWarning" | "suppressHydrationWarning" | "accessKey" | "className" | "contentEditable" | "contextMenu" | "hidden" | "lang" | "spellCheck" | "tabIndex" | "radioGroup" | "role" | "about" | "datatype" | "inlist" | "prefix" | "property" | "resource" | "typeof" | "vocab" | "autoCapitalize" | "autoCorrect" | "autoSave" | "itemProp" | "itemScope" | "itemType" | "itemID" | "itemRef" | "results" | "security" | "unselectable" | "inputMode" | "is" | "aria-activedescendant" | "aria-atomic" | "aria-autocomplete" | "aria-busy" | "aria-checked" | "aria-colcount" | "aria-colindex" | "aria-colspan" | "aria-controls" | "aria-current" | "aria-describedby" | "aria-details" | "aria-disabled" | "aria-dropeffect" | "aria-errormessage" | "aria-expanded" | "aria-flowto" | "aria-grabbed" | "aria-haspopup" | "aria-hidden" | "aria-invalid" | "aria-keyshortcuts" | "aria-label" | "aria-labelledby" | "aria-level" | "aria-live" | "aria-modal" | "aria-multiline" | "aria-multiselectable" | "aria-orientation" | "aria-owns" | "aria-placeholder" | "aria-posinset" | "aria-pressed" | "aria-readonly" | "aria-relevant" | "aria-required" | "aria-roledescription" | "aria-rowcount" | "aria-rowindex" | "aria-rowspan" | "aria-selected" | "aria-setsize" | "aria-sort" | "aria-valuemax" | "aria-valuemin" | "aria-valuenow" | "aria-valuetext" | "dangerouslySetInnerHTML" | "onCopy" | "onCopyCapture" | "onCut" | "onCutCapture" | "onPaste" | "onPasteCapture" | "onCompositionEnd" | "onCompositionEndCapture" | "onCompositionStart" | "onCompositionStartCapture" | "onCompositionUpdate" | "onCompositionUpdateCapture" | "onFocusCapture" | "onBlurCapture" | "onChange" | "onChangeCapture" | "onBeforeInput" | "onBeforeInputCapture" | "onInput" | "onInputCapture" | "onReset" | "onResetCapture" | "onSubmit" | "onSubmitCapture" | "onInvalid" | "onInvalidCapture" | "onLoad" | "onLoadCapture" | "onError" | "onErrorCapture" | "onKeyDown" | "onKeyDownCapture" | "onKeyPress" | "onKeyPressCapture" | "onKeyUp" | "onKeyUpCapture" | "onAbort" | "onAbortCapture" | "onCanPlay" | "onCanPlayCapture" | "onCanPlayThrough" | "onCanPlayThroughCapture" | "onDurationChange" | "onDurationChangeCapture" | "onEmptied" | "onEmptiedCapture" | "onEncrypted" | "onEncryptedCapture" | "onEnded" | "onEndedCapture" | "onLoadedData" | "onLoadedDataCapture" | "onLoadedMetadata" | "onLoadedMetadataCapture" | "onLoadStart" | "onLoadStartCapture" | "onPause" | "onPauseCapture" | "onPlay" | "onPlayCapture" | "onPlaying" | "onPlayingCapture" | "onProgress" | "onProgressCapture" | "onRateChange" | "onRateChangeCapture" | "onSeeked" | "onSeekedCapture" | "onSeeking" | "onSeekingCapture" | "onStalled" | "onStalledCapture" | "onSuspend" | "onSuspendCapture" | "onTimeUpdate" | "onTimeUpdateCapture" | "onVolumeChange" | "onVolumeChangeCapture" | "onWaiting" | "onWaitingCapture" | "onAuxClick" | "onAuxClickCapture" | "onClick" | "onClickCapture" | "onContextMenu" | "onContextMenuCapture" | "onDoubleClick" | "onDoubleClickCapture" | "onDrag" | "onDragCapture" | "onDragEnd" | "onDragEndCapture" | "onDragEnter" | "onDragEnterCapture" | "onDragExit" | "onDragExitCapture" | "onDragLeave" | "onDragLeaveCapture" | "onDragOver" | "onDragOverCapture" | "onDragStart" | "onDragStartCapture" | "onDrop" | "onDropCapture" | "onMouseDown" | "onMouseDownCapture" | "onMouseEnter" | "onMouseLeave" | "onMouseMove" | "onMouseMoveCapture" | "onMouseOut" | "onMouseOutCapture" | "onMouseOver" | "onMouseOverCapture" | "onMouseUp" | "onMouseUpCapture" | "onSelect" | "onSelectCapture" | "onTouchCancel" | "onTouchCancelCapture" | "onTouchEnd" | "onTouchEndCapture" | "onTouchMove" | "onTouchMoveCapture" | "onTouchStart" | "onTouchStartCapture" | "onPointerDown" | "onPointerDownCapture" | "onPointerMove" | "onPointerMoveCapture" | "onPointerUp" | "onPointerUpCapture" | "onPointerCancel" | "onPointerCancelCapture" | "onPointerEnter" | "onPointerEnterCapture" | "onPointerLeave" | "onPointerLeaveCapture" | "onPointerOver" | "onPointerOverCapture" | "onPointerOut" | "onPointerOutCapture" | "onGotPointerCapture" | "onGotPointerCaptureCapture" | "onLostPointerCapture" | "onLostPointerCaptureCapture" | "onScroll" | "onScrollCapture" | "onWheel" | "onWheelCapture" | "onAnimationStart" | "onAnimationStartCapture" | "onAnimationEnd" | "onAnimationEndCapture" | "onAnimationIteration" | "onAnimationIterationCapture" | "onTransitionEnd" | "onTransitionEndCapture"> & import("react").RefAttributes<HTMLButtonElement>>;
diff --git a/packages/editor/dist/components/menu/menubutton.js b/packages/editor/dist/components/menu/menubutton.js
index 11a3d7537..c9537ab55 100644
--- a/packages/editor/dist/components/menu/menubutton.js
+++ b/packages/editor/dist/components/menu/menubutton.js
@@ -11,10 +11,11 @@ var __assign = (this && this.__assign) || function () {
};
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useRef } from "react";
-import { Flex, Text, Button } from "rebass";
+import { Flex, Text } from "rebass";
import { Icon } from "../../toolbar/components/icon";
import { Icons } from "../../toolbar/icons";
import { useToolbarLocation } from "../../toolbar/stores/toolbar-store";
+import { Button } from "../button";
export function MenuButton(props) {
var item = props.item, isFocused = props.isFocused, onMouseEnter = props.onMouseEnter, onMouseLeave = props.onMouseLeave, onClick = props.onClick;
var title = item.title, key = item.key, icon = item.icon, tooltip = item.tooltip, isDisabled = item.isDisabled, isChecked = item.isChecked, menu = item.menu, modifier = item.modifier;
@@ -29,7 +30,7 @@ export function MenuButton(props) {
":hover": {
bg: isBottom ? "transparent" : "hover",
},
- } }, { children: [_jsxs(Flex, { children: [icon && (_jsx(Icon, { path: Icons[icon], color: "text", size: "medium", sx: { mr: 2 } })), _jsx(Text, __assign({ as: "span", variant: "body" }, { children: title }))] }), isChecked || menu || modifier ? (_jsxs(Flex, __assign({ sx: { ml: 4 } }, { children: [isChecked && _jsx(Icon, { path: Icons.check, size: 14 }), menu && _jsx(Icon, { path: Icons.chevronRight, size: 14 }), modifier && (_jsx(Text, __assign({ as: "span", sx: {
+ } }, { children: [_jsxs(Flex, { children: [icon && (_jsx(Icon, { path: Icons[icon], color: "text", size: "medium", sx: { mr: 2 } })), _jsx(Text, __assign({ as: "span", variant: "body", sx: { fontSize: "inherit" } }, { children: title }))] }), isChecked || menu || modifier ? (_jsxs(Flex, __assign({ sx: { ml: 4 } }, { children: [isChecked && _jsx(Icon, { path: Icons.check, size: 14 }), menu && _jsx(Icon, { path: Icons.chevronRight, size: 14 }), modifier && (_jsx(Text, __assign({ as: "span", sx: {
fontFamily: "body",
fontSize: "menu",
color: "fontTertiary",
diff --git a/packages/editor/dist/hooks/useRefValue.d.ts b/packages/editor/dist/hooks/useRefValue.d.ts
new file mode 100644
index 000000000..de0bdea82
--- /dev/null
+++ b/packages/editor/dist/hooks/useRefValue.d.ts
@@ -0,0 +1,2 @@
+/// <reference types="react" />
+export declare function useRefValue<T>(value: T): import("react").MutableRefObject<T>;
diff --git a/packages/editor/dist/hooks/useRefValue.js b/packages/editor/dist/hooks/useRefValue.js
new file mode 100644
index 000000000..253549414
--- /dev/null
+++ b/packages/editor/dist/hooks/useRefValue.js
@@ -0,0 +1,8 @@
+import { useEffect, useRef } from "react";
+export function useRefValue(value) {
+ var refValue = useRef(value);
+ useEffect(function () {
+ refValue.current = value;
+ }, [value]);
+ return refValue;
+}
diff --git a/packages/editor/dist/index.d.ts b/packages/editor/dist/index.d.ts
index 7d395def8..204080ab2 100644
--- a/packages/editor/dist/index.d.ts
+++ b/packages/editor/dist/index.d.ts
@@ -4,8 +4,9 @@ import { EditorOptions } from "@tiptap/react";
import Toolbar from "./toolbar";
import { Theme } from "@notesnook/theme";
import { AttachmentOptions } from "./extensions/attachment";
+import { Editor } from "./types";
declare const useTiptap: (options?: Partial<EditorOptions & AttachmentOptions & {
theme: Theme;
-}>, deps?: import("react").DependencyList) => import("@tiptap/react").Editor | null;
+}>, deps?: import("react").DependencyList) => Editor | null;
export { useTiptap, Toolbar };
export * from "./extensions/react";
diff --git a/packages/editor/dist/index.js b/packages/editor/dist/index.js
index fc8c16f53..e7f3fd760 100644
--- a/packages/editor/dist/index.js
+++ b/packages/editor/dist/index.js
@@ -26,7 +26,7 @@ import Placeholder from "@tiptap/extension-placeholder";
import Underline from "@tiptap/extension-underline";
import { useEditor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
-import { useMemo } from "react";
+import { useEffect, useMemo, useRef } from "react";
import { EditorView } from "prosemirror-view";
import Toolbar from "./toolbar";
import TextAlign from "@tiptap/extension-text-align";
@@ -57,6 +57,9 @@ import { NodeViewSelectionNotifier, usePortalProvider, } from "./extensions/reac
import { OutlineList } from "./extensions/outline-list";
import { OutlineListItem } from "./extensions/outline-list-item";
import { Table } from "./extensions/table";
+// export class Editor extends TiptapEditor {
+// get instance(): TiptapEditor {}
+// }
EditorView.prototype.updateState = function updateState(state) {
if (!this.docView)
return; // This prevents the matchesNode error on hot reloads
@@ -139,10 +142,14 @@ var useTiptap = function (options, deps) {
injectCSS: false,
}); }, [theme, onDownloadAttachment, onOpenAttachmentPicker, PortalProviderAPI]);
var editor = useEditor(__assign(__assign({}, defaultOptions), restOptions), deps);
- /**
- * Add editor to global for use in React Native.
- */
- global.editor = editor;
+ var editorRef = useRef(editor);
+ useEffect(function () {
+ editorRef.current = editor;
+ if (editor && !editor.current)
+ Object.defineProperty(editor, "current", {
+ get: function () { return editorRef.current; },
+ });
+ }, [editor]);
return editor;
};
export { useTiptap, Toolbar };
diff --git a/packages/editor/dist/toolbar/components/counter.d.ts b/packages/editor/dist/toolbar/components/counter.d.ts
index 1cf4a9015..bfbe39347 100644
--- a/packages/editor/dist/toolbar/components/counter.d.ts
+++ b/packages/editor/dist/toolbar/components/counter.d.ts
@@ -1,4 +1,4 @@
-/// <reference types="react" />
+import React from "react";
export declare type CounterProps = {
title: string;
onIncrease: () => void;
@@ -6,4 +6,6 @@ export declare type CounterProps = {
onReset: () => void;
value: string;
};
-export declare function Counter(props: CounterProps): JSX.Element;
+declare function _Counter(props: CounterProps): JSX.Element;
+export declare const Counter: React.MemoExoticComponent<typeof _Counter>;
+export {};
diff --git a/packages/editor/dist/toolbar/components/counter.js b/packages/editor/dist/toolbar/components/counter.js
index 682495755..1ba7e4b07 100644
--- a/packages/editor/dist/toolbar/components/counter.js
+++ b/packages/editor/dist/toolbar/components/counter.js
@@ -10,10 +10,11 @@ var __assign = (this && this.__assign) || function () {
return __assign.apply(this, arguments);
};
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
+import React from "react";
import { Flex, Text } from "rebass";
import { Button } from "../../components/button";
import { ToolButton } from "./tool-button";
-export function Counter(props) {
+function _Counter(props) {
var title = props.title, onDecrease = props.onDecrease, onIncrease = props.onIncrease, onReset = props.onReset, value = props.value;
return (_jsxs(Flex, __assign({ sx: {
alignItems: "center",
@@ -25,3 +26,6 @@ export function Counter(props) {
bg: "transparent",
}, onClick: onReset }, { children: _jsx(Text, __assign({ variant: "body", sx: { fontSize: "subBody", mx: 1, textAlign: "center" }, title: "Reset ".concat(title) }, { children: value })) })), _jsx(ToolButton, { toggled: false, title: "Increase ".concat(title), icon: "plus", variant: "small", onClick: onIncrease })] })));
}
+export var Counter = React.memo(_Counter, function (prev, next) {
+ return prev.value === next.value;
+});
diff --git a/packages/editor/dist/toolbar/components/splitbutton.d.ts b/packages/editor/dist/toolbar/components/splitbutton.d.ts
index b6877ad0a..0db2f1020 100644
--- a/packages/editor/dist/toolbar/components/splitbutton.d.ts
+++ b/packages/editor/dist/toolbar/components/splitbutton.d.ts
@@ -1,6 +1,9 @@
import { PropsWithChildren } from "react";
import { ToolButtonProps } from "./tool-button";
+import React from "react";
export declare type SplitButtonProps = ToolButtonProps & {
onOpen: () => void;
};
-export declare function SplitButton(props: PropsWithChildren<SplitButtonProps>): JSX.Element;
+declare function _SplitButton(props: PropsWithChildren<SplitButtonProps>): JSX.Element;
+export declare const SplitButton: React.MemoExoticComponent<typeof _SplitButton>;
+export {};
diff --git a/packages/editor/dist/toolbar/components/splitbutton.js b/packages/editor/dist/toolbar/components/splitbutton.js
index 3a697199d..9303df153 100644
--- a/packages/editor/dist/toolbar/components/splitbutton.js
+++ b/packages/editor/dist/toolbar/components/splitbutton.js
@@ -28,7 +28,8 @@ import { Icon } from "./icon";
import { ToolButton } from "./tool-button";
import { useToolbarLocation } from "../stores/toolbar-store";
import { Button } from "../../components/button";
-export function SplitButton(props) {
+import React from "react";
+function _SplitButton(props) {
var children = props.children, toggled = props.toggled, onOpen = props.onOpen, toolButtonProps = __rest(props, ["children", "toggled", "onOpen"]);
var ref = useRef(null);
var toolbarLocation = useToolbarLocation();
@@ -46,3 +47,6 @@ export function SplitButton(props) {
},
}, onClick: onOpen }, { children: _jsx(Icon, { path: toolbarLocation === "bottom" ? Icons.chevronUp : Icons.chevronDown, color: "text", size: "small" }) }))] })), children] }));
}
+export var SplitButton = React.memo(_SplitButton, function (prev, next) {
+ return prev.toggled === next.toggled;
+});
diff --git a/packages/editor/dist/toolbar/components/toolbutton.d.ts b/packages/editor/dist/toolbar/components/toolbutton.d.ts
index a3ee82353..daa747276 100644
--- a/packages/editor/dist/toolbar/components/toolbutton.d.ts
+++ b/packages/editor/dist/toolbar/components/toolbutton.d.ts
@@ -12,4 +12,11 @@ export declare type ToolButtonProps = ButtonProps & {
buttonRef?: React.MutableRefObject<HTMLButtonElement | null | undefined>;
variant?: ToolButtonVariant;
};
-export declare function ToolButton(props: ToolButtonProps): JSX.Element;
+export declare const ToolButton: React.NamedExoticComponent<ButtonProps & {
+ icon: IconNames;
+ iconColor?: "icon" | "text" | "blue" | "gray" | "green" | "orange" | "purple" | "red" | "yellow" | "checked" | "disabled" | "placeholder" | "background" | "border" | "overlay" | "hover" | keyof import("@notesnook/theme/dist/theme/colorscheme/static").StaticColors | "primary" | "bgTransparent" | "accent" | "bgSecondary" | "bgSecondaryText" | "fontSecondary" | "fontTertiary" | "secondary" | undefined;
+ iconSize?: number | "medium" | "small" | "big" | undefined;
+ toggled: boolean;
+ buttonRef?: React.MutableRefObject<HTMLButtonElement | null | undefined> | undefined;
+ variant?: ToolButtonVariant | undefined;
+}>;
diff --git a/packages/editor/dist/toolbar/components/toolbutton.js b/packages/editor/dist/toolbar/components/toolbutton.js
index 84c026088..37db47a16 100644
--- a/packages/editor/dist/toolbar/components/toolbutton.js
+++ b/packages/editor/dist/toolbar/components/toolbutton.js
@@ -21,12 +21,16 @@ var __rest = (this && this.__rest) || function (s, e) {
return t;
};
import { jsx as _jsx } from "react/jsx-runtime";
+import React from "react";
import { Icons } from "../icons";
import { Button } from "../../components/button";
import { Icon } from "./icon";
-export function ToolButton(props) {
+export var ToolButton = React.memo(function ToolButton(props) {
var id = props.id, icon = props.icon, iconSize = props.iconSize, iconColor = props.iconColor, toggled = props.toggled, sx = props.sx, buttonRef = props.buttonRef, _a = props.variant, variant = _a === void 0 ? "normal" : _a, buttonProps = __rest(props, ["id", "icon", "iconSize", "iconColor", "toggled", "sx", "buttonRef", "variant"]);
+ console.log("rerendering", props.title);
return (_jsx(Button, __assign({ ref: buttonRef, tabIndex: -1, id: "tool-".concat(id || icon), sx: __assign({ flexShrink: 0, p: variant === "small" ? "small" : 1, borderRadius: variant === "small" ? "small" : "default", m: 0, bg: toggled ? "hover" : "transparent", mr: variant === "small" ? 0 : 1, ":hover": { bg: ["transparent", "hover"] }, ":active": { bg: "hover" }, ":last-of-type": {
mr: 0,
} }, sx), onMouseDown: function (e) { return e.preventDefault(); } }, buttonProps, { children: _jsx(Icon, { path: Icons[icon], color: iconColor || "icon", size: iconSize || (variant === "small" ? "medium" : "big") }) })));
-}
+}, function (prev, next) {
+ return prev.toggled === next.toggled;
+});
diff --git a/packages/editor/dist/toolbar/icons.d.ts b/packages/editor/dist/toolbar/icons.d.ts
index 201600fde..76bc98db7 100644
--- a/packages/editor/dist/toolbar/icons.d.ts
+++ b/packages/editor/dist/toolbar/icons.d.ts
@@ -4,6 +4,7 @@ export declare const Icons: {
underline: string;
strikethrough: string;
code: string;
+ codeRemove: string;
alignCenter: string;
alignLeft: string;
alignRight: string;
@@ -21,6 +22,8 @@ export declare const Icons: {
highlight: string;
textColor: string;
link: string;
+ linkRemove: string;
+ linkEdit: string;
url: string;
image: string;
imageSettings: string;
diff --git a/packages/editor/dist/toolbar/icons.js b/packages/editor/dist/toolbar/icons.js
index 310c4065f..0a02c91b2 100644
--- a/packages/editor/dist/toolbar/icons.js
+++ b/packages/editor/dist/toolbar/icons.js
@@ -1,10 +1,11 @@
-import { mdiAttachment, mdiBorderHorizontal, mdiCheck, mdiChevronDown, mdiCodeBraces, mdiCodeTags, mdiDotsVertical, mdiFormatAlignCenter, mdiFormatAlignJustify, mdiFormatAlignLeft, mdiFormatAlignRight, mdiFormatBold, mdiFormatClear, mdiFormatColorHighlight, mdiFormatColorText, mdiFormatItalic, mdiFormatListBulleted, mdiFormatListNumbered, mdiFormatQuoteClose, mdiFormatStrikethrough, mdiFormatSubscript, mdiFormatSuperscript, mdiFormatTextdirectionLToR, mdiFormatTextdirectionRToL, mdiFormatUnderline, mdiImage, mdiInvertColorsOff, mdiLinkPlus, mdiLoading, mdiTable, mdiTableBorder, mdiTableRowPlusAfter, mdiTableRowPlusBefore, mdiTableRowRemove, mdiTableColumnPlusAfter, mdiTableColumnPlusBefore, mdiTableColumnRemove, mdiUploadOutline, mdiPlus, mdiFormatColorFill, mdiClose, mdiSortDescending, mdiArrowExpandRight, mdiArrowExpandLeft, mdiArrowExpandDown, mdiArrowExpandUp, mdiTableMergeCells, mdiTableSplitCell, mdiDeleteOutline, mdiDownloadOutline, mdiFormatListCheckbox, mdiDrag, mdiCheckboxMarkedOutline, mdiChevronUp, mdiArrowUp, mdiArrowDown, mdiRegex, mdiFormatLetterCase, mdiFormatLetterMatches, mdiMoviePlusOutline, mdiLink, mdiChevronRight, mdiTableColumnWidth, mdiTableRowHeight, mdiMinus, mdiPaletteOutline, mdiCircle, mdiChevronLeft, mdiTableCog, mdiTableOff, mdiRectangle, mdiImageEditOutline, mdiArrowLeft, mdiMovieCogOutline, } from "@mdi/js";
+import { mdiAttachment, mdiBorderHorizontal, mdiCheck, mdiChevronDown, mdiCodeBraces, mdiCodeTags, mdiDotsVertical, mdiFormatAlignCenter, mdiFormatAlignJustify, mdiFormatAlignLeft, mdiFormatAlignRight, mdiFormatBold, mdiFormatClear, mdiFormatColorHighlight, mdiFormatColorText, mdiFormatItalic, mdiFormatListBulleted, mdiFormatListNumbered, mdiFormatQuoteClose, mdiFormatStrikethrough, mdiFormatSubscript, mdiFormatSuperscript, mdiFormatTextdirectionLToR, mdiFormatTextdirectionRToL, mdiFormatUnderline, mdiImage, mdiInvertColorsOff, mdiLinkPlus, mdiLoading, mdiTable, mdiTableBorder, mdiTableRowPlusAfter, mdiTableRowPlusBefore, mdiTableRowRemove, mdiTableColumnPlusAfter, mdiTableColumnPlusBefore, mdiTableColumnRemove, mdiUploadOutline, mdiPlus, mdiFormatColorFill, mdiClose, mdiSortDescending, mdiArrowExpandRight, mdiArrowExpandLeft, mdiArrowExpandDown, mdiArrowExpandUp, mdiTableMergeCells, mdiTableSplitCell, mdiDeleteOutline, mdiDownloadOutline, mdiFormatListCheckbox, mdiDrag, mdiCheckboxMarkedOutline, mdiChevronUp, mdiArrowUp, mdiArrowDown, mdiRegex, mdiFormatLetterCase, mdiFormatLetterMatches, mdiMoviePlusOutline, mdiLink, mdiChevronRight, mdiTableColumnWidth, mdiTableRowHeight, mdiMinus, mdiPaletteOutline, mdiCircle, mdiChevronLeft, mdiTableCog, mdiTableOff, mdiRectangle, mdiImageEditOutline, mdiArrowLeft, mdiMovieCogOutline, mdiLinkOff, } from "@mdi/js";
export var Icons = {
bold: mdiFormatBold,
italic: mdiFormatItalic,
underline: mdiFormatUnderline,
strikethrough: mdiFormatStrikethrough,
code: mdiCodeTags,
+ codeRemove: "M3.62109375 1.83837892 2.26318358 3.13037107 6.46289063 7.536621 1.9995117 12l6.0000003 6 1.40039025-1.400391L4.80029295 12l3.0292968-3.0292965 7.0283205 7.371093-.2578125.2578125L16.000488 18l.224121-.224121 4.3125 4.52490225 1.35791025-1.29492225-4.34326125-4.55712825L22.000488 12l-6-6-1.40039025 1.40039063L19.19970675 12l-3.016113 3.016113L9.156738 7.6435545l.24316425-.24316387L7.999512 6l-.2109375.2109375Z",
alignCenter: mdiFormatAlignCenter,
alignLeft: mdiFormatAlignLeft,
alignRight: mdiFormatAlignRight,
@@ -22,6 +23,8 @@ export var Icons = {
highlight: mdiFormatColorHighlight,
textColor: mdiFormatColorText,
link: mdiLinkPlus,
+ linkRemove: mdiLinkOff,
+ linkEdit: "m19 14 1.28 1.28c.22.21.22.56 0 .77l-1 1L17.23 15l1-1c.11-.11.25-.17.39-.17s.27.06.38.17m-.3 3.63-6.06 6.07h-2.06v-2.06l6.07-6.06zM7 7h4v2H7c-1.6568542 0-3 1.343146-3 3s1.3431458 3 3 3h4v2H7c-2.7614237 0-5-2.238576-5-5 0-2.7614237 2.2385763-5 5-5m10 0c2.761424 0 5 2.2385763 5 5h-2c0-1.656854-1.343146-3-3-3h-4V7h4m-9 4h8v2H8v-2",
url: mdiLink,
image: mdiImage,
imageSettings: mdiImageEditOutline,
diff --git a/packages/editor/dist/toolbar/toolbar.js b/packages/editor/dist/toolbar/toolbar.js
index 0dfeab71b..2a647d319 100644
--- a/packages/editor/dist/toolbar/toolbar.js
+++ b/packages/editor/dist/toolbar/toolbar.js
@@ -26,7 +26,15 @@ export function Toolbar(props) {
setToolbarLocation(location);
}, [isMobile, location]);
var tools = [
- ["insertBlock", "tableSettings", "imageSettings"],
+ [
+ "insertBlock",
+ "tableSettings",
+ "imageSettings",
+ "embedSettings",
+ "attachmentSettings",
+ "linkRemove",
+ "codeRemove",
+ ],
[
"bold",
"italic",
diff --git a/packages/editor/dist/toolbar/tooldefinitions.js b/packages/editor/dist/toolbar/tooldefinitions.js
index ba9c7e55f..94d007542 100644
--- a/packages/editor/dist/toolbar/tooldefinitions.js
+++ b/packages/editor/dist/toolbar/tooldefinitions.js
@@ -19,10 +19,20 @@ var tools = {
icon: "link",
title: "Link",
},
+ linkRemove: {
+ icon: "linkRemove",
+ title: "Link remove",
+ conditional: true,
+ },
code: {
icon: "code",
title: "Code",
},
+ codeRemove: {
+ icon: "codeRemove",
+ title: "Code",
+ conditional: true,
+ },
clearformatting: {
icon: "formatClear",
title: "Clear all formatting",
diff --git a/packages/editor/dist/toolbar/tools/alignment.js b/packages/editor/dist/toolbar/tools/alignment.js
index 9ea25b34e..7de0cb967 100644
--- a/packages/editor/dist/toolbar/tools/alignment.js
+++ b/packages/editor/dist/toolbar/tools/alignment.js
@@ -24,7 +24,7 @@ import { jsx as _jsx } from "react/jsx-runtime";
import { ToolButton } from "../components/tool-button";
function AlignmentTool(props) {
var editor = props.editor, alignment = props.alignment, toolProps = __rest(props, ["editor", "alignment"]);
- return (_jsx(ToolButton, __assign({}, toolProps, { onClick: function () { return editor.chain().focus().setTextAlign(alignment).run(); }, toggled: editor.isActive({ textAlign: alignment }) })));
+ return (_jsx(ToolButton, __assign({}, toolProps, { onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().setTextAlign(alignment).run(); }, toggled: editor.isActive({ textAlign: alignment }) })));
}
export function AlignCenter(props) {
return _jsx(AlignmentTool, __assign({ alignment: "center" }, props));
diff --git a/packages/editor/dist/toolbar/tools/attachment.js b/packages/editor/dist/toolbar/tools/attachment.js
index c086123ca..964391fde 100644
--- a/packages/editor/dist/toolbar/tools/attachment.js
+++ b/packages/editor/dist/toolbar/tools/attachment.js
@@ -24,12 +24,13 @@ export function AttachmentSettings(props) {
export function DownloadAttachment(props) {
var editor = props.editor;
return (_jsx(ToolButton, __assign({}, props, { toggled: false, onClick: function () {
+ var _a;
var attachmentNode = findSelectedNode(editor, "attachment");
var attachment = ((attachmentNode === null || attachmentNode === void 0 ? void 0 : attachmentNode.attrs) || {});
- editor === null || editor === void 0 ? void 0 : editor.chain().focus().downloadAttachment(attachment).run();
+ (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().downloadAttachment(attachment).run();
} })));
}
export function RemoveAttachment(props) {
var editor = props.editor;
- return (_jsx(ToolButton, __assign({}, props, { toggled: false, onClick: function () { return editor === null || editor === void 0 ? void 0 : editor.chain().focus().removeAttachment().run(); } })));
+ return (_jsx(ToolButton, __assign({}, props, { toggled: false, onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().removeAttachment().run(); } })));
}
diff --git a/packages/editor/dist/toolbar/tools/block.js b/packages/editor/dist/toolbar/tools/block.js
index e1919b2c0..51e4f28a0 100644
--- a/packages/editor/dist/toolbar/tools/block.js
+++ b/packages/editor/dist/toolbar/tools/block.js
@@ -32,11 +32,12 @@ import { Icon } from "../components/icon";
import { EmbedPopup } from "../popups/embed-popup";
import { TablePopup } from "../popups/table-popup";
import { useIsMobile, useToolbarLocation } from "../stores/toolbar-store";
-import { ResponsivePresenter, } from "../../components/responsive";
+import { ResponsivePresenter } from "../../components/responsive";
import { showPopup } from "../../components/popup-presenter";
import { ImageUploadPopup } from "../popups/image-upload";
import { Button } from "../../components/button";
export function InsertBlock(props) {
+ var editor = props.editor;
var buttonRef = useRef(null);
var _a = __read(useState(false), 2), isOpen = _a[0], setIsOpen = _a[1];
var toolbarLocation = useToolbarLocation();
@@ -52,7 +53,7 @@ export function InsertBlock(props) {
isMobile ? embedMobile(editor) : embedDesktop(editor),
table(editor),
];
- }, [editor, isMobile]);
+ }, [isMobile]);
return (_jsxs(_Fragment, { children: [_jsx(Button, __assign({ ref: buttonRef, sx: {
p: 1,
m: 0,
@@ -77,7 +78,7 @@ var horizontalRule = function (editor) { return ({
title: "Horizontal rule",
icon: "horizontalRule",
isChecked: editor === null || editor === void 0 ? void 0 : editor.isActive("horizontalRule"),
- onClick: function () { return editor === null || editor === void 0 ? void 0 : editor.chain().focus().setHorizontalRule().run(); },
+ onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().setHorizontalRule().run(); },
}); };
var codeblock = function (editor) { return ({
key: "codeblock",
@@ -85,7 +86,7 @@ var codeblock = function (editor) { return ({
title: "Code block",
icon: "codeblock",
isChecked: editor === null || editor === void 0 ? void 0 : editor.isActive("codeBlock"),
- onClick: function () { return editor === null || editor === void 0 ? void 0 : editor.chain().focus().toggleCodeBlock().run(); },
+ onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().toggleCodeBlock().run(); },
}); };
var blockquote = function (editor) { return ({
key: "blockquote",
@@ -93,7 +94,7 @@ var blockquote = function (editor) { return ({
title: "Quote",
icon: "blockquote",
isChecked: editor === null || editor === void 0 ? void 0 : editor.isActive("blockQuote"),
- onClick: function () { return editor === null || editor === void 0 ? void 0 : editor.chain().focus().toggleBlockquote().run(); },
+ onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().toggleBlockquote().run(); },
}); };
var image = function (editor, isMobile) { return ({
key: "image",
@@ -108,9 +109,7 @@ var image = function (editor, isMobile) { return ({
type: "button",
title: "Upload from disk",
icon: "upload",
- onClick: function () {
- return editor === null || editor === void 0 ? void 0 : editor.chain().focus().openAttachmentPicker("image").run();
- },
+ onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().openAttachmentPicker("image").run(); },
},
isMobile ? uploadImageFromURLMobile(editor) : uploadImageFromURL(editor),
],
@@ -153,9 +152,10 @@ var embedMobile = function (editor) { return ({
component: function (_a) {
var onClick = _a.onClick;
return (_jsx(EmbedPopup, { title: "Insert embed", onClose: function (embed) {
+ var _a;
if (!embed)
return onClick === null || onClick === void 0 ? void 0 : onClick();
- editor === null || editor === void 0 ? void 0 : editor.chain().insertEmbed(embed).run();
+ (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().insertEmbed(embed).run();
onClick === null || onClick === void 0 ? void 0 : onClick();
} }));
},
@@ -174,9 +174,10 @@ var embedDesktop = function (editor) { return ({
showPopup({
theme: editor.storage.theme,
popup: function (hide) { return (_jsx(EmbedPopup, { title: "Insert embed", onClose: function (embed) {
+ var _a;
if (!embed)
return hide();
- editor === null || editor === void 0 ? void 0 : editor.chain().insertEmbed(embed).run();
+ (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().insertEmbed(embed).run();
hide();
} })); },
});
@@ -188,7 +189,7 @@ var attachment = function (editor) { return ({
title: "Attachment",
icon: "attachment",
isChecked: editor === null || editor === void 0 ? void 0 : editor.isActive("attachment"),
- onClick: function () { return editor === null || editor === void 0 ? void 0 : editor.chain().focus().openAttachmentPicker("file").run(); },
+ onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().openAttachmentPicker("file").run(); },
}); };
var tasklist = function (editor) { return ({
key: "tasklist",
@@ -196,7 +197,7 @@ var tasklist = function (editor) { return ({
title: "Task list",
icon: "checkbox",
isChecked: editor === null || editor === void 0 ? void 0 : editor.isActive("taskList"),
- onClick: function () { return editor === null || editor === void 0 ? void 0 : editor.chain().focus().toggleTaskList().run(); },
+ onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().toggleTaskList().run(); },
}); };
var uploadImageFromURLMobile = function (editor) { return ({
key: "upload-from-url",
@@ -212,7 +213,8 @@ var uploadImageFromURLMobile = function (editor) { return ({
component: function (_a) {
var onClick = _a.onClick;
return (_jsx(ImageUploadPopup, { onInsert: function (image) {
- editor === null || editor === void 0 ? void 0 : editor.commands.insertImage(image);
+ var _a;
+ (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().insertImage(image).run();
onClick === null || onClick === void 0 ? void 0 : onClick();
}, onClose: function () {
onClick === null || onClick === void 0 ? void 0 : onClick();
@@ -233,7 +235,8 @@ var uploadImageFromURL = function (editor) { return ({
showPopup({
theme: editor.storage.theme,
popup: function (hide) { return (_jsx(ImageUploadPopup, { onInsert: function (image) {
- editor === null || editor === void 0 ? void 0 : editor.chain().focus().insertImage(image).run();
+ var _a;
+ (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().insertImage(image).run();
hide();
}, onClose: hide })); },
});
diff --git a/packages/editor/dist/toolbar/tools/colors.d.ts b/packages/editor/dist/toolbar/tools/colors.d.ts
index 952dc0117..e29d3e326 100644
--- a/packages/editor/dist/toolbar/tools/colors.d.ts
+++ b/packages/editor/dist/toolbar/tools/colors.d.ts
@@ -1,13 +1,13 @@
-/// <reference types="react" />
-import { Editor } from "@tiptap/core";
+import React from "react";
import { ToolProps } from "../types";
declare type ColorToolProps = ToolProps & {
- onColorChange: (editor: Editor, color?: string) => void;
- getActiveColor: (editor: Editor) => string;
+ onColorChange: (color?: string) => void;
+ getActiveColor: () => string;
title: string;
cacheKey: string;
};
-export declare function ColorTool(props: ColorToolProps): JSX.Element;
+declare function _ColorTool(props: ColorToolProps): JSX.Element;
+export declare const ColorTool: React.MemoExoticComponent<typeof _ColorTool>;
export declare function Highlight(props: ToolProps): JSX.Element;
export declare function TextColor(props: ToolProps): JSX.Element;
export {};
diff --git a/packages/editor/dist/toolbar/tools/colors.js b/packages/editor/dist/toolbar/tools/colors.js
index 06b38800c..d5951834f 100644
--- a/packages/editor/dist/toolbar/tools/colors.js
+++ b/packages/editor/dist/toolbar/tools/colors.js
@@ -37,7 +37,7 @@ var __read = (this && this.__read) || function (o, n) {
return ar;
};
import { jsx as _jsx } from "react/jsx-runtime";
-import { useState } from "react";
+import React, { useState } from "react";
import tinycolor from "tinycolor2";
import { PopupWrapper } from "../../components/popup-presenter";
import { config } from "../../utils/config";
@@ -45,9 +45,10 @@ import { SplitButton } from "../components/split-button";
import { ColorPicker } from "../popups/color-picker";
import { useToolbarLocation } from "../stores/toolbar-store";
import { getToolbarElement } from "../utils/dom";
-export function ColorTool(props) {
+// TODO test rerendering
+function _ColorTool(props) {
var editor = props.editor, onColorChange = props.onColorChange, getActiveColor = props.getActiveColor, title = props.title, cacheKey = props.cacheKey, toolProps = __rest(props, ["editor", "onColorChange", "getActiveColor", "title", "cacheKey"]);
- var activeColor = getActiveColor(editor) || config.get(cacheKey);
+ var activeColor = getActiveColor() || config.get(cacheKey);
var tColor = tinycolor(activeColor);
var isBottom = useToolbarLocation() === "bottom";
var _a = __read(useState(false), 2), isOpen = _a[0], setIsOpen = _a[1];
@@ -57,31 +58,36 @@ export function ColorTool(props) {
":hover": {
bg: activeColor ? tColor.darken(5).toRgbString() : "transparent",
},
- }, onOpen: function () { return setIsOpen(function (s) { return !s; }); }, toggled: isOpen, onClick: function () { return onColorChange(editor, activeColor); } }, { children: _jsx(PopupWrapper, { isOpen: isOpen, id: props.icon, group: "color", position: {
+ }, onOpen: function () { return setIsOpen(function (s) { return !s; }); }, toggled: isOpen, onClick: function () { return onColorChange(activeColor); } }, { children: _jsx(PopupWrapper, { isOpen: isOpen, id: props.icon, group: "color", position: {
isTargetAbsolute: true,
target: getToolbarElement(),
align: isBottom ? "center" : "end",
location: isBottom ? "top" : "below",
yOffset: 10,
}, focusOnRender: false, blocking: false, renderPopup: function (close) { return (_jsx(ColorPicker, { color: activeColor, onClear: function () {
- onColorChange(editor);
+ onColorChange();
config.set(cacheKey, null);
}, onChange: function (color) {
- onColorChange(editor, color);
+ onColorChange(color);
config.set(cacheKey, color);
}, onClose: close, title: title })); } }) })));
}
+export var ColorTool = React.memo(_ColorTool, function () { return true; });
export function Highlight(props) {
- return (_jsx(ColorTool, __assign({}, props, { cacheKey: "highlight", getActiveColor: function (editor) { return editor.getAttributes("highlight").color; }, title: "Background color", onColorChange: function (editor, color) {
+ var editor = props.editor;
+ return (_jsx(ColorTool, __assign({}, props, { cacheKey: "highlight", getActiveColor: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.getAttributes("highlight").color; }, title: "Background color", onColorChange: function (color) {
+ var _a, _b;
return color
- ? editor.chain().focus().toggleHighlight({ color: color }).run()
- : editor.chain().focus().unsetHighlight().run();
+ ? (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().toggleHighlight({ color: color }).run()
+ : (_b = editor.current) === null || _b === void 0 ? void 0 : _b.chain().focus().unsetHighlight().run();
} })));
}
export function TextColor(props) {
- return (_jsx(ColorTool, __assign({}, props, { cacheKey: "textColor", getActiveColor: function (editor) { return editor.getAttributes("textStyle").color; }, title: "Text color", onColorChange: function (editor, color) {
+ var editor = props.editor;
+ return (_jsx(ColorTool, __assign({}, props, { cacheKey: "textColor", getActiveColor: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.getAttributes("textStyle").color; }, title: "Text color", onColorChange: function (color) {
+ var _a, _b;
return color
- ? editor.chain().focus().setColor(color).run()
- : editor.chain().focus().unsetColor().run();
+ ? (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().setColor(color).run()
+ : (_b = editor.current) === null || _b === void 0 ? void 0 : _b.chain().focus().unsetColor().run();
} })));
}
diff --git a/packages/editor/dist/toolbar/tools/embed.js b/packages/editor/dist/toolbar/tools/embed.js
index faa1f3157..83b5990fa 100644
--- a/packages/editor/dist/toolbar/tools/embed.js
+++ b/packages/editor/dist/toolbar/tools/embed.js
@@ -44,25 +44,30 @@ export function EmbedSettings(props) {
export function EmbedAlignLeft(props) {
var editor = props.editor;
return (_jsx(ToolButton, __assign({}, props, { toggled: false, onClick: function () {
- return editor.chain().focus().setEmbedAlignment({ align: "left" }).run();
+ var _a;
+ return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().setEmbedAlignment({ align: "left" }).run();
} })));
}
export function EmbedAlignRight(props) {
var editor = props.editor;
return (_jsx(ToolButton, __assign({}, props, { toggled: false, onClick: function () {
- return editor.chain().focus().setEmbedAlignment({ align: "right" }).run();
+ var _a;
+ return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().setEmbedAlignment({ align: "right" }).run();
} })));
}
export function EmbedAlignCenter(props) {
var editor = props.editor;
return (_jsx(ToolButton, __assign({}, props, { toggled: false, onClick: function () {
- return editor.chain().focus().setEmbedAlignment({ align: "center" }).run();
+ var _a;
+ return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().setEmbedAlignment({ align: "center" }).run();
} })));
}
+// TODO: stop re-rendering
export function EmbedProperties(props) {
var editor = props.editor;
var _a = __read(useState(false), 2), isOpen = _a[0], setIsOpen = _a[1];
var buttonRef = useRef();
+ // TODO: improve perf by deferring this until user opens the popup
var embedNode = useMemo(function () { return findSelectedNode(editor, "embed"); }, []);
var embed = ((embedNode === null || embedNode === void 0 ? void 0 : embedNode.attrs) || {});
return (_jsxs(_Fragment, { children: [_jsx(ToolButton, __assign({ buttonRef: buttonRef, toggled: isOpen }, props, { onClick: function () { return setIsOpen(function (s) { return !s; }); } })), _jsx(ResponsivePresenter, __assign({ isOpen: isOpen, desktop: "menu", mobile: "sheet", onClose: function () { return setIsOpen(false); }, blocking: true, focusOnRender: false, position: {
diff --git a/packages/editor/dist/toolbar/tools/font.js b/packages/editor/dist/toolbar/tools/font.js
index 862745874..a5eea4131 100644
--- a/packages/editor/dist/toolbar/tools/font.js
+++ b/packages/editor/dist/toolbar/tools/font.js
@@ -16,27 +16,27 @@ var __read = (this && this.__read) || function (o, n) {
};
import { jsx as _jsx } from "react/jsx-runtime";
import { Dropdown } from "../components/dropdown";
-import { useCallback } from "react";
+import { useCallback, useMemo } from "react";
import { Counter } from "../components/counter";
-var defaultFontSizes = [
- 8, 12, 14, 16, 18, 20, 24, 28, 32, 36, 42, 48, 60, 72, 100,
-];
+import { useRefValue } from "../../hooks/use-ref-value";
export function FontSize(props) {
var editor = props.editor;
- var _a = editor.getAttributes("textStyle").fontSize, fontSize = _a === void 0 ? "16px" : _a;
- var fontSizeAsNumber = parseInt(fontSize.replace("px", ""));
+ var _fontSize = editor.getAttributes("textStyle").fontSize;
+ var fontSize = _fontSize || "16px";
+ var fontSizeAsNumber = useRefValue(parseInt(fontSize.replace("px", "")));
var decreaseFontSize = useCallback(function () {
- return Math.max(8, fontSizeAsNumber - 1);
- }, [fontSizeAsNumber]);
+ return Math.max(8, fontSizeAsNumber.current - 1);
+ }, []);
+ var increaseFontSize = useCallback(function () {
+ return Math.min(120, fontSizeAsNumber.current + 1);
+ }, []);
return (_jsx(Counter, { title: "font size", onDecrease: function () {
- return editor.chain().focus().setFontSize("".concat(decreaseFontSize(), "px")).run();
+ var _a;
+ return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().setFontSize("".concat(decreaseFontSize(), "px")).run();
}, onIncrease: function () {
- return editor
- .chain()
- .focus()
- .setFontSize("".concat(fontSizeAsNumber + 1, "px"))
- .run();
- }, onReset: function () { return editor.chain().focus().setFontSize("16px").run(); }, value: fontSize }));
+ var _a;
+ (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().setFontSize("".concat(increaseFontSize(), "px")).run();
+ }, onReset: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().setFontSize("16px").run(); }, value: fontSize }));
}
var fontFamilies = {
System: "Open Sans",
@@ -51,7 +51,8 @@ export function FontFamily(props) {
var _b = __read(_a, 2), key = _b[0], value = _b[1];
return editor.isActive("textStyle", { fontFamily: value });
})) === null || _a === void 0 ? void 0 : _a.map(function (a) { return a; })) === null || _b === void 0 ? void 0 : _b.at(0)) || "System";
- return (_jsx(Dropdown, { selectedItem: currentFontFamily, items: toMenuItems(editor, currentFontFamily), menuWidth: 130 }));
+ var items = useMemo(function () { return toMenuItems(editor, currentFontFamily); }, [currentFontFamily]);
+ return (_jsx(Dropdown, { selectedItem: currentFontFamily, items: items, menuWidth: 130 }));
}
function toMenuItems(editor, currentFontFamily) {
var menuItems = [];
@@ -62,7 +63,7 @@ function toMenuItems(editor, currentFontFamily) {
type: "button",
title: key,
isChecked: key === currentFontFamily,
- onClick: function () { return editor.chain().focus().setFontFamily(value).run(); },
+ onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().setFontFamily(value).run(); },
});
};
for (var key in fontFamilies) {
diff --git a/packages/editor/dist/toolbar/tools/headings.js b/packages/editor/dist/toolbar/tools/headings.js
index dae693f29..1a8e2c672 100644
--- a/packages/editor/dist/toolbar/tools/headings.js
+++ b/packages/editor/dist/toolbar/tools/headings.js
@@ -26,6 +26,7 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
import { jsx as _jsx } from "react/jsx-runtime";
import { Dropdown } from "../components/dropdown";
import { useToolbarLocation } from "../stores/toolbar-store";
+import { useMemo } from "react";
var defaultLevels = [1, 2, 3, 4, 5, 6];
export function Headings(props) {
var editor = props.editor;
@@ -33,7 +34,8 @@ export function Headings(props) {
var currentHeadingLevel = defaultLevels.find(function (level) {
return editor.isActive("heading", { level: level });
});
- return (_jsx(Dropdown, { selectedItem: currentHeadingLevel ? "Heading ".concat(currentHeadingLevel) : "Paragraph", items: toMenuItems(editor, toolbarLocation, currentHeadingLevel), menuWidth: 130 }));
+ var items = useMemo(function () { return toMenuItems(editor, toolbarLocation, currentHeadingLevel); }, [currentHeadingLevel]);
+ return (_jsx(Dropdown, { selectedItem: currentHeadingLevel ? "Heading ".concat(currentHeadingLevel) : "Paragraph", items: items, menuWidth: 130 }));
}
function toMenuItems(editor, toolbarLocation, currentHeadingLevel) {
var menuItems = defaultLevels.map(function (level) { return ({
@@ -42,11 +44,8 @@ function toMenuItems(editor, toolbarLocation, currentHeadingLevel) {
title: toolbarLocation === "bottom" ? "H".concat(level) : "Heading ".concat(level),
isChecked: level === currentHeadingLevel,
onClick: function () {
- return editor
- .chain()
- .focus()
- .setHeading({ level: level })
- .run();
+ var _a;
+ return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().updateAttributes("textStyle", { fontSize: null, fontStyle: null }).setHeading({ level: level }).run();
},
}); });
var paragraph = {
@@ -54,7 +53,7 @@ function toMenuItems(editor, toolbarLocation, currentHeadingLevel) {
type: "button",
title: "Paragraph",
isChecked: !currentHeadingLevel,
- onClick: function () { return editor.chain().focus().setParagraph().run(); },
+ onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().setParagraph().run(); },
};
return __spreadArray([paragraph], __read(menuItems), false);
}
diff --git a/packages/editor/dist/toolbar/tools/image.js b/packages/editor/dist/toolbar/tools/image.js
index 100437359..89fe5de34 100644
--- a/packages/editor/dist/toolbar/tools/image.js
+++ b/packages/editor/dist/toolbar/tools/image.js
@@ -53,25 +53,29 @@ export function ImageSettings(props) {
export function ImageAlignLeft(props) {
var editor = props.editor;
return (_jsx(ToolButton, __assign({}, props, { toggled: false, onClick: function () {
- return editor.chain().focus().setImageAlignment({ align: "left" }).run();
+ var _a;
+ return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().setImageAlignment({ align: "left" }).run();
} })));
}
export function ImageAlignRight(props) {
var editor = props.editor;
return (_jsx(ToolButton, __assign({}, props, { toggled: false, onClick: function () {
- return editor.chain().focus().setImageAlignment({ align: "right" }).run();
+ var _a;
+ return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().setImageAlignment({ align: "right" }).run();
} })));
}
export function ImageAlignCenter(props) {
var editor = props.editor;
return (_jsx(ToolButton, __assign({}, props, { toggled: false, onClick: function () {
- return editor.chain().focus().setImageAlignment({ align: "center" }).run();
+ var _a;
+ return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().setImageAlignment({ align: "center" }).run();
} })));
}
export function ImageProperties(props) {
var editor = props.editor;
var _a = __read(useState(false), 2), isOpen = _a[0], setIsOpen = _a[1];
var buttonRef = useRef();
+ // TODO: defer until user opens the popup
var image = useMemo(function () { return findSelectedNode(editor, "image"); }, []);
var _b = ((image === null || image === void 0 ? void 0 : image.attrs) ||
{}), float = _b.float, align = _b.align, width = _b.width, height = _b.height;
diff --git a/packages/editor/dist/toolbar/tools/index.d.ts b/packages/editor/dist/toolbar/tools/index.d.ts
index 699577808..63eab4098 100644
--- a/packages/editor/dist/toolbar/tools/index.d.ts
+++ b/packages/editor/dist/toolbar/tools/index.d.ts
@@ -1,6 +1,6 @@
import React from "react";
import { ToolProps } from "../types";
-import { Bold, Italic, Underline, Strikethrough, Code, Subscript, Superscript, ClearFormatting, Link } from "./inline";
+import { Bold, Italic, Underline, Strikethrough, Code, Subscript, Superscript, ClearFormatting, Link, LinkRemove, CodeRemove } from "./inline";
import { InsertBlock } from "./block";
import { FontSize, FontFamily } from "./font";
import { AlignCenter, AlignLeft, AlignRight, AlignJustify } from "./alignment";
@@ -19,10 +19,12 @@ declare const tools: {
underline: typeof Underline;
strikethrough: typeof Strikethrough;
code: typeof Code;
+ codeRemove: typeof CodeRemove;
subscript: typeof Subscript;
superscript: typeof Superscript;
clearformatting: typeof ClearFormatting;
link: typeof Link;
+ linkRemove: typeof LinkRemove;
insertBlock: typeof InsertBlock;
numberedList: typeof NumberedList;
bulletList: typeof BulletList;
diff --git a/packages/editor/dist/toolbar/tools/index.js b/packages/editor/dist/toolbar/tools/index.js
index 1e6ad1ef1..5d8af3eee 100644
--- a/packages/editor/dist/toolbar/tools/index.js
+++ b/packages/editor/dist/toolbar/tools/index.js
@@ -1,4 +1,4 @@
-import { Bold, Italic, Underline, Strikethrough, Code, Subscript, Superscript, ClearFormatting, Link, } from "./inline";
+import { Bold, Italic, Underline, Strikethrough, Code, Subscript, Superscript, ClearFormatting, Link, LinkRemove, CodeRemove, } from "./inline";
import { InsertBlock } from "./block";
import { FontSize, FontFamily } from "./font";
import { AlignCenter, AlignLeft, AlignRight, AlignJustify } from "./alignment";
@@ -16,10 +16,12 @@ var tools = {
underline: Underline,
strikethrough: Strikethrough,
code: Code,
+ codeRemove: CodeRemove,
subscript: Subscript,
superscript: Superscript,
clearformatting: ClearFormatting,
link: Link,
+ linkRemove: LinkRemove,
insertBlock: InsertBlock,
numberedList: NumberedList,
bulletList: BulletList,
diff --git a/packages/editor/dist/toolbar/tools/inline.d.ts b/packages/editor/dist/toolbar/tools/inline.d.ts
index 87ad73d07..71a3fec4e 100644
--- a/packages/editor/dist/toolbar/tools/inline.d.ts
+++ b/packages/editor/dist/toolbar/tools/inline.d.ts
@@ -8,4 +8,6 @@ export declare function Bold(props: ToolProps): JSX.Element;
export declare function Subscript(props: ToolProps): JSX.Element;
export declare function Superscript(props: ToolProps): JSX.Element;
export declare function ClearFormatting(props: ToolProps): JSX.Element;
+export declare function LinkRemove(props: ToolProps): JSX.Element | null;
+export declare function CodeRemove(props: ToolProps): JSX.Element | null;
export declare function Link(props: ToolProps): JSX.Element;
diff --git a/packages/editor/dist/toolbar/tools/inline.js b/packages/editor/dist/toolbar/tools/inline.js
index 46944240b..f6b32e755 100644
--- a/packages/editor/dist/toolbar/tools/inline.js
+++ b/packages/editor/dist/toolbar/tools/inline.js
@@ -31,81 +31,98 @@ import { useCallback, useRef, useState } from "react";
import { ResponsivePresenter } from "../../components/responsive";
import { Popup } from "../components/popup";
import { LinkPopup } from "../popups/link-popup";
-function InlineTool(props) {
- var editor = props.editor, title = props.title, icon = props.icon, isToggled = props.isToggled, onClick = props.onClick;
- return (_jsx(ToolButton, { title: title, id: icon, icon: icon, onClick: function () { return onClick(editor); }, toggled: isToggled(editor) }));
-}
+import { useToolbarLocation } from "../stores/toolbar-store";
export function Italic(props) {
- return (_jsx(InlineTool, __assign({}, props, { isToggled: function (editor) { return editor.isActive("italic"); }, onClick: function (editor) { return editor.chain().focus().toggleItalic().run(); } })));
+ var editor = props.editor;
+ return (_jsx(ToolButton, __assign({}, props, { toggled: editor.isActive("italic"), onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().toggleItalic().run(); } })));
}
export function Strikethrough(props) {
- return (_jsx(InlineTool, __assign({}, props, { isToggled: function (editor) { return editor.isActive("strikethrough"); }, onClick: function (editor) { return editor.chain().focus().toggleStrike().run(); } })));
+ var editor = props.editor;
+ return (_jsx(ToolButton, __assign({}, props, { toggled: editor.isActive("strike"), onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().toggleStrike().run(); } })));
}
export function Underline(props) {
- return (_jsx(InlineTool, __assign({}, props, { isToggled: function (editor) { return editor.isActive("underline"); }, onClick: function (editor) { return editor.chain().focus().toggleUnderline().run(); } })));
+ var editor = props.editor;
+ return (_jsx(ToolButton, __assign({}, props, { toggled: editor.isActive("underline"), onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().toggleUnderline().run(); } })));
}
export function Code(props) {
- return (_jsx(InlineTool, __assign({}, props, { isToggled: function (editor) { return editor.isActive("code"); }, onClick: function (editor) { return editor.chain().focus().toggleCode().run(); } })));
+ var editor = props.editor;
+ return (_jsx(ToolButton, __assign({}, props, { toggled: editor.isActive("code"), onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().toggleCode().run(); } })));
}
export function Bold(props) {
- return (_jsx(InlineTool, __assign({}, props, { isToggled: function (editor) { return editor.isActive("bold"); }, onClick: function (editor) { return editor.chain().focus().toggleBold().run(); } })));
+ var editor = props.editor;
+ return (_jsx(ToolButton, __assign({}, props, { toggled: editor.isActive("bold"), onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().toggleBold().run(); } })));
}
export function Subscript(props) {
- return (_jsx(InlineTool, __assign({}, props, { isToggled: function (editor) { return editor.isActive("subscript"); }, onClick: function (editor) { return editor.chain().focus().toggleSubscript().run(); } })));
+ var editor = props.editor;
+ return (_jsx(ToolButton, __assign({}, props, { toggled: editor.isActive("subscript"), onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().toggleSubscript().run(); } })));
}
export function Superscript(props) {
- return (_jsx(InlineTool, __assign({}, props, { isToggled: function (editor) { return editor.isActive("superscript"); }, onClick: function (editor) { return editor.chain().focus().toggleSuperscript().run(); } })));
+ var editor = props.editor;
+ return (_jsx(ToolButton, __assign({}, props, { toggled: editor.isActive("superscript"), onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().toggleSuperscript().run(); } })));
}
export function ClearFormatting(props) {
- return (_jsx(InlineTool, __assign({}, props, { isToggled: function () { return false; }, onClick: function (editor) {
- return editor.chain().focus().clearNodes().unsetAllMarks().run();
+ var editor = props.editor;
+ return (_jsx(ToolButton, __assign({}, props, { toggled: false, onClick: function () {
+ var _a;
+ return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().clearNodes().unsetAllMarks().unsetMark("link").run();
} })));
}
+export function LinkRemove(props) {
+ var editor = props.editor;
+ var isBottom = useToolbarLocation() === "bottom";
+ if (!editor.isActive("link") || !isBottom)
+ return null;
+ return (_jsx(ToolButton, __assign({}, props, { toggled: false, onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().unsetMark("link").run(); } })));
+}
+export function CodeRemove(props) {
+ var editor = props.editor;
+ var isBottom = useToolbarLocation() === "bottom";
+ if (!editor.isActive("code") || !isBottom)
+ return null;
+ return (_jsx(ToolButton, __assign({}, props, { toggled: false, onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().unsetMark("code").run(); } })));
+}
export function Link(props) {
var editor = props.editor, title = props.title, icon = props.icon;
var buttonRef = useRef(null);
- var targetRef = useRef();
var _a = __read(useState(false), 2), isOpen = _a[0], setIsOpen = _a[1];
var _b = __read(useState(), 2), href = _b[0], setHref = _b[1];
var _c = __read(useState(), 2), text = _c[0], setText = _c[1];
var currentUrl = editor.getAttributes("link").href;
var isEditing = !!currentUrl;
var onDone = useCallback(function (href, text) {
+ var _a;
if (!href)
return;
- var commandChain = editor
- .chain()
- .focus()
+ var commandChain = (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus();
+ if (!commandChain)
+ return;
+ commandChain
.extendMarkRange("link")
- .setLink({ href: href, target: "_blank" });
- if (text)
- commandChain = commandChain.insertContent(text).focus();
- commandChain.run();
+ .toggleLink({ href: href, target: "_blank" })
+ .insertContent(text || href)
+ .focus()
+ .unsetMark("link")
+ .insertContent(" ")
+ .run();
setIsOpen(false);
}, []);
- return (_jsxs(_Fragment, { children: [_jsx(ToolButton, { id: icon, buttonRef: buttonRef, title: title, icon: icon, onClick: function () {
+ return (_jsxs(_Fragment, { children: [_jsx(ToolButton, { id: icon, buttonRef: buttonRef, title: title, icon: isEditing ? "linkEdit" : icon, onClick: function () {
if (isEditing)
setHref(currentUrl);
var _a = editor.state.selection, from = _a.from, to = _a.to, $from = _a.$from;
var selectedNode = $from.node();
- var pos = selectedNode.isTextblock ? $from.before() : $from.pos;
- var domNode = editor.view.nodeDOM(pos);
- targetRef.current = domNode;
var selectedText = isEditing
? selectedNode.textContent
: editor.state.doc.textBetween(from, to);
setText(selectedText);
setIsOpen(true);
}, toggled: isOpen || !!isEditing }), _jsx(ResponsivePresenter, __assign({ mobile: "sheet", desktop: "menu", position: {
- target: targetRef.current || buttonRef.current || undefined,
+ target: buttonRef.current || undefined,
isTargetAbsolute: true,
location: "below",
align: "center",
yOffset: 5,
- }, title: isEditing ? "Edit link" : "Insert link", isOpen: isOpen, items: [], onClose: function () {
- editor.commands.focus();
- setIsOpen(false);
- }, focusOnRender: false }, { children: _jsx(Popup, __assign({ title: isEditing ? "Edit link" : "Insert link", onClose: function () { return setIsOpen(false); } }, { children: _jsx(LinkPopup, { href: href, text: text, isEditing: isEditing, onDone: function (_a) {
+ }, title: isEditing ? "Edit link" : "Insert link", isOpen: isOpen, items: [], onClose: function () { return setIsOpen(false); }, focusOnRender: false }, { children: _jsx(Popup, __assign({ title: isEditing ? "Edit link" : "Insert link", onClose: function () { return setIsOpen(false); } }, { children: _jsx(LinkPopup, { href: href, text: text, isEditing: isEditing, onDone: function (_a) {
var href = _a.href, text = _a.text;
onDone(href, text);
} }) })) }))] }));
diff --git a/packages/editor/dist/toolbar/tools/lists.js b/packages/editor/dist/toolbar/tools/lists.js
index db8491fae..b57a97006 100644
--- a/packages/editor/dist/toolbar/tools/lists.js
+++ b/packages/editor/dist/toolbar/tools/lists.js
@@ -38,43 +38,52 @@ var __read = (this && this.__read) || function (o, n) {
};
import { jsx as _jsx } from "react/jsx-runtime";
import { Box, Button, Flex } from "rebass";
-import { useRef, useState } from "react";
+import { useCallback, useRef, useState } from "react";
import { SplitButton } from "../components/split-button";
import { useToolbarLocation } from "../stores/toolbar-store";
import { getToolbarElement } from "../utils/dom";
import { PopupWrapper } from "../../components/popup-presenter";
-function ListTool(props) {
- var editor = props.editor, options = props.options, toolProps = __rest(props, ["editor", "options"]);
- var isActive = editor.isActive(options.type);
+import React from "react";
+function _ListTool(props) {
+ var editor = props.editor, onClick = props.onClick, isActive = props.isActive, subTypes = props.subTypes, type = props.type, toolProps = __rest(props, ["editor", "onClick", "isActive", "subTypes", "type"]);
var toolbarLocation = useToolbarLocation();
var isBottom = toolbarLocation === "bottom";
var _a = __read(useState(false), 2), isOpen = _a[0], setIsOpen = _a[1];
var buttonRef = useRef();
- return (_jsx(SplitButton, __assign({}, toolProps, { buttonRef: buttonRef, onClick: function () { return options.onClick(editor); }, toggled: isActive || isOpen, sx: { mr: 0 }, onOpen: function () { return setIsOpen(function (s) { return !s; }); } }, { children: _jsx(PopupWrapper, { isOpen: isOpen, group: "lists", id: toolProps.title, blocking: false, focusOnRender: false, position: {
+ return (_jsx(SplitButton, __assign({}, toolProps, { buttonRef: buttonRef, onClick: onClick, toggled: isActive || isOpen, sx: { mr: 0 }, onOpen: function () { return setIsOpen(function (s) { return !s; }); } }, { children: _jsx(PopupWrapper, { isOpen: isOpen, group: "lists", id: toolProps.title, blocking: false, focusOnRender: false, position: {
isTargetAbsolute: true,
target: isBottom ? getToolbarElement() : buttonRef.current || "mouse",
align: "center",
location: isBottom ? "top" : "below",
yOffset: isBottom ? 10 : 5,
- }, renderPopup: function () { return (_jsx(Box, __assign({ sx: { display: "grid", gridTemplateColumns: "1fr 1fr 1fr", p: 1 } }, { children: options.subTypes.map(function (item) { return (_jsx(Button, __assign({ variant: "menuitem", sx: { width: 80 }, onClick: function () {
- var chain = editor.chain().focus();
+ }, onClosed: function () { return setIsOpen(false); }, renderPopup: function () { return (_jsx(Box, __assign({ sx: {
+ bg: "background",
+ display: "grid",
+ gridTemplateColumns: "1fr 1fr 1fr",
+ p: 1,
+ } }, { children: subTypes.map(function (item) { return (_jsx(Button, __assign({ variant: "menuitem", sx: { width: 80 }, onClick: function () {
+ var _a;
+ var chain = (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus();
+ if (!chain)
+ return;
if (!isActive) {
- if (options.type === "bulletList")
+ if (type === "bulletList")
chain = chain.toggleBulletList();
else
chain = chain.toggleOrderedList();
}
return chain
- .updateAttributes(options.type, { listType: item.type })
+ .updateAttributes(type, { listType: item.type })
.run();
} }, { children: _jsx(ListThumbnail, { listStyleType: item.type }) }), item.title)); }) }))); } }) })));
}
+var ListTool = React.memo(_ListTool, function (prev, next) {
+ return prev.isActive === next.isActive;
+});
export function NumberedList(props) {
- var options = {
- type: "orderedList",
- icon: "numberedList",
- onClick: function (editor) { return editor.chain().focus().toggleOrderedList().run(); },
- subTypes: [
+ var editor = props.editor;
+ var onClick = useCallback(function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().toggleOrderedList().run(); }, []);
+ return (_jsx(ListTool, __assign({}, props, { type: "orderedList", isActive: editor.isActive("orderedList"), onClick: onClick, subTypes: [
{ type: "decimal", title: "Decimal", items: ["1", "2", "3"] },
{ type: "upper-alpha", title: "Upper alpha", items: ["A", "B", "C"] },
{ type: "lower-alpha", title: "Lower alpha", items: ["a", "b", "c"] },
@@ -89,22 +98,16 @@ export function NumberedList(props) {
items: ["i", "ii", "iii"],
},
{ type: "lower-greek", title: "Lower Greek", items: ["α", "β", "γ"] },
- ],
- };
- return _jsx(ListTool, __assign({}, props, { options: options }));
+ ] })));
}
export function BulletList(props) {
- var options = {
- type: "bulletList",
- icon: "bulletList",
- onClick: function (editor) { return editor.chain().focus().toggleOrderedList().run(); },
- subTypes: [
+ var editor = props.editor;
+ var onClick = useCallback(function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().toggleOrderedList().run(); }, []);
+ return (_jsx(ListTool, __assign({}, props, { type: "bulletList", onClick: onClick, isActive: editor.isActive("bulletList"), subTypes: [
{ type: "disc", title: "Decimal", items: ["1", "2", "3"] },
{ type: "circle", title: "Upper alpha", items: ["A", "B", "C"] },
{ type: "square", title: "Lower alpha", items: ["a", "b", "c"] },
- ],
- };
- return _jsx(ListTool, __assign({}, props, { options: options }));
+ ] })));
}
function ListThumbnail(props) {
var listStyleType = props.listStyleType;
diff --git a/packages/editor/dist/toolbar/tools/table.js b/packages/editor/dist/toolbar/tools/table.js
index 56cc0014a..fd3dedd0d 100644
--- a/packages/editor/dist/toolbar/tools/table.js
+++ b/packages/editor/dist/toolbar/tools/table.js
@@ -128,20 +128,18 @@ export function CellProperties(props) {
] })) }));
}
export function CellBackgroundColor(props) {
- return (_jsx(ColorTool, __assign({}, props, { cacheKey: "cellBackgroundColor", getActiveColor: function (editor) {
- return editor.getAttributes("tableCell").backgroundColor;
- }, title: "Cell background color", onColorChange: function (editor, color) {
- return editor.chain().setCellAttribute("backgroundColor", color).run();
- } })));
+ var editor = props.editor;
+ return (_jsx(ColorTool, __assign({}, props, { cacheKey: "cellBackgroundColor", getActiveColor: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.getAttributes("tableCell").backgroundColor; }, title: "Cell background color", onColorChange: function (color) { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().setCellAttribute("backgroundColor", color).run(); } })));
}
export function CellTextColor(props) {
- return (_jsx(ColorTool, __assign({}, props, { cacheKey: "cellTextColor", getActiveColor: function (editor) { return editor.getAttributes("tableCell").color; }, title: "Cell text color", onColorChange: function (editor, color) {
- return editor.chain().focus().setCellAttribute("color", color).run();
- } })));
+ var editor = props.editor;
+ return (_jsx(ColorTool, __assign({}, props, { cacheKey: "cellTextColor", getActiveColor: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.getAttributes("tableCell").color; }, title: "Cell text color", onColorChange: function (color) { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().setCellAttribute("color", color).run(); } })));
}
export function CellBorderColor(props) {
- return (_jsx(ColorTool, __assign({}, props, { cacheKey: "cellBorderColor", getActiveColor: function (editor) { return editor.getAttributes("tableCell").borderColor; }, title: "Cell border color", onColorChange: function (editor, color) {
- return editor.chain().focus().setCellAttribute("borderColor", color).run();
+ var editor = props.editor;
+ return (_jsx(ColorTool, __assign({}, props, { cacheKey: "cellBorderColor", getActiveColor: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.getAttributes("tableCell").borderColor; }, title: "Cell border color", onColorChange: function (color) {
+ var _a;
+ return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().setCellAttribute("borderColor", color).run();
} })));
}
export function CellBorderWidth(props) {
@@ -160,19 +158,19 @@ export function CellBorderWidth(props) {
return editor.commands.setCellAttribute("borderWidth", increaseBorderWidth());
}, onReset: function () { return editor.commands.setCellAttribute("borderWidth", 1); }, value: borderWidth + "px" })] })));
}
-var insertColumnLeft = function (editor) { return (__assign(__assign({}, getToolDefinition("insertColumnLeft")), { key: "addColumnLeft", type: "button", onClick: function () { return editor.chain().focus().addColumnBefore().run(); } })); };
-var insertColumnRight = function (editor) { return (__assign(__assign({}, getToolDefinition("insertColumnRight")), { key: "addColumnRight", type: "button", title: "Add column right", onClick: function () { return editor.chain().focus().addColumnAfter().run(); }, icon: "insertColumnRight" })); };
+var insertColumnLeft = function (editor) { return (__assign(__assign({}, getToolDefinition("insertColumnLeft")), { key: "addColumnLeft", type: "button", onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().addColumnBefore().run(); } })); };
+var insertColumnRight = function (editor) { return (__assign(__assign({}, getToolDefinition("insertColumnRight")), { key: "addColumnRight", type: "button", title: "Add column right", onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().addColumnAfter().run(); }, icon: "insertColumnRight" })); };
var moveColumnLeft = function (editor) { return (__assign(__assign({}, getToolDefinition("moveColumnLeft")), { key: "moveColumnLeft", type: "button", onClick: function () { return moveColumnLeftAction(editor); } })); };
var moveColumnRight = function (editor) { return (__assign(__assign({}, getToolDefinition("moveColumnRight")), { key: "moveColumnRight", type: "button", onClick: function () { return moveColumnRightAction(editor); } })); };
-var deleteColumn = function (editor) { return (__assign(__assign({}, getToolDefinition("deleteColumn")), { key: "deleteColumn", type: "button", onClick: function () { return editor.chain().focus().deleteColumn().run(); } })); };
-var splitCells = function (editor) { return (__assign(__assign({}, getToolDefinition("splitCells")), { key: "splitCells", type: "button", onClick: function () { return editor.chain().focus().splitCell().run(); } })); };
-var mergeCells = function (editor) { return (__assign(__assign({}, getToolDefinition("mergeCells")), { key: "mergeCells", type: "button", onClick: function () { return editor.chain().focus().mergeCells().run(); } })); };
-var insertRowAbove = function (editor) { return (__assign(__assign({}, getToolDefinition("insertRowAbove")), { key: "insertRowAbove", type: "button", onClick: function () { return editor.chain().focus().addRowBefore().run(); } })); };
-var insertRowBelow = function (editor) { return (__assign(__assign({}, getToolDefinition("insertRowBelow")), { key: "insertRowBelow", type: "button", onClick: function () { return editor.chain().focus().addRowAfter().run(); } })); };
+var deleteColumn = function (editor) { return (__assign(__assign({}, getToolDefinition("deleteColumn")), { key: "deleteColumn", type: "button", onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().deleteColumn().run(); } })); };
+var splitCells = function (editor) { return (__assign(__assign({}, getToolDefinition("splitCells")), { key: "splitCells", type: "button", onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().splitCell().run(); } })); };
+var mergeCells = function (editor) { return (__assign(__assign({}, getToolDefinition("mergeCells")), { key: "mergeCells", type: "button", onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().mergeCells().run(); } })); };
+var insertRowAbove = function (editor) { return (__assign(__assign({}, getToolDefinition("insertRowAbove")), { key: "insertRowAbove", type: "button", onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().addRowBefore().run(); } })); };
+var insertRowBelow = function (editor) { return (__assign(__assign({}, getToolDefinition("insertRowBelow")), { key: "insertRowBelow", type: "button", onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().addRowAfter().run(); } })); };
var moveRowUp = function (editor) { return (__assign(__assign({}, getToolDefinition("moveRowUp")), { key: "moveRowUp", type: "button", onClick: function () { return moveRowUpAction(editor); } })); };
var moveRowDown = function (editor) { return (__assign(__assign({}, getToolDefinition("moveRowDown")), { key: "moveRowDown", type: "button", onClick: function () { return moveRowDownAction(editor); } })); };
-var deleteRow = function (editor) { return (__assign(__assign({}, getToolDefinition("deleteRow")), { key: "deleteRow", type: "button", onClick: function () { return editor.chain().focus().deleteRow().run(); } })); };
-var deleteTable = function (editor) { return (__assign(__assign({}, getToolDefinition("deleteTable")), { key: "deleteTable", type: "button", onClick: function () { return editor.chain().focus().deleteTable().run(); } })); };
+var deleteRow = function (editor) { return (__assign(__assign({}, getToolDefinition("deleteRow")), { key: "deleteRow", type: "button", onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().deleteRow().run(); } })); };
+var deleteTable = function (editor) { return (__assign(__assign({}, getToolDefinition("deleteTable")), { key: "deleteTable", type: "button", onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().deleteTable().run(); } })); };
var cellProperties = function (editor) { return (__assign(__assign({}, getToolDefinition("cellProperties")), { key: "cellProperties", type: "button", onClick: function () {
showPopup({
theme: editor.storage.theme,
diff --git a/packages/editor/dist/toolbar/tools/textdirection.js b/packages/editor/dist/toolbar/tools/textdirection.js
index fc9247232..1b773f019 100644
--- a/packages/editor/dist/toolbar/tools/textdirection.js
+++ b/packages/editor/dist/toolbar/tools/textdirection.js
@@ -24,7 +24,7 @@ import { jsx as _jsx } from "react/jsx-runtime";
import { ToolButton } from "../components/tool-button";
function TextDirectionTool(props) {
var editor = props.editor, direction = props.direction, toolProps = __rest(props, ["editor", "direction"]);
- return (_jsx(ToolButton, __assign({}, toolProps, { onClick: function () { return editor.chain().focus().setTextDirection(direction).run(); }, toggled: editor.isActive({ textDirection: direction }) })));
+ return (_jsx(ToolButton, __assign({}, toolProps, { onClick: function () { var _a; return (_a = editor.current) === null || _a === void 0 ? void 0 : _a.chain().focus().setTextDirection(direction).run(); }, toggled: editor.isActive({ textDirection: direction }) })));
}
export function RightToLeft(props) {
return _jsx(TextDirectionTool, __assign({ direction: "rtl" }, props));
diff --git a/packages/editor/dist/toolbar/types.d.ts b/packages/editor/dist/toolbar/types.d.ts
index f1658e4bc..b15f7fc8c 100644
--- a/packages/editor/dist/toolbar/types.d.ts
+++ b/packages/editor/dist/toolbar/types.d.ts
@@ -1,4 +1,4 @@
-import { Editor } from "@tiptap/core";
+import { Editor } from "../types";
import { IconNames } from "./icons";
import { ToolId } from "./tools";
export declare type ToolButtonVariant = "small" | "normal";
diff --git a/packages/editor/dist/types.d.ts b/packages/editor/dist/types.d.ts
new file mode 100644
index 000000000..9aa191120
--- /dev/null
+++ b/packages/editor/dist/types.d.ts
@@ -0,0 +1,9 @@
+import { Editor as TiptapEditor } from "@tiptap/core";
+export interface Editor extends TiptapEditor {
+ /**
+ * Use this to get the latest instance of the editor.
+ * This is required to reduce unnecessary rerenders of
+ * toolbar elements.
+ */
+ current?: TiptapEditor;
+}
diff --git a/packages/editor/dist/types.js b/packages/editor/dist/types.js
new file mode 100644
index 000000000..cb0ff5c3b
--- /dev/null
+++ b/packages/editor/dist/types.js
@@ -0,0 +1 @@
+export {};
diff --git a/packages/editor/src/components/menu/menu-button.tsx b/packages/editor/src/components/menu/menu-button.tsx
index 2c46b31cb..d78421c39 100644
--- a/packages/editor/src/components/menu/menu-button.tsx
+++ b/packages/editor/src/components/menu/menu-button.tsx
@@ -1,8 +1,9 @@
import { useRef } from "react";
-import { Flex, Text, Button } from "rebass";
+import { Flex, Text } from "rebass";
import { Icon } from "../../toolbar/components/icon";
import { Icons } from "../../toolbar/icons";
import { useToolbarLocation } from "../../toolbar/stores/toolbar-store";
+import { Button } from "../button";
import { MenuButton } from "./types";
type MenuButtonProps = {
@@ -57,7 +58,7 @@ export function MenuButton(props: MenuButtonProps) {
sx={{ mr: 2 }}
/>
)}
- <Text as="span" variant={"body"}>
+ <Text as="span" variant={"body"} sx={{ fontSize: "inherit" }}>
{title}
</Text>
</Flex>
diff --git a/packages/editor/src/global.d.ts b/packages/editor/src/global.d.ts
deleted file mode 100644
index 04b2a5b56..000000000
--- a/packages/editor/src/global.d.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { Editor } from "@tiptap/react";
-
-declare global {
- /**
- * Current tiptap instance registered with global for use in React Native
- */
- var editor: Editor | null;
-}
diff --git a/packages/editor/src/hooks/use-ref-value.ts b/packages/editor/src/hooks/use-ref-value.ts
new file mode 100644
index 000000000..d7f4ddff8
--- /dev/null
+++ b/packages/editor/src/hooks/use-ref-value.ts
@@ -0,0 +1,10 @@
+import { useEffect, useRef } from "react";
+
+export function useRefValue<T>(value: T) {
+ const refValue = useRef(value);
+
+ useEffect(() => {
+ refValue.current = value;
+ }, [value]);
+ return refValue;
+}
diff --git a/packages/editor/src/index.ts b/packages/editor/src/index.ts
index 2b6fe9ebf..b38616b44 100644
--- a/packages/editor/src/index.ts
+++ b/packages/editor/src/index.ts
@@ -4,7 +4,7 @@ import Placeholder from "@tiptap/extension-placeholder";
import Underline from "@tiptap/extension-underline";
import { EditorOptions, useEditor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
-import { useEffect, useMemo } from "react";
+import { useEffect, useMemo, useRef } from "react";
import { EditorView } from "prosemirror-view";
import Toolbar from "./toolbar";
import TextAlign from "@tiptap/extension-text-align";
@@ -41,6 +41,11 @@ import {
import { OutlineList } from "./extensions/outline-list";
import { OutlineListItem } from "./extensions/outline-list-item";
import { Table } from "./extensions/table";
+import { Editor } from "./types";
+
+// export class Editor extends TiptapEditor {
+// get instance(): TiptapEditor {}
+// }
EditorView.prototype.updateState = function updateState(state) {
if (!(this as any).docView) return; // This prevents the matchesNode error on hot reloads
@@ -140,12 +145,18 @@ const useTiptap = (
...restOptions,
},
deps
- );
+ ) as Editor | null;
+
+ const editorRef = useRef(editor);
+ useEffect(() => {
+ editorRef.current = editor;
+
+ if (editor && !editor.current)
+ Object.defineProperty(editor, "current", {
+ get: () => editorRef.current,
+ });
+ }, [editor]);
- /**
- * Add editor to global for use in React Native.
- */
- global.editor = editor;
return editor;
};
diff --git a/packages/editor/src/toolbar/components/counter.tsx b/packages/editor/src/toolbar/components/counter.tsx
index b747efec2..5aa69b51f 100644
--- a/packages/editor/src/toolbar/components/counter.tsx
+++ b/packages/editor/src/toolbar/components/counter.tsx
@@ -1,3 +1,4 @@
+import React from "react";
import { Flex, Text } from "rebass";
import { Button } from "../../components/button";
import { ToolButton } from "./tool-button";
@@ -9,7 +10,7 @@ export type CounterProps = {
onReset: () => void;
value: string;
};
-export function Counter(props: CounterProps) {
+function _Counter(props: CounterProps) {
const { title, onDecrease, onIncrease, onReset, value } = props;
return (
@@ -55,3 +56,7 @@ export function Counter(props: CounterProps) {
</Flex>
);
}
+
+export const Counter = React.memo(_Counter, (prev, next) => {
+ return prev.value === next.value;
+});
diff --git a/packages/editor/src/toolbar/components/split-button.tsx b/packages/editor/src/toolbar/components/split-button.tsx
index e7e13311b..54a6e76f5 100644
--- a/packages/editor/src/toolbar/components/split-button.tsx
+++ b/packages/editor/src/toolbar/components/split-button.tsx
@@ -10,9 +10,10 @@ import {
} from "../../components/popup-presenter";
import { PositionOptions } from "../../utils/position";
import { Button } from "../../components/button";
+import React from "react";
export type SplitButtonProps = ToolButtonProps & { onOpen: () => void };
-export function SplitButton(props: PropsWithChildren<SplitButtonProps>) {
+function _SplitButton(props: PropsWithChildren<SplitButtonProps>) {
const { children, toggled, onOpen, ...toolButtonProps } = props;
const ref = useRef<HTMLDivElement>(null);
@@ -54,3 +55,6 @@ export function SplitButton(props: PropsWithChildren<SplitButtonProps>) {
</>
);
}
+export const SplitButton = React.memo(_SplitButton, (prev, next) => {
+ return prev.toggled === next.toggled;
+});
diff --git a/packages/editor/src/toolbar/components/tool-button.tsx b/packages/editor/src/toolbar/components/tool-button.tsx
index 3e1b23ff6..dd5a9d053 100644
--- a/packages/editor/src/toolbar/components/tool-button.tsx
+++ b/packages/editor/src/toolbar/components/tool-button.tsx
@@ -16,46 +16,52 @@ export type ToolButtonProps = ButtonProps & {
buttonRef?: React.MutableRefObject<HTMLButtonElement | null | undefined>;
variant?: ToolButtonVariant;
};
-export function ToolButton(props: ToolButtonProps) {
- const {
- id,
- icon,
- iconSize,
- iconColor,
- toggled,
- sx,
- buttonRef,
- variant = "normal",
- ...buttonProps
- } = props;
+export const ToolButton = React.memo(
+ function ToolButton(props: ToolButtonProps) {
+ const {
+ id,
+ icon,
+ iconSize,
+ iconColor,
+ toggled,
+ sx,
+ buttonRef,
+ variant = "normal",
+ ...buttonProps
+ } = props;
+ console.log("rerendering", props.title);
- return (
- <Button
- ref={buttonRef}
- tabIndex={-1}
- id={`tool-${id || icon}`}
- sx={{
- flexShrink: 0,
- p: variant === "small" ? "small" : 1,
- borderRadius: variant === "small" ? "small" : "default",
- m: 0,
- bg: toggled ? "hover" : "transparent",
- mr: variant === "small" ? 0 : 1,
- ":hover": { bg: ["transparent", "hover"] },
- ":active": { bg: "hover" },
- ":last-of-type": {
- mr: 0,
- },
- ...sx,
- }}
- onMouseDown={(e) => e.preventDefault()}
- {...buttonProps}
- >
- <Icon
- path={Icons[icon]}
- color={iconColor || "icon"}
- size={iconSize || (variant === "small" ? "medium" : "big")}
- />
- </Button>
- );
-}
+ return (
+ <Button
+ ref={buttonRef}
+ tabIndex={-1}
+ id={`tool-${id || icon}`}
+ sx={{
+ flexShrink: 0,
+ p: variant === "small" ? "small" : 1,
+ borderRadius: variant === "small" ? "small" : "default",
+ m: 0,
+ bg: toggled ? "hover" : "transparent",
+ mr: variant === "small" ? 0 : 1,
+ ":hover": { bg: ["transparent", "hover"] },
+ ":active": { bg: "hover" },
+ ":last-of-type": {
+ mr: 0,
+ },
+ ...sx,
+ }}
+ onMouseDown={(e) => e.preventDefault()}
+ {...buttonProps}
+ >
+ <Icon
+ path={Icons[icon]}
+ color={iconColor || "icon"}
+ size={iconSize || (variant === "small" ? "medium" : "big")}
+ />
+ </Button>
+ );
+ },
+ (prev, next) => {
+ return prev.toggled === next.toggled;
+ }
+);
diff --git a/packages/editor/src/toolbar/components/toolbar-group.tsx b/packages/editor/src/toolbar/components/toolbar-group.tsx
index 73051475c..fb416e62f 100644
--- a/packages/editor/src/toolbar/components/toolbar-group.tsx
+++ b/packages/editor/src/toolbar/components/toolbar-group.tsx
@@ -12,6 +12,7 @@ export type ToolbarGroupProps = FlexProps & {
};
export function ToolbarGroup(props: ToolbarGroupProps) {
const { tools, editor, ...flexProps } = props;
+
return (
<Flex className="toolbar-group" {...flexProps}>
{tools.map((toolId) => {
diff --git a/packages/editor/src/toolbar/icons.ts b/packages/editor/src/toolbar/icons.ts
index 7494d9199..b1161b8fd 100644
--- a/packages/editor/src/toolbar/icons.ts
+++ b/packages/editor/src/toolbar/icons.ts
@@ -96,6 +96,7 @@ import {
mdiImageEditOutline,
mdiArrowLeft,
mdiMovieCogOutline,
+ mdiLinkOff,
} from "@mdi/js";
export const Icons = {
@@ -104,6 +105,7 @@ export const Icons = {
underline: mdiFormatUnderline,
strikethrough: mdiFormatStrikethrough,
code: mdiCodeTags,
+ codeRemove: `M3.62109375 1.83837892 2.26318358 3.13037107 6.46289063 7.536621 1.9995117 12l6.0000003 6 1.40039025-1.400391L4.80029295 12l3.0292968-3.0292965 7.0283205 7.371093-.2578125.2578125L16.000488 18l.224121-.224121 4.3125 4.52490225 1.35791025-1.29492225-4.34326125-4.55712825L22.000488 12l-6-6-1.40039025 1.40039063L19.19970675 12l-3.016113 3.016113L9.156738 7.6435545l.24316425-.24316387L7.999512 6l-.2109375.2109375Z`,
alignCenter: mdiFormatAlignCenter,
alignLeft: mdiFormatAlignLeft,
alignRight: mdiFormatAlignRight,
@@ -121,6 +123,10 @@ export const Icons = {
highlight: mdiFormatColorHighlight,
textColor: mdiFormatColorText,
link: mdiLinkPlus,
+ linkRemove: mdiLinkOff,
+ linkEdit:
+ "m19 14 1.28 1.28c.22.21.22.56 0 .77l-1 1L17.23 15l1-1c.11-.11.25-.17.39-.17s.27.06.38.17m-.3 3.63-6.06 6.07h-2.06v-2.06l6.07-6.06zM7 7h4v2H7c-1.6568542 0-3 1.343146-3 3s1.3431458 3 3 3h4v2H7c-2.7614237 0-5-2.238576-5-5 0-2.7614237 2.2385763-5 5-5m10 0c2.761424 0 5 2.2385763 5 5h-2c0-1.656854-1.343146-3-3-3h-4V7h4m-9 4h8v2H8v-2",
+
url: mdiLink,
image: mdiImage,
imageSettings: mdiImageEditOutline,
diff --git a/packages/editor/src/toolbar/tool-definitions.ts b/packages/editor/src/toolbar/tool-definitions.ts
index 25220ecd1..29df22592 100644
--- a/packages/editor/src/toolbar/tool-definitions.ts
+++ b/packages/editor/src/toolbar/tool-definitions.ts
@@ -22,10 +22,20 @@ const tools: Record<ToolId, ToolDefinition> = {
icon: "link",
title: "Link",
},
+ linkRemove: {
+ icon: "linkRemove",
+ title: "Link remove",
+ conditional: true,
+ },
code: {
icon: "code",
title: "Code",
},
+ codeRemove: {
+ icon: "codeRemove",
+ title: "Code",
+ conditional: true,
+ },
clearformatting: {
icon: "formatClear",
title: "Clear all formatting",
diff --git a/packages/editor/src/toolbar/toolbar.tsx b/packages/editor/src/toolbar/toolbar.tsx
index 4e850b239..972bdda97 100644
--- a/packages/editor/src/toolbar/toolbar.tsx
+++ b/packages/editor/src/toolbar/toolbar.tsx
@@ -51,7 +51,15 @@ export function Toolbar(props: ToolbarProps) {
}, [isMobile, location]);
const tools: ToolbarDefinition = [
- ["insertBlock", "tableSettings", "imageSettings"],
+ [
+ "insertBlock",
+ "tableSettings",
+ "imageSettings",
+ "embedSettings",
+ "attachmentSettings",
+ "linkRemove",
+ "codeRemove",
+ ],
[
"bold",
"italic",
diff --git a/packages/editor/src/toolbar/tools/alignment.tsx b/packages/editor/src/toolbar/tools/alignment.tsx
index 56b129b3d..a4126df68 100644
--- a/packages/editor/src/toolbar/tools/alignment.tsx
+++ b/packages/editor/src/toolbar/tools/alignment.tsx
@@ -13,7 +13,9 @@ function AlignmentTool(props: AlignmentToolProps) {
return (
<ToolButton
{...toolProps}
- onClick={() => editor.chain().focus().setTextAlign(alignment).run()}
+ onClick={() =>
+ editor.current?.chain().focus().setTextAlign(alignment).run()
+ }
toggled={editor.isActive({ textAlign: alignment })}
/>
);
diff --git a/packages/editor/src/toolbar/tools/attachment.tsx b/packages/editor/src/toolbar/tools/attachment.tsx
index 7abae7359..cbed39145 100644
--- a/packages/editor/src/toolbar/tools/attachment.tsx
+++ b/packages/editor/src/toolbar/tools/attachment.tsx
@@ -30,7 +30,7 @@ export function DownloadAttachment(props: ToolProps) {
onClick={() => {
const attachmentNode = findSelectedNode(editor, "attachment");
const attachment = (attachmentNode?.attrs || {}) as Attachment;
- editor?.chain().focus().downloadAttachment(attachment).run();
+ editor.current?.chain().focus().downloadAttachment(attachment).run();
}}
/>
);
@@ -42,7 +42,7 @@ export function RemoveAttachment(props: ToolProps) {
<ToolButton
{...props}
toggled={false}
- onClick={() => editor?.chain().focus().removeAttachment().run()}
+ onClick={() => editor.current?.chain().focus().removeAttachment().run()}
/>
);
}
diff --git a/packages/editor/src/toolbar/tools/block.tsx b/packages/editor/src/toolbar/tools/block.tsx
index 8841c1bad..90bffc187 100644
--- a/packages/editor/src/toolbar/tools/block.tsx
+++ b/packages/editor/src/toolbar/tools/block.tsx
@@ -1,29 +1,19 @@
import { ToolProps } from "../types";
-import { Editor } from "@tiptap/core";
-import { ToolButton } from "../components/tool-button";
-import { ToolId } from ".";
-import { IconNames, Icons } from "../icons";
-import { useEffect, useMemo, useRef, useState } from "react";
-import { Dropdown } from "../components/dropdown";
+import { Editor } from "../../types";
+import { Icons } from "../icons";
+import { useMemo, useRef, useState } from "react";
import { Icon } from "../components/icon";
-import { Box, Flex, Text } from "rebass";
-import { Popup } from "../components/popup";
import { EmbedPopup } from "../popups/embed-popup";
import { TablePopup } from "../popups/table-popup";
import { MenuItem } from "../../components/menu/types";
import { useIsMobile, useToolbarLocation } from "../stores/toolbar-store";
-import {
- DesktopOnly,
- MobileOnly,
- ResponsivePresenter,
-} from "../../components/responsive";
-import { ActionSheetPresenter } from "../../components/action-sheet";
-import { getToolbarElement } from "../utils/dom";
+import { ResponsivePresenter } from "../../components/responsive";
import { showPopup } from "../../components/popup-presenter";
import { ImageUploadPopup } from "../popups/image-upload";
import { Button } from "../../components/button";
export function InsertBlock(props: ToolProps) {
+ const { editor } = props;
const buttonRef = useRef<HTMLButtonElement>(null);
const [isOpen, setIsOpen] = useState(false);
const toolbarLocation = useToolbarLocation();
@@ -40,7 +30,7 @@ export function InsertBlock(props: ToolProps) {
isMobile ? embedMobile(editor) : embedDesktop(editor),
table(editor),
];
- }, [editor, isMobile]);
+ }, [isMobile]);
return (
<>
@@ -82,34 +72,34 @@ export function InsertBlock(props: ToolProps) {
);
}
-const horizontalRule = (editor: Editor | null): MenuItem => ({
+const horizontalRule = (editor: Editor): MenuItem => ({
key: "hr",
type: "button",
title: "Horizontal rule",
icon: "horizontalRule",
isChecked: editor?.isActive("horizontalRule"),
- onClick: () => editor?.chain().focus().setHorizontalRule().run(),
+ onClick: () => editor.current?.chain().focus().setHorizontalRule().run(),
});
-const codeblock = (editor: Editor | null): MenuItem => ({
+const codeblock = (editor: Editor): MenuItem => ({
key: "codeblock",
type: "button",
title: "Code block",
icon: "codeblock",
isChecked: editor?.isActive("codeBlock"),
- onClick: () => editor?.chain().focus().toggleCodeBlock().run(),
+ onClick: () => editor.current?.chain().focus().toggleCodeBlock().run(),
});
-const blockquote = (editor: Editor | null): MenuItem => ({
+const blockquote = (editor: Editor): MenuItem => ({
key: "blockquote",
type: "button",
title: "Quote",
icon: "blockquote",
isChecked: editor?.isActive("blockQuote"),
- onClick: () => editor?.chain().focus().toggleBlockquote().run(),
+ onClick: () => editor.current?.chain().focus().toggleBlockquote().run(),
});
-const image = (editor: Editor | null, isMobile: boolean): MenuItem => ({
+const image = (editor: Editor, isMobile: boolean): MenuItem => ({
key: "image",
type: "button",
title: "Image",
@@ -123,14 +113,14 @@ const image = (editor: Editor | null, isMobile: boolean): MenuItem => ({
title: "Upload from disk",
icon: "upload",
onClick: () =>
- editor?.chain().focus().openAttachmentPicker("image").run(),
+ editor.current?.chain().focus().openAttachmentPicker("image").run(),
},
isMobile ? uploadImageFromURLMobile(editor) : uploadImageFromURL(editor),
],
},
});
-const table = (editor: Editor | null): MenuItem => ({
+const table = (editor: Editor): MenuItem => ({
key: "table",
type: "button",
title: "Table",
@@ -161,7 +151,7 @@ const table = (editor: Editor | null): MenuItem => ({
},
});
-const embedMobile = (editor: Editor | null): MenuItem => ({
+const embedMobile = (editor: Editor): MenuItem => ({
key: "embed",
type: "button",
title: "Embed",
@@ -178,7 +168,7 @@ const embedMobile = (editor: Editor | null): MenuItem => ({
title="Insert embed"
onClose={(embed) => {
if (!embed) return onClick?.();
- editor?.chain().insertEmbed(embed).run();
+ editor.current?.chain().insertEmbed(embed).run();
onClick?.();
}}
/>
@@ -189,7 +179,7 @@ const embedMobile = (editor: Editor | null): MenuItem => ({
},
});
-const embedDesktop = (editor: Editor | null): MenuItem => ({
+const embedDesktop = (editor: Editor): MenuItem => ({
key: "embed",
type: "button",
title: "Embed",
@@ -203,7 +193,7 @@ const embedDesktop = (editor: Editor | null): MenuItem => ({
title="Insert embed"
onClose={(embed) => {
if (!embed) return hide();
- editor?.chain().insertEmbed(embed).run();
+ editor.current?.chain().insertEmbed(embed).run();
hide();
}}
/>
@@ -212,25 +202,26 @@ const embedDesktop = (editor: Editor | null): MenuItem => ({
},
});
-const attachment = (editor: Editor | null): MenuItem => ({
+const attachment = (editor: Editor): MenuItem => ({
key: "attachment",
type: "button",
title: "Attachment",
icon: "attachment",
isChecked: editor?.isActive("attachment"),
- onClick: () => editor?.chain().focus().openAttachmentPicker("file").run(),
+ onClick: () =>
+ editor.current?.chain().focus().openAttachmentPicker("file").run(),
});
-const tasklist = (editor: Editor | null): MenuItem => ({
+const tasklist = (editor: Editor): MenuItem => ({
key: "tasklist",
type: "button",
title: "Task list",
icon: "checkbox",
isChecked: editor?.isActive("taskList"),
- onClick: () => editor?.chain().focus().toggleTaskList().run(),
+ onClick: () => editor.current?.chain().focus().toggleTaskList().run(),
});
-const uploadImageFromURLMobile = (editor: Editor | null): MenuItem => ({
+const uploadImageFromURLMobile = (editor: Editor): MenuItem => ({
key: "upload-from-url",
type: "button",
title: "Attach from URL",
@@ -244,7 +235,7 @@ const uploadImageFromURLMobile = (editor: Editor | null): MenuItem => ({
component: ({ onClick }) => (
<ImageUploadPopup
onInsert={(image) => {
- editor?.commands.insertImage(image);
+ editor.current?.chain().focus().insertImage(image).run();
onClick?.();
}}
onClose={() => {
@@ -257,7 +248,7 @@ const uploadImageFromURLMobile = (editor: Editor | null): MenuItem => ({
},
});
-const uploadImageFromURL = (editor: Editor | null): MenuItem => ({
+const uploadImageFromURL = (editor: Editor): MenuItem => ({
key: "upload-from-url",
type: "button",
title: "Attach from URL",
@@ -269,7 +260,7 @@ const uploadImageFromURL = (editor: Editor | null): MenuItem => ({
popup: (hide) => (
<ImageUploadPopup
onInsert={(image) => {
- editor?.chain().focus().insertImage(image).run();
+ editor.current?.chain().focus().insertImage(image).run();
hide();
}}
onClose={hide}
diff --git a/packages/editor/src/toolbar/tools/colors.tsx b/packages/editor/src/toolbar/tools/colors.tsx
index 94f30eca2..0e20b5ecc 100644
--- a/packages/editor/src/toolbar/tools/colors.tsx
+++ b/packages/editor/src/toolbar/tools/colors.tsx
@@ -1,5 +1,5 @@
import { Editor } from "@tiptap/core";
-import { useState } from "react";
+import React, { useState } from "react";
import tinycolor from "tinycolor2";
import { PopupWrapper } from "../../components/popup-presenter";
import { config } from "../../utils/config";
@@ -10,12 +10,13 @@ import { ToolProps } from "../types";
import { getToolbarElement } from "../utils/dom";
type ColorToolProps = ToolProps & {
- onColorChange: (editor: Editor, color?: string) => void;
- getActiveColor: (editor: Editor) => string;
+ onColorChange: (color?: string) => void;
+ getActiveColor: () => string;
title: string;
cacheKey: string;
};
-export function ColorTool(props: ColorToolProps) {
+// TODO test rerendering
+function _ColorTool(props: ColorToolProps) {
const {
editor,
onColorChange,
@@ -24,7 +25,7 @@ export function ColorTool(props: ColorToolProps) {
cacheKey,
...toolProps
} = props;
- const activeColor = getActiveColor(editor) || config.get(cacheKey);
+ const activeColor = getActiveColor() || config.get(cacheKey);
const tColor = tinycolor(activeColor);
const isBottom = useToolbarLocation() === "bottom";
const [isOpen, setIsOpen] = useState<boolean>(false);
@@ -42,7 +43,7 @@ export function ColorTool(props: ColorToolProps) {
}}
onOpen={() => setIsOpen((s) => !s)}
toggled={isOpen}
- onClick={() => onColorChange(editor, activeColor)}
+ onClick={() => onColorChange(activeColor)}
>
<PopupWrapper
isOpen={isOpen}
@@ -61,11 +62,11 @@ export function ColorTool(props: ColorToolProps) {
<ColorPicker
color={activeColor}
onClear={() => {
- onColorChange(editor);
+ onColorChange();
config.set(cacheKey, null);
}}
onChange={(color) => {
- onColorChange(editor, color);
+ onColorChange(color);
config.set(cacheKey, color);
}}
onClose={close}
@@ -77,33 +78,38 @@ export function ColorTool(props: ColorToolProps) {
);
}
+export const ColorTool = React.memo(_ColorTool, () => true);
+
export function Highlight(props: ToolProps) {
+ const { editor } = props;
+
return (
<ColorTool
{...props}
cacheKey="highlight"
- getActiveColor={(editor) => editor.getAttributes("highlight").color}
+ getActiveColor={() => editor.current?.getAttributes("highlight").color}
title={"Background color"}
- onColorChange={(editor, color) =>
+ onColorChange={(color) =>
color
- ? editor.chain().focus().toggleHighlight({ color }).run()
- : editor.chain().focus().unsetHighlight().run()
+ ? editor.current?.chain().focus().toggleHighlight({ color }).run()
+ : editor.current?.chain().focus().unsetHighlight().run()
}
/>
);
}
export function TextColor(props: ToolProps) {
+ const { editor } = props;
return (
<ColorTool
{...props}
cacheKey={"textColor"}
- getActiveColor={(editor) => editor.getAttributes("textStyle").color}
+ getActiveColor={() => editor.current?.getAttributes("textStyle").color}
title="Text color"
- onColorChange={(editor, color) =>
+ onColorChange={(color) =>
color
- ? editor.chain().focus().setColor(color).run()
- : editor.chain().focus().unsetColor().run()
+ ? editor.current?.chain().focus().setColor(color).run()
+ : editor.current?.chain().focus().unsetColor().run()
}
/>
);
diff --git a/packages/editor/src/toolbar/tools/embed.tsx b/packages/editor/src/toolbar/tools/embed.tsx
index 274fd5082..40fcc76fd 100644
--- a/packages/editor/src/toolbar/tools/embed.tsx
+++ b/packages/editor/src/toolbar/tools/embed.tsx
@@ -31,7 +31,11 @@ export function EmbedAlignLeft(props: ToolProps) {
{...props}
toggled={false}
onClick={() =>
- editor.chain().focus().setEmbedAlignment({ align: "left" }).run()
+ editor.current
+ ?.chain()
+ .focus()
+ .setEmbedAlignment({ align: "left" })
+ .run()
}
/>
);
@@ -44,7 +48,11 @@ export function EmbedAlignRight(props: ToolProps) {
{...props}
toggled={false}
onClick={() =>
- editor.chain().focus().setEmbedAlignment({ align: "right" }).run()
+ editor.current
+ ?.chain()
+ .focus()
+ .setEmbedAlignment({ align: "right" })
+ .run()
}
/>
);
@@ -57,17 +65,23 @@ export function EmbedAlignCenter(props: ToolProps) {
{...props}
toggled={false}
onClick={() =>
- editor.chain().focus().setEmbedAlignment({ align: "center" }).run()
+ editor.current
+ ?.chain()
+ .focus()
+ .setEmbedAlignment({ align: "center" })
+ .run()
}
/>
);
}
+// TODO: stop re-rendering
export function EmbedProperties(props: ToolProps) {
const { editor } = props;
const [isOpen, setIsOpen] = useState(false);
const buttonRef = useRef<HTMLButtonElement>();
+ // TODO: improve perf by deferring this until user opens the popup
const embedNode = useMemo(() => findSelectedNode(editor, "embed"), []);
const embed = (embedNode?.attrs || {}) as Embed;
diff --git a/packages/editor/src/toolbar/tools/font.tsx b/packages/editor/src/toolbar/tools/font.tsx
index 617808544..a4b9e00dd 100644
--- a/packages/editor/src/toolbar/tools/font.tsx
+++ b/packages/editor/src/toolbar/tools/font.tsx
@@ -1,36 +1,43 @@
import { ToolProps } from "../types";
+import { Editor } from "../../types";
import { Dropdown } from "../components/dropdown";
import { MenuItem } from "../../components/menu/types";
-import { Editor } from "@tiptap/core";
-import { useCallback, useEffect } from "react";
+import { useCallback, useEffect, useMemo, useRef } from "react";
import { Counter } from "../components/counter";
+import { useRefValue } from "../../hooks/use-ref-value";
-const defaultFontSizes = [
- 8, 12, 14, 16, 18, 20, 24, 28, 32, 36, 42, 48, 60, 72, 100,
-];
export function FontSize(props: ToolProps) {
const { editor } = props;
- const { fontSize = "16px" } = editor.getAttributes("textStyle");
- const fontSizeAsNumber = parseInt(fontSize.replace("px", ""));
+ const { fontSize: _fontSize } = editor.getAttributes("textStyle");
+ const fontSize = _fontSize || "16px";
+ const fontSizeAsNumber = useRefValue(parseInt(fontSize.replace("px", "")));
const decreaseFontSize = useCallback(() => {
- return Math.max(8, fontSizeAsNumber - 1);
- }, [fontSizeAsNumber]);
+ return Math.max(8, fontSizeAsNumber.current - 1);
+ }, []);
+
+ const increaseFontSize = useCallback(() => {
+ return Math.min(120, fontSizeAsNumber.current + 1);
+ }, []);
return (
<Counter
title="font size"
onDecrease={() =>
- editor.chain().focus().setFontSize(`${decreaseFontSize()}px`).run()
- }
- onIncrease={() =>
- editor
- .chain()
+ editor.current
+ ?.chain()
.focus()
- .setFontSize(`${fontSizeAsNumber + 1}px`)
+ .setFontSize(`${decreaseFontSize()}px`)
.run()
}
- onReset={() => editor.chain().focus().setFontSize(`16px`).run()}
+ onIncrease={() => {
+ editor.current
+ ?.chain()
+ .focus()
+ .setFontSize(`${increaseFontSize()}px`)
+ .run();
+ }}
+ onReset={() => editor.current?.chain().focus().setFontSize(`16px`).run()}
value={fontSize}
/>
);
@@ -51,13 +58,13 @@ export function FontFamily(props: ToolProps) {
)
?.map((a) => a)
?.at(0) || "System";
+ const items = useMemo(
+ () => toMenuItems(editor, currentFontFamily),
+ [currentFontFamily]
+ );
return (
- <Dropdown
- selectedItem={currentFontFamily}
- items={toMenuItems(editor, currentFontFamily)}
- menuWidth={130}
- />
+ <Dropdown selectedItem={currentFontFamily} items={items} menuWidth={130} />
);
}
@@ -70,7 +77,7 @@ function toMenuItems(editor: Editor, currentFontFamily: string): MenuItem[] {
type: "button",
title: key,
isChecked: key === currentFontFamily,
- onClick: () => editor.chain().focus().setFontFamily(value).run(),
+ onClick: () => editor.current?.chain().focus().setFontFamily(value).run(),
});
}
return menuItems;
diff --git a/packages/editor/src/toolbar/tools/headings.tsx b/packages/editor/src/toolbar/tools/headings.tsx
index ea303c47a..3f610edae 100644
--- a/packages/editor/src/toolbar/tools/headings.tsx
+++ b/packages/editor/src/toolbar/tools/headings.tsx
@@ -1,9 +1,10 @@
import { ToolProps } from "../types";
-import { Editor } from "@tiptap/core";
+import { Editor } from "../../types";
import { ToolId } from ".";
import { Dropdown } from "../components/dropdown";
import { MenuItem } from "../../components/menu/types";
import { ToolbarLocation, useToolbarLocation } from "../stores/toolbar-store";
+import { useMemo } from "react";
const defaultLevels = [1, 2, 3, 4, 5, 6];
@@ -14,12 +15,17 @@ export function Headings(props: ToolProps) {
const currentHeadingLevel = defaultLevels.find((level) =>
editor.isActive("heading", { level })
);
+ const items = useMemo(
+ () => toMenuItems(editor, toolbarLocation, currentHeadingLevel),
+ [currentHeadingLevel]
+ );
+
return (
<Dropdown
selectedItem={
currentHeadingLevel ? `Heading ${currentHeadingLevel}` : "Paragraph"
}
- items={toMenuItems(editor, toolbarLocation, currentHeadingLevel)}
+ items={items}
menuWidth={130}
/>
);
@@ -36,9 +42,10 @@ function toMenuItems(
title: toolbarLocation === "bottom" ? `H${level}` : `Heading ${level}`,
isChecked: level === currentHeadingLevel,
onClick: () =>
- editor
- .chain()
+ editor.current
+ ?.chain()
.focus()
+ .updateAttributes("textStyle", { fontSize: null, fontStyle: null })
.setHeading({ level: level as any })
.run(),
}));
@@ -47,7 +54,7 @@ function toMenuItems(
type: "button",
title: "Paragraph",
isChecked: !currentHeadingLevel,
- onClick: () => editor.chain().focus().setParagraph().run(),
+ onClick: () => editor.current?.chain().focus().setParagraph().run(),
};
return [paragraph, ...menuItems];
}
diff --git a/packages/editor/src/toolbar/tools/image.tsx b/packages/editor/src/toolbar/tools/image.tsx
index 30c701c3e..2bcd90f76 100644
--- a/packages/editor/src/toolbar/tools/image.tsx
+++ b/packages/editor/src/toolbar/tools/image.tsx
@@ -47,7 +47,11 @@ export function ImageAlignLeft(props: ToolProps) {
{...props}
toggled={false}
onClick={() =>
- editor.chain().focus().setImageAlignment({ align: "left" }).run()
+ editor.current
+ ?.chain()
+ .focus()
+ .setImageAlignment({ align: "left" })
+ .run()
}
/>
);
@@ -60,7 +64,11 @@ export function ImageAlignRight(props: ToolProps) {
{...props}
toggled={false}
onClick={() =>
- editor.chain().focus().setImageAlignment({ align: "right" }).run()
+ editor.current
+ ?.chain()
+ .focus()
+ .setImageAlignment({ align: "right" })
+ .run()
}
/>
);
@@ -73,7 +81,11 @@ export function ImageAlignCenter(props: ToolProps) {
{...props}
toggled={false}
onClick={() =>
- editor.chain().focus().setImageAlignment({ align: "center" }).run()
+ editor.current
+ ?.chain()
+ .focus()
+ .setImageAlignment({ align: "center" })
+ .run()
}
/>
);
@@ -84,6 +96,7 @@ export function ImageProperties(props: ToolProps) {
const [isOpen, setIsOpen] = useState(false);
const buttonRef = useRef<HTMLButtonElement>();
+ // TODO: defer until user opens the popup
const image = useMemo(() => findSelectedNode(editor, "image"), []);
const { float, align, width, height } = (image?.attrs ||
{}) as ImageAlignmentOptions & ImageSizeOptions;
diff --git a/packages/editor/src/toolbar/tools/index.ts b/packages/editor/src/toolbar/tools/index.ts
index 31d38882c..24fa7f82f 100644
--- a/packages/editor/src/toolbar/tools/index.ts
+++ b/packages/editor/src/toolbar/tools/index.ts
@@ -10,6 +10,8 @@ import {
Superscript,
ClearFormatting,
Link,
+ LinkRemove,
+ CodeRemove,
} from "./inline";
import { InsertBlock } from "./block";
import { FontSize, FontFamily } from "./font";
@@ -68,10 +70,12 @@ const tools = {
underline: Underline,
strikethrough: Strikethrough,
code: Code,
+ codeRemove: CodeRemove,
subscript: Subscript,
superscript: Superscript,
clearformatting: ClearFormatting,
link: Link,
+ linkRemove: LinkRemove,
insertBlock: InsertBlock,
numberedList: NumberedList,
bulletList: BulletList,
diff --git a/packages/editor/src/toolbar/tools/inline.tsx b/packages/editor/src/toolbar/tools/inline.tsx
index c1ce8559f..4f77c5d44 100644
--- a/packages/editor/src/toolbar/tools/inline.tsx
+++ b/packages/editor/src/toolbar/tools/inline.tsx
@@ -1,114 +1,138 @@
import { ToolProps } from "../types";
-import { Editor } from "@tiptap/core";
import { ToolButton } from "../components/tool-button";
-import { useCallback, useRef, useState } from "react";
+import { useCallback, useMemo, useRef, useState } from "react";
import { ResponsivePresenter } from "../../components/responsive";
import { Popup } from "../components/popup";
import { LinkPopup } from "../popups/link-popup";
-
-type InlineToolProps = ToolProps & {
- isToggled: (editor: Editor) => boolean;
- onClick: (editor: Editor) => boolean;
-};
-function InlineTool(props: InlineToolProps) {
- const { editor, title, icon, isToggled, onClick } = props;
- return (
- <ToolButton
- title={title}
- id={icon}
- icon={icon}
- onClick={() => onClick(editor)}
- toggled={isToggled(editor)}
- />
- );
-}
+import { useToolbarLocation } from "../stores/toolbar-store";
export function Italic(props: ToolProps) {
+ const { editor } = props;
return (
- <InlineTool
+ <ToolButton
{...props}
- isToggled={(editor) => editor.isActive("italic")}
- onClick={(editor) => editor.chain().focus().toggleItalic().run()}
+ toggled={editor.isActive("italic")}
+ onClick={() => editor.current?.chain().focus().toggleItalic().run()}
/>
);
}
export function Strikethrough(props: ToolProps) {
+ const { editor } = props;
return (
- <InlineTool
+ <ToolButton
{...props}
- isToggled={(editor) => editor.isActive("strikethrough")}
- onClick={(editor) => editor.chain().focus().toggleStrike().run()}
+ toggled={editor.isActive("strike")}
+ onClick={() => editor.current?.chain().focus().toggleStrike().run()}
/>
);
}
export function Underline(props: ToolProps) {
+ const { editor } = props;
return (
- <InlineTool
+ <ToolButton
{...props}
- isToggled={(editor) => editor.isActive("underline")}
- onClick={(editor) => editor.chain().focus().toggleUnderline().run()}
+ toggled={editor.isActive("underline")}
+ onClick={() => editor.current?.chain().focus().toggleUnderline().run()}
/>
);
}
export function Code(props: ToolProps) {
+ const { editor } = props;
+
return (
- <InlineTool
+ <ToolButton
{...props}
- isToggled={(editor) => editor.isActive("code")}
- onClick={(editor) => editor.chain().focus().toggleCode().run()}
+ toggled={editor.isActive("code")}
+ onClick={() => editor.current?.chain().focus().toggleCode().run()}
/>
);
}
export function Bold(props: ToolProps) {
+ const { editor } = props;
+
return (
- <InlineTool
+ <ToolButton
{...props}
- isToggled={(editor) => editor.isActive("bold")}
- onClick={(editor) => editor.chain().focus().toggleBold().run()}
+ toggled={editor.isActive("bold")}
+ onClick={() => editor.current?.chain().focus().toggleBold().run()}
/>
);
}
export function Subscript(props: ToolProps) {
+ const { editor } = props;
return (
- <InlineTool
+ <ToolButton
{...props}
- isToggled={(editor) => editor.isActive("subscript")}
- onClick={(editor) => editor.chain().focus().toggleSubscript().run()}
+ toggled={editor.isActive("subscript")}
+ onClick={() => editor.current?.chain().focus().toggleSubscript().run()}
/>
);
}
export function Superscript(props: ToolProps) {
+ const { editor } = props;
return (
- <InlineTool
+ <ToolButton
{...props}
- isToggled={(editor) => editor.isActive("superscript")}
- onClick={(editor) => editor.chain().focus().toggleSuperscript().run()}
+ toggled={editor.isActive("superscript")}
+ onClick={() => editor.current?.chain().focus().toggleSuperscript().run()}
/>
);
}
export function ClearFormatting(props: ToolProps) {
+ const { editor } = props;
return (
- <InlineTool
+ <ToolButton
{...props}
- isToggled={() => false}
- onClick={(editor) =>
- editor.chain().focus().clearNodes().unsetAllMarks().run()
+ toggled={false}
+ onClick={() =>
+ editor.current
+ ?.chain()
+ .focus()
+ .clearNodes()
+ .unsetAllMarks()
+ .unsetMark("link")
+ .run()
}
/>
);
}
+export function LinkRemove(props: ToolProps) {
+ const { editor } = props;
+ const isBottom = useToolbarLocation() === "bottom";
+ if (!editor.isActive("link") || !isBottom) return null;
+ return (
+ <ToolButton
+ {...props}
+ toggled={false}
+ onClick={() => editor.current?.chain().focus().unsetMark("link").run()}
+ />
+ );
+}
+
+export function CodeRemove(props: ToolProps) {
+ const { editor } = props;
+ const isBottom = useToolbarLocation() === "bottom";
+ if (!editor.isActive("code") || !isBottom) return null;
+ return (
+ <ToolButton
+ {...props}
+ toggled={false}
+ onClick={() => editor.current?.chain().focus().unsetMark("code").run()}
+ />
+ );
+}
+
export function Link(props: ToolProps) {
const { editor, title, icon } = props;
const buttonRef = useRef<HTMLButtonElement>(null);
- const targetRef = useRef<HTMLElement>();
const [isOpen, setIsOpen] = useState(false);
const [href, setHref] = useState<string>();
@@ -119,14 +143,18 @@ export function Link(props: ToolProps) {
const onDone = useCallback((href: string, text: string) => {
if (!href) return;
- let commandChain = editor
- .chain()
- .focus()
+ let commandChain = editor.current?.chain().focus();
+ if (!commandChain) return;
+
+ commandChain
.extendMarkRange("link")
- .setLink({ href, target: "_blank" });
- if (text) commandChain = commandChain.insertContent(text).focus();
+ .toggleLink({ href, target: "_blank" })
+ .insertContent(text || href)
+ .focus()
+ .unsetMark("link")
+ .insertContent(" ")
+ .run();
- commandChain.run();
setIsOpen(false);
}, []);
@@ -136,17 +164,12 @@ export function Link(props: ToolProps) {
id={icon}
buttonRef={buttonRef}
title={title}
- icon={icon}
+ icon={isEditing ? "linkEdit" : icon}
onClick={() => {
if (isEditing) setHref(currentUrl);
let { from, to, $from } = editor.state.selection;
-
const selectedNode = $from.node();
- const pos = selectedNode.isTextblock ? $from.before() : $from.pos;
-
- const domNode = editor.view.nodeDOM(pos) as HTMLElement;
- targetRef.current = domNode;
const selectedText = isEditing
? selectedNode.textContent
@@ -161,7 +184,7 @@ export function Link(props: ToolProps) {
mobile="sheet"
desktop="menu"
position={{
- target: targetRef.current || buttonRef.current || undefined,
+ target: buttonRef.current || undefined,
isTargetAbsolute: true,
location: "below",
align: "center",
@@ -170,10 +193,7 @@ export function Link(props: ToolProps) {
title={isEditing ? "Edit link" : "Insert link"}
isOpen={isOpen}
items={[]}
- onClose={() => {
- editor.commands.focus();
- setIsOpen(false);
- }}
+ onClose={() => setIsOpen(false)}
focusOnRender={false}
>
<Popup
@@ -193,3 +213,57 @@ export function Link(props: ToolProps) {
</>
);
}
+
+// export function Link(props: ToolProps) {
+// const { editor, title, icon } = props;
+// const buttonRef = useRef<HTMLButtonElement>(null);
+// const [isOpen, setIsOpen] = useState(false);
+
+// const [href, setHref] = useState<string>();
+// const [text, setText] = useState<string>();
+// const currentUrl = editor.getAttributes("link").href;
+// const isEditing = !!currentUrl;
+
+// const onDone = useCallback((href: string, text: string) => {
+// if (!href) return;
+
+// let commandChain = editor.current?.chain().focus();
+// if (!commandChain) return;
+
+// commandChain
+// .extendMarkRange("link")
+// .toggleLink({ href, target: "_blank" })
+// .insertContent(text || href)
+// .focus()
+// .unsetMark("link")
+// .insertContent(" ")
+// .run();
+
+// setIsOpen(false);
+// }, []);
+
+// return (
+// <>
+// <ToolButton
+// id={icon}
+// buttonRef={buttonRef}
+// title={title}
+// icon={icon}
+// onClick={() => {
+// if (isEditing) setHref(currentUrl);
+
+// let { from, to, $from } = editor.state.selection;
+// const selectedNode = $from.node();
+
+// const selectedText = isEditing
+// ? selectedNode.textContent
+// : editor.state.doc.textBetween(from, to);
+
+// setText(selectedText);
+// setIsOpen(true);
+// }}
+// toggled={isOpen || !!isEditing}
+// />
+// </>
+// );
+// }
diff --git a/packages/editor/src/toolbar/tools/lists.tsx b/packages/editor/src/toolbar/tools/lists.tsx
index 079766898..3c01aa21f 100644
--- a/packages/editor/src/toolbar/tools/lists.tsx
+++ b/packages/editor/src/toolbar/tools/lists.tsx
@@ -2,32 +2,31 @@ import { ToolProps } from "../types";
import { Editor } from "@tiptap/core";
import { Box, Button, Flex } from "rebass";
import { IconNames } from "../icons";
-import { useRef, useState } from "react";
+import { useCallback, useMemo, useRef, useState } from "react";
import { SplitButton } from "../components/split-button";
import { useToolbarLocation } from "../stores/toolbar-store";
import { getToolbarElement } from "../utils/dom";
import { PopupWrapper } from "../../components/popup-presenter";
+import React from "react";
type ListSubType<TListStyleTypes> = {
items: string[];
title: string;
type: TListStyleTypes;
};
-type ListOptions<TListStyleTypes> = {
+
+type ListToolProps<TListStyleTypes> = ToolProps & {
+ isActive: boolean;
icon: IconNames;
type: "bulletList" | "orderedList";
- onClick: (editor: Editor) => void;
+ onClick: () => void;
subTypes: ListSubType<TListStyleTypes>[];
};
-type ListToolProps<TListStyleTypes> = ToolProps & {
- options: ListOptions<TListStyleTypes>;
-};
-function ListTool<TListStyleTypes extends string>(
+function _ListTool<TListStyleTypes extends string>(
props: ListToolProps<TListStyleTypes>
) {
- const { editor, options, ...toolProps } = props;
- const isActive = editor.isActive(options.type);
+ const { editor, onClick, isActive, subTypes, type, ...toolProps } = props;
const toolbarLocation = useToolbarLocation();
const isBottom = toolbarLocation === "bottom";
const [isOpen, setIsOpen] = useState(false);
@@ -37,7 +36,7 @@ function ListTool<TListStyleTypes extends string>(
<SplitButton
{...toolProps}
buttonRef={buttonRef}
- onClick={() => options.onClick(editor)}
+ onClick={onClick}
toggled={isActive || isOpen}
sx={{ mr: 0 }}
onOpen={() => setIsOpen((s) => !s)}
@@ -55,26 +54,32 @@ function ListTool<TListStyleTypes extends string>(
location: isBottom ? "top" : "below",
yOffset: isBottom ? 10 : 5,
}}
+ onClosed={() => setIsOpen(false)}
renderPopup={() => (
<Box
- sx={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", p: 1 }}
+ sx={{
+ bg: "background",
+ display: "grid",
+ gridTemplateColumns: "1fr 1fr 1fr",
+ p: 1,
+ }}
>
- {options.subTypes.map((item) => (
+ {subTypes.map((item) => (
<Button
key={item.title}
variant={"menuitem"}
sx={{ width: 80 }}
onClick={() => {
- let chain = editor.chain().focus();
+ let chain = editor.current?.chain().focus();
+ if (!chain) return;
if (!isActive) {
- if (options.type === "bulletList")
- chain = chain.toggleBulletList();
+ if (type === "bulletList") chain = chain.toggleBulletList();
else chain = chain.toggleOrderedList();
}
return chain
- .updateAttributes(options.type, { listType: item.type })
+ .updateAttributes(type, { listType: item.type })
.run();
}}
>
@@ -88,6 +93,10 @@ function ListTool<TListStyleTypes extends string>(
);
}
+const ListTool = React.memo(_ListTool, (prev, next) => {
+ return prev.isActive === next.isActive;
+});
+
type NumberedListStyleTypes =
| "lower-roman"
| "upper-roman"
@@ -97,43 +106,60 @@ type NumberedListStyleTypes =
| "decimal";
export function NumberedList(props: ToolProps) {
- const options: ListOptions<NumberedListStyleTypes> = {
- type: "orderedList",
- icon: "numberedList",
- onClick: (editor) => editor.chain().focus().toggleOrderedList().run(),
- subTypes: [
- { type: "decimal", title: "Decimal", items: ["1", "2", "3"] },
- { type: "upper-alpha", title: "Upper alpha", items: ["A", "B", "C"] },
- { type: "lower-alpha", title: "Lower alpha", items: ["a", "b", "c"] },
- {
- type: "upper-roman",
- title: "Upper Roman",
- items: ["I", "II", "III"],
- },
- {
- type: "lower-roman",
- title: "Lower Roman",
- items: ["i", "ii", "iii"],
- },
- { type: "lower-greek", title: "Lower Greek", items: ["α", "β", "γ"] },
- ],
- };
- return <ListTool {...props} options={options} />;
+ const { editor } = props;
+
+ const onClick = useCallback(
+ () => editor.current?.chain().focus().toggleOrderedList().run(),
+ []
+ );
+
+ return (
+ <ListTool
+ {...props}
+ type="orderedList"
+ isActive={editor.isActive("orderedList")}
+ onClick={onClick}
+ subTypes={[
+ { type: "decimal", title: "Decimal", items: ["1", "2", "3"] },
+ { type: "upper-alpha", title: "Upper alpha", items: ["A", "B", "C"] },
+ { type: "lower-alpha", title: "Lower alpha", items: ["a", "b", "c"] },
+ {
+ type: "upper-roman",
+ title: "Upper Roman",
+ items: ["I", "II", "III"],
+ },
+ {
+ type: "lower-roman",
+ title: "Lower Roman",
+ items: ["i", "ii", "iii"],
+ },
+ { type: "lower-greek", title: "Lower Greek", items: ["α", "β", "γ"] },
+ ]}
+ />
+ );
}
type BulletListStyleTypes = "circle" | "square" | "disc";
export function BulletList(props: ToolProps) {
- const options: ListOptions<BulletListStyleTypes> = {
- type: "bulletList",
- icon: "bulletList",
- onClick: (editor) => editor.chain().focus().toggleOrderedList().run(),
- subTypes: [
- { type: "disc", title: "Decimal", items: ["1", "2", "3"] },
- { type: "circle", title: "Upper alpha", items: ["A", "B", "C"] },
- { type: "square", title: "Lower alpha", items: ["a", "b", "c"] },
- ],
- };
- return <ListTool {...props} options={options} />;
+ const { editor } = props;
+ const onClick = useCallback(
+ () => editor.current?.chain().focus().toggleOrderedList().run(),
+ []
+ );
+
+ return (
+ <ListTool
+ {...props}
+ type="bulletList"
+ onClick={onClick}
+ isActive={editor.isActive("bulletList")}
+ subTypes={[
+ { type: "disc", title: "Decimal", items: ["1", "2", "3"] },
+ { type: "circle", title: "Upper alpha", items: ["A", "B", "C"] },
+ { type: "square", title: "Lower alpha", items: ["a", "b", "c"] },
+ ]}
+ />
+ );
}
type ListThumbnailProps = { listStyleType: string };
diff --git a/packages/editor/src/toolbar/tools/table.tsx b/packages/editor/src/toolbar/tools/table.tsx
index cd17b0f7d..5b652607e 100644
--- a/packages/editor/src/toolbar/tools/table.tsx
+++ b/packages/editor/src/toolbar/tools/table.tsx
@@ -1,5 +1,5 @@
import { ToolProps } from "../types";
-import { Editor } from "@tiptap/core";
+import { Editor } from "../../types";
import { ToolButton } from "../components/tool-button";
import { useCallback, useMemo, useRef, useState } from "react";
import { Flex, Text } from "rebass";
@@ -196,44 +196,56 @@ export function CellProperties(props: ToolProps) {
}
export function CellBackgroundColor(props: ToolProps) {
+ const { editor } = props;
+
return (
<ColorTool
{...props}
cacheKey="cellBackgroundColor"
- getActiveColor={(editor) =>
- editor.getAttributes("tableCell").backgroundColor
+ getActiveColor={() =>
+ editor.current?.getAttributes("tableCell").backgroundColor
}
title={"Cell background color"}
- onColorChange={(editor, color) =>
- editor.chain().setCellAttribute("backgroundColor", color).run()
+ onColorChange={(color) =>
+ editor.current?.chain().setCellAttribute("backgroundColor", color).run()
}
/>
);
}
export function CellTextColor(props: ToolProps) {
+ const { editor } = props;
+
return (
<ColorTool
{...props}
cacheKey="cellTextColor"
- getActiveColor={(editor) => editor.getAttributes("tableCell").color}
+ getActiveColor={() => editor.current?.getAttributes("tableCell").color}
title={"Cell text color"}
- onColorChange={(editor, color) =>
- editor.chain().focus().setCellAttribute("color", color).run()
+ onColorChange={(color) =>
+ editor.current?.chain().focus().setCellAttribute("color", color).run()
}
/>
);
}
export function CellBorderColor(props: ToolProps) {
+ const { editor } = props;
+
return (
<ColorTool
{...props}
cacheKey="cellBorderColor"
- getActiveColor={(editor) => editor.getAttributes("tableCell").borderColor}
+ getActiveColor={() =>
+ editor.current?.getAttributes("tableCell").borderColor
+ }
title={"Cell border color"}
- onColorChange={(editor, color) =>
- editor.chain().focus().setCellAttribute("borderColor", color).run()
+ onColorChange={(color) =>
+ editor.current
+ ?.chain()
+ .focus()
+ .setCellAttribute("borderColor", color)
+ .run()
}
/>
);
@@ -276,7 +288,7 @@ const insertColumnLeft = (editor: Editor): MenuButton => ({
...getToolDefinition("insertColumnLeft"),
key: "addColumnLeft",
type: "button",
- onClick: () => editor.chain().focus().addColumnBefore().run(),
+ onClick: () => editor.current?.chain().focus().addColumnBefore().run(),
});
const insertColumnRight = (editor: Editor): MenuButton => ({
@@ -284,7 +296,7 @@ const insertColumnRight = (editor: Editor): MenuButton => ({
key: "addColumnRight",
type: "button",
title: "Add column right",
- onClick: () => editor.chain().focus().addColumnAfter().run(),
+ onClick: () => editor.current?.chain().focus().addColumnAfter().run(),
icon: "insertColumnRight",
});
@@ -306,35 +318,35 @@ const deleteColumn = (editor: Editor): MenuButton => ({
...getToolDefinition("deleteColumn"),
key: "deleteColumn",
type: "button",
- onClick: () => editor.chain().focus().deleteColumn().run(),
+ onClick: () => editor.current?.chain().focus().deleteColumn().run(),
});
const splitCells = (editor: Editor): MenuButton => ({
...getToolDefinition("splitCells"),
key: "splitCells",
type: "button",
- onClick: () => editor.chain().focus().splitCell().run(),
+ onClick: () => editor.current?.chain().focus().splitCell().run(),
});
const mergeCells = (editor: Editor): MenuButton => ({
...getToolDefinition("mergeCells"),
key: "mergeCells",
type: "button",
- onClick: () => editor.chain().focus().mergeCells().run(),
+ onClick: () => editor.current?.chain().focus().mergeCells().run(),
});
const insertRowAbove = (editor: Editor): MenuButton => ({
...getToolDefinition("insertRowAbove"),
key: "insertRowAbove",
type: "button",
- onClick: () => editor.chain().focus().addRowBefore().run(),
+ onClick: () => editor.current?.chain().focus().addRowBefore().run(),
});
const insertRowBelow = (editor: Editor): MenuButton => ({
...getToolDefinition("insertRowBelow"),
key: "insertRowBelow",
type: "button",
- onClick: () => editor.chain().focus().addRowAfter().run(),
+ onClick: () => editor.current?.chain().focus().addRowAfter().run(),
});
const moveRowUp = (editor: Editor): MenuButton => ({
@@ -354,14 +366,14 @@ const deleteRow = (editor: Editor): MenuButton => ({
...getToolDefinition("deleteRow"),
key: "deleteRow",
type: "button",
- onClick: () => editor.chain().focus().deleteRow().run(),
+ onClick: () => editor.current?.chain().focus().deleteRow().run(),
});
const deleteTable = (editor: Editor): MenuButton => ({
...getToolDefinition("deleteTable"),
key: "deleteTable",
type: "button",
- onClick: () => editor.chain().focus().deleteTable().run(),
+ onClick: () => editor.current?.chain().focus().deleteTable().run(),
});
const cellProperties = (editor: Editor): MenuButton => ({
diff --git a/packages/editor/src/toolbar/tools/text-direction.tsx b/packages/editor/src/toolbar/tools/text-direction.tsx
index 8765e1ebe..8603fb431 100644
--- a/packages/editor/src/toolbar/tools/text-direction.tsx
+++ b/packages/editor/src/toolbar/tools/text-direction.tsx
@@ -10,7 +10,9 @@ function TextDirectionTool(props: TextDirectionToolProps) {
return (
<ToolButton
{...toolProps}
- onClick={() => editor.chain().focus().setTextDirection(direction).run()}
+ onClick={() =>
+ editor.current?.chain().focus().setTextDirection(direction).run()
+ }
toggled={editor.isActive({ textDirection: direction })}
/>
);
diff --git a/packages/editor/src/toolbar/types.ts b/packages/editor/src/toolbar/types.ts
index ce9ec9613..06b429e7d 100644
--- a/packages/editor/src/toolbar/types.ts
+++ b/packages/editor/src/toolbar/types.ts
@@ -1,4 +1,4 @@
-import { Editor } from "@tiptap/core";
+import { Editor } from "../types";
import { IconNames } from "./icons";
import { ToolId } from "./tools";
diff --git a/packages/editor/src/types.ts b/packages/editor/src/types.ts
new file mode 100644
index 000000000..35436db5f
--- /dev/null
+++ b/packages/editor/src/types.ts
@@ -0,0 +1,9 @@
+import { Editor as TiptapEditor } from "@tiptap/core";
+export interface Editor extends TiptapEditor {
+ /**
+ * Use this to get the latest instance of the editor.
+ * This is required to reduce unnecessary rerenders of
+ * toolbar elements.
+ */
+ current?: TiptapEditor;
+}
diff --git a/packages/editor/tsconfig.json b/packages/editor/tsconfig.json
index 21d316c7d..8551ae6bf 100644
--- a/packages/editor/tsconfig.json
+++ b/packages/editor/tsconfig.json
@@ -102,5 +102,5 @@
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
},
- "include": ["src/"]
+ "include": ["src/", "../notesnook-web/global.d.ts"]
}