Skip to content

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

feat: improve popups & toolbars for mobile

thecodrr43a355ce255f
diff --git a/packages/editor/dist/components/actionsheet/index.d.ts b/packages/editor/dist/components/actionsheet/index.d.ts
new file mode 100644
index 000000000..09b4627e5
--- /dev/null
+++ b/packages/editor/dist/components/actionsheet/index.d.ts
@@ -0,0 +1,11 @@
+import { PropsWithChildren } from "react";
+import { MenuItem } from "../menu/types";
+export declare type ActionSheetPresenterProps = {
+ items?: MenuItem[];
+ isOpen: boolean;
+ onClose?: () => void;
+ blocking?: boolean;
+ focusOnRender?: boolean;
+ title?: string;
+};
+export declare function ActionSheetPresenter(props: PropsWithChildren<ActionSheetPresenterProps>): JSX.Element;
diff --git a/packages/editor/dist/components/actionsheet/index.js b/packages/editor/dist/components/actionsheet/index.js
new file mode 100644
index 000000000..2369788ef
--- /dev/null
+++ b/packages/editor/dist/components/actionsheet/index.js
@@ -0,0 +1,128 @@
+var __assign = (this && this.__assign) || function () {
+ __assign = Object.assign || function(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+};
+var __read = (this && this.__read) || function (o, n) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
+ if (!m) return o;
+ var i = m.call(o), r, ar = [], e;
+ try {
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
+ }
+ catch (error) { e = { error: error }; }
+ finally {
+ try {
+ if (r && !r.done && (m = i["return"])) m.call(i);
+ }
+ finally { if (e) throw e.error; }
+ }
+ return ar;
+};
+import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
+import React, { useCallback, useRef, useState } from "react";
+import { useTheme } from "emotion-theming";
+import Sheet from "react-modal-sheet";
+import { Button, Flex, Text } from "rebass";
+import { Icon } from "../../toolbar/components/icon";
+import { Icons } from "../../toolbar/icons";
+import { MenuButton } from "../menu/menu-button";
+import { MenuSeparator } from "../menu/menu-separator";
+function useHistory(initial) {
+ var _a = __read(useState(initial), 2), current = _a[0], setCurrent = _a[1];
+ var _b = __read(useState(false), 2), canGoBack = _b[0], setCanGoBack = _b[1];
+ var stack = useRef([initial]);
+ var goBack = useCallback(function () {
+ if (!canGoBack)
+ return;
+ var prev = stack.current.pop();
+ setCurrent(prev);
+ if (stack.current.length <= 1)
+ setCanGoBack(false);
+ }, [canGoBack]);
+ var navigate = useCallback(function (state) {
+ console.log("NAVI", state);
+ setCurrent(function (prev) {
+ if (prev)
+ stack.current.push(prev);
+ return state;
+ });
+ setCanGoBack(true);
+ }, []);
+ return { current: current, goBack: goBack, navigate: navigate, canGoBack: canGoBack };
+}
+export function ActionSheetPresenter(props) {
+ var isOpen = props.isOpen, title = props.title, items = props.items, onClose = props.onClose, _a = props.blocking, blocking = _a === void 0 ? true : _a, _b = props.focusOnRender, focusOnRender = _b === void 0 ? true : _b, children = props.children;
+ var theme = useTheme();
+ var contentRef = useRef();
+ var focusedElement = useRef();
+ // hijack the back button temporarily for a more native experience
+ // on mobile phones.
+ var onPopState = useCallback(function (e) {
+ if (onClose) {
+ onClose();
+ e.preventDefault();
+ return true;
+ }
+ }, [isOpen, onClose]);
+ return (_jsxs(Sheet, __assign({ isOpen: isOpen, onClose: onClose || (function () { }), springConfig: {
+ stiffness: 300,
+ damping: 30,
+ mass: 0.2,
+ duration: 300,
+ }, onOpenStart: function () {
+ var _a;
+ window.addEventListener("popstate", onPopState);
+ window.addEventListener("beforeunload", onPopState);
+ if (focusOnRender) {
+ focusedElement.current =
+ document.activeElement || undefined;
+ (_a = contentRef.current) === null || _a === void 0 ? void 0 : _a.focus({ preventScroll: true });
+ }
+ }, onCloseEnd: function () {
+ var _a;
+ window.removeEventListener("popstate", onPopState);
+ window.removeEventListener("beforeunload", onPopState);
+ if (focusOnRender) {
+ (_a = focusedElement.current) === null || _a === void 0 ? void 0 : _a.focus({ preventScroll: true });
+ }
+ } }, { children: [_jsxs(Sheet.Container, __assign({ style: {
+ borderTopLeftRadius: 20,
+ borderTopRightRadius: 20,
+ boxShadow: theme.shadows.menu,
+ } }, { children: [_jsx(Sheet.Header, { disableDrag: !onClose }), _jsxs(Sheet.Content, { children: [_jsx("div", { id: "action-sheet-focus", ref: function (ref) { return (contentRef.current = ref || undefined); }, tabIndex: -1 }), _jsx(ContentContainer, __assign({ items: items, title: title, onClose: onClose }, { children: children }))] })] })), blocking ? (_jsx(Sheet.Backdrop, { style: { border: "none" }, onTap: onClose })) : (_jsx(_Fragment, {}))] })));
+}
+function ContentContainer(props) {
+ var _a;
+ var title = props.title, items = props.items, onClose = props.onClose, children = props.children;
+ var _b = useHistory({
+ title: title,
+ items: items,
+ }), current = _b.current, goBack = _b.goBack, canGoBack = _b.canGoBack, navigate = _b.navigate;
+ return (_jsxs(Flex, __assign({ sx: { flexDirection: "column" } }, { children: [_jsxs(Flex, __assign({ id: "header", sx: { alignItems: "center", mx: 2, mb: 2 } }, { children: [canGoBack && (_jsx(Button, __assign({ variant: "icon", sx: { p: 1, mr: 2 }, onClick: goBack }, { children: _jsx(Icon, { path: Icons.chevronLeft, size: "big" }) }))), (current === null || current === void 0 ? void 0 : current.title) && (_jsx(Text, __assign({ variant: "title", sx: { ml: 1, fontSize: "title" } }, { children: current === null || current === void 0 ? void 0 : current.title })))] })), children
+ ? children
+ : (_a = current === null || current === void 0 ? void 0 : current.items) === null || _a === void 0 ? void 0 : _a.map(function (item) {
+ switch (item.type) {
+ case "separator":
+ return _jsx(MenuSeparator, {}, item.key);
+ case "button":
+ return (_jsx(MenuButton, { item: item, onClick: function (e) {
+ if (item.menu) {
+ navigate(item.menu);
+ }
+ else if (item.onClick) {
+ item.onClick();
+ onClose === null || onClose === void 0 ? void 0 : onClose();
+ }
+ } }, item.key));
+ case "popup":
+ return (_jsx(React.Fragment, { children: _jsx(item.component, { onClick: onClose }) }, item.key));
+ }
+ })] })));
+}
diff --git a/packages/editor/dist/components/inlineinput/index.d.ts b/packages/editor/dist/components/inlineinput/index.d.ts
new file mode 100644
index 000000000..d9936bb07
--- /dev/null
+++ b/packages/editor/dist/components/inlineinput/index.d.ts
@@ -0,0 +1,9 @@
+/// <reference types="react" />
+import { InputProps } from "@rebass/forms";
+import { FlexProps } from "rebass";
+declare type LabelInputProps = InputProps & {
+ label: string;
+ containerProps?: FlexProps;
+};
+export declare function InlineInput(props: LabelInputProps): JSX.Element;
+export {};
diff --git a/packages/editor/dist/components/inlineinput/index.js b/packages/editor/dist/components/inlineinput/index.js
new file mode 100644
index 000000000..9da0383b7
--- /dev/null
+++ b/packages/editor/dist/components/inlineinput/index.js
@@ -0,0 +1,37 @@
+var __assign = (this && this.__assign) || function () {
+ __assign = Object.assign || function(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+};
+var __rest = (this && this.__rest) || function (s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
+ t[p[i]] = s[p[i]];
+ }
+ return t;
+};
+import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
+import { Input } from "@rebass/forms";
+import { Flex, Text } from "rebass";
+export function InlineInput(props) {
+ var label = props.label, containerProps = props.containerProps, sx = props.sx, inputProps = __rest(props, ["label", "containerProps", "sx"]);
+ return (_jsxs(Flex, __assign({}, containerProps, { sx: __assign(__assign({ flex: 1 }, containerProps === null || containerProps === void 0 ? void 0 : containerProps.sx), { outline: "1px solid var(--border)", p: 2, borderRadius: "default", ":focus-within": {
+ outlineColor: "primary",
+ outlineWidth: "1.8px",
+ } }) }, { children: [_jsx(Input, __assign({ variant: "clean", sx: __assign(__assign({}, sx), { p: 0 }) }, inputProps)), _jsx(Text, __assign({ variant: "body", sx: {
+ flexShrink: 0,
+ color: "fontTertiary",
+ borderLeft: "1px solid var(--border)",
+ pl: 1,
+ } }, { children: label }))] })));
+}
diff --git a/packages/editor/dist/components/menu/index.d.ts b/packages/editor/dist/components/menu/index.d.ts
index c6bb7b61b..6af5e4dea 100644
--- a/packages/editor/dist/components/menu/index.d.ts
+++ b/packages/editor/dist/components/menu/index.d.ts
@@ -1 +1,15 @@
-export { MenuPresenter } from "./menu";
+import { PropsWithChildren } from "react";
+import { FlexProps } from "rebass";
+import { MenuItem as MenuItemType } from "./types";
+import { PopupPresenterProps as _PopupPresenterProps } from "../popup-presenter";
+declare type MenuProps = MenuContainerProps & {
+ items?: MenuItemType[];
+ onClose: () => void;
+};
+export declare function Menu(props: MenuProps): JSX.Element;
+declare type MenuContainerProps = FlexProps & {
+ title?: string;
+};
+export declare type MenuPresenterProps = _PopupPresenterProps & MenuProps;
+export declare function MenuPresenter(props: PropsWithChildren<MenuPresenterProps>): JSX.Element;
+export {};
diff --git a/packages/editor/dist/components/menu/index.js b/packages/editor/dist/components/menu/index.js
index c6bb7b61b..b005047eb 100644
--- a/packages/editor/dist/components/menu/index.js
+++ b/packages/editor/dist/components/menu/index.js
@@ -1 +1,122 @@
-export { MenuPresenter } from "./menu";
+var __assign = (this && this.__assign) || function () {
+ __assign = Object.assign || function(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+};
+var __rest = (this && this.__rest) || function (s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
+ t[p[i]] = s[p[i]];
+ }
+ return t;
+};
+import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
+import { useCallback, useRef, useEffect, } from "react";
+import { Box, Flex, Text } from "rebass";
+import { getPosition } from "../../utils/position";
+import { useFocus } from "./use-focus";
+import { MenuSeparator } from "./menu-separator";
+import { MenuButton } from "./menu-button";
+import { PopupPresenter as _PopupPresenter, } from "../popup-presenter";
+export function Menu(props) {
+ var _a = props.items, items = _a === void 0 ? [] : _a, title = props.title, onClose = props.onClose, containerProps = __rest(props, ["items", "title", "onClose"]);
+ var hoverTimeout = useRef();
+ var onAction = useCallback(function (e, item) {
+ e === null || e === void 0 ? void 0 : e.stopPropagation();
+ if (onClose)
+ onClose();
+ if (item.onClick) {
+ item.onClick();
+ }
+ }, [onClose]);
+ var _b = useFocus(items, function (e) {
+ var item = items[focusIndex];
+ if (item)
+ onAction(e, item);
+ }, function () { return onClose(); }), focusIndex = _b.focusIndex, setFocusIndex = _b.setFocusIndex, isSubmenuOpen = _b.isSubmenuOpen, setIsSubmenuOpen = _b.setIsSubmenuOpen;
+ var focusedItem = items[focusIndex];
+ var subMenuRef = useRef(null);
+ useEffect(function () {
+ var item = items[focusIndex];
+ if (!item || !subMenuRef.current)
+ return;
+ var menuItemElement = document.getElementById(item.key);
+ if (!menuItemElement)
+ return;
+ if (!isSubmenuOpen) {
+ subMenuRef.current.style.visibility = "hidden";
+ return;
+ }
+ var _a = getPosition(subMenuRef.current, {
+ // yOffset: menuItemElement.offsetHeight,
+ target: menuItemElement,
+ location: "right",
+ }), top = _a.top, left = _a.left;
+ subMenuRef.current.style.visibility = "visible";
+ subMenuRef.current.style.top = "".concat(top, "px");
+ subMenuRef.current.style.left = "".concat(left, "px");
+ }, [isSubmenuOpen, focusIndex, items]);
+ return (_jsxs(_Fragment, { children: [_jsx(MenuContainer, __assign({}, containerProps, { children: items.map(function (item, index) {
+ switch (item.type) {
+ case "separator":
+ return _jsx(MenuSeparator, {}, item.key);
+ case "button":
+ return (_jsx(MenuButton, { item: item, onClick: function (e) {
+ if (item.menu) {
+ setFocusIndex(index);
+ setIsSubmenuOpen(true);
+ }
+ else
+ onAction(e, item);
+ }, isFocused: focusIndex === index, onMouseEnter: function () {
+ if (item.isDisabled) {
+ setFocusIndex(-1);
+ return;
+ }
+ if (hoverTimeout.current)
+ clearTimeout(hoverTimeout.current);
+ setFocusIndex(index);
+ setIsSubmenuOpen(false);
+ if (item.menu) {
+ hoverTimeout.current = setTimeout(function () {
+ setIsSubmenuOpen(true);
+ }, 500);
+ }
+ }, onMouseLeave: function () {
+ if (hoverTimeout.current)
+ clearTimeout(hoverTimeout.current);
+ } }, item.key));
+ case "popup":
+ return _jsx(item.component, { onClick: function (e) { return onAction(e, item); } });
+ }
+ }) })), (focusedItem === null || focusedItem === void 0 ? void 0 : focusedItem.type) === "button" && (focusedItem === null || focusedItem === void 0 ? void 0 : focusedItem.menu) && isSubmenuOpen && (_jsx(Flex, __assign({ ref: subMenuRef, style: { visibility: "hidden" }, sx: {
+ position: "absolute",
+ } }, { children: _jsx(Menu, { items: focusedItem.menu.items, onClose: onClose }) })))] }));
+}
+function MenuContainer(props) {
+ var children = props.children, title = props.title, sx = props.sx, flexProps = __rest(props, ["children", "title", "sx"]);
+ return (_jsxs(Box, __assign({ className: "menuContainer", as: "ul", tabIndex: -1, sx: __assign({ bg: "background", py: 1, display: "flex", flexDirection: "column", position: "relative", listStyle: "none", padding: 0, margin: 0, borderRadius: "default", boxShadow: "menu", border: "1px solid var(--border)", minWidth: 220 }, sx) }, flexProps, { children: [title && (_jsx(Text, __assign({ sx: {
+ fontFamily: "body",
+ fontSize: "subtitle",
+ color: "primary",
+ py: "8px",
+ px: 3,
+ borderBottom: "1px solid",
+ borderBottomColor: "border",
+ wordWrap: "break-word",
+ } }, { children: title }))), children] })));
+}
+export function MenuPresenter(props) {
+ var _a = props.items, items = _a === void 0 ? [] : _a, restProps = __rest(props, ["items"]);
+ return (_jsx(_PopupPresenter, __assign({}, restProps, { children: props.children ? props.children : _jsx(Menu, __assign({ items: items }, restProps)) })));
+}
diff --git a/packages/editor/dist/components/menu/menu.d.ts b/packages/editor/dist/components/menu/menu.d.ts
deleted file mode 100644
index fd9896f7b..000000000
--- a/packages/editor/dist/components/menu/menu.d.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { PropsWithChildren } from "react";
-import { FlexProps } from "rebass";
-import { MenuOptions } from "./useMenu";
-import { MenuItem as MenuItemType } from "./types";
-declare type MenuProps = MenuContainerProps & {
- items: MenuItemType[];
- closeMenu: () => void;
-};
-export declare function Menu(props: MenuProps): JSX.Element;
-declare type MenuContainerProps = FlexProps & {
- title?: string;
-};
-export declare type PopupType = "sheet" | "menu" | "none";
-export declare type PopupPresenterProps = MenuPresenterProps & ActionSheetPresenterProps & {
- mobile?: PopupType;
- desktop?: PopupType;
-};
-export declare function PopupPresenter(props: PropsWithChildren<PopupPresenterProps>): JSX.Element | null;
-export declare type MenuPresenterProps = MenuContainerProps & {
- items?: MenuItemType[];
- onClose?: () => void;
- isOpen: boolean;
- options?: MenuOptions;
-};
-export declare function MenuPresenter(props: PropsWithChildren<MenuPresenterProps>): JSX.Element;
-export declare type ActionSheetPresenterProps = MenuContainerProps & {
- items?: MenuItemType[];
- isOpen: boolean;
- onClose?: () => void;
- blocking?: boolean;
-};
-export declare function ActionSheetPresenter(props: PropsWithChildren<ActionSheetPresenterProps>): JSX.Element;
-export {};
diff --git a/packages/editor/dist/components/menu/menu.js b/packages/editor/dist/components/menu/menu.js
deleted file mode 100644
index 70029a615..000000000
--- a/packages/editor/dist/components/menu/menu.js
+++ /dev/null
@@ -1,286 +0,0 @@
-var __assign = (this && this.__assign) || function () {
- __assign = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
-var __rest = (this && this.__rest) || function (s, e) {
- var t = {};
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
- t[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
- t[p[i]] = s[p[i]];
- }
- return t;
-};
-var __read = (this && this.__read) || function (o, n) {
- var m = typeof Symbol === "function" && o[Symbol.iterator];
- if (!m) return o;
- var i = m.call(o), r, ar = [], e;
- try {
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
- }
- catch (error) { e = { error: error }; }
- finally {
- try {
- if (r && !r.done && (m = i["return"])) m.call(i);
- }
- finally { if (e) throw e.error; }
- }
- return ar;
-};
-import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
-import { useCallback, useRef, useEffect, useState, } from "react";
-import { Box, Flex, Text } from "rebass";
-import { getPosition } from "./useMenu";
-// import { FlexScrollContainer } from "../scrollcontainer";
-import MenuItem from "./menuitem";
-// import { useMenuTrigger, useMenu, getPosition } from "../../hooks/useMenu";
-import Modal from "react-modal";
-import { useTheme } from "emotion-theming";
-import Sheet from "react-modal-sheet";
-import { useIsMobile } from "../../toolbar/stores/toolbar-store";
-// import { store as selectionStore } from "../../stores/selectionstore";
-function useMenuFocus(items, onAction, onClose) {
- var _a = __read(useState(-1), 2), focusIndex = _a[0], setFocusIndex = _a[1];
- var _b = __read(useState(false), 2), isSubmenuOpen = _b[0], setIsSubmenuOpen = _b[1];
- var moveItemIntoView = useCallback(function (index) {
- var item = items[index];
- if (!item)
- return;
- var element = document.getElementById(item.key);
- if (!element)
- return;
- element.scrollIntoView({
- behavior: "auto",
- });
- }, [items]);
- var onKeyDown = useCallback(function (e) {
- var isSeperator = function (i) { var _a, _b; return items && (((_a = items[i]) === null || _a === void 0 ? void 0 : _a.type) === "seperator" || ((_b = items[i]) === null || _b === void 0 ? void 0 : _b.isDisabled)); };
- var moveDown = function (i) { return (i < items.length - 1 ? ++i : 0); };
- var moveUp = function (i) { return (i > 0 ? --i : items.length - 1); };
- var hasSubmenu = function (i) { var _a; return items && ((_a = items[i]) === null || _a === void 0 ? void 0 : _a.hasSubmenu); };
- var openSubmenu = function (index) {
- if (!hasSubmenu(index))
- return;
- setIsSubmenuOpen(true);
- };
- var closeSubmenu = function (index) {
- if (!hasSubmenu(index))
- return;
- setIsSubmenuOpen(false);
- };
- setFocusIndex(function (i) {
- var nextIndex = i;
- switch (e.key) {
- case "ArrowUp":
- if (isSubmenuOpen)
- break;
- nextIndex = moveUp(i);
- while (isSeperator(nextIndex)) {
- nextIndex = moveUp(nextIndex);
- }
- break;
- case "ArrowDown":
- if (isSubmenuOpen)
- break;
- nextIndex = moveDown(i);
- while (isSeperator(nextIndex)) {
- nextIndex = moveDown(nextIndex);
- }
- break;
- case "ArrowRight":
- openSubmenu(i);
- break;
- case "ArrowLeft":
- closeSubmenu(i);
- break;
- case "Enter":
- onAction && onAction(e);
- break;
- case "Escape":
- onClose && onClose(e);
- break;
- default:
- break;
- }
- if (nextIndex !== i)
- moveItemIntoView(nextIndex);
- return nextIndex;
- });
- }, [items, isSubmenuOpen, moveItemIntoView, onAction]);
- useEffect(function () {
- window.addEventListener("keydown", onKeyDown);
- return function () {
- window.removeEventListener("keydown", onKeyDown);
- };
- }, [onKeyDown]);
- return { focusIndex: focusIndex, setFocusIndex: setFocusIndex, isSubmenuOpen: isSubmenuOpen, setIsSubmenuOpen: setIsSubmenuOpen };
-}
-export function Menu(props) {
- var _a;
- var items = props.items, title = props.title, closeMenu = props.closeMenu, containerProps = __rest(props, ["items", "title", "closeMenu"]);
- var hoverTimeout = useRef();
- var onAction = useCallback(function (e, item) {
- e === null || e === void 0 ? void 0 : e.stopPropagation();
- if (closeMenu)
- closeMenu();
- if (item.onClick) {
- item.onClick();
- }
- }, [closeMenu]);
- var _b = useMenuFocus(items, function (e) {
- var item = items[focusIndex];
- if (item)
- onAction(e, item);
- }, function () { return closeMenu(); }), focusIndex = _b.focusIndex, setFocusIndex = _b.setFocusIndex, isSubmenuOpen = _b.isSubmenuOpen, setIsSubmenuOpen = _b.setIsSubmenuOpen;
- var subMenuRef = useRef(null);
- useEffect(function () {
- var item = items[focusIndex];
- if (!item || !subMenuRef.current)
- return;
- var menuItemElement = document.getElementById(item.key);
- if (!menuItemElement)
- return;
- if (!isSubmenuOpen) {
- subMenuRef.current.style.visibility = "hidden";
- return;
- }
- var _a = getPosition(subMenuRef.current, {
- // yOffset: menuItemElement.offsetHeight,
- target: menuItemElement,
- location: "right",
- }), top = _a.top, left = _a.left;
- subMenuRef.current.style.visibility = "visible";
- subMenuRef.current.style.top = "".concat(top, "px");
- subMenuRef.current.style.left = "".concat(left, "px");
- }, [isSubmenuOpen, focusIndex, items]);
- return (_jsxs(_Fragment, { children: [_jsx(MenuContainer, __assign({}, containerProps, { children: items.map(function (item, index) { return (_jsx(MenuItem, { item: item, onClick: function (e) {
- var _a;
- if ((_a = item.items) === null || _a === void 0 ? void 0 : _a.length) {
- setFocusIndex(index);
- setIsSubmenuOpen(true);
- }
- else
- onAction(e, item);
- }, isFocused: focusIndex === index, onMouseEnter: function () {
- var _a;
- if (item.isDisabled) {
- setFocusIndex(-1);
- return;
- }
- if (hoverTimeout.current)
- clearTimeout(hoverTimeout.current);
- setFocusIndex(index);
- setIsSubmenuOpen(false);
- if ((_a = item.items) === null || _a === void 0 ? void 0 : _a.length) {
- hoverTimeout.current = setTimeout(function () {
- setIsSubmenuOpen(true);
- }, 500);
- }
- }, onMouseLeave: function () {
- if (hoverTimeout.current)
- clearTimeout(hoverTimeout.current);
- } }, item.key)); }) })), isSubmenuOpen && (_jsx(Flex, __assign({ ref: subMenuRef, style: { visibility: "hidden" }, sx: {
- position: "absolute",
- } }, { children: _jsx(Menu, { items: ((_a = items[focusIndex]) === null || _a === void 0 ? void 0 : _a.items) || [], closeMenu: closeMenu }) })))] }));
-}
-function MenuContainer(props) {
- var children = props.children, title = props.title, sx = props.sx, flexProps = __rest(props, ["children", "title", "sx"]);
- return (_jsxs(Box, __assign({ className: "menuContainer", as: "ul", tabIndex: -1, sx: __assign({ bg: "background", py: 1, display: "flex", flexDirection: "column", position: "relative", listStyle: "none", padding: 0, margin: 0, borderRadius: "default", boxShadow: "menu", border: "1px solid var(--border)", minWidth: 220 }, sx) }, flexProps, { children: [title && (_jsx(Text, __assign({ sx: {
- fontFamily: "body",
- fontSize: "subtitle",
- color: "primary",
- py: "8px",
- px: 3,
- borderBottom: "1px solid",
- borderBottomColor: "border",
- wordWrap: "break-word",
- } }, { children: title }))), children] })));
-}
-export function PopupPresenter(props) {
- var _a = props.mobile, mobile = _a === void 0 ? "menu" : _a, _b = props.desktop, desktop = _b === void 0 ? "menu" : _b, restProps = __rest(props, ["mobile", "desktop"]);
- var isMobile = useIsMobile();
- if (isMobile && mobile === "sheet")
- return _jsx(ActionSheetPresenter, __assign({}, restProps));
- else if (mobile === "menu" || desktop === "menu")
- return _jsx(MenuPresenter, __assign({}, restProps));
- else
- return props.isOpen ? _jsx(_Fragment, { children: props.children }) : null;
-}
-export function MenuPresenter(props) {
- var className = props.className, _a = props.options, options = _a === void 0 ? { type: "menu", position: {} } : _a, _b = props.items, items = _b === void 0 ? [] : _b, isOpen = props.isOpen, _c = props.onClose, onClose = _c === void 0 ? function () { } : _c, children = props.children, containerProps = __rest(props, ["className", "options", "items", "isOpen", "onClose", "children"]);
- var position = options.position, type = options.type;
- var isAutocomplete = type === "autocomplete";
- var contentRef = useRef();
- var repositionMenu = useCallback(function (position) {
- if (!contentRef.current || !position)
- return;
- var menu = contentRef.current;
- var menuPosition = getPosition(menu, position);
- menu.style.top = menuPosition.top + "px";
- menu.style.left = menuPosition.left + "px";
- }, []);
- useEffect(function () {
- repositionMenu(position);
- }, [position]);
- useEffect(function () {
- function onWindowResize() {
- repositionMenu(position);
- }
- window.addEventListener("resize", onWindowResize);
- return function () {
- window.removeEventListener("resize", onWindowResize);
- };
- }, [position]);
- return (_jsx(Modal, __assign({ contentRef: function (ref) { return (contentRef.current = ref); }, className: className || "menuContainer", role: "menu", isOpen: isOpen, appElement: document.body, shouldCloseOnEsc: true, shouldReturnFocusAfterClose: true, shouldCloseOnOverlayClick: true, shouldFocusAfterRender: !isAutocomplete, ariaHideApp: !isAutocomplete, preventScroll: !isAutocomplete, onRequestClose: onClose, portalClassName: className || "menuPresenter", onAfterOpen: function (obj) {
- if (!obj || !position)
- return;
- repositionMenu(position);
- }, overlayElement: function (props, contentEl) {
- return (_jsx(Box, __assign({}, props, {
- //@ts-ignore
- style: __assign(__assign({}, props.style), { position: isAutocomplete ? "initial" : "fixed", zIndex: 1000, backgroundColor: isAutocomplete ? "transparent" : "unset" }) }, { children: contentEl })));
- }, contentElement: function (props, children) { return (_jsx(Box, __assign({}, props, { style: {}, sx: {
- top: 0,
- left: 0,
- right: 0,
- bottom: 0,
- display: "flex",
- width: "fit-content",
- height: "fit-content",
- position: "absolute",
- backgroundColor: undefined,
- padding: 0,
- zIndex: 0,
- outline: 0,
- isolation: "isolate",
- } }, { children: children }))); }, style: {
- content: {},
- overlay: {
- zIndex: 999,
- background: "transparent",
- },
- } }, { children: props.children ? (props.children) : (_jsx(Menu, __assign({ items: items, closeMenu: onClose }, containerProps))) })));
-}
-export function ActionSheetPresenter(props) {
- var _a = props.items, items = _a === void 0 ? [] : _a, isOpen = props.isOpen, _b = props.onClose, onClose = _b === void 0 ? function () { } : _b, children = props.children, sx = props.sx, _c = props.blocking, blocking = _c === void 0 ? true : _c, containerProps = __rest(props, ["items", "isOpen", "onClose", "children", "sx", "blocking"]);
- var theme = useTheme();
- return (_jsxs(Sheet, __assign({ isOpen: isOpen, onClose: onClose, springConfig: {
- stiffness: 300,
- damping: 30,
- mass: 0.2,
- duration: 300,
- } }, { children: [_jsxs(Sheet.Container, __assign({ style: {
- borderTopLeftRadius: 20,
- borderTopRightRadius: 20,
- boxShadow: theme.shadows.menu,
- } }, { children: [_jsx(Sheet.Header, {}), _jsx(Sheet.Content, { children: props.children ? (props.children) : (_jsx(Menu, __assign({ items: items, closeMenu: onClose, sx: __assign({ flex: 1, boxShadow: "none", border: "none" }, sx) }, containerProps))) })] })), _jsx(Sheet.Backdrop, { style: { backgroundColor: "transparent", border: "none" }, onTap: onClose })] })));
-}
diff --git a/packages/editor/dist/components/menu/menubutton.d.ts b/packages/editor/dist/components/menu/menubutton.d.ts
new file mode 100644
index 000000000..11b6437af
--- /dev/null
+++ b/packages/editor/dist/components/menu/menubutton.d.ts
@@ -0,0 +1,11 @@
+/// <reference types="react" />
+import { MenuButton } from "./types";
+declare type MenuButtonProps = {
+ item: MenuButton;
+ isFocused?: boolean;
+ onMouseEnter?: () => void;
+ onMouseLeave?: () => void;
+ onClick: (e?: any) => void;
+};
+export declare function MenuButton(props: MenuButtonProps): JSX.Element;
+export {};
diff --git a/packages/editor/dist/components/menu/menubutton.js b/packages/editor/dist/components/menu/menubutton.js
new file mode 100644
index 000000000..11fb5f7fa
--- /dev/null
+++ b/packages/editor/dist/components/menu/menubutton.js
@@ -0,0 +1,34 @@
+var __assign = (this && this.__assign) || function () {
+ __assign = Object.assign || function(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+};
+import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
+import { useRef } from "react";
+import { Flex, Text, Button } from "rebass";
+import { Icon } from "../../toolbar/components/icon";
+import { Icons } from "../../toolbar/icons";
+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;
+ var itemRef = useRef(null);
+ return (_jsx(Flex, __assign({ as: "li", sx: { flexShrink: 0, flexDirection: "column" }, onMouseEnter: onMouseEnter, onMouseLeave: onMouseLeave }, { children: _jsxs(Button, __assign({ id: key, "data-test-id": "MenuButton-".concat(key), ref: itemRef, tabIndex: -1, variant: "menuitem", title: tooltip, disabled: isDisabled, onClick: onClick, sx: {
+ bg: isFocused ? "hover" : "transparent",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ ":hover": {
+ bg: "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: {
+ fontFamily: "body",
+ fontSize: "menu",
+ color: "fontTertiary",
+ } }, { children: modifier })))] }))) : null] }), key) })));
+}
diff --git a/packages/editor/dist/components/menu/menuitem.d.ts b/packages/editor/dist/components/menu/menuitem.d.ts
deleted file mode 100644
index 9348c2448..000000000
--- a/packages/editor/dist/components/menu/menuitem.d.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/// <reference types="react" />
-import { MenuItem } from "./types";
-declare type MenuItemProps = {
- item: MenuItem;
- isFocused: boolean;
- onMouseEnter: () => void;
- onMouseLeave: () => void;
- onClick: (e?: any) => void;
-};
-declare function MenuItem(props: MenuItemProps): JSX.Element;
-export default MenuItem;
diff --git a/packages/editor/dist/components/menu/menuitem.js b/packages/editor/dist/components/menu/menuitem.js
deleted file mode 100644
index d2142d11a..000000000
--- a/packages/editor/dist/components/menu/menuitem.js
+++ /dev/null
@@ -1,45 +0,0 @@
-var __assign = (this && this.__assign) || function () {
- __assign = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
-import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
-// import { Check, ChevronRight, Pro } from "../icons";
-import { useRef } from "react";
-import { Flex, Box, Text, Button } from "rebass";
-import { Icon } from "../../toolbar/components/icon";
-import { Icons } from "../../toolbar/icons";
-function MenuItem(props) {
- var item = props.item, isFocused = props.isFocused, onMouseEnter = props.onMouseEnter, onMouseLeave = props.onMouseLeave, onClick = props.onClick;
- var title = item.title, key = item.key,
- // color,
- icon = item.icon,
- // iconColor,
- type = item.type, tooltip = item.tooltip, isDisabled = item.isDisabled, isChecked = item.isChecked, items = item.items, Component = item.component, modifier = item.modifier;
- var itemRef = useRef(null);
- if (type === "seperator")
- return (_jsx(Box, { as: "li", sx: {
- width: "95%",
- height: "0.5px",
- bg: "border",
- my: 2,
- alignSelf: "center",
- } }, key));
- return (_jsx(Flex, __assign({ as: "li", sx: { flex: 1, flexDirection: "column" }, onMouseEnter: onMouseEnter, onMouseLeave: onMouseLeave }, { children: Component ? (_jsx(Component, { onClick: onClick })) : (_jsxs(Button, __assign({ id: key, "data-test-id": "menuitem-".concat(key), ref: itemRef, tabIndex: -1, variant: "menuitem", title: tooltip, disabled: isDisabled, onClick: onClick, sx: {
- bg: isFocused ? "hover" : "transparent",
- display: "flex",
- alignItems: "center",
- justifyContent: "space-between",
- } }, { 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 }))] }), _jsxs(Flex, { children: [isChecked && _jsx(Icon, { path: Icons.check, size: 14 }), (items === null || items === void 0 ? void 0 : items.length) && _jsx(Icon, { path: Icons.chevronRight, size: 14 }), modifier && (_jsx(Text, __assign({ as: "span", sx: {
- fontFamily: "body",
- fontSize: "menu",
- color: "fontTertiary",
- } }, { children: modifier })))] })] }), key)) })));
-}
-export default MenuItem;
diff --git a/packages/editor/dist/components/menu/menuseparator.d.ts b/packages/editor/dist/components/menu/menuseparator.d.ts
new file mode 100644
index 000000000..14ee7a7d6
--- /dev/null
+++ b/packages/editor/dist/components/menu/menuseparator.d.ts
@@ -0,0 +1,2 @@
+/// <reference types="react" />
+export declare function MenuSeparator(): JSX.Element;
diff --git a/packages/editor/dist/components/menu/menuseparator.js b/packages/editor/dist/components/menu/menuseparator.js
new file mode 100644
index 000000000..8e610c345
--- /dev/null
+++ b/packages/editor/dist/components/menu/menuseparator.js
@@ -0,0 +1,11 @@
+import { jsx as _jsx } from "react/jsx-runtime";
+import { Box } from "rebass";
+export function MenuSeparator() {
+ return (_jsx(Box, { as: "li", sx: {
+ width: "95%",
+ height: "0.5px",
+ bg: "border",
+ my: 2,
+ alignSelf: "center",
+ } }));
+}
diff --git a/packages/editor/dist/components/menu/types.d.ts b/packages/editor/dist/components/menu/types.d.ts
index 843b21a8f..82ecdffe2 100644
--- a/packages/editor/dist/components/menu/types.d.ts
+++ b/packages/editor/dist/components/menu/types.d.ts
@@ -3,19 +3,28 @@ import { IconNames } from "../../toolbar/icons";
declare type MenuItemComponentProps = {
onClick?: (e?: any) => void;
};
-export declare type MenuItem = {
- type: "menuitem" | "seperator";
+export declare type MenuItemTypes = "button" | "separator" | "popup";
+export declare type BaseMenuItem<TType extends MenuItemTypes> = {
+ type: TType;
key: string;
- component?: (props: MenuItemComponentProps) => JSX.Element;
+ isHidden?: boolean;
+};
+export declare type MenuSeperator = BaseMenuItem<"separator">;
+export declare type MenuPopup = BaseMenuItem<"popup"> & {
+ component: (props: MenuItemComponentProps) => JSX.Element;
+};
+export declare type MenuButton = BaseMenuItem<"button"> & {
onClick?: () => void;
- title?: string;
+ title: string;
icon?: IconNames;
tooltip?: string;
isDisabled?: boolean;
- isHidden?: boolean;
isChecked?: boolean;
- hasSubmenu?: boolean;
modifier?: string;
- items?: MenuItem[];
+ menu?: {
+ title: string;
+ items: MenuItem[];
+ };
};
+export declare type MenuItem = MenuButton | MenuSeperator | MenuPopup;
export {};
diff --git a/packages/editor/dist/components/menu/types.js b/packages/editor/dist/components/menu/types.js
index 3c9704885..cb0ff5c3b 100644
--- a/packages/editor/dist/components/menu/types.js
+++ b/packages/editor/dist/components/menu/types.js
@@ -1,20 +1 @@
-// export type ResolverFunction<T, TData> = (
-// data: any,
-// item: MenuItem<TData>
-// ) => T;
-// export type Resolvable<T, TData> = T | ResolverFunction<T, TData>;
-// export type MenuItem<TData> = {
-// type: "menuitem" | "seperator";
-// key: string;
-// component?: Resolvable<(props: any) => JSX.Element, TData>;
-// onClick?: (data: TData, item: MenuItem<TData>) => void;
-// title?: Resolvable<string, TData>;
-// icon?: Resolvable<string, TData>;
-// tooltip?: Resolvable<string, TData>;
-// disabled?: Resolvable<string, TData>;
-// hidden?: Resolvable<boolean, TData>;
-// checked?: Resolvable<boolean, TData>;
-// modifier?: Resolvable<string[], TData>;
-// items?: Resolvable<MenuItem<TData>[], TData>;
-// };
export {};
diff --git a/packages/editor/dist/components/menu/usefocus.d.ts b/packages/editor/dist/components/menu/usefocus.d.ts
new file mode 100644
index 000000000..36b4ee2ca
--- /dev/null
+++ b/packages/editor/dist/components/menu/usefocus.d.ts
@@ -0,0 +1,8 @@
+/// <reference types="react" />
+import { MenuItem } from "./types";
+export declare function useFocus(items: MenuItem[], onAction: (event: KeyboardEvent) => void, onClose: (event: KeyboardEvent) => void): {
+ focusIndex: number;
+ setFocusIndex: import("react").Dispatch<import("react").SetStateAction<number>>;
+ isSubmenuOpen: boolean;
+ setIsSubmenuOpen: import("react").Dispatch<import("react").SetStateAction<boolean>>;
+};
diff --git a/packages/editor/dist/components/menu/usefocus.js b/packages/editor/dist/components/menu/usefocus.js
new file mode 100644
index 000000000..452c61c97
--- /dev/null
+++ b/packages/editor/dist/components/menu/usefocus.js
@@ -0,0 +1,98 @@
+var __read = (this && this.__read) || function (o, n) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
+ if (!m) return o;
+ var i = m.call(o), r, ar = [], e;
+ try {
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
+ }
+ catch (error) { e = { error: error }; }
+ finally {
+ try {
+ if (r && !r.done && (m = i["return"])) m.call(i);
+ }
+ finally { if (e) throw e.error; }
+ }
+ return ar;
+};
+import { useCallback, useEffect, useState } from "react";
+export function useFocus(items, onAction, onClose) {
+ var _a = __read(useState(-1), 2), focusIndex = _a[0], setFocusIndex = _a[1];
+ var _b = __read(useState(false), 2), isSubmenuOpen = _b[0], setIsSubmenuOpen = _b[1];
+ var moveItemIntoView = useCallback(function (index) {
+ var item = items[index];
+ if (!item)
+ return;
+ var element = document.getElementById(item.key);
+ if (!element)
+ return;
+ element.scrollIntoView({
+ behavior: "auto",
+ });
+ }, [items]);
+ var onKeyDown = useCallback(function (e) {
+ var as = function (i) { return items[i]; };
+ var isSeperator = function (i) {
+ var _a, _b;
+ return items &&
+ (((_a = items[i]) === null || _a === void 0 ? void 0 : _a.type) === "separator" || ((_b = as(i)) === null || _b === void 0 ? void 0 : _b.isDisabled));
+ };
+ var moveDown = function (i) { return (i < items.length - 1 ? ++i : 0); };
+ var moveUp = function (i) { return (i > 0 ? --i : items.length - 1); };
+ var hasSubmenu = function (i) { return items && as(i).menu; };
+ var openSubmenu = function (index) {
+ if (!hasSubmenu(index))
+ return;
+ setIsSubmenuOpen(true);
+ };
+ var closeSubmenu = function (index) {
+ if (!hasSubmenu(index))
+ return;
+ setIsSubmenuOpen(false);
+ };
+ setFocusIndex(function (i) {
+ var nextIndex = i;
+ switch (e.key) {
+ case "ArrowUp":
+ if (isSubmenuOpen)
+ break;
+ nextIndex = moveUp(i);
+ while (isSeperator(nextIndex)) {
+ nextIndex = moveUp(nextIndex);
+ }
+ break;
+ case "ArrowDown":
+ if (isSubmenuOpen)
+ break;
+ nextIndex = moveDown(i);
+ while (isSeperator(nextIndex)) {
+ nextIndex = moveDown(nextIndex);
+ }
+ break;
+ case "ArrowRight":
+ openSubmenu(i);
+ break;
+ case "ArrowLeft":
+ closeSubmenu(i);
+ break;
+ case "Enter":
+ onAction && onAction(e);
+ break;
+ case "Escape":
+ onClose && onClose(e);
+ break;
+ default:
+ break;
+ }
+ if (nextIndex !== i)
+ moveItemIntoView(nextIndex);
+ return nextIndex;
+ });
+ }, [items, isSubmenuOpen, moveItemIntoView, onAction]);
+ useEffect(function () {
+ window.addEventListener("keydown", onKeyDown);
+ return function () {
+ window.removeEventListener("keydown", onKeyDown);
+ };
+ }, [onKeyDown]);
+ return { focusIndex: focusIndex, setFocusIndex: setFocusIndex, isSubmenuOpen: isSubmenuOpen, setIsSubmenuOpen: setIsSubmenuOpen };
+}
diff --git a/packages/editor/dist/components/popuppresenter/index.d.ts b/packages/editor/dist/components/popuppresenter/index.d.ts
new file mode 100644
index 000000000..869d13772
--- /dev/null
+++ b/packages/editor/dist/components/popuppresenter/index.d.ts
@@ -0,0 +1,28 @@
+import { PropsWithChildren } from "react";
+import { PositionOptions } from "../../utils/position";
+import { Theme } from "@notesnook/theme";
+import React from "react";
+export declare type PopupPresenterProps = {
+ isOpen: boolean;
+ onClose: () => void;
+ position: PositionOptions;
+ blocking?: boolean;
+ focusOnRender?: boolean;
+ movable?: boolean;
+};
+export declare function PopupPresenter(props: PropsWithChildren<PopupPresenterProps>): JSX.Element;
+export declare type PopupWrapperProps = {
+ id: string;
+ group: string;
+ position: PositionOptions;
+ isOpen: boolean;
+ onClosed?: () => void;
+ renderPopup: (closePopup: () => void) => React.ReactNode;
+} & Partial<Omit<PopupPresenterProps, "onClose">>;
+export declare function PopupWrapper(props: PopupWrapperProps): null;
+declare type ShowPopupOptions = {
+ theme: Theme;
+ popup: (closePopup: () => void) => React.ReactNode;
+} & Partial<PopupPresenterProps>;
+export declare function showPopup(options: ShowPopupOptions): void;
+export {};
diff --git a/packages/editor/dist/components/popuppresenter/index.js b/packages/editor/dist/components/popuppresenter/index.js
new file mode 100644
index 000000000..48c22b5d4
--- /dev/null
+++ b/packages/editor/dist/components/popuppresenter/index.js
@@ -0,0 +1,199 @@
+var __assign = (this && this.__assign) || function () {
+ __assign = Object.assign || function(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+};
+var __rest = (this && this.__rest) || function (s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
+ t[p[i]] = s[p[i]];
+ }
+ return t;
+};
+import { jsx as _jsx } from "react/jsx-runtime";
+import { useCallback, useRef, useEffect, } from "react";
+import { Box } from "rebass";
+import { getPosition } from "../../utils/position";
+import Modal from "react-modal";
+import ReactDOM from "react-dom";
+import { ThemeProvider } from "emotion-theming";
+import { getPopupContainer, getToolbarElement } from "../../toolbar/utils/dom";
+import { useToolbarStore } from "../../toolbar/stores/toolbar-store";
+import { EditorContext, usePopupRenderer, } from "./popuprenderer";
+export function PopupPresenter(props) {
+ var isOpen = props.isOpen, position = props.position, onClose = props.onClose, _a = props.blocking, blocking = _a === void 0 ? true : _a, _b = props.focusOnRender, focusOnRender = _b === void 0 ? true : _b, children = props.children;
+ var contentRef = useRef();
+ var observerRef = useRef();
+ var repositionPopup = useCallback(function (position) {
+ if (!contentRef.current || !position)
+ return;
+ var popup = contentRef.current;
+ var popupPosition = getPosition(popup, position);
+ popup.style.top = popupPosition.top + "px";
+ popup.style.left = popupPosition.left + "px";
+ }, []);
+ useEffect(function () {
+ repositionPopup(position);
+ }, [position]);
+ useEffect(function () {
+ function onWindowResize() {
+ repositionPopup(position);
+ }
+ window.addEventListener("resize", onWindowResize);
+ return function () {
+ window.removeEventListener("resize", onWindowResize);
+ };
+ }, [position]);
+ var attachMoveHandlers = useCallback(function () {
+ if (!contentRef.current || !isOpen)
+ return;
+ var movableBar = contentRef.current.querySelector(".movable");
+ if (!movableBar)
+ return;
+ var popup = contentRef.current;
+ var offset = { x: 0, y: 0 };
+ function mouseDown(e) {
+ offset.x = e.clientX - popup.offsetLeft;
+ offset.y = e.clientY - popup.offsetTop;
+ window.addEventListener("mousemove", mouseMove);
+ }
+ function mouseMove(e) {
+ if (!e.buttons)
+ mouseUp();
+ var top = e.clientY - offset.y;
+ var left = e.clientX - offset.x;
+ requestAnimationFrame(function () {
+ popup.style.top = top + "px";
+ popup.style.left = left + "px";
+ });
+ }
+ function mouseUp() {
+ window.removeEventListener("mousemove", mouseMove);
+ }
+ movableBar.addEventListener("mousedown", mouseDown);
+ window.addEventListener("mouseup", mouseUp);
+ }, [isOpen]);
+ var handleResize = useCallback(function () {
+ var popup = contentRef.current;
+ if (!popup)
+ return;
+ var oldHeight = popup.offsetHeight;
+ observerRef.current = new ResizeObserver(function (e) {
+ var _a = popup.getBoundingClientRect(), height = _a.height, y = _a.y;
+ var delta = height - oldHeight;
+ if (delta > 0) {
+ // means the new size is bigger so we need to adjust the position
+ // if required. We only do this in case the newly resized popup
+ // is going out of the window.
+ var windowHeight = document.body.clientHeight - 20;
+ if (y + height > windowHeight) {
+ popup.style.top = windowHeight - height + "px";
+ }
+ }
+ oldHeight = height;
+ });
+ observerRef.current.observe(popup, { box: "border-box" });
+ }, []);
+ return (_jsx(Modal, __assign({ contentRef: function (ref) { return (contentRef.current = ref); }, className: "popup-presenter", role: "menu", isOpen: isOpen, appElement: document.body, shouldCloseOnEsc: true, shouldReturnFocusAfterClose: true, shouldCloseOnOverlayClick: true, shouldFocusAfterRender: focusOnRender, ariaHideApp: blocking, preventScroll: blocking, onRequestClose: onClose, portalClassName: "popup-presenter-portal", onAfterOpen: function (obj) {
+ if (!obj || !position)
+ return;
+ repositionPopup(position);
+ handleResize();
+ attachMoveHandlers();
+ }, onAfterClose: function () { var _a; return (_a = observerRef.current) === null || _a === void 0 ? void 0 : _a.disconnect(); }, overlayElement: function (props, contentEl) {
+ return (_jsx(Box, __assign({}, props, {
+ //@ts-ignore
+ style: __assign(__assign({}, props.style), { position: !blocking ? "initial" : "fixed", zIndex: 1000, backgroundColor: !blocking ? "transparent" : "unset" }) }, { children: contentEl })));
+ }, contentElement: function (props, children) { return (_jsx(Box, __assign({}, props, { style: {}, sx: {
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ display: "flex",
+ width: "fit-content",
+ height: "fit-content",
+ position: "absolute",
+ backgroundColor: undefined,
+ padding: 0,
+ zIndex: 0,
+ outline: 0,
+ isolation: "isolate",
+ } }, { children: children }))); }, style: {
+ content: {},
+ overlay: {
+ zIndex: 999,
+ background: "transparent",
+ },
+ } }, { children: children })));
+}
+export function PopupWrapper(props) {
+ var id = props.id, group = props.group, position = props.position, renderPopup = props.renderPopup, isOpen = props.isOpen, onClosed = props.onClosed, presenterProps = __rest(props, ["id", "group", "position", "renderPopup", "isOpen", "onClosed"]);
+ var closePopup = useToolbarStore(function (store) { return store.closePopup; });
+ var openPopup = useToolbarStore(function (store) { return store.openPopup; });
+ var closePopupGroup = useToolbarStore(function (store) { return store.closePopupGroup; });
+ var isPopupOpen = useToolbarStore(function (store) { return !!store.openedPopups[id]; });
+ var PopupRenderer = usePopupRenderer();
+ var isBottom = useToolbarStore(function (store) { return store.toolbarLocation === "bottom"; });
+ if (isBottom)
+ group = "popup";
+ useEffect(function () {
+ if (isPopupOpen) {
+ closePopupGroup(group, [id]);
+ }
+ }, [onClosed, isPopupOpen, closePopupGroup, id, group]);
+ useEffect(function () {
+ if (!isPopupOpen)
+ onClosed === null || onClosed === void 0 ? void 0 : onClosed();
+ }, [isPopupOpen]);
+ useEffect(function () {
+ console.log("Opening popup", id, isOpen);
+ if (isOpen)
+ openPopup({ id: id, group: group });
+ else
+ closePopup(id);
+ }, [isOpen, id, group, openPopup]);
+ useEffect(function () {
+ return function () {
+ PopupRenderer === null || PopupRenderer === void 0 ? void 0 : PopupRenderer.closePopup(id);
+ };
+ }, [id]);
+ useEffect(function () {
+ if (PopupRenderer && isPopupOpen) {
+ PopupRenderer.openPopup(id, function () { return (_jsx(PopupPresenter, __assign({ isOpen: isPopupOpen, onClose: function () { return closePopup(id); }, position: position, blocking: true, focusOnRender: true }, presenterProps, { children: _jsx(Box, __assign({ sx: {
+ boxShadow: "menu",
+ borderRadius: "default",
+ overflow: "hidden",
+ // width,
+ } }, { children: _jsx(EditorContext.Consumer, { children: function () {
+ return renderPopup(function () { return PopupRenderer.closePopup(id); });
+ } }) })) }), id)); });
+ }
+ else if (PopupRenderer && !isPopupOpen) {
+ PopupRenderer.closePopup(id);
+ }
+ }, [PopupRenderer, isPopupOpen]);
+ return null;
+}
+export function showPopup(options) {
+ var theme = options.theme, popup = options.popup, props = __rest(options, ["theme", "popup"]);
+ function hide() {
+ ReactDOM.unmountComponentAtNode(getPopupContainer());
+ }
+ ReactDOM.render(_jsx(ThemeProvider, __assign({ theme: theme }, { children: _jsx(PopupPresenter, __assign({ isOpen: true, onClose: hide, position: {
+ target: getToolbarElement(),
+ isTargetAbsolute: true,
+ location: "below",
+ align: "end",
+ yOffset: 10,
+ }, blocking: true, focusOnRender: true }, props, { children: popup(hide) })) })), getPopupContainer());
+}
diff --git a/packages/editor/dist/components/popuppresenter/popuprenderer.d.ts b/packages/editor/dist/components/popuppresenter/popuprenderer.d.ts
new file mode 100644
index 000000000..bafffe0dc
--- /dev/null
+++ b/packages/editor/dist/components/popuppresenter/popuprenderer.d.ts
@@ -0,0 +1,20 @@
+import React, { PropsWithChildren } from "react";
+import { Editor } from "@tiptap/core";
+export declare const PopupRendererContext: React.Context<PopupRenderer | null>;
+export declare const EditorContext: React.Context<Editor | null>;
+export declare type PopupRendererProps = PropsWithChildren<{
+ editor: Editor;
+}>;
+declare type PopupRendererState = {
+ popups: Record<string, React.FunctionComponent>;
+};
+export declare class PopupRenderer extends React.Component<PopupRendererProps> {
+ popupContainer: HTMLDivElement | null;
+ state: PopupRendererState;
+ openPopup(id: string, popup: React.FunctionComponent): void;
+ closePopup(id: string): void;
+ render(): React.ReactNode;
+}
+export declare function usePopupRenderer(): PopupRenderer | null;
+export declare function useEditorContext(): Editor;
+export {};
diff --git a/packages/editor/dist/components/popuppresenter/popuprenderer.js b/packages/editor/dist/components/popuppresenter/popuprenderer.js
new file mode 100644
index 000000000..25cfb0db8
--- /dev/null
+++ b/packages/editor/dist/components/popuppresenter/popuprenderer.js
@@ -0,0 +1,81 @@
+var __extends = (this && this.__extends) || (function () {
+ var extendStatics = function (d, b) {
+ extendStatics = Object.setPrototypeOf ||
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
+ return extendStatics(d, b);
+ };
+ return function (d, b) {
+ if (typeof b !== "function" && b !== null)
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
+ extendStatics(d, b);
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+ };
+})();
+var __assign = (this && this.__assign) || function () {
+ __assign = Object.assign || function(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+};
+var __read = (this && this.__read) || function (o, n) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
+ if (!m) return o;
+ var i = m.call(o), r, ar = [], e;
+ try {
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
+ }
+ catch (error) { e = { error: error }; }
+ finally {
+ try {
+ if (r && !r.done && (m = i["return"])) m.call(i);
+ }
+ finally { if (e) throw e.error; }
+ }
+ return ar;
+};
+import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
+import React, { useContext } from "react";
+export var PopupRendererContext = React.createContext(null);
+export var EditorContext = React.createContext(null);
+var PopupRenderer = /** @class */ (function (_super) {
+ __extends(PopupRenderer, _super);
+ function PopupRenderer() {
+ var _this = _super !== null && _super.apply(this, arguments) || this;
+ _this.popupContainer = null;
+ _this.state = {
+ popups: {},
+ };
+ return _this;
+ }
+ PopupRenderer.prototype.openPopup = function (id, popup) {
+ var _a;
+ this.setState({ popups: __assign(__assign({}, this.state.popups), (_a = {}, _a[id] = popup, _a)) });
+ };
+ PopupRenderer.prototype.closePopup = function (id) {
+ var _a;
+ this.setState({ popups: __assign(__assign({}, this.state.popups), (_a = {}, _a[id] = null, _a)) });
+ };
+ PopupRenderer.prototype.render = function () {
+ return (_jsxs(PopupRendererContext.Provider, __assign({ value: this }, { children: [this.props.children, _jsxs(EditorContext.Provider, __assign({ value: this.props.editor }, { children: [Object.entries(this.state.popups).map(function (_a) {
+ var _b = __read(_a, 2), id = _b[0], Popup = _b[1];
+ if (!Popup)
+ return null;
+ return _jsx(Popup, {}, id);
+ }), _jsx("div", { id: "popup-container" })] }))] })));
+ };
+ return PopupRenderer;
+}(React.Component));
+export { PopupRenderer };
+export function usePopupRenderer() {
+ return useContext(PopupRendererContext);
+}
+export function useEditorContext() {
+ return useContext(EditorContext);
+}
diff --git a/packages/editor/dist/components/responsive/index.d.ts b/packages/editor/dist/components/responsive/index.d.ts
index 309abd87f..f734f5329 100644
--- a/packages/editor/dist/components/responsive/index.d.ts
+++ b/packages/editor/dist/components/responsive/index.d.ts
@@ -1,4 +1,6 @@
import { PropsWithChildren } from "react";
+import { ActionSheetPresenterProps } from "../action-sheet";
+import { MenuPresenterProps } from "../menu";
declare type ResponsiveContainerProps = {
mobile?: JSX.Element;
desktop?: JSX.Element;
@@ -6,4 +8,10 @@ declare type ResponsiveContainerProps = {
export declare function ResponsiveContainer(props: ResponsiveContainerProps): JSX.Element | null;
export declare function DesktopOnly(props: PropsWithChildren<{}>): JSX.Element;
export declare function MobileOnly(props: PropsWithChildren<{}>): JSX.Element;
+export declare type PopupType = "sheet" | "menu" | "none";
+export declare type ResponsivePresenterProps = MenuPresenterProps & ActionSheetPresenterProps & {
+ mobile?: PopupType;
+ desktop?: PopupType;
+};
+export declare function ResponsivePresenter(props: PropsWithChildren<ResponsivePresenterProps>): JSX.Element | null;
export {};
diff --git a/packages/editor/dist/components/responsive/index.js b/packages/editor/dist/components/responsive/index.js
index 7087e0f0d..23b6fa224 100644
--- a/packages/editor/dist/components/responsive/index.js
+++ b/packages/editor/dist/components/responsive/index.js
@@ -1,7 +1,31 @@
+var __assign = (this && this.__assign) || function () {
+ __assign = Object.assign || function(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+};
+var __rest = (this && this.__rest) || function (s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
+ t[p[i]] = s[p[i]];
+ }
+ return t;
+};
import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
-import { useToolbarStore } from "../../toolbar/stores/toolbar-store";
+import { useIsMobile, } from "../../toolbar/stores/toolbar-store";
+import { ActionSheetPresenter, } from "../action-sheet";
+import { MenuPresenter } from "../menu";
export function ResponsiveContainer(props) {
- var isMobile = useToolbarStore(function (store) { return store.isMobile; });
+ var isMobile = useIsMobile();
if (isMobile)
return props.mobile || null;
else
@@ -13,3 +37,13 @@ export function DesktopOnly(props) {
export function MobileOnly(props) {
return _jsx(ResponsiveContainer, { mobile: _jsx(_Fragment, { children: props.children }) });
}
+export function ResponsivePresenter(props) {
+ var _a = props.mobile, mobile = _a === void 0 ? "menu" : _a, _b = props.desktop, desktop = _b === void 0 ? "menu" : _b, restProps = __rest(props, ["mobile", "desktop"]);
+ var isMobile = useIsMobile();
+ if (isMobile && mobile === "sheet")
+ return _jsx(ActionSheetPresenter, __assign({}, restProps));
+ else if (mobile === "menu" || desktop === "menu")
+ return _jsx(MenuPresenter, __assign({}, restProps));
+ else
+ return props.isOpen ? _jsx(_Fragment, { children: props.children }) : null;
+}
diff --git a/packages/editor/dist/components/tabs/index.d.ts b/packages/editor/dist/components/tabs/index.d.ts
new file mode 100644
index 000000000..28e7a9dac
--- /dev/null
+++ b/packages/editor/dist/components/tabs/index.d.ts
@@ -0,0 +1,12 @@
+import React, { PropsWithChildren } from "react";
+import { FlexProps } from "rebass";
+export declare type TabProps = {
+ title: string | React.ReactElement;
+};
+export declare function Tab(props: PropsWithChildren<TabProps>): JSX.Element;
+export declare type TabsProps = {
+ activeIndex: number;
+ containerProps?: FlexProps;
+ onTabChanged?: (index: number) => void;
+};
+export declare function Tabs(props: PropsWithChildren<TabsProps>): JSX.Element;
diff --git a/packages/editor/dist/components/tabs/index.js b/packages/editor/dist/components/tabs/index.js
new file mode 100644
index 000000000..941466ad4
--- /dev/null
+++ b/packages/editor/dist/components/tabs/index.js
@@ -0,0 +1,65 @@
+var __assign = (this && this.__assign) || function () {
+ __assign = Object.assign || function(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+};
+var __read = (this && this.__read) || function (o, n) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
+ if (!m) return o;
+ var i = m.call(o), r, ar = [], e;
+ try {
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
+ }
+ catch (error) { e = { error: error }; }
+ finally {
+ try {
+ if (r && !r.done && (m = i["return"])) m.call(i);
+ }
+ finally { if (e) throw e.error; }
+ }
+ return ar;
+};
+import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
+import React, { Children, useMemo, useState } from "react";
+import { Button, Flex } from "rebass";
+export function Tab(props) {
+ return _jsx(_Fragment, { children: props.children });
+}
+export function Tabs(props) {
+ var activeIndex = props.activeIndex, children = props.children, containerProps = props.containerProps, onTabChanged = props.onTabChanged;
+ var _a = __read(useState(activeIndex || 0), 2), activeTab = _a[0], setActiveTab = _a[1];
+ var tabs = useMemo(function () {
+ return Children.map(children, function (child) {
+ if (React.isValidElement(child))
+ return { title: child.props.title, component: child };
+ });
+ }, [children]);
+ return (_jsxs(Flex, __assign({ sx: { flexDirection: "column" } }, { children: [_jsx(Flex, __assign({ sx: {
+ mb: 1,
+ } }, { children: tabs === null || tabs === void 0 ? void 0 : tabs.map(function (tab, index) { return (_jsx(Button, __assign({ sx: {
+ flex: 1,
+ p: 0,
+ py: 1,
+ borderRadius: 0,
+ borderTopLeftRadius: "default",
+ borderTopRightRadius: "default",
+ bg: activeTab === index ? "bgSecondary" : "transparent",
+ fontWeight: activeTab === index ? "bold" : "normal",
+ color: "text",
+ ":last-of-type": { mr: 0 },
+ borderBottom: "2px solid",
+ borderBottomColor: activeTab === index ? "primary" : "transparent",
+ ":hover": {
+ bg: "hover",
+ },
+ }, onClick: function () {
+ setActiveTab(index);
+ onTabChanged === null || onTabChanged === void 0 ? void 0 : onTabChanged(index);
+ } }, { children: tab.title }), index.toString())); }) })), _jsx(Flex, __assign({}, containerProps, { children: tabs && tabs[activeTab].component }))] })));
+}
diff --git a/packages/editor/dist/extensions/attachment/component.js b/packages/editor/dist/extensions/attachment/component.js
index d2e408281..16aef78e4 100644
--- a/packages/editor/dist/extensions/attachment/component.js
+++ b/packages/editor/dist/extensions/attachment/component.js
@@ -13,7 +13,7 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
import { Box, Flex, Text } from "rebass";
import { ToolButton } from "../../toolbar/components/tool-button";
import { useRef } from "react";
-import { MenuPresenter } from "../../components/menu/menu";
+// import { MenuPresenter } from "../../components/menu/menu";
import { Icon } from "../../toolbar/components/icon";
import { Icons } from "../../toolbar/icons";
export function AttachmentComponent(props) {
@@ -25,44 +25,35 @@ export function AttachmentComponent(props) {
// useEffect(() => {
// setIsToolbarVisible(isActive);
// }, [isActive]);
- return (_jsxs(_Fragment, { children: [_jsxs(Box, __assign({ ref: elementRef, as: "span", contentEditable: false, variant: "body", sx: {
- display: "inline-flex",
- overflow: "hidden",
- position: "relative",
- zIndex: 1,
- userSelect: "none",
- alignItems: "center",
- backgroundColor: "bgSecondary",
- px: 1,
- borderRadius: "default",
- border: "1px solid var(--border)",
- cursor: "pointer",
- maxWidth: 250,
- borderColor: isActive ? "primary" : "border",
- ":hover": {
- bg: "hover",
- },
- }, title: filename }, { children: [_jsx(Icon, { path: Icons.attachment, size: 14 }), _jsx(Text, __assign({ as: "span", sx: {
- ml: "small",
- fontSize: "0.85rem",
- whiteSpace: "nowrap",
- textOverflow: "ellipsis",
- overflow: "hidden",
- }, className: "filename" }, { children: filename })), _jsx(Text, __assign({ as: "span", className: "size", sx: {
- ml: 1,
- fontSize: "subBody",
- color: "fontTertiary",
- flexShrink: 0,
- } }, { children: formatBytes(size) }))] })), _jsx(MenuPresenter, __assign({ isOpen: isActive, onClose: function () { }, items: [], options: {
- type: "autocomplete",
- position: {
- target: elementRef.current || undefined,
- location: "top",
- yOffset: -5,
- isTargetAbsolute: true,
- align: "end",
- },
- } }, { children: _jsx(AttachmentToolbar, { editor: editor }) }))] }));
+ return (_jsx(_Fragment, { children: _jsxs(Box, __assign({ ref: elementRef, as: "span", contentEditable: false, variant: "body", sx: {
+ display: "inline-flex",
+ overflow: "hidden",
+ position: "relative",
+ zIndex: 1,
+ userSelect: "none",
+ alignItems: "center",
+ backgroundColor: "bgSecondary",
+ px: 1,
+ borderRadius: "default",
+ border: "1px solid var(--border)",
+ cursor: "pointer",
+ maxWidth: 250,
+ borderColor: isActive ? "primary" : "border",
+ ":hover": {
+ bg: "hover",
+ },
+ }, title: filename }, { children: [_jsx(Icon, { path: Icons.attachment, size: 14 }), _jsx(Text, __assign({ as: "span", sx: {
+ ml: "small",
+ fontSize: "0.85rem",
+ whiteSpace: "nowrap",
+ textOverflow: "ellipsis",
+ overflow: "hidden",
+ }, className: "filename" }, { children: filename })), _jsx(Text, __assign({ as: "span", className: "size", sx: {
+ ml: 1,
+ fontSize: "subBody",
+ color: "fontTertiary",
+ flexShrink: 0,
+ } }, { children: formatBytes(size) }))] })) }));
}
function formatBytes(bytes, decimals) {
if (decimals === void 0) { decimals = 1; }
diff --git a/packages/editor/dist/extensions/codeblock/component.js b/packages/editor/dist/extensions/codeblock/component.js
index 7fd2e23c2..42a765f77 100644
--- a/packages/editor/dist/extensions/codeblock/component.js
+++ b/packages/editor/dist/extensions/codeblock/component.js
@@ -68,10 +68,11 @@ import { refractor } from "refractor/lib/core";
import "prism-themes/themes/prism-dracula.min.css";
import { Button, Flex, Text } from "rebass";
import Languages from "./languages.json";
-import { PopupPresenter } from "../../components/menu/menu";
import { Input } from "@rebass/forms";
import { Icon } from "../../toolbar/components/icon";
import { Icons } from "../../toolbar/icons";
+import { ResponsivePresenter } from "../../components/responsive";
+import { Popup } from "../../toolbar/components/popup";
export function CodeblockComponent(props) {
var editor = props.editor, updateAttributes = props.updateAttributes, node = props.node, forwardRef = props.forwardRef;
var _a = node === null || node === void 0 ? void 0 : node.attrs, language = _a.language, indentLength = _a.indentLength, indentType = _a.indentType, caretPosition = _a.caretPosition;
@@ -140,57 +141,52 @@ export function CodeblockComponent(props) {
mr: 1,
bg: isOpen ? "codeSelection" : "transparent",
":hover": { bg: "codeSelection" },
- }, onClick: function () { return setIsOpen(true); }, title: "Change language" }, { children: _jsx(Text, __assign({ variant: "subBody", spellCheck: false, sx: { color: "codeFg" } }, { children: (languageDefinition === null || languageDefinition === void 0 ? void 0 : languageDefinition.title) || "Plaintext" })) }))] }))] })), _jsx(PopupPresenter, __assign({ isOpen: isOpen, onClose: function () {
- setIsOpen(false);
- editor.commands.focus();
- }, mobile: "sheet", desktop: "menu", options: {
- type: "menu",
- position: {
- target: toolbarRef.current || undefined,
- align: "end",
- isTargetAbsolute: true,
- location: "top",
- yOffset: 5,
- },
- } }, { children: _jsx(LanguageSelector, { selectedLanguage: (languageDefinition === null || languageDefinition === void 0 ? void 0 : languageDefinition.filename) || "Plaintext", onLanguageSelected: function (language) { return updateAttributes({ language: language }); } }) }))] }));
+ }, onClick: function () { return setIsOpen(true); }, title: "Change language" }, { children: _jsx(Text, __assign({ variant: "subBody", spellCheck: false, sx: { color: "codeFg" } }, { children: (languageDefinition === null || languageDefinition === void 0 ? void 0 : languageDefinition.title) || "Plaintext" })) }))] }))] })), _jsx(ResponsivePresenter, __assign({ isOpen: isOpen, onClose: function () { return setIsOpen(false); }, mobile: "sheet", desktop: "menu", position: {
+ target: toolbarRef.current || undefined,
+ align: "end",
+ isTargetAbsolute: true,
+ location: "top",
+ yOffset: 5,
+ }, title: "Change code block language" }, { children: _jsx(LanguageSelector, { selectedLanguage: (languageDefinition === null || languageDefinition === void 0 ? void 0 : languageDefinition.filename) || "Plaintext", onLanguageSelected: function (language) {
+ updateAttributes({ language: language });
+ setIsOpen(false);
+ }, onClose: function () { return setIsOpen(false); } }) }))] }));
}
function LanguageSelector(props) {
- var onLanguageSelected = props.onLanguageSelected, selectedLanguage = props.selectedLanguage;
+ var onLanguageSelected = props.onLanguageSelected, selectedLanguage = props.selectedLanguage, onClose = props.onClose;
var _a = __read(useState(Languages), 2), languages = _a[0], setLanguages = _a[1];
- return (_jsxs(Flex, __assign({ sx: {
- flexDirection: "column",
- height: 200,
- width: 300,
- boxShadow: "menu",
- borderRadius: "default",
- overflowY: "auto",
- bg: "background",
- marginRight: 2,
- } }, { children: [_jsx(Input, { autoFocus: true, placeholder: "Search languages", sx: {
- width: "auto",
- position: "sticky",
- top: 2,
- bg: "background",
- mx: 2,
- p: "7px",
- }, onChange: function (e) {
- if (!e.target.value)
- return setLanguages(Languages);
- var query = e.target.value.toLowerCase();
- setLanguages(Languages.filter(function (lang) {
- var _a;
- return (lang.title.toLowerCase().indexOf(query) > -1 ||
- ((_a = lang.alias) === null || _a === void 0 ? void 0 : _a.some(function (alias) { return alias.toLowerCase().indexOf(query) > -1; })));
- }));
- } }), _jsx(Flex, __assign({ sx: {
- flexDirection: "column",
- pt: 2,
- mt: 1,
- } }, { children: languages.map(function (lang) { return (_jsxs(Button, __assign({ variant: "menuitem", sx: {
- textAlign: "left",
- py: 1,
- display: "flex",
- justifyContent: "space-between",
- alignItems: "center",
- }, onClick: function () { return onLanguageSelected(lang.filename); } }, { children: [_jsx(Text, __assign({ variant: "body" }, { children: lang.title })), selectedLanguage === lang.filename ? (_jsx(Icon, { path: Icons.check, size: "small" })) : lang.alias ? (_jsx(Text, __assign({ variant: "subBody", sx: { fontSize: "10px" } }, { children: lang.alias.slice(0, 3).join(", ") }))) : null] }))); }) }))] })));
+ return (_jsx(Popup, __assign({ title: "Select language", onClose: onClose }, { children: _jsxs(Flex, __assign({ sx: {
+ flexDirection: "column",
+ height: 200,
+ width: ["auto", 300],
+ overflowY: "auto",
+ bg: "background",
+ } }, { children: [_jsx(Input, { autoFocus: true, placeholder: "Search languages", sx: {
+ width: "auto",
+ position: "sticky",
+ top: 0,
+ bg: "background",
+ mx: 2,
+ p: "7px",
+ zIndex: 999,
+ }, onChange: function (e) {
+ if (!e.target.value)
+ return setLanguages(Languages);
+ var query = e.target.value.toLowerCase();
+ setLanguages(Languages.filter(function (lang) {
+ var _a;
+ return (lang.title.toLowerCase().indexOf(query) > -1 ||
+ ((_a = lang.alias) === null || _a === void 0 ? void 0 : _a.some(function (alias) { return alias.toLowerCase().indexOf(query) > -1; })));
+ }));
+ } }), _jsx(Flex, __assign({ sx: {
+ flexDirection: "column",
+ pt: 1,
+ mt: 1,
+ } }, { children: languages.map(function (lang) { return (_jsxs(Button, __assign({ variant: "menuitem", sx: {
+ textAlign: "left",
+ py: 1,
+ display: "flex",
+ justifyContent: "space-between",
+ alignItems: "center",
+ }, onClick: function () { return onLanguageSelected(lang.filename); } }, { children: [_jsx(Text, __assign({ variant: "body" }, { children: lang.title })), selectedLanguage === lang.filename ? (_jsx(Icon, { path: Icons.check, size: "small" })) : lang.alias ? (_jsx(Text, __assign({ variant: "subBody", sx: { fontSize: "10px" } }, { children: lang.alias.slice(0, 3).join(", ") }))) : null] }), lang.title)); }) }))] })) })));
}
diff --git a/packages/editor/dist/extensions/embed/component.d.ts b/packages/editor/dist/extensions/embed/component.d.ts
index 6e14c0ab6..65b1ee648 100644
--- a/packages/editor/dist/extensions/embed/component.d.ts
+++ b/packages/editor/dist/extensions/embed/component.d.ts
@@ -1,4 +1,4 @@
/// <reference types="react" />
import { EmbedAlignmentOptions, EmbedAttributes } from "./embed";
-import { ReactNodeViewProps } from "../react";
-export declare function EmbedComponent(props: ReactNodeViewProps<EmbedAttributes & EmbedAlignmentOptions>): JSX.Element;
+import { SelectionBasedReactNodeViewProps } from "../react";
+export declare function EmbedComponent(props: SelectionBasedReactNodeViewProps<EmbedAttributes & EmbedAlignmentOptions>): JSX.Element;
diff --git a/packages/editor/dist/extensions/embed/component.js b/packages/editor/dist/extensions/embed/component.js
index 0f370c7d0..240d9af68 100644
--- a/packages/editor/dist/extensions/embed/component.js
+++ b/packages/editor/dist/extensions/embed/component.js
@@ -29,19 +29,13 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
import { Box, Flex } from "rebass";
import { Resizable } from "re-resizable";
import { ToolButton } from "../../toolbar/components/tool-button";
-import { useEffect, useRef, useState } from "react";
-import { PopupPresenter } from "../../components/menu/menu";
+import { useRef, useState } from "react";
import { EmbedPopup } from "../../toolbar/popups/embed-popup";
+import { ResponsivePresenter } from "../../components/responsive";
export function EmbedComponent(props) {
- var _a = props.node.attrs, src = _a.src, width = _a.width, height = _a.height, align = _a.align;
- var editor = props.editor, updateAttributes = props.updateAttributes;
+ var editor = props.editor, updateAttributes = props.updateAttributes, selected = props.selected, node = props.node;
var embedRef = useRef();
- var isActive = editor.isActive("embed", { src: src });
- var _b = __read(useState(), 2), isToolbarVisible = _b[0], setIsToolbarVisible = _b[1];
- var theme = editor.storage.theme;
- useEffect(function () {
- setIsToolbarVisible(isActive);
- }, [isActive]);
+ var _a = node.attrs, src = _a.src, width = _a.width, height = _a.height, align = _a.align;
return (_jsx(_Fragment, { children: _jsx(Box, __assign({ sx: {
display: "flex",
justifyContent: align === "center" ? "center" : align === "left" ? "start" : "end",
@@ -60,12 +54,12 @@ export function EmbedComponent(props) {
// borderLeft: "20px solid var(--bgSecondary)",
borderTopLeftRadius: "default",
borderTopRightRadius: "default",
- borderColor: isActive ? "border" : "bgSecondary",
+ borderColor: selected ? "border" : "bgSecondary",
cursor: "pointer",
":hover": {
borderColor: "border",
},
- } }, { children: isToolbarVisible && (_jsx(EmbedToolbar, { editor: editor, align: align, height: height || 0, width: width || 0, src: src })) })), _jsx(Box, __assign({ as: "iframe", ref: embedRef, src: src, width: "100%", height: "100%", sx: {
+ } }, { children: selected && (_jsx(EmbedToolbar, { editor: editor, align: align, height: height || 0, width: width || 0, src: src })) })), _jsx(Box, __assign({ as: "iframe", ref: embedRef, src: src, width: "100%", height: "100%", sx: {
border: "none",
// border: isActive
// ? "2px solid var(--primary)"
@@ -76,7 +70,8 @@ export function EmbedComponent(props) {
function EmbedToolbar(props) {
var editor = props.editor, height = props.height, width = props.width, src = props.src;
var _a = __read(useState(false), 2), isOpen = _a[0], setIsOpen = _a[1];
- return (_jsxs(Flex, __assign({ sx: {
+ var ref = useRef();
+ return (_jsxs(Flex, __assign({ ref: ref, sx: {
flexDirection: "column",
position: "absolute",
top: -40,
@@ -109,5 +104,11 @@ function EmbedToolbar(props) {
mr: 1,
borderRight: "1px solid var(--border)",
":last-of-type": { mr: 0, pr: 0, borderRight: "none" },
- } }, { children: _jsx(ToolButton, { toggled: isOpen, title: "Embed properties", id: "embedProperties", icon: "more", onClick: function () { return setIsOpen(function (s) { return !s; }); } }) }))] })), _jsx(PopupPresenter, __assign({ isOpen: isOpen, desktop: "none", mobile: "sheet", onClose: function () { return setIsOpen(false); }, blocking: true }, { children: _jsx(EmbedPopup, { title: "Embed properties", icon: "close", onClose: function () { return setIsOpen(false); }, embed: props, onSourceChanged: function (src) { }, onSizeChanged: function (size) { return editor.commands.setEmbedSize(size); } }) }))] })));
+ } }, { children: _jsx(ToolButton, { toggled: isOpen, title: "Embed properties", id: "embedProperties", icon: "more", 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: {
+ target: ref.current || "mouse",
+ align: "start",
+ location: "below",
+ yOffset: 10,
+ isTargetAbsolute: true,
+ } }, { children: _jsx(EmbedPopup, { title: "Embed properties", onClose: function () { return setIsOpen(false); }, embed: props, onSourceChanged: function (src) { }, onSizeChanged: function (size) { return editor.commands.setEmbedSize(size); } }) }))] })));
}
diff --git a/packages/editor/dist/extensions/embed/embed.js b/packages/editor/dist/extensions/embed/embed.js
index 3dcea2686..b2c6e7c3a 100644
--- a/packages/editor/dist/extensions/embed/embed.js
+++ b/packages/editor/dist/extensions/embed/embed.js
@@ -10,7 +10,7 @@ var __assign = (this && this.__assign) || function () {
return __assign.apply(this, arguments);
};
import { Node, mergeAttributes } from "@tiptap/core";
-import { createNodeView } from "../react";
+import { createSelectionBasedNodeView, NodeViewSelectionNotifierPlugin, } from "../react";
import { EmbedComponent } from "./component";
export var EmbedNode = Node.create({
name: "embed",
@@ -49,8 +49,11 @@ export var EmbedNode = Node.create({
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
];
},
+ addProseMirrorPlugins: function () {
+ return [NodeViewSelectionNotifierPlugin];
+ },
addNodeView: function () {
- return createNodeView(EmbedComponent);
+ return createSelectionBasedNodeView(EmbedComponent);
},
addCommands: function () {
var _this = this;
diff --git a/packages/editor/dist/extensions/image/component.d.ts b/packages/editor/dist/extensions/image/component.d.ts
index dddb30e41..0ae7c84cd 100644
--- a/packages/editor/dist/extensions/image/component.d.ts
+++ b/packages/editor/dist/extensions/image/component.d.ts
@@ -1,4 +1,4 @@
/// <reference types="react" />
import { ImageAlignmentOptions, ImageAttributes } from "./image";
-import { ReactNodeViewProps } from "../react";
-export declare function ImageComponent(props: ReactNodeViewProps<ImageAttributes & ImageAlignmentOptions>): JSX.Element;
+import { SelectionBasedReactNodeViewProps } from "../react";
+export declare function ImageComponent(props: SelectionBasedReactNodeViewProps<ImageAttributes & ImageAlignmentOptions>): JSX.Element;
diff --git a/packages/editor/dist/extensions/image/component.js b/packages/editor/dist/extensions/image/component.js
index 88eb598db..d5151a082 100644
--- a/packages/editor/dist/extensions/image/component.js
+++ b/packages/editor/dist/extensions/image/component.js
@@ -29,20 +29,14 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
import { Box, Flex, Image } from "rebass";
import { Resizable } from "re-resizable";
import { ToolButton } from "../../toolbar/components/tool-button";
-import { useEffect, useRef, useState } from "react";
-import { PopupPresenter } from "../../components/menu/menu";
-import { Popup } from "../../toolbar/components/popup";
+import { useRef, useState } from "react";
+import { ResponsivePresenter } from "../../components/responsive";
import { ImageProperties } from "../../toolbar/popups/image-properties";
+import { Popup } from "../../toolbar/components/popup";
export function ImageComponent(props) {
- var _a = props.node.attrs, src = _a.src, alt = _a.alt, title = _a.title, width = _a.width, height = _a.height, align = _a.align, float = _a.float;
- var editor = props.editor, updateAttributes = props.updateAttributes;
+ var editor = props.editor, updateAttributes = props.updateAttributes, node = props.node, selected = props.selected;
+ var _a = node.attrs, src = _a.src, alt = _a.alt, title = _a.title, width = _a.width, height = _a.height, align = _a.align, float = _a.float;
var imageRef = useRef();
- var isActive = editor.isActive("image", { src: src });
- var _b = __read(useState(), 2), isToolbarVisible = _b[0], setIsToolbarVisible = _b[1];
- var theme = editor.storage.theme;
- useEffect(function () {
- setIsToolbarVisible(isActive);
- }, [isActive]);
return (_jsx(_Fragment, { children: _jsx(Box, __assign({ sx: {
display: float ? "block" : "flex",
justifyContent: float
@@ -62,8 +56,8 @@ export function ImageComponent(props) {
width: ref.clientWidth,
height: ref.clientHeight,
});
- }, lockAspectRatio: true }, { children: [_jsx(Flex, __assign({ sx: { position: "relative", justifyContent: "end" } }, { children: isToolbarVisible && (_jsx(ImageToolbar, { editor: editor, float: float, align: align, height: height || 0, width: width || 0 })) })), _jsx(Image, __assign({ ref: imageRef, src: src, alt: alt, title: title, width: "100%", height: "100%", sx: {
- border: isActive
+ }, lockAspectRatio: true }, { children: [selected && (_jsx(Flex, __assign({ sx: { position: "relative", justifyContent: "end" } }, { children: _jsx(ImageToolbar, { editor: editor, float: float, align: align, height: height || 0, width: width || 0 }) }))), _jsx(Image, __assign({ ref: imageRef, src: src, alt: alt, title: title, width: "100%", height: "100%", sx: {
+ border: selected
? "2px solid var(--primary)"
: "2px solid transparent",
borderRadius: "default",
@@ -72,7 +66,8 @@ export function ImageComponent(props) {
function ImageToolbar(props) {
var editor = props.editor, float = props.float, height = props.height, width = props.width;
var _a = __read(useState(false), 2), isOpen = _a[0], setIsOpen = _a[1];
- return (_jsxs(Flex, __assign({ sx: {
+ var ref = useRef();
+ return (_jsxs(Flex, __assign({ ref: ref, sx: {
flexDirection: "column",
position: "absolute",
top: -40,
@@ -105,10 +100,13 @@ function ImageToolbar(props) {
mr: 1,
borderRight: "1px solid var(--border)",
":last-of-type": { mr: 0, pr: 0, borderRight: "none" },
- } }, { children: _jsx(ToolButton, { toggled: isOpen, title: "Image properties", id: "imageProperties", icon: "more", onClick: function () { return setIsOpen(function (s) { return !s; }); } }) }))] })), _jsx(PopupPresenter, __assign({ mobile: "sheet", desktop: "none", isOpen: isOpen, onClose: function () { return setIsOpen(false); }, blocking: false }, { children: _jsx(Popup, __assign({ title: "Image properties", action: {
- icon: "close",
- onClick: function () {
- setIsOpen(false);
- },
+ } }, { children: _jsx(ToolButton, { toggled: isOpen, title: "Image properties", id: "imageProperties", icon: "more", 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: {
+ target: ref.current || "mouse",
+ align: "start",
+ location: "below",
+ yOffset: 10,
+ isTargetAbsolute: true,
+ } }, { children: _jsx(Popup, __assign({ title: "Image properties", onClose: function () {
+ setIsOpen(false);
} }, { children: _jsx(ImageProperties, __assign({}, props)) })) }))] })));
}
diff --git a/packages/editor/dist/extensions/image/image.js b/packages/editor/dist/extensions/image/image.js
index 99181b0a8..f072fea9f 100644
--- a/packages/editor/dist/extensions/image/image.js
+++ b/packages/editor/dist/extensions/image/image.js
@@ -26,7 +26,7 @@ var __read = (this && this.__read) || function (o, n) {
return ar;
};
import { Node, nodeInputRule, mergeAttributes } from "@tiptap/core";
-import { createNodeView } from "../react";
+import { createSelectionBasedNodeView, NodeViewSelectionNotifierPlugin, } from "../react";
import { ImageComponent } from "./component";
export var inputRegex = /(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/;
export var ImageNode = Node.create({
@@ -81,7 +81,10 @@ export var ImageNode = Node.create({
];
},
addNodeView: function () {
- return createNodeView(ImageComponent);
+ return createSelectionBasedNodeView(ImageComponent);
+ },
+ addProseMirrorPlugins: function () {
+ return [NodeViewSelectionNotifierPlugin];
},
addCommands: function () {
var _this = this;
diff --git a/packages/editor/dist/extensions/outlinelist/outlinelistitem.d.ts b/packages/editor/dist/extensions/outlinelist/outlinelistitem.d.ts
deleted file mode 100644
index 301a3af7d..000000000
--- a/packages/editor/dist/extensions/outlinelist/outlinelistitem.d.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { Node } from "@tiptap/core";
-export interface ListItemOptions {
- HTMLAttributes: Record<string, any>;
-}
-export declare const OutlineListItem: Node<ListItemOptions, any>;
diff --git a/packages/editor/dist/extensions/outlinelist/outlinelistitem.js b/packages/editor/dist/extensions/outlinelist/outlinelistitem.js
deleted file mode 100644
index 95efbeb62..000000000
--- a/packages/editor/dist/extensions/outlinelist/outlinelistitem.js
+++ /dev/null
@@ -1,39 +0,0 @@
-import { Node, mergeAttributes } from "@tiptap/core";
-import { onBackspacePressed } from "../list-item/commands";
-export var OutlineListItem = Node.create({
- name: "outlineListItem",
- addOptions: function () {
- return {
- HTMLAttributes: {},
- };
- },
- content: "paragraph block*",
- defining: true,
- parseHTML: function () {
- return [
- {
- tag: "ul[data-list-type=\"outline\"] > li",
- },
- ];
- },
- renderHTML: function (_a) {
- var HTMLAttributes = _a.HTMLAttributes;
- return [
- "li",
- mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
- 0,
- ];
- },
- addKeyboardShortcuts: function () {
- var _this = this;
- return {
- Enter: function () { return _this.editor.commands.splitListItem(_this.name); },
- Tab: function () { return _this.editor.commands.sinkListItem(_this.name); },
- "Shift-Tab": function () { return _this.editor.commands.liftListItem(_this.name); },
- Backspace: function (_a) {
- var editor = _a.editor;
- return onBackspacePressed(editor, _this.name, _this.type);
- },
- };
- },
-});
diff --git a/packages/editor/dist/extensions/react/plugin.d.ts b/packages/editor/dist/extensions/react/plugin.d.ts
index db477afb4..6fcf944a9 100644
--- a/packages/editor/dist/extensions/react/plugin.d.ts
+++ b/packages/editor/dist/extensions/react/plugin.d.ts
@@ -8,6 +8,4 @@ export declare class ReactNodeViewState {
notifyNewSelection(fromPos: number, toPos: number): void;
}
export declare const stateKey: PluginKey<any>;
-export declare const plugin: Plugin<ReactNodeViewState>;
-declare const plugins: () => Plugin<ReactNodeViewState>[];
-export default plugins;
+export declare const NodeViewSelectionNotifierPlugin: Plugin<ReactNodeViewState>;
diff --git a/packages/editor/dist/extensions/react/plugin.js b/packages/editor/dist/extensions/react/plugin.js
index 0d5b73052..3559110ac 100644
--- a/packages/editor/dist/extensions/react/plugin.js
+++ b/packages/editor/dist/extensions/react/plugin.js
@@ -17,7 +17,7 @@ var ReactNodeViewState = /** @class */ (function () {
}());
export { ReactNodeViewState };
export var stateKey = new PluginKey("reactNodeView");
-export var plugin = new Plugin({
+export var NodeViewSelectionNotifierPlugin = new Plugin({
state: {
init: function () {
return new ReactNodeViewState();
@@ -37,5 +37,3 @@ export var plugin = new Plugin({
};
},
});
-var plugins = function () { return [plugin]; };
-export default plugins;
diff --git a/packages/editor/dist/extensions/react/reactportalprovider.d.ts b/packages/editor/dist/extensions/react/reactportalprovider.d.ts
index b3df1ee34..62e1d0f5c 100644
--- a/packages/editor/dist/extensions/react/reactportalprovider.d.ts
+++ b/packages/editor/dist/extensions/react/reactportalprovider.d.ts
@@ -23,7 +23,7 @@ export declare class PortalProvider extends React.Component<BasePortalProviderPr
static displayName: string;
portalProviderAPI: PortalProviderAPI;
constructor(props: BasePortalProviderProps);
- render(): React.ReactChild | JSX.Element | null;
+ render(): JSX.Element | React.ReactChild | null;
componentDidUpdate(): void;
}
export declare class PortalRenderer extends React.Component<{
diff --git a/packages/editor/dist/toolbar/components/counter.d.ts b/packages/editor/dist/toolbar/components/counter.d.ts
new file mode 100644
index 000000000..1cf4a9015
--- /dev/null
+++ b/packages/editor/dist/toolbar/components/counter.d.ts
@@ -0,0 +1,9 @@
+/// <reference types="react" />
+export declare type CounterProps = {
+ title: string;
+ onIncrease: () => void;
+ onDecrease: () => void;
+ onReset: () => void;
+ value: string;
+};
+export declare function Counter(props: CounterProps): JSX.Element;
diff --git a/packages/editor/dist/toolbar/components/counter.js b/packages/editor/dist/toolbar/components/counter.js
new file mode 100644
index 000000000..a4063471e
--- /dev/null
+++ b/packages/editor/dist/toolbar/components/counter.js
@@ -0,0 +1,24 @@
+var __assign = (this && this.__assign) || function () {
+ __assign = Object.assign || function(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+};
+import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
+import { Flex, Text } from "rebass";
+import { ToolButton } from "./tool-button";
+export 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",
+ mr: 1,
+ ":last-of-type": {
+ mr: 0,
+ },
+ } }, { children: [_jsx(ToolButton, { toggled: false, title: "Decrease ".concat(title), icon: "minus", variant: "small", onClick: onDecrease }), _jsx(Text, __assign({ variant: "body", sx: { fontSize: "subBody", mx: 1, textAlign: "center" }, title: "Reset ".concat(title), onClick: onReset }, { children: value })), _jsx(ToolButton, { toggled: false, title: "Increase ".concat(title), icon: "plus", variant: "small", onClick: onIncrease })] })));
+}
diff --git a/packages/editor/dist/toolbar/components/dropdown.js b/packages/editor/dist/toolbar/components/dropdown.js
index ffc78e618..17a7543a8 100644
--- a/packages/editor/dist/toolbar/components/dropdown.js
+++ b/packages/editor/dist/toolbar/components/dropdown.js
@@ -30,13 +30,16 @@ import { useRef, useState } from "react";
import { Button, Text } from "rebass";
import { Icon } from "./icon";
import { Icons } from "../icons";
-import { MenuPresenter } from "../../components/menu/menu";
-import { useToolbarLocation } from "../stores/toolbar-store";
+import { useIsMobile, useToolbarLocation } from "../stores/toolbar-store";
+import { MenuPresenter } from "../../components/menu";
+import { getToolbarElement } from "../utils/dom";
export function Dropdown(props) {
var items = props.items, selectedItem = props.selectedItem, buttonRef = props.buttonRef, menuWidth = props.menuWidth;
var internalRef = useRef();
var _a = __read(useState(false), 2), isOpen = _a[0], setIsOpen = _a[1];
var toolbarLocation = useToolbarLocation();
+ var isMobile = useIsMobile();
+ var isBottom = toolbarLocation === "bottom";
return (_jsxs(_Fragment, { children: [_jsxs(Button, __assign({ ref: function (ref) {
internalRef.current = ref;
if (buttonRef)
@@ -52,13 +55,19 @@ export function Dropdown(props) {
":last-of-type": {
mr: 0,
},
- }, onClick: function () { return setIsOpen(function (s) { return !s; }); }, onMouseDown: function (e) { return e.preventDefault(); } }, { children: [typeof selectedItem === "string" ? (_jsx(Text, __assign({ sx: { fontSize: "subBody", mr: 1, color: "text" } }, { children: selectedItem }))) : (selectedItem), _jsx(Icon, { path: toolbarLocation === "bottom" ? Icons.chevronUp : Icons.chevronDown, size: "small", color: "text" })] })), _jsx(MenuPresenter, { options: {
- type: "menu",
- position: {
- target: internalRef.current || undefined,
- isTargetAbsolute: true,
- location: toolbarLocation === "bottom" ? "top" : "below",
- yOffset: 5,
- },
- }, isOpen: isOpen, items: items, onClose: function () { return setIsOpen(false); }, sx: { minWidth: menuWidth } })] }));
+ }, onClick: function () { return setIsOpen(function (s) { return !s; }); }, onMouseDown: function (e) { return e.preventDefault(); } }, { children: [typeof selectedItem === "string" ? (_jsx(Text, __assign({ sx: { fontSize: "subBody", mr: 1, color: "text" } }, { children: selectedItem }))) : (selectedItem), _jsx(Icon, { path: isBottom ? Icons.chevronUp : Icons.chevronDown, size: "small", color: "text" })] })), _jsx(MenuPresenter, { isOpen: isOpen, items: items, onClose: function () { return setIsOpen(false); }, position: {
+ target: isBottom
+ ? getToolbarElement()
+ : internalRef.current || "mouse",
+ isTargetAbsolute: true,
+ location: isBottom ? "top" : "below",
+ align: "center",
+ yOffset: 5,
+ }, blocking: !isMobile, focusOnRender: !isMobile, sx: {
+ minWidth: menuWidth,
+ maxWidth: isBottom ? "95vw" : "auto",
+ p: isBottom ? 1 : 0,
+ flexDirection: isBottom ? "row" : "column",
+ overflowX: isBottom ? "auto" : "hidden",
+ } })] }));
}
diff --git a/packages/editor/dist/toolbar/components/moretools.d.ts b/packages/editor/dist/toolbar/components/moretools.d.ts
new file mode 100644
index 000000000..76d87de17
--- /dev/null
+++ b/packages/editor/dist/toolbar/components/moretools.d.ts
@@ -0,0 +1,9 @@
+/// <reference types="react" />
+import { ToolProps } from "../types";
+import { ToolId } from "../tools";
+declare type MoreToolsProps = ToolProps & {
+ popupId: string;
+ tools: ToolId[];
+};
+export declare function MoreTools(props: MoreToolsProps): JSX.Element;
+export {};
diff --git a/packages/editor/dist/toolbar/components/moretools.js b/packages/editor/dist/toolbar/components/moretools.js
new file mode 100644
index 000000000..903cf7d18
--- /dev/null
+++ b/packages/editor/dist/toolbar/components/moretools.js
@@ -0,0 +1,56 @@
+var __assign = (this && this.__assign) || function () {
+ __assign = Object.assign || function(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+};
+var __read = (this && this.__read) || function (o, n) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
+ if (!m) return o;
+ var i = m.call(o), r, ar = [], e;
+ try {
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
+ }
+ catch (error) { e = { error: error }; }
+ finally {
+ try {
+ if (r && !r.done && (m = i["return"])) m.call(i);
+ }
+ finally { if (e) throw e.error; }
+ }
+ return ar;
+};
+import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
+import { useRef, useState } from "react";
+import { PopupWrapper } from "../../components/popup-presenter";
+import { ToolButton } from "../components/tool-button";
+import { useToolbarLocation } from "../stores/toolbar-store";
+import { getToolbarElement } from "../utils/dom";
+import { ToolbarGroup } from "./toolbar-group";
+export function MoreTools(props) {
+ var popupId = props.popupId, editor = props.editor, tools = props.tools;
+ var toolbarLocation = useToolbarLocation();
+ var isBottom = toolbarLocation === "bottom";
+ var buttonRef = useRef();
+ var _a = __read(useState(false), 2), isOpen = _a[0], setIsOpen = _a[1];
+ return (_jsxs(_Fragment, { children: [_jsx(ToolButton, __assign({}, props, { toggled: isOpen, buttonRef: buttonRef, onMouseDown: function (e) { return e.preventDefault(); }, onClick: function () { return setIsOpen(function (s) { return !s; }); } })), _jsx(PopupWrapper, { isOpen: isOpen, group: "toolbarGroup", id: popupId, onClosed: function () { return setIsOpen(false); }, position: {
+ isTargetAbsolute: true,
+ target: isBottom ? getToolbarElement() : buttonRef.current || "mouse",
+ align: "center",
+ location: isBottom ? "top" : "below",
+ yOffset: isBottom ? 10 : 5,
+ }, focusOnRender: false, blocking: false, renderPopup: function () { return (_jsx(ToolbarGroup, { tools: tools, editor: editor, sx: {
+ flex: 1,
+ p: 1,
+ boxShadow: "menu",
+ bg: "background",
+ borderRadius: "default",
+ overflowX: "auto",
+ maxWidth: "95vw",
+ } })); } })] }));
+}
diff --git a/packages/editor/dist/toolbar/components/popup.d.ts b/packages/editor/dist/toolbar/components/popup.d.ts
index 2f5082aec..efb36e4e5 100644
--- a/packages/editor/dist/toolbar/components/popup.d.ts
+++ b/packages/editor/dist/toolbar/components/popup.d.ts
@@ -1,17 +1,6 @@
-import { ButtonProps } from "rebass";
-import { IconNames } from "../icons";
import { PropsWithChildren } from "react";
-import { SchemeColors } from "@notesnook/theme/dist/theme/colorscheme";
export declare type PopupProps = {
title?: string;
- action?: PopupButtonProps;
+ onClose: () => void;
};
export declare function Popup(props: PropsWithChildren<PopupProps>): JSX.Element;
-declare type PopupButtonProps = ButtonProps & {
- text?: string;
- loading?: boolean;
- icon?: IconNames;
- iconSize?: number;
- iconColor?: keyof SchemeColors;
-};
-export {};
diff --git a/packages/editor/dist/toolbar/components/popup.js b/packages/editor/dist/toolbar/components/popup.js
index 608217705..4c57b3efb 100644
--- a/packages/editor/dist/toolbar/components/popup.js
+++ b/packages/editor/dist/toolbar/components/popup.js
@@ -9,37 +9,26 @@ var __assign = (this && this.__assign) || function () {
};
return __assign.apply(this, arguments);
};
-var __rest = (this && this.__rest) || function (s, e) {
- var t = {};
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
- t[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
- t[p[i]] = s[p[i]];
- }
- return t;
-};
-import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
+import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { Button, Flex, Text } from "rebass";
import { Icon } from "./icon";
import { Icons } from "../icons";
+import { DesktopOnly, MobileOnly } from "../../components/responsive";
export function Popup(props) {
- var title = props.title, action = props.action, children = props.children;
- return (_jsxs(Flex, __assign({ sx: {
- bg: "background",
- flexDirection: "column",
- // borderRadius: "default",
- // border: "1px solid var(--border)",
- // boxShadow: "menu",
- } }, { children: [title && (_jsxs(Flex, __assign({ sx: {
- justifyContent: "space-between",
- alignItems: "center",
- mx: 1,
- mt: 1,
- } }, { children: [_jsx(Text, __assign({ variant: "subtitle" }, { children: title })), action && (_jsx(PopupButton, __assign({ "data-test-id": "popup-no", color: "text" }, action)))] }))), children] })));
-}
-function PopupButton(props) {
- var text = props.text, loading = props.loading, icon = props.icon, iconColor = props.iconColor, iconSize = props.iconSize, restProps = __rest(props, ["text", "loading", "icon", "iconColor", "iconSize"]);
- return (_jsx(Button, __assign({ variant: "icon", sx: { p: 1, px: 2 } }, restProps, { children: loading ? (_jsx(Icon, { path: Icons.loading, size: 16, rotate: true, color: "primary" })) : icon ? (_jsx(Icon, { path: Icons[icon], size: iconSize || 18, color: iconColor || "icon" })) : (text) })));
+ var title = props.title, onClose = props.onClose, children = props.children;
+ return (_jsxs(_Fragment, { children: [_jsx(DesktopOnly, { children: _jsxs(Flex, __assign({ sx: {
+ overflow: "hidden",
+ bg: "background",
+ flexDirection: "column",
+ borderRadius: "default",
+ // border: "1px solid var(--border)",
+ boxShadow: "menu",
+ minWidth: 200,
+ } }, { children: [_jsxs(Flex, __assign({ className: "movable", sx: {
+ bg: "bgSecondary",
+ justifyContent: "space-between",
+ alignItems: "center",
+ p: 1,
+ mb: 1,
+ } }, { children: [_jsx(Text, __assign({ variant: "body" }, { children: title })), _jsx(Button, __assign({ variant: "tool", sx: { p: 0, bg: "transparent" }, onClick: onClose }, { children: _jsx(Icon, { path: Icons.close, size: 16 }) }))] })), children] })) }), _jsx(MobileOnly, { children: children })] }));
}
diff --git a/packages/editor/dist/toolbar/components/splitbutton.d.ts b/packages/editor/dist/toolbar/components/splitbutton.d.ts
index 3df3edd5b..b6877ad0a 100644
--- a/packages/editor/dist/toolbar/components/splitbutton.d.ts
+++ b/packages/editor/dist/toolbar/components/splitbutton.d.ts
@@ -1,8 +1,6 @@
import { PropsWithChildren } from "react";
import { ToolButtonProps } from "./tool-button";
-import { PopupPresenterProps } from "../../components/menu/menu";
-declare type SplitButtonProps = ToolButtonProps & {
- popupPresenterProps?: Partial<PopupPresenterProps>;
+export declare type SplitButtonProps = ToolButtonProps & {
+ onOpen: () => void;
};
export declare function SplitButton(props: PropsWithChildren<SplitButtonProps>): JSX.Element;
-export {};
diff --git a/packages/editor/dist/toolbar/components/splitbutton.js b/packages/editor/dist/toolbar/components/splitbutton.js
index 03636b396..88f24575a 100644
--- a/packages/editor/dist/toolbar/components/splitbutton.js
+++ b/packages/editor/dist/toolbar/components/splitbutton.js
@@ -20,55 +20,28 @@ var __rest = (this && this.__rest) || function (s, e) {
}
return t;
};
-var __read = (this && this.__read) || function (o, n) {
- var m = typeof Symbol === "function" && o[Symbol.iterator];
- if (!m) return o;
- var i = m.call(o), r, ar = [], e;
- try {
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
- }
- catch (error) { e = { error: error }; }
- finally {
- try {
- if (r && !r.done && (m = i["return"])) m.call(i);
- }
- finally { if (e) throw e.error; }
- }
- return ar;
-};
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
-import { useRef, useState } from "react";
+import { useRef } from "react";
import { Button, Flex } from "rebass";
import { Icons } from "../icons";
import { Icon } from "./icon";
import { ToolButton } from "./tool-button";
-import { PopupPresenter, } from "../../components/menu/menu";
import { useToolbarLocation } from "../stores/toolbar-store";
export function SplitButton(props) {
- var popupPresenterProps = props.popupPresenterProps, children = props.children, toolButtonProps = __rest(props, ["popupPresenterProps", "children"]);
- var _a = __read(useState(false), 2), isOpen = _a[0], setIsOpen = _a[1];
+ var children = props.children, toggled = props.toggled, onOpen = props.onOpen, toolButtonProps = __rest(props, ["children", "toggled", "onOpen"]);
var ref = useRef(null);
var toolbarLocation = useToolbarLocation();
return (_jsxs(_Fragment, { children: [_jsxs(Flex, __assign({ ref: ref, sx: {
borderRadius: "default",
- bg: isOpen ? "hover" : "transparent",
+ bg: toggled ? "hover" : "transparent",
":hover": { bg: "hover" },
- } }, { children: [_jsx(ToolButton, __assign({}, toolButtonProps)), _jsx(Button, __assign({ sx: {
+ } }, { children: [_jsx(ToolButton, __assign({}, toolButtonProps, { toggled: toggled })), _jsx(Button, __assign({ sx: {
p: 0,
m: 0,
- bg: "transparent",
+ bg: toggled ? "hover" : "transparent",
":hover": { bg: "hover" },
":last-of-type": {
mr: 0,
},
- }, onClick: function () { return setIsOpen(function (s) { return !s; }); }, onMouseDown: function (e) { return e.preventDefault(); } }, { children: _jsx(Icon, { path: toolbarLocation === "bottom" ? Icons.chevronUp : Icons.chevronDown, color: "text", size: "small" }) }))] })), _jsx(PopupPresenter, __assign({ isOpen: isOpen, onClose: function () { return setIsOpen(false); }, options: {
- type: "menu",
- position: {
- target: ref.current || undefined,
- isTargetAbsolute: true,
- location: toolbarLocation === "bottom" ? "top" : "below",
- yOffset: 5,
- align: "center",
- },
- }, items: [] }, popupPresenterProps, { children: children }))] }));
+ }, onClick: onOpen, onMouseDown: function (e) { return e.preventDefault(); } }, { children: _jsx(Icon, { path: toolbarLocation === "bottom" ? Icons.chevronUp : Icons.chevronDown, color: "text", size: "small" }) }))] })), children] }));
}
diff --git a/packages/editor/dist/toolbar/components/toolbargroup.d.ts b/packages/editor/dist/toolbar/components/toolbargroup.d.ts
new file mode 100644
index 000000000..40eb720b3
--- /dev/null
+++ b/packages/editor/dist/toolbar/components/toolbargroup.d.ts
@@ -0,0 +1,9 @@
+/// <reference types="react" />
+import { ToolbarGroupDefinition } from "../types";
+import { FlexProps } from "rebass";
+import { Editor } from "@tiptap/core";
+export declare type ToolbarGroupProps = FlexProps & {
+ tools: ToolbarGroupDefinition;
+ editor: Editor;
+};
+export declare function ToolbarGroup(props: ToolbarGroupProps): JSX.Element;
diff --git a/packages/editor/dist/toolbar/components/toolbargroup.js b/packages/editor/dist/toolbar/components/toolbargroup.js
new file mode 100644
index 000000000..c7c0eff6b
--- /dev/null
+++ b/packages/editor/dist/toolbar/components/toolbargroup.js
@@ -0,0 +1,42 @@
+var __assign = (this && this.__assign) || function () {
+ __assign = Object.assign || function(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+};
+var __rest = (this && this.__rest) || function (s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
+ t[p[i]] = s[p[i]];
+ }
+ return t;
+};
+import { jsx as _jsx } from "react/jsx-runtime";
+import { findTool } from "../tools";
+import { Flex } from "rebass";
+import { MoreTools } from "./more-tools";
+import { getToolDefinition } from "../tool-definitions";
+export function ToolbarGroup(props) {
+ var tools = props.tools, editor = props.editor, flexProps = __rest(props, ["tools", "editor"]);
+ return (_jsx(Flex, __assign({ className: "toolbar-group" }, flexProps, { children: tools.map(function (toolId) {
+ if (Array.isArray(toolId)) {
+ return (_jsx(MoreTools, { title: "More", icon: "more", popupId: toolId.join(""), tools: toolId, editor: editor }, "more-tools"));
+ }
+ else {
+ var Component = findTool(toolId);
+ var toolDefinition = getToolDefinition(toolId);
+ if (toolId === "textColor")
+ console.log("Rendering", toolId);
+ return (_jsx(Component, __assign({ editor: editor }, toolDefinition), toolDefinition.title));
+ }
+ }) })));
+}
diff --git a/packages/editor/dist/toolbar/components/toolbutton.js b/packages/editor/dist/toolbar/components/toolbutton.js
index 7454167c0..2ceb0a7a1 100644
--- a/packages/editor/dist/toolbar/components/toolbutton.js
+++ b/packages/editor/dist/toolbar/components/toolbutton.js
@@ -26,7 +26,7 @@ import { Icons } from "../icons";
import { Icon } from "./icon";
export 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"]);
- return (_jsx(Button, __assign({ ref: buttonRef, tabIndex: -1, id: "tool-".concat(id), sx: __assign({ p: variant === "small" ? "small" : 1, borderRadius: variant === "small" ? "small" : "default", m: 0, bg: toggled ? "hover" : "transparent", mr: variant === "small" ? 0 : 1, ":hover": { bg: "hover" }, ":last-of-type": {
+ return (_jsx(Button, __assign({ ref: buttonRef, tabIndex: -1, id: "tool-".concat(id), 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: "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" }) })));
}
diff --git a/packages/editor/dist/toolbar/floatingmenus/searchreplace.d.ts b/packages/editor/dist/toolbar/floatingmenus/searchreplace.d.ts
index 78197e973..aa18f7a1a 100644
--- a/packages/editor/dist/toolbar/floatingmenus/searchreplace.d.ts
+++ b/packages/editor/dist/toolbar/floatingmenus/searchreplace.d.ts
@@ -1,3 +1,2 @@
-/// <reference types="react" />
import { FloatingMenuProps } from "./types";
-export declare function SearchReplaceFloatingMenu(props: FloatingMenuProps): JSX.Element | null;
+export declare function SearchReplaceFloatingMenu(props: FloatingMenuProps): null;
diff --git a/packages/editor/dist/toolbar/floatingmenus/searchreplace.js b/packages/editor/dist/toolbar/floatingmenus/searchreplace.js
index 87ab7dfe7..23b13f4da 100644
--- a/packages/editor/dist/toolbar/floatingmenus/searchreplace.js
+++ b/packages/editor/dist/toolbar/floatingmenus/searchreplace.js
@@ -1,29 +1,29 @@
-var __assign = (this && this.__assign) || function () {
- __assign = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
-import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
-import { PopupPresenter, } from "../../components/menu/menu";
-import { SearchReplacePopup } from "../popups/search-replace";
export function SearchReplaceFloatingMenu(props) {
var editor = props.editor;
var isSearching = editor.storage.searchreplace.isSearching;
if (!isSearching)
return null;
- return (_jsx(_Fragment, { children: _jsx(PopupPresenter, __assign({ mobile: "sheet", desktop: "menu", isOpen: true, onClose: function () { return editor.commands.endSearch(); }, options: {
- type: "autocomplete",
- position: {
- target: document.querySelector(".editor-toolbar") || "mouse",
- isTargetAbsolute: true,
- location: "below",
- align: "end",
- },
- } }, { children: _jsx(SearchReplacePopup, { editor: editor }) })) }));
+ return null;
+ // return (
+ // <>
+ // <PopupPresenter
+ // mobile="sheet"
+ // desktop="menu"
+ // isOpen
+ // onClose={() => editor.commands.endSearch()}
+ // options={{
+ // type: "autocomplete",
+ // position: {
+ // target:
+ // document.querySelector<HTMLElement>(".editor-toolbar") || "mouse",
+ // isTargetAbsolute: true,
+ // location: "below",
+ // align: "end",
+ // },
+ // }}
+ // >
+ // <SearchReplacePopup editor={editor} />
+ // </PopupPresenter>
+ // </>
+ // );
}
diff --git a/packages/editor/dist/toolbar/floatingmenus/table/table.js b/packages/editor/dist/toolbar/floatingmenus/table/table.js
index 03695e410..583bdac14 100644
--- a/packages/editor/dist/toolbar/floatingmenus/table/table.js
+++ b/packages/editor/dist/toolbar/floatingmenus/table/table.js
@@ -28,10 +28,11 @@ var __read = (this && this.__read) || function (o, n) {
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useState } from "react";
import { Flex } from "rebass";
-import { MenuPresenter } from "../../../components/menu/menu";
-import { ColumnProperties, InsertColumnRight, InsertRowBelow, RowProperties, } from "./tools";
-import { getToolbarElement } from "../../utils/dom";
import { useToolbarLocation } from "../../stores/toolbar-store";
+import { PopupPresenter } from "../../../components/popup-presenter";
+import { getToolbarElement } from "../../utils/dom";
+import { InsertColumnRight, InsertRowBelow, RowProperties, TableProperties, } from "../../tools/table";
+import { getToolDefinition } from "../../tool-definitions";
export function TableRowFloatingMenu(props) {
var editor = props.editor;
// const theme = editor.storage.theme as Theme;
@@ -64,10 +65,7 @@ export function TableRowFloatingMenu(props) {
}, [editor.state.selection]);
if (!position)
return null;
- return (_jsx(MenuPresenter, __assign({ isOpen: true, items: [], onClose: function () { }, options: {
- type: "autocomplete",
- position: position,
- } }, { children: _jsxs(Flex, __assign({ sx: {
+ return (_jsx(PopupPresenter, __assign({ isOpen: true, blocking: false, focusOnRender: false, onClose: function () { }, position: position }, { children: _jsxs(Flex, __assign({ sx: {
bg: "background",
flexWrap: "nowrap",
borderRadius: "default",
@@ -75,7 +73,7 @@ export function TableRowFloatingMenu(props) {
":hover": {
opacity: 1,
},
- } }, { children: [_jsx(RowProperties, { title: "Row properties", editor: editor, variant: "small", icon: "more" }), _jsx(InsertRowBelow, { title: "Insert row below", icon: "insertRowBelow", editor: editor, variant: "small" })] })) })));
+ } }, { children: [_jsx(RowProperties, __assign({}, getToolDefinition("rowProperties"), { icon: "more", variant: "small", editor: editor })), _jsx(InsertRowBelow, __assign({}, getToolDefinition("insertRowBelow"), { editor: editor, variant: "small" }))] })) })));
}
export function TableColumnFloatingMenu(props) {
var editor = props.editor;
@@ -110,10 +108,7 @@ export function TableColumnFloatingMenu(props) {
}, [editor.state.selection]);
if (!position)
return null;
- return (_jsx(MenuPresenter, __assign({ isOpen: true, items: [], onClose: function () { }, options: {
- type: "autocomplete",
- position: position,
- } }, { children: _jsxs(Flex, __assign({ sx: {
+ return (_jsx(PopupPresenter, __assign({ isOpen: true, onClose: function () { }, blocking: false, position: position, focusOnRender: false }, { children: _jsxs(Flex, __assign({ sx: {
bg: "background",
flexWrap: "nowrap",
borderRadius: "default",
@@ -122,21 +117,18 @@ export function TableColumnFloatingMenu(props) {
":hover": {
opacity: 1,
},
- } }, { children: [_jsx(ColumnProperties, { currentCell: position.target, title: "Column properties", editor: editor, icon: "more", variant: "small" }), _jsx(InsertColumnRight, { editor: editor, title: "Insert column right", variant: "small", icon: "plus" })] })) })));
+ } }, { children: [_jsx(TableProperties, { editor: editor, title: "tableProperties", icon: "more", variant: "small" }), _jsx(InsertColumnRight, __assign({}, getToolDefinition("insertColumnRight"), { editor: editor, variant: "small", icon: "plus" }))] })) })));
}
export function TableFloatingMenu(props) {
var editor = props.editor;
var toolbarLocation = useToolbarLocation();
if (!editor.isActive("table"))
return null;
- return (_jsx(MenuPresenter, __assign({ isOpen: true, items: [], onClose: function () { }, options: {
- type: "autocomplete",
- position: {
- isTargetAbsolute: true,
- target: getToolbarElement(),
- location: toolbarLocation === "bottom" ? "top" : "below",
- },
- } }, { children: _jsxs(Flex, __assign({ sx: {
+ return (_jsx(PopupPresenter, __assign({ isOpen: true, onClose: function () { }, blocking: false, position: {
+ isTargetAbsolute: true,
+ target: getToolbarElement(),
+ location: toolbarLocation === "bottom" ? "top" : "below",
+ }, focusOnRender: false }, { children: _jsx(Flex, { sx: {
bg: "background",
flexWrap: "nowrap",
borderRadius: "default",
@@ -145,5 +137,5 @@ export function TableFloatingMenu(props) {
":hover": {
opacity: 1,
},
- } }, { children: [_jsx(RowProperties, { title: "Row properties", editor: editor, variant: "normal", icon: "rowProperties" }), _jsx(InsertRowBelow, { title: "Insert row below", icon: "insertRowBelow", editor: editor, variant: "normal" }), _jsx(ColumnProperties, { title: "Column properties", editor: editor, icon: "columnProperties", variant: "normal" }), _jsx(InsertColumnRight, { editor: editor, title: "Insert column right", variant: "normal", icon: "insertColumnRight" })] })) })));
+ } }) })));
}
diff --git a/packages/editor/dist/toolbar/floatingmenus/table/tools.d.ts b/packages/editor/dist/toolbar/floatingmenus/table/tools.d.ts
deleted file mode 100644
index ff7bd737e..000000000
--- a/packages/editor/dist/toolbar/floatingmenus/table/tools.d.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-/// <reference types="react" />
-import { ToolButtonProps } from "../../components/tool-button";
-import { ToolProps } from "../../types";
-declare type TableToolProps = ToolProps & {
- variant: ToolButtonProps["variant"];
-};
-export declare function RowProperties(props: TableToolProps): JSX.Element;
-export declare function InsertRowBelow(props: TableToolProps): JSX.Element;
-declare type ColumnPropertiesProps = TableToolProps & {
- currentCell?: HTMLElement;
-};
-export declare function ColumnProperties(props: ColumnPropertiesProps): JSX.Element;
-export declare function InsertColumnRight(props: TableToolProps): JSX.Element;
-export {};
diff --git a/packages/editor/dist/toolbar/floatingmenus/table/tools.js b/packages/editor/dist/toolbar/floatingmenus/table/tools.js
deleted file mode 100644
index 5510ac2e0..000000000
--- a/packages/editor/dist/toolbar/floatingmenus/table/tools.js
+++ /dev/null
@@ -1,242 +0,0 @@
-var __assign = (this && this.__assign) || function () {
- __assign = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-var __generator = (this && this.__generator) || function (thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
-};
-var __rest = (this && this.__rest) || function (s, e) {
- var t = {};
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
- t[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
- t[p[i]] = s[p[i]];
- }
- return t;
-};
-var __read = (this && this.__read) || function (o, n) {
- var m = typeof Symbol === "function" && o[Symbol.iterator];
- if (!m) return o;
- var i = m.call(o), r, ar = [], e;
- try {
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
- }
- catch (error) { e = { error: error }; }
- finally {
- try {
- if (r && !r.done && (m = i["return"])) m.call(i);
- }
- finally { if (e) throw e.error; }
- }
- return ar;
-};
-var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
- if (ar || !(i in from)) {
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
- ar[i] = from[i];
- }
- }
- return to.concat(ar || Array.prototype.slice.call(from));
-};
-import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
-import { useState } from "react";
-import { MenuPresenter, PopupPresenter, } from "../../../components/menu/menu";
-import { ToolButton } from "../../components/tool-button";
-import { CellProperties } from "../../popups/cell-properties";
-import { moveColumnLeft, moveColumnRight, moveRowDown, moveRowUp, } from "./actions";
-export function RowProperties(props) {
- var editor = props.editor, toolProps = __rest(props, ["editor"]);
- var _a = __read(useState(false), 2), isMenuOpen = _a[0], setIsMenuOpen = _a[1];
- return (_jsxs(_Fragment, { children: [_jsx(ToolButton, __assign({ toggled: isMenuOpen }, toolProps, { onClick: function () { return setIsMenuOpen(true); } })), _jsx(MenuPresenter, { isOpen: isMenuOpen, onClose: function () {
- setIsMenuOpen(false);
- editor.commands.focus();
- }, options: {
- type: "menu",
- position: {},
- }, items: [
- {
- key: "addRowAbove",
- type: "menuitem",
- title: "Add row above",
- onClick: function () { return editor.chain().focus().addRowBefore().run(); },
- icon: "insertRowAbove",
- },
- {
- key: "moveRowUp",
- type: "menuitem",
- title: "Move row up",
- onClick: function () { return moveRowUp(editor); },
- icon: "moveRowUp",
- },
- {
- key: "moveRowDown",
- type: "menuitem",
- title: "Move row down",
- onClick: function () { return moveRowDown(editor); },
- icon: "moveRowDown",
- },
- {
- key: "deleteRow",
- type: "menuitem",
- title: "Delete row",
- onClick: function () { return editor.chain().focus().deleteRow().run(); },
- icon: "deleteRow",
- },
- ] })] }));
-}
-export function InsertRowBelow(props) {
- var editor = props.editor, toolProps = __rest(props, ["editor"]);
- return (_jsx(ToolButton, __assign({ toggled: false }, toolProps, { onClick: function () { return editor.chain().focus().addRowAfter().run(); } })));
-}
-export function ColumnProperties(props) {
- var _this = this;
- var editor = props.editor, currentCell = props.currentCell, toolProps = __rest(props, ["editor", "currentCell"]);
- var _a = __read(useState(false), 2), isMenuOpen = _a[0], setIsMenuOpen = _a[1];
- var isInsideCellSelection = !editor.state.selection.empty &&
- editor.state.selection.$anchor.node().type.name === "tableCell";
- var _b = __read(useState(false), 2), showCellProps = _b[0], setShowCellProps = _b[1];
- var _c = __read(useState(null), 2), menuPosition = _c[0], setMenuPosition = _c[1];
- var columnProperties = [
- {
- key: "addColumnLeft",
- type: "menuitem",
- title: "Add column left",
- onClick: function () { return editor.chain().focus().addColumnBefore().run(); },
- icon: "insertColumnLeft",
- },
- {
- key: "addColumnRight",
- type: "menuitem",
- title: "Add column right",
- onClick: function () { return editor.chain().focus().addColumnAfter().run(); },
- icon: "insertColumnRight",
- },
- {
- key: "moveColumnLeft",
- type: "menuitem",
- title: "Move column left",
- onClick: function () { return moveColumnLeft(editor); },
- icon: "moveColumnLeft",
- },
- {
- key: "moveColumnRight",
- type: "menuitem",
- title: "Move column right",
- onClick: function () { return moveColumnRight(editor); },
- icon: "moveColumnRight",
- },
- {
- key: "deleteColumn",
- type: "menuitem",
- title: "Delete column",
- onClick: function () { return editor.chain().focus().deleteColumn().run(); },
- icon: "deleteColumn",
- },
- ];
- var mergeSplitProperties = [
- {
- key: "splitCells",
- type: "menuitem",
- title: "Split cells",
- onClick: function () { return editor.chain().focus().splitCell().run(); },
- icon: "splitCells",
- },
- {
- key: "mergeCells",
- type: "menuitem",
- title: "Merge cells",
- onClick: function () { return editor.chain().focus().mergeCells().run(); },
- icon: "mergeCells",
- },
- ];
- var cellProperties = [
- {
- key: "cellProperties",
- type: "menuitem",
- title: "Cell properties",
- onClick: function () {
- setShowCellProps(true);
- setMenuPosition({
- target: currentCell || undefined,
- isTargetAbsolute: true,
- yOffset: 10,
- location: "below",
- });
- },
- icon: "cellProperties",
- },
- ];
- var tableProperties = [
- {
- key: "deleteTable",
- type: "menuitem",
- title: "Delete table",
- icon: "deleteTable",
- onClick: function () { return editor.chain().focus().deleteTable().run(); },
- },
- ];
- return (_jsxs(_Fragment, { children: [_jsx(ToolButton, __assign({ toggled: isMenuOpen }, toolProps, { onClick: function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
- return [2 /*return*/, setIsMenuOpen(true)];
- }); }); } })), _jsx(PopupPresenter, { isOpen: isMenuOpen, onClose: function () {
- setIsMenuOpen(false);
- editor.commands.focus();
- }, mobile: "sheet", items: isInsideCellSelection
- ? __spreadArray(__spreadArray([], __read(mergeSplitProperties), false), __read(cellProperties), false) : __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read(columnProperties), false), [
- { type: "seperator", key: "cellSeperator" }
- ], false), __read(cellProperties), false), [
- { type: "seperator", key: "tableSeperator" }
- ], false), __read(tableProperties), false) }), _jsx(PopupPresenter, __assign({ isOpen: showCellProps, onClose: function () {
- setShowCellProps(false);
- editor.commands.focus();
- }, options: {
- type: "menu",
- position: menuPosition || {},
- }, mobile: "sheet" }, { children: _jsx(CellProperties, { editor: editor, onClose: function () { return setShowCellProps(false); } }) }))] }));
-}
-export function InsertColumnRight(props) {
- var editor = props.editor, toolProps = __rest(props, ["editor"]);
- return (_jsx(ToolButton, __assign({}, toolProps, { toggled: false, onClick: function () { return editor.chain().focus().addColumnAfter().run(); } })));
-}
diff --git a/packages/editor/dist/toolbar/hooks/useToolbarContext.d.ts b/packages/editor/dist/toolbar/hooks/useToolbarContext.d.ts
deleted file mode 100644
index 3ab7ab463..000000000
--- a/packages/editor/dist/toolbar/hooks/useToolbarContext.d.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import React from "react";
-export declare const ToolbarContext: React.Context<{
- currentPopup?: string | undefined;
- setCurrentPopup?: React.Dispatch<React.SetStateAction<string | undefined>> | undefined;
-}>;
-export declare function useToolbarContext(): {
- currentPopup?: string | undefined;
- setCurrentPopup?: React.Dispatch<React.SetStateAction<string | undefined>> | undefined;
-};
diff --git a/packages/editor/dist/toolbar/hooks/useToolbarContext.js b/packages/editor/dist/toolbar/hooks/useToolbarContext.js
deleted file mode 100644
index e94a87fa6..000000000
--- a/packages/editor/dist/toolbar/hooks/useToolbarContext.js
+++ /dev/null
@@ -1,5 +0,0 @@
-import React, { useContext } from "react";
-export var ToolbarContext = React.createContext({});
-export function useToolbarContext() {
- return useContext(ToolbarContext);
-}
diff --git a/packages/editor/dist/toolbar/icons.d.ts b/packages/editor/dist/toolbar/icons.d.ts
index 4e896d47f..e32b1aa1c 100644
--- a/packages/editor/dist/toolbar/icons.d.ts
+++ b/packages/editor/dist/toolbar/icons.d.ts
@@ -45,6 +45,7 @@ export declare const Icons: {
moveColumnLeft: string;
deleteColumn: string;
cellProperties: string;
+ cellBorderColor: string;
backgroundColor: string;
borderColor: string;
sortDesc: string;
@@ -62,6 +63,7 @@ export declare const Icons: {
regex: string;
embed: string;
palette: string;
+ tableSettings: string;
plus: string;
minus: string;
close: string;
@@ -70,6 +72,7 @@ export declare const Icons: {
chevronDown: string;
chevronUp: string;
chevronRight: string;
+ chevronLeft: string;
circle: string;
none: string;
};
diff --git a/packages/editor/dist/toolbar/icons.js b/packages/editor/dist/toolbar/icons.js
index 5f0ec5dae..ec4094a23 100644
--- a/packages/editor/dist/toolbar/icons.js
+++ b/packages/editor/dist/toolbar/icons.js
@@ -1,4 +1,4 @@
-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, mdiSquareRoundedBadgeOutline, mdiFormatColorFill, mdiBorderAllVariant, mdiClose, mdiSortDescending, mdiArrowExpandRight, mdiArrowExpandLeft, mdiArrowExpandDown, mdiArrowExpandUp, mdiTrashCanOutline, mdiTableMergeCells, mdiTableSplitCell, mdiDeleteOutline, mdiDownloadOutline, mdiFormatListCheckbox, mdiDrag, mdiCheckboxMarkedOutline, mdiChevronUp, mdiArrowUp, mdiArrowDown, mdiRegex, mdiFormatLetterCase, mdiFormatLetterMatches, mdiMoviePlusOutline, mdiLink, mdiChevronRight, mdiTableColumnWidth, mdiTableRowHeight, mdiMinus, mdiPaletteOutline, mdiCircle, } 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, } from "@mdi/js";
export var Icons = {
bold: mdiFormatBold,
italic: mdiFormatItalic,
@@ -45,11 +45,12 @@ export var Icons = {
moveColumnRight: mdiArrowExpandRight,
moveColumnLeft: mdiArrowExpandLeft,
deleteColumn: mdiTableColumnRemove,
- cellProperties: mdiSquareRoundedBadgeOutline,
+ cellProperties: mdiRectangle,
+ cellBorderColor: "M4 24q-.825 0-1.412-.587Q2 22.825 2 22q0-.825.588-1.413Q3.175 20 4 20h16q.825 0 1.413.587Q22 21.175 22 22q0 .825-.587 1.413Q20.825 24 20 24Zm1-6q-.425 0-.713-.288Q4 17.425 4 17v-2.325q0-.2.075-.388q.075-.187.225-.337l8.75-8.75l3.75 3.75l-8.75 8.75q-.15.15-.337.225q-.188.075-.388.075Zm1-2h.9L14 8.95L13.05 8L6 15.1Zm11.925-8.15l-3.75-3.75l1.8-1.8q.275-.3.7-.288q.425.013.7.288l2.35 2.35q.275.275.275.688q0 .412-.275.712ZM6 16Z",
backgroundColor: mdiFormatColorFill,
- borderColor: mdiBorderAllVariant,
+ borderColor: "M4 24q-.825 0-1.412-.587Q2 22.825 2 22q0-.825.588-1.413Q3.175 20 4 20h16q.825 0 1.413.587Q22 21.175 22 22q0 .825-.587 1.413Q20.825 24 20 24Zm1-6q-.425 0-.713-.288Q4 17.425 4 17v-2.325q0-.2.075-.388q.075-.187.225-.337l8.75-8.75l3.75 3.75l-8.75 8.75q-.15.15-.337.225q-.188.075-.388.075Zm1-2h.9L14 8.95L13.05 8L6 15.1Zm11.925-8.15l-3.75-3.75l1.8-1.8q.275-.3.7-.288q.425.013.7.288l2.35 2.35q.275.275.275.688q0 .412-.275.712ZM6 16Z",
sortDesc: mdiSortDescending,
- deleteTable: mdiTrashCanOutline,
+ deleteTable: mdiTableOff,
mergeCells: mdiTableMergeCells,
splitCells: mdiTableSplitCell,
checklist: mdiFormatListCheckbox,
@@ -63,6 +64,7 @@ export var Icons = {
regex: mdiRegex,
embed: mdiMoviePlusOutline,
palette: mdiPaletteOutline,
+ tableSettings: mdiTableCog,
plus: mdiPlus,
minus: mdiMinus,
close: mdiClose,
@@ -71,6 +73,7 @@ export var Icons = {
chevronDown: mdiChevronDown,
chevronUp: mdiChevronUp,
chevronRight: mdiChevronRight,
+ chevronLeft: mdiChevronLeft,
circle: mdiCircle,
none: "",
};
diff --git a/packages/editor/dist/toolbar/popups/cellproperties.js b/packages/editor/dist/toolbar/popups/cellproperties.js
index 5debd0e59..9a81a6fb6 100644
--- a/packages/editor/dist/toolbar/popups/cellproperties.js
+++ b/packages/editor/dist/toolbar/popups/cellproperties.js
@@ -26,57 +26,37 @@ var __read = (this && this.__read) || function (o, n) {
return ar;
};
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
-import { Slider } from "@rebass/forms";
import { useRef, useState } from "react";
-import { Flex, Text } from "rebass";
-import { MenuPresenter } from "../../components/menu/menu";
+import { Box, Flex, Text } from "rebass";
+import { Tab, Tabs } from "../../components/tabs";
+import { Icon } from "../components/icon";
+// import { MenuPresenter } from "../../components/menu/menu";
import { Popup } from "../components/popup";
import { ToolButton } from "../components/tool-button";
+import { Icons } from "../icons";
+import { ColorPicker } from "./color-picker";
export function CellProperties(props) {
var editor = props.editor, onClose = props.onClose;
var attributes = editor.getAttributes("tableCell");
- return (_jsx(Popup, __assign({ title: "Cell properties", action: {
- icon: "close",
- iconColor: "error",
- onClick: onClose,
- } }, { children: _jsxs(Flex, __assign({ sx: { flexDirection: "column", px: 1, mb: 2 } }, { children: [_jsx(ColorPickerTool, { color: attributes.backgroundColor, title: "Background color", icon: "backgroundColor", onColorChange: function (color) {
- return editor.commands.setCellAttribute("backgroundColor", color);
- } }), _jsx(ColorPickerTool, { color: attributes.color, title: "Text color", icon: "textColor", onColorChange: function (color) {
- return editor.commands.setCellAttribute("color", color);
- } }), _jsx(ColorPickerTool, { color: attributes.borderColor, title: "Border color", icon: "borderColor", onColorChange: function (color) {
- return editor.commands.setCellAttribute("borderColor", color);
- } }), _jsxs(Flex, __assign({ sx: { flexDirection: "column" } }, { children: [_jsxs(Flex, __assign({ sx: {
- justifyContent: "space-between",
- alignItems: "center",
- mt: 1,
- } }, { children: [_jsx(Text, __assign({ variant: "body" }, { children: "Border width" })), _jsxs(Text, __assign({ variant: "body" }, { children: [attributes.borderWidth || 1, "px"] }))] })), _jsx(Slider, { min: 1, max: 5, value: attributes.borderWidth || 1, onChange: function (e) {
- editor.commands.setCellAttribute("borderWidth", e.target.valueAsNumber);
+ return (_jsx(Popup, __assign({ title: "Cell properties", onClose: onClose }, { children: _jsxs(Tabs, __assign({ activeIndex: 0 }, { children: [_jsxs(Tab, __assign({ title: _jsx(Icon, { title: "Cell background color", path: Icons.backgroundColor, size: 16 }) }, { children: [_jsx(Box, { mt: 2 }), _jsx(ColorPicker, { expanded: true, color: attributes.backgroundColor, onChange: function (color) {
+ return editor.commands.setCellAttribute("backgroundColor", color);
+ }, onClear: function () {
+ return editor.commands.setCellAttribute("backgroundColor", undefined);
+ } })] })), _jsxs(Tab, __assign({ title: _jsx(Icon, { title: "Cell text color", path: Icons.textColor, size: 16 }) }, { children: [_jsx(Box, { mt: 2 }), _jsx(ColorPicker, { expanded: true, color: attributes.color, onChange: function (color) {
+ return editor.commands.setCellAttribute("color", color);
+ }, onClear: function () { return editor.commands.setCellAttribute("color", undefined); } })] })), _jsxs(Tab, __assign({ title: _jsx(Icon, { title: "Cell border color", path: Icons.cellBorderColor, size: 16 }) }, { children: [_jsx(Box, { mt: 2 }), _jsx(ColorPicker, { expanded: true, color: attributes.borderColor, onChange: function (color) {
+ return editor.commands.setCellAttribute("borderColor", color);
+ }, onClear: function () {
+ return editor.commands.setCellAttribute("borderColor", undefined);
} })] }))] })) })));
}
function ColorPickerTool(props) {
var color = props.color, title = props.title, icon = props.icon, onColorChange = props.onColorChange;
var _a = __read(useState(false), 2), isOpen = _a[0], setIsOpen = _a[1];
var buttonRef = useRef(null);
- return (_jsxs(_Fragment, { children: [_jsxs(Flex, __assign({ sx: { justifyContent: "space-between", alignItems: "center", mt: 1 } }, { children: [_jsx(Text, __assign({ variant: "body" }, { children: title })), _jsx(ToolButton, { buttonRef: buttonRef, toggled: isOpen, title: title, id: icon, icon: icon, variant: "small", sx: {
- borderRadius: "small",
- backgroundColor: color || "transparent",
- ":hover": { bg: color, filter: "brightness(90%)" },
- }, onClick: function () { return setIsOpen(true); } })] })), _jsx(MenuPresenter, __assign({ isOpen: isOpen, onClose: function () { return setIsOpen(false); }, items: [], options: {
- type: "menu",
- position: {
- target: buttonRef.current || undefined,
- location: "below",
- align: "center",
- isTargetAbsolute: true,
- yOffset: 5,
- },
- } }, { children: _jsx(Flex, { sx: {
- flexDirection: "column",
- bg: "background",
- boxShadow: "menu",
- border: "1px solid var(--border)",
- borderRadius: "default",
- p: 1,
- width: 160,
- } }) }))] }));
+ return (_jsx(_Fragment, { children: _jsxs(Flex, __assign({ sx: { justifyContent: "space-between", alignItems: "center", mt: 1 } }, { children: [_jsx(Text, __assign({ variant: "body" }, { children: title })), _jsx(ToolButton, { buttonRef: buttonRef, toggled: isOpen, title: title, id: icon, icon: icon, variant: "small", sx: {
+ borderRadius: "small",
+ backgroundColor: color || "transparent",
+ ":hover": { bg: color, filter: "brightness(90%)" },
+ }, onClick: function () { return setIsOpen(true); } })] })) }));
}
diff --git a/packages/editor/dist/toolbar/popups/colorpicker.d.ts b/packages/editor/dist/toolbar/popups/colorpicker.d.ts
new file mode 100644
index 000000000..4995db1ea
--- /dev/null
+++ b/packages/editor/dist/toolbar/popups/colorpicker.d.ts
@@ -0,0 +1,13 @@
+/// <reference types="react" />
+export declare const DEFAULT_COLORS: string[];
+declare type ColorPickerProps = {
+ colors?: string[];
+ color: string;
+ onClear: () => void;
+ expanded?: boolean;
+ onChange: (color: string) => void;
+ onClose?: () => void;
+ title?: string;
+};
+export declare function ColorPicker(props: ColorPickerProps): JSX.Element;
+export {};
diff --git a/packages/editor/dist/toolbar/popups/colorpicker.js b/packages/editor/dist/toolbar/popups/colorpicker.js
new file mode 100644
index 000000000..5ea0343fc
--- /dev/null
+++ b/packages/editor/dist/toolbar/popups/colorpicker.js
@@ -0,0 +1,125 @@
+var __assign = (this && this.__assign) || function () {
+ __assign = Object.assign || function(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+};
+var __read = (this && this.__read) || function (o, n) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
+ if (!m) return o;
+ var i = m.call(o), r, ar = [], e;
+ try {
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
+ }
+ catch (error) { e = { error: error }; }
+ finally {
+ try {
+ if (r && !r.done && (m = i["return"])) m.call(i);
+ }
+ finally { if (e) throw e.error; }
+ }
+ return ar;
+};
+import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
+import { Box, Button, Flex, Text } from "rebass";
+import { Input } from "@rebass/forms";
+import { Icon } from "../components/icon";
+import { Icons } from "../icons";
+import { useState } from "react";
+import tinycolor from "tinycolor2";
+import { HexColorPicker } from "react-colorful";
+export var DEFAULT_COLORS = [
+ "#e91e63",
+ "#9c27b0",
+ "#673ab7",
+ "#3f51b5",
+ "#2196f3",
+ "#03a9f4",
+ "#00bcd4",
+ "#009688",
+ "#4caf50",
+ "#8bc34a",
+ "#cddc39",
+ "#ffeb3b",
+ "#ffc107",
+ "#f44336",
+];
+var PALETTE_SIZE = [35, 35, 25];
+export function ColorPicker(props) {
+ var _a = props.colors, colors = _a === void 0 ? DEFAULT_COLORS : _a, color = props.color, onClear = props.onClear, onChange = props.onChange, title = props.title, onClose = props.onClose, expanded = props.expanded;
+ var _b = __read(useState(expanded || false), 2), isPickerOpen = _b[0], setIsPickerOpen = _b[1];
+ var tColor = tinycolor(color || colors[0]);
+ var _c = __read(useState(tColor.toHexString()), 2), currentColor = _c[0], setCurrentColor = _c[1];
+ return (_jsxs(Flex, __assign({ sx: {
+ bg: "background",
+ flexDirection: "column",
+ ".react-colorful": {
+ width: "auto",
+ height: 150,
+ },
+ ".react-colorful__saturation": {
+ borderRadius: ["default", 0],
+ },
+ width: ["calc(100vw - 20px)", 250],
+ // width: ["auto", 250],
+ } }, { children: [onClose && (_jsxs(Box, __assign({ sx: {
+ display: ["none", "flex"],
+ justifyContent: "space-between",
+ p: 2,
+ pb: isPickerOpen ? 2 : 0,
+ //pb: 0,
+ alignItems: "center",
+ }, onClick: onClose }, { children: [_jsx(Text, __assign({ variant: "title" }, { children: title })), _jsx(Button, __assign({ variant: "icon", sx: { p: 0 } }, { children: _jsx(Icon, { path: Icons.close, size: "big" }) }))] }))), isPickerOpen ? (_jsxs(_Fragment, { children: [_jsx(HexColorPicker, { color: currentColor, onChange: onChange }), _jsx(Input, { variant: "clean", placeholder: "#000000", spellCheck: false, sx: {
+ my: 2,
+ p: 0,
+ borderRadius: 0,
+ fontSize: ["title", "title", "body"],
+ color: "fontTertiary",
+ textAlign: "center",
+ letterSpacing: 1.5,
+ }, value: currentColor.toUpperCase(), maxLength: 7, onChange: function (e) {
+ var value = e.target.value;
+ if (!value)
+ return;
+ setCurrentColor(value);
+ } })] })) : null, _jsxs(Flex, { children: [_jsxs(Flex, __assign({ className: "hide-scrollbar", sx: {
+ flex: 1,
+ p: 1,
+ overflowX: ["auto", "hidden"],
+ flexWrap: ["nowrap", "wrap"],
+ } }, { children: [_jsx(Button, __assign({ variant: "icon", sx: {
+ flexShrink: 0,
+ width: PALETTE_SIZE,
+ height: PALETTE_SIZE,
+ borderRadius: 50,
+ boxShadow: "menu",
+ p: 0,
+ ml: [2, 2, 1],
+ }, onClick: onClear }, { children: _jsx(Icon, { path: Icons.colorClear, color: "text", size: 15 }) })), _jsx(Button, __assign({ variant: "secondary", sx: {
+ flexShrink: 0,
+ bg: currentColor,
+ width: PALETTE_SIZE,
+ height: PALETTE_SIZE,
+ borderRadius: 50,
+ // boxShadow: "menu",
+ p: 0,
+ ml: [2, 2, 1],
+ }, onClick: function () { return setIsPickerOpen(function (s) { return !s; }); } }, { children: _jsx(Icon, { path: Icons.palette, color: tColor.isDark() ? "static" : "icon", size: 18 }) })), colors.map(function (color) { return (_jsx(Button, { variant: "secondary", sx: {
+ flex: "0 0 auto",
+ bg: color,
+ width: PALETTE_SIZE,
+ height: PALETTE_SIZE,
+ ml: [2, 1, 1],
+ mb: [0, 1, 1],
+ borderRadius: 50,
+ // boxShadow: "menu",
+ }, onClick: function () {
+ setCurrentColor(color);
+ onChange(color);
+ } }, color)); })] })), onClose && (_jsx(Button, __assign({ variant: "icon", sx: { display: ["block", "none"], px: 2 }, onClick: onClose }, { children: _jsx(Icon, { path: Icons.close, size: "big" }) })))] })] })));
+}
diff --git a/packages/editor/dist/toolbar/popups/embedpopup.d.ts b/packages/editor/dist/toolbar/popups/embedpopup.d.ts
index dd78097a9..14571c5c5 100644
--- a/packages/editor/dist/toolbar/popups/embedpopup.d.ts
+++ b/packages/editor/dist/toolbar/popups/embedpopup.d.ts
@@ -1,11 +1,9 @@
/// <reference types="react" />
import { EmbedAlignmentOptions, EmbedAttributes, EmbedSizeOptions } from "../../extensions/embed";
-import { IconNames } from "../icons";
declare type Embed = Required<EmbedAttributes> & EmbedAlignmentOptions;
export declare type EmbedPopupProps = {
- onClose: (embed: Embed) => void;
+ onClose: (embed?: Embed) => void;
title?: string;
- icon?: IconNames;
embed?: Embed;
onSizeChanged?: (size: EmbedSizeOptions) => void;
onSourceChanged?: (src: string) => void;
diff --git a/packages/editor/dist/toolbar/popups/embedpopup.js b/packages/editor/dist/toolbar/popups/embedpopup.js
index b317fe550..e197e180c 100644
--- a/packages/editor/dist/toolbar/popups/embedpopup.js
+++ b/packages/editor/dist/toolbar/popups/embedpopup.js
@@ -31,8 +31,10 @@ import { useCallback, useEffect, useState } from "react";
import { Popup } from "../components/popup";
import { Input, Textarea } from "@rebass/forms";
import { convertUrlToEmbedUrl } from "@social-embed/lib";
+import { InlineInput } from "../../components/inline-input";
+import { Tabs, Tab } from "../../components/tabs";
export function EmbedPopup(props) {
- var onClose = props.onClose, onSizeChanged = props.onSizeChanged, onSourceChanged = props.onSourceChanged, title = props.title, icon = props.icon, embed = props.embed;
+ var onClose = props.onClose, onSizeChanged = props.onSizeChanged, onSourceChanged = props.onSourceChanged, title = props.title, embed = props.embed;
var _a = __read(useState((embed === null || embed === void 0 ? void 0 : embed.width) || 300), 2), width = _a[0], setWidth = _a[1];
var _b = __read(useState((embed === null || embed === void 0 ? void 0 : embed.height) || 150), 2), height = _b[0], setHeight = _b[1];
var _c = __read(useState((embed === null || embed === void 0 ? void 0 : embed.src) || ""), 2), src = _c[0], setSrc = _c[1];
@@ -61,59 +63,49 @@ export function EmbedPopup(props) {
useEffect(function () {
onSourceChanged && onSourceChanged(src);
}, [onSourceChanged, src]);
- return (_jsx(Popup, __assign({ title: title, action: {
- icon: icon,
- onClick: function () {
- setError(null);
- var _src = src;
- var _width = width;
- var _height = height;
- if (embedSource === "code") {
- var document_1 = new DOMParser().parseFromString(src, "text/html");
- if (document_1.getElementsByTagName("iframe").length <= 0)
- return setError("Embed code must include an iframe.");
- var srcValue = getAttribute(document_1, "src");
- if (!srcValue)
- return setError("Embed code must include an iframe with an src attribute.");
- _src = srcValue;
- var widthValue = getAttribute(document_1, "width");
- if (widthValue && !isNaN(parseInt(widthValue)))
- _width = parseInt(widthValue);
- var heightValue = getAttribute(document_1, "height");
- if (heightValue && !isNaN(parseInt(heightValue)))
- _height = parseInt(heightValue);
- }
- var convertedUrl = convertUrlToEmbedUrl(_src);
- if (!!convertedUrl)
- _src = convertedUrl;
- onClose({
- height: _height,
- width: _width,
- src: _src,
- });
- },
- } }, { children: _jsxs(Flex, __assign({ sx: { flexDirection: "column", p: 1 } }, { children: [error && (_jsxs(Text, __assign({ variant: "error", sx: {
+ return (_jsx(Popup, __assign({ title: title, onClose: function () { return onClose(); } }, { children: _jsxs(Flex, __assign({ sx: { flexDirection: "column", width: ["auto", 300] } }, { children: [error && (_jsxs(Text, __assign({ variant: "error", sx: {
bg: "errorBg",
color: "error",
p: 1,
borderRadius: "default",
- } }, { children: ["Error: ", error] }))), _jsxs(Flex, __assign({ sx: { mb: 1 } }, { children: [_jsx(Button, __assign({ variant: "dialog", sx: {
- pb: 1,
- mr: 1,
- borderRadius: 0,
- color: embedSource === "url" ? "primary" : "text",
- borderBottom: "2px solid",
- borderBottomColor: embedSource === "url" ? "primary" : "transparent",
- }, onClick: function () { return setEmbedSource("url"); } }, { children: "From URL" })), _jsx(Button, __assign({ variant: "dialog", sx: {
- pb: 1,
- borderRadius: 0,
- color: embedSource === "code" ? "primary" : "text",
- borderBottom: "2px solid",
- borderBottomColor: embedSource === "code" ? "primary" : "transparent",
- }, onClick: function () { return setEmbedSource("code"); } }, { children: "From code" }))] })), embedSource === "url" ? (_jsx(Input, { placeholder: "Enter embed source URL", value: src, autoFocus: true, onChange: function (e) { return setSrc(e.target.value); }, sx: { mt: 1, fontSize: "body" } })) : (_jsx(Textarea, { autoFocus: true, variant: "forms.input", sx: { fontSize: "subBody", fontFamily: "monospace", mt: 1 }, minHeight: [200, 100], onChange: function (e) { return setSrc(e.target.value); }, placeholder: "Paste embed code here. Only iframes are supported." })), embedSource === "url" ? (_jsxs(Flex, __assign({ sx: { alignItems: "center", mt: 1 } }, { children: [_jsx(Input, { type: "number", placeholder: "Width", value: width, sx: {
- mr: 1,
- fontSize: "body",
- }, onChange: function (e) { return onSizeChange(e.target.valueAsNumber); } }), _jsx(Input, { type: "number", placeholder: "Height", value: height, sx: { fontSize: "body" }, onChange: function (e) { return onSizeChange(undefined, e.target.valueAsNumber); } })] }))) : null] })) })));
+ } }, { children: ["Error: ", error] }))), _jsxs(Tabs, __assign({ activeIndex: 0, containerProps: { sx: { mx: 1, mb: 1, flexDirection: "column" } }, onTabChanged: function (index) { return setEmbedSource(index === 0 ? "url" : "code"); } }, { children: [_jsxs(Tab, __assign({ title: "From URL" }, { children: [_jsx(Input, { placeholder: "Enter embed source URL", value: src, autoFocus: true, onChange: function (e) { return setSrc(e.target.value); }, sx: { fontSize: "body" } }), _jsxs(Flex, __assign({ sx: { alignItems: "center", mt: 1 } }, { children: [_jsx(InlineInput, { containerProps: { sx: { mr: 1 } }, label: "width", type: "number", placeholder: "Width", value: width, sx: {
+ mr: 1,
+ fontSize: "body",
+ }, onChange: function (e) { return onSizeChange(e.target.valueAsNumber); } }), _jsx(InlineInput, { label: "height", type: "number", placeholder: "Height", value: height, sx: { fontSize: "body" }, onChange: function (e) {
+ return onSizeChange(undefined, e.target.valueAsNumber);
+ } })] }))] })), _jsx(Tab, __assign({ title: "From code" }, { children: _jsx(Textarea, { autoFocus: true, variant: "forms.input", sx: { fontSize: "subBody", fontFamily: "monospace" }, minHeight: [200, 100], onChange: function (e) { return setSrc(e.target.value); }, placeholder: "Paste embed code here. Only iframes are supported." }) }))] })), _jsx(Button, __assign({ variant: "primary", sx: {
+ alignSelf: ["stretch", "end", "end"],
+ my: 1,
+ mr: 1,
+ }, onClick: function () {
+ setError(null);
+ var _src = src;
+ var _width = width;
+ var _height = height;
+ if (embedSource === "code") {
+ var document_1 = new DOMParser().parseFromString(src, "text/html");
+ if (document_1.getElementsByTagName("iframe").length <= 0)
+ return setError("Embed code must include an iframe.");
+ var srcValue = getAttribute(document_1, "src");
+ if (!srcValue)
+ return setError("Embed code must include an iframe with an src attribute.");
+ _src = srcValue;
+ var widthValue = getAttribute(document_1, "width");
+ if (widthValue && !isNaN(parseInt(widthValue)))
+ _width = parseInt(widthValue);
+ var heightValue = getAttribute(document_1, "height");
+ if (heightValue && !isNaN(parseInt(heightValue)))
+ _height = parseInt(heightValue);
+ }
+ var convertedUrl = convertUrlToEmbedUrl(_src);
+ if (!!convertedUrl)
+ _src = convertedUrl;
+ onClose({
+ height: _height,
+ width: _width,
+ src: _src,
+ });
+ } }, { children: title }))] })) })));
}
function getAttribute(document, id) {
var element = document.querySelector("[".concat(id, "]"));
diff --git a/packages/editor/dist/toolbar/popups/tablepopup.d.ts b/packages/editor/dist/toolbar/popups/tablepopup.d.ts
index 44a07a5ea..0e35ac702 100644
--- a/packages/editor/dist/toolbar/popups/tablepopup.d.ts
+++ b/packages/editor/dist/toolbar/popups/tablepopup.d.ts
@@ -5,8 +5,6 @@ declare type TableSize = {
};
export declare type TablePopupProps = {
onInsertTable: (size: TableSize) => void;
- cellSize?: number;
- autoExpand?: boolean;
};
export declare function TablePopup(props: TablePopupProps): JSX.Element;
export {};
diff --git a/packages/editor/dist/toolbar/popups/tablepopup.js b/packages/editor/dist/toolbar/popups/tablepopup.js
index 531da41ef..4ded0d648 100644
--- a/packages/editor/dist/toolbar/popups/tablepopup.js
+++ b/packages/editor/dist/toolbar/popups/tablepopup.js
@@ -26,16 +26,19 @@ var __read = (this && this.__read) || function (o, n) {
return ar;
};
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
-import { Box, Flex, Text } from "rebass";
+import { Box, Button, Flex, Text } from "rebass";
import { useEffect, useState } from "react";
-import { Popup } from "../components/popup";
-import { Input } from "@rebass/forms";
+import { useIsMobile } from "../stores/toolbar-store";
+import { InlineInput } from "../../components/inline-input";
var MAX_COLUMNS = 20;
var MAX_ROWS = 20;
var MIN_COLUMNS = 12;
var MIN_ROWS = 6;
export function TablePopup(props) {
- var onInsertTable = props.onInsertTable, cellSize = props.cellSize, autoExpand = props.autoExpand;
+ var isMobile = useIsMobile();
+ var autoExpand = !isMobile;
+ var cellSize = isMobile ? 30 : 15;
+ var onInsertTable = props.onInsertTable;
var _a = __read(useState({
column: 0,
row: 0,
@@ -63,56 +66,59 @@ export function TablePopup(props) {
};
});
}, [cellLocation, autoExpand]);
- return (_jsx(Popup, __assign({ title: "Insert table", action: {
- icon: "check",
- onClick: function () {
- onInsertTable({
- columns: cellLocation.column,
- rows: cellLocation.row,
- });
- },
- } }, { children: _jsxs(Flex, __assign({ sx: { p: 1, flexDirection: "column", alignItems: "center" } }, { children: [_jsx(Box, __assign({ sx: {
- display: "grid",
- gridTemplateColumns: "repeat(".concat(tableSize.columns, ", minmax(").concat(cellSize || 15, "px, 1fr))"),
- gap: "small",
- bg: "background",
- width: "100%",
- }, onTouchMove: function (e) {
- var touch = e.touches.item(0);
- var element = document.elementFromPoint(touch.pageX, touch.pageY);
- if (!element)
- return;
- var index = element.dataset.index;
- if (!index)
- return;
- setCellLocation(getCellLocation(parseInt(index), tableSize));
- } }, { children: Array(tableSize.columns * tableSize.rows)
- .fill(0)
- .map(function (_, index) { return (_jsx(Box, { "data-index": index, height: cellSize || 15, sx: {
- border: "1px solid var(--disabled)",
- borderRadius: "small",
- bg: isCellHighlighted(index, cellLocation, tableSize)
- ? "disabled"
- : "transparent",
- }, onTouchStart: function () {
- setCellLocation(getCellLocation(index, tableSize));
- }, onMouseEnter: function () {
- setCellLocation(getCellLocation(index, tableSize));
- }, onClick: function () {
- onInsertTable({
- columns: cellLocation.column,
- rows: cellLocation.row,
- });
- } })); }) })), _jsxs(Flex, __assign({ sx: {
- display: ["flex", "none"],
- my: 1,
- alignItems: "center",
- justifyContent: "center",
- } }, { children: [_jsx(Input, { placeholder: "".concat(cellLocation.column, " columns"), sx: { mr: 1 }, type: "number", value: cellLocation.column, onChange: function (e) {
- setCellLocation(function (l) { return (__assign(__assign({}, l), { column: e.target.valueAsNumber || 0 })); });
- } }), _jsx(Input, { placeholder: "".concat(cellLocation.row, " rows"), type: "number", value: cellLocation.row, onChange: function (e) {
- setCellLocation(function (l) { return (__assign(__assign({}, l), { row: e.target.valueAsNumber || 0 })); });
- } })] })), _jsxs(Text, __assign({ variant: "body", sx: { mt: 1, display: ["none", "block"] } }, { children: [cellLocation.column, "x", cellLocation.row] }))] })) })));
+ return (_jsxs(Flex, __assign({ sx: { p: 1, flexDirection: "column", alignItems: "center" } }, { children: [_jsx(Box, __assign({ sx: {
+ display: "grid",
+ gridTemplateColumns: "repeat(".concat(tableSize.columns, ", minmax(").concat(cellSize, "px, 1fr))"),
+ gap: "small",
+ bg: "background",
+ width: "100%",
+ }, onTouchMove: function (e) {
+ var touch = e.touches.item(0);
+ var element = document.elementFromPoint(touch.pageX, touch.pageY);
+ if (!element)
+ return;
+ var index = element.dataset.index;
+ if (!index)
+ return;
+ setCellLocation(getCellLocation(parseInt(index), tableSize));
+ } }, { children: Array(tableSize.columns * tableSize.rows)
+ .fill(0)
+ .map(function (_, index) { return (_jsx(Box, { "data-index": index, height: cellSize || 15, sx: {
+ border: "1px solid var(--disabled)",
+ borderRadius: "small",
+ bg: isCellHighlighted(index, cellLocation, tableSize)
+ ? "disabled"
+ : "transparent",
+ }, onTouchStart: function () {
+ setCellLocation(getCellLocation(index, tableSize));
+ }, onMouseEnter: function () {
+ setCellLocation(getCellLocation(index, tableSize));
+ }, onClick: function () {
+ onInsertTable({
+ columns: cellLocation.column,
+ rows: cellLocation.row,
+ });
+ } })); }) })), _jsxs(Flex, __assign({ sx: {
+ display: ["flex", "none", "none"],
+ my: 1,
+ alignItems: "center",
+ justifyContent: "center",
+ } }, { children: [_jsx(InlineInput, { containerProps: { sx: { mr: 1 } }, label: "columns", placeholder: "".concat(cellLocation.column, " columns"), type: "number", value: cellLocation.column, onChange: function (e) {
+ setCellLocation(function (l) { return (__assign(__assign({}, l), { column: e.target.valueAsNumber || 0 })); });
+ } }), _jsx(InlineInput, { label: "rows", placeholder: "".concat(cellLocation.row, " rows"), type: "number", value: cellLocation.row, onChange: function (e) {
+ setCellLocation(function (l) { return (__assign(__assign({}, l), { row: e.target.valueAsNumber || 0 })); });
+ } })] })), _jsxs(Text, __assign({ variant: "body", sx: { mt: 1, display: ["none", "block", "block"] } }, { children: [cellLocation.column, " x ", cellLocation.row] })), _jsx(Button, __assign({ variant: "primary", sx: {
+ display: ["block", "none", "none"],
+ alignSelf: ["stretch", "end", "end"],
+ py: 2,
+ }, onClick: function () {
+ return onInsertTable({
+ columns: cellLocation.column,
+ rows: cellLocation.row,
+ });
+ }, disabled: !cellLocation.column || !cellLocation.row }, { children: !cellLocation.column || !cellLocation.row
+ ? "Please set a table size"
+ : "Insert a ".concat(cellLocation.column, " x ").concat(cellLocation.row, " table") }))] })));
}
function getCellLocation(index, tableSize) {
var cellIndex = index + 1;
diff --git a/packages/editor/dist/toolbar/stores/toolbarstore.d.ts b/packages/editor/dist/toolbar/stores/toolbarstore.d.ts
index 58587008a..b5edf835b 100644
--- a/packages/editor/dist/toolbar/stores/toolbarstore.d.ts
+++ b/packages/editor/dist/toolbar/stores/toolbarstore.d.ts
@@ -1,9 +1,18 @@
export declare type ToolbarLocation = "top" | "bottom";
+export declare type PopupRef = {
+ id: string;
+ group: string;
+};
interface ToolbarState {
isMobile: boolean;
+ openedPopups: Record<string, PopupRef | false>;
setIsMobile: (isMobile: boolean) => void;
toolbarLocation: ToolbarLocation;
setToolbarLocation: (location: ToolbarLocation) => void;
+ isPopupOpen: (popupId: string) => boolean;
+ openPopup: (ref: PopupRef) => void;
+ closePopup: (popupId: string) => void;
+ closePopupGroup: (groupId: string, excluded: string[]) => void;
}
export declare const useToolbarStore: import("zustand").UseBoundStore<ToolbarState, import("zustand").StoreApi<ToolbarState>>;
export declare function useToolbarLocation(): ToolbarLocation;
diff --git a/packages/editor/dist/toolbar/stores/toolbarstore.js b/packages/editor/dist/toolbar/stores/toolbarstore.js
index 92897309b..2ada77d41 100644
--- a/packages/editor/dist/toolbar/stores/toolbarstore.js
+++ b/packages/editor/dist/toolbar/stores/toolbarstore.js
@@ -1,6 +1,18 @@
+var __assign = (this && this.__assign) || function () {
+ __assign = Object.assign || function(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+};
import create from "zustand";
-export var useToolbarStore = create(function (set) { return ({
+export var useToolbarStore = create(function (set, get) { return ({
isMobile: false,
+ openedPopups: {},
setIsMobile: function (isMobile) {
return set(function (state) {
state.isMobile = isMobile;
@@ -12,6 +24,29 @@ export var useToolbarStore = create(function (set) { return ({
state.toolbarLocation = location;
});
},
+ closePopup: function (id) {
+ return set(function (state) {
+ var _a;
+ state.openedPopups = __assign(__assign({}, state.openedPopups), (_a = {}, _a[id] = false, _a));
+ });
+ },
+ isPopupOpen: function (id) { return !!get().openedPopups[id]; },
+ openPopup: function (ref) {
+ return set(function (state) {
+ var _a;
+ state.openedPopups = __assign(__assign({}, state.openedPopups), (_a = {}, _a[ref.id] = ref, _a));
+ });
+ },
+ closePopupGroup: function (group, excluded) {
+ return set(function (state) {
+ for (var key in state.openedPopups) {
+ var ref = state.openedPopups[key];
+ if (ref && ref.group === group && !excluded.includes(ref.id)) {
+ state.openedPopups[key] = false;
+ }
+ }
+ });
+ },
}); });
export function useToolbarLocation() {
return useToolbarStore(function (store) { return store.toolbarLocation; });
diff --git a/packages/editor/dist/toolbar/toolbar.js b/packages/editor/dist/toolbar/toolbar.js
index 46bd88bac..5143b98ba 100644
--- a/packages/editor/dist/toolbar/toolbar.js
+++ b/packages/editor/dist/toolbar/toolbar.js
@@ -9,55 +9,24 @@ var __assign = (this && this.__assign) || function () {
};
return __assign.apply(this, arguments);
};
-var __rest = (this && this.__rest) || function (s, e) {
- var t = {};
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
- t[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
- t[p[i]] = s[p[i]];
- }
- return t;
-};
-var __read = (this && this.__read) || function (o, n) {
- var m = typeof Symbol === "function" && o[Symbol.iterator];
- if (!m) return o;
- var i = m.call(o), r, ar = [], e;
- try {
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
- }
- catch (error) { e = { error: error }; }
- finally {
- try {
- if (r && !r.done && (m = i["return"])) m.call(i);
- }
- finally { if (e) throw e.error; }
- }
- return ar;
-};
-import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
+import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Flex } from "rebass";
-import { findToolById } from "./tools";
import { ThemeProvider } from "emotion-theming";
import { EditorFloatingMenus } from "./floating-menus";
-import { getToolDefinition } from "./tool-definitions";
-import { ToolButton } from "./components/tool-button";
-import { useEffect, useRef, useState } from "react";
-import { MenuPresenter } from "../components/menu";
-import { Popup } from "./components/popup";
-import { ToolbarContext, useToolbarContext } from "./hooks/useToolbarContext";
-import { useToolbarLocation, useToolbarStore, } from "./stores/toolbar-store";
+import { useEffect } from "react";
+import { useToolbarStore, } from "./stores/toolbar-store";
+import { ToolbarGroup } from "./components/toolbar-group";
+import { EditorContext, PopupRenderer, } from "../components/popup-presenter/popuprenderer";
export function Toolbar(props) {
var editor = props.editor, theme = props.theme, location = props.location, isMobile = props.isMobile;
- var _a = __read(useState(), 2), currentPopup = _a[0], setCurrentPopup = _a[1];
- var _b = useToolbarStore(), setIsMobile = _b.setIsMobile, setToolbarLocation = _b.setToolbarLocation;
+ var setIsMobile = useToolbarStore(function (store) { return store.setIsMobile; });
+ var setToolbarLocation = useToolbarStore(function (store) { return store.setToolbarLocation; });
useEffect(function () {
setIsMobile(isMobile || false);
setToolbarLocation(location);
}, [isMobile, location]);
var tools = [
- ["insertBlock"],
+ ["insertBlock", "tableSettings"],
[
"bold",
"italic",
@@ -80,51 +49,13 @@ export function Toolbar(props) {
];
if (!editor)
return null;
- return (_jsxs(ThemeProvider, __assign({ theme: theme }, { children: [_jsx(ToolbarContext.Provider, __assign({ value: {
- setCurrentPopup: setCurrentPopup,
- currentPopup: currentPopup,
- } }, { children: _jsx(Flex, __assign({ className: "editor-toolbar", sx: { flexWrap: ["nowrap", "wrap"], overflowX: ["auto", "hidden"] } }, { children: tools.map(function (tools) {
- return (_jsx(ToolbarGroup, { tools: tools, editor: editor, sx: {
- flexShrink: 0,
- pr: 2,
- mr: 2,
- borderRight: "1px solid var(--border)",
- ":last-of-type": { mr: 0, pr: 0, borderRight: "none" },
- } }));
- }) })) })), _jsx(EditorFloatingMenus, { editor: editor })] })));
-}
-function ToolbarGroup(props) {
- var tools = props.tools, editor = props.editor, flexProps = __rest(props, ["tools", "editor"]);
- return (_jsx(Flex, __assign({ className: "toolbar-group" }, flexProps, { children: tools.map(function (toolId) {
- if (Array.isArray(toolId)) {
- return (_jsx(MoreTools, { popupId: toolId.join(""), tools: toolId, editor: editor }));
- }
- else {
- var Component = findToolById(toolId);
- var toolDefinition = getToolDefinition(toolId);
- return _jsx(Component, __assign({ editor: editor }, toolDefinition));
- }
- }) })));
-}
-function MoreTools(props) {
- var popupId = props.popupId;
- var _a = useToolbarContext(), currentPopup = _a.currentPopup, setCurrentPopup = _a.setCurrentPopup;
- var toolbarLocation = useToolbarLocation();
- var buttonRef = useRef();
- var show = popupId === currentPopup;
- var setShow = function (state) {
- return setCurrentPopup === null || setCurrentPopup === void 0 ? void 0 : setCurrentPopup(state ? popupId : undefined);
- };
- return (_jsxs(_Fragment, { children: [_jsx(ToolButton, { icon: "more", title: "More", toggled: show, buttonRef: buttonRef, onMouseDown: function (e) { return e.preventDefault(); }, onClick: function () { return setShow(!show); } }), _jsx(MenuPresenter, __assign({ isOpen: show, onClose: function () { return setShow(false); }, items: [], options: {
- type: "autocomplete",
- position: {
- isTargetAbsolute: true,
- target: buttonRef.current || "mouse",
- align: "center",
- location: toolbarLocation === "bottom" ? "top" : "below",
- yOffset: 5,
- },
- } }, { children: _jsx(Popup, { children: _jsx(ToolbarGroup, { tools: props.tools, editor: props.editor, sx: {
- p: 1,
- } }) }) }))] }));
+ return (_jsx(ThemeProvider, __assign({ theme: theme }, { children: _jsx(EditorContext.Provider, __assign({ value: editor }, { children: _jsxs(PopupRenderer, __assign({ editor: editor }, { children: [_jsx(Flex, __assign({ className: "editor-toolbar", sx: { flexWrap: ["nowrap", "wrap"], overflowX: ["auto", "hidden"] } }, { children: tools.map(function (tools) {
+ return (_jsx(ToolbarGroup, { tools: tools, editor: editor, sx: {
+ flexShrink: 0,
+ pr: 2,
+ mr: 2,
+ borderRight: "1px solid var(--border)",
+ ":last-of-type": { mr: 0, pr: 0, borderRight: "none" },
+ } }, tools.join("")));
+ }) })), _jsx(EditorFloatingMenus, { editor: editor })] })) })) })));
}
diff --git a/packages/editor/dist/toolbar/tooldefinitions.js b/packages/editor/dist/toolbar/tooldefinitions.js
index 3960b3767..bf4aefbfc 100644
--- a/packages/editor/dist/toolbar/tooldefinitions.js
+++ b/packages/editor/dist/toolbar/tooldefinitions.js
@@ -91,6 +91,111 @@ var tools = {
icon: "textColor",
title: "Text color",
},
+ tableSettings: {
+ icon: "tableSettings",
+ title: "Table settings",
+ conditional: true,
+ },
+ columnProperties: {
+ icon: "columnProperties",
+ title: "Column properties",
+ conditional: true,
+ },
+ rowProperties: {
+ icon: "rowProperties",
+ title: "Row properties",
+ conditional: true,
+ },
+ cellProperties: {
+ icon: "cellProperties",
+ title: "Cell properties",
+ conditional: true,
+ },
+ insertColumnLeft: {
+ icon: "insertColumnLeft",
+ title: "Insert column left",
+ conditional: true,
+ },
+ insertColumnRight: {
+ icon: "insertColumnRight",
+ title: "Insert column right",
+ conditional: true,
+ },
+ moveColumnLeft: {
+ icon: "moveColumnLeft",
+ title: "Move column left",
+ conditional: true,
+ },
+ moveColumnRight: {
+ icon: "moveColumnLeft",
+ title: "Move column right",
+ conditional: true,
+ },
+ deleteColumn: {
+ icon: "deleteColumn",
+ title: "Delete column",
+ conditional: true,
+ },
+ splitCells: {
+ icon: "splitCells",
+ title: "Split cells",
+ conditional: true,
+ },
+ mergeCells: {
+ icon: "mergeCells",
+ title: "Merge cells",
+ conditional: true,
+ },
+ insertRowAbove: {
+ icon: "insertRowAbove",
+ title: "Insert row above",
+ conditional: true,
+ },
+ insertRowBelow: {
+ icon: "insertRowBelow",
+ title: "Insert row below",
+ conditional: true,
+ },
+ moveRowUp: {
+ icon: "moveRowUp",
+ title: "Move row up",
+ conditional: true,
+ },
+ moveRowDown: {
+ icon: "moveRowDown",
+ title: "Move row down",
+ conditional: true,
+ },
+ deleteRow: {
+ icon: "deleteRow",
+ title: "Delete row",
+ conditional: true,
+ },
+ deleteTable: {
+ icon: "deleteTable",
+ title: "Delete table",
+ conditional: true,
+ },
+ cellBackgroundColor: {
+ icon: "backgroundColor",
+ title: "Cell background color",
+ conditional: true,
+ },
+ cellBorderColor: {
+ icon: "cellBorderColor",
+ title: "Cell border color",
+ conditional: true,
+ },
+ cellTextColor: {
+ icon: "textColor",
+ title: "Cell text color",
+ conditional: true,
+ },
+ cellBorderWidth: {
+ icon: "none",
+ title: "Cell border width",
+ conditional: true,
+ },
};
export function getToolDefinition(id) {
return tools[id];
diff --git a/packages/editor/dist/toolbar/tools/block.js b/packages/editor/dist/toolbar/tools/block.js
index 1f16cb0af..26a762b6f 100644
--- a/packages/editor/dist/toolbar/tools/block.js
+++ b/packages/editor/dist/toolbar/tools/block.js
@@ -27,18 +27,31 @@ var __read = (this && this.__read) || function (o, n) {
};
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { Icons } from "../icons";
-import { ActionSheetPresenter, MenuPresenter, } from "../../components/menu/menu";
-import { useRef, useState } from "react";
+import { useMemo, useRef, useState } from "react";
import { Icon } from "../components/icon";
import { Button } from "rebass";
import { EmbedPopup } from "../popups/embed-popup";
import { TablePopup } from "../popups/table-popup";
-import { useToolbarLocation } from "../stores/toolbar-store";
-import { DesktopOnly, MobileOnly } from "../../components/responsive";
+import { useIsMobile, useToolbarLocation } from "../stores/toolbar-store";
+import { ResponsivePresenter, } from "../../components/responsive";
+import { showPopup } from "../../components/popup-presenter";
export function InsertBlock(props) {
var buttonRef = useRef();
var _a = __read(useState(false), 2), isOpen = _a[0], setIsOpen = _a[1];
var toolbarLocation = useToolbarLocation();
+ var isMobile = useIsMobile();
+ var menuItems = useMemo(function () {
+ return [
+ tasklist(editor),
+ horizontalRule(editor),
+ codeblock(editor),
+ blockquote(editor),
+ image(editor),
+ attachment(editor),
+ isMobile ? embedMobile(editor) : embedDesktop(editor),
+ table(editor),
+ ];
+ }, [isMobile]);
return (_jsxs(_Fragment, { children: [_jsx(Button, __assign({ ref: buttonRef, sx: {
p: 1,
m: 0,
@@ -50,37 +63,16 @@ export function InsertBlock(props) {
":last-of-type": {
mr: 0,
},
- }, onMouseDown: function (e) { return e.preventDefault(); }, onClick: function () { return setIsOpen(function (s) { return !s; }); } }, { children: _jsx(Icon, { path: Icons.plus, size: 18, color: "primary" }) })), _jsx(DesktopOnly, { children: _jsx(MenuPresenter, { options: {
- type: "menu",
- position: {
- target: buttonRef.current || undefined,
- isTargetAbsolute: true,
- location: toolbarLocation === "bottom" ? "top" : "below",
- yOffset: 5,
- },
- }, isOpen: isOpen, items: [
- tasklist(editor),
- horizontalRule(editor),
- codeblock(editor),
- blockquote(editor),
- image(editor),
- attachment(editor),
- embed(editor),
- table(editor),
- ], onClose: function () { return setIsOpen(false); } }) }), _jsx(MobileOnly, { children: _jsx(ActionSheetPresenter, { isOpen: isOpen, items: [
- tasklist(editor),
- horizontalRule(editor),
- codeblock(editor),
- blockquote(editor),
- imageActionSheet(editor),
- attachment(editor),
- embedActionSheet(editor),
- tableActionSheet(editor),
- ], onClose: function () { return setIsOpen(false); } }) })] }));
+ }, onMouseDown: function (e) { return e.preventDefault(); }, onClick: function () { return setIsOpen(function (s) { return !s; }); } }, { children: _jsx(Icon, { path: Icons.plus, size: 18, color: "primary" }) })), _jsx(ResponsivePresenter, { desktop: "menu", mobile: "sheet", title: "Choose a block to insert", isOpen: isOpen, items: menuItems, onClose: function () { return setIsOpen(false); }, position: {
+ target: buttonRef.current || undefined,
+ isTargetAbsolute: true,
+ location: toolbarLocation === "bottom" ? "top" : "below",
+ yOffset: 5,
+ } })] }));
}
var horizontalRule = function (editor) { return ({
key: "hr",
- type: "menuitem",
+ type: "button",
title: "Horizontal rule",
icon: "horizontalRule",
isChecked: editor === null || editor === void 0 ? void 0 : editor.isActive("horizontalRule"),
@@ -88,7 +80,7 @@ var horizontalRule = function (editor) { return ({
}); };
var codeblock = function (editor) { return ({
key: "codeblock",
- type: "menuitem",
+ type: "button",
title: "Code block",
icon: "codeblock",
isChecked: editor === null || editor === void 0 ? void 0 : editor.isActive("codeBlock"),
@@ -96,7 +88,7 @@ var codeblock = function (editor) { return ({
}); };
var blockquote = function (editor) { return ({
key: "blockquote",
- type: "menuitem",
+ type: "button",
title: "Quote",
icon: "blockquote",
isChecked: editor === null || editor === void 0 ? void 0 : editor.isActive("blockQuote"),
@@ -104,134 +96,98 @@ var blockquote = function (editor) { return ({
}); };
var image = function (editor) { return ({
key: "image",
- type: "menuitem",
+ type: "button",
title: "Image",
icon: "image",
- items: [
- {
- key: "upload-from-disk",
- type: "menuitem",
- title: "Upload from disk",
- icon: "upload",
- onClick: function () { },
- },
- {
- key: "upload-from-url",
- type: "menuitem",
- title: "Attach from URL",
- icon: "link",
- onClick: function () { },
- },
- ],
-}); };
-var imageActionSheet = function (editor) { return ({
- key: "image",
- type: "menuitem",
- title: "Image",
- icon: "image",
- items: [
- {
- key: "imageOptions",
- type: "menuitem",
- component: function (_a) {
- var onClick = _a.onClick;
- var _b = __read(useState(true), 2), isOpen = _b[0], setIsOpen = _b[1];
- return (_jsx(ActionSheetPresenter, { isOpen: isOpen, onClose: function () { return setIsOpen(false); }, items: [
- {
- key: "upload-from-disk",
- type: "menuitem",
- title: "Upload from disk",
- icon: "upload",
- onClick: function () {
- return editor === null || editor === void 0 ? void 0 : editor.chain().focus().openAttachmentPicker("image").run();
- },
- },
- {
- key: "upload-from-url",
- type: "menuitem",
- title: "Attach from URL",
- icon: "link",
- onClick: function () { },
- },
- ] }));
+ menu: {
+ title: "Insert an image",
+ items: [
+ {
+ key: "upload-from-disk",
+ type: "button",
+ title: "Upload from disk",
+ icon: "upload",
+ onClick: function () { },
},
- },
- ],
-}); };
-var embed = function (editor) { return ({
- key: "embed",
- type: "menuitem",
- title: "Embed",
- icon: "embed",
+ {
+ key: "upload-from-url",
+ type: "button",
+ title: "Attach from URL",
+ icon: "link",
+ onClick: function () { },
+ },
+ ],
+ },
}); };
var table = function (editor) { return ({
key: "table",
- type: "menuitem",
+ type: "button",
title: "Table",
icon: "table",
- items: [
- {
- key: "table-size-selector",
- type: "menuitem",
- component: function (props) { return (_jsx(TablePopup, { onInsertTable: function (size) {
- var _a;
- editor === null || editor === void 0 ? void 0 : editor.chain().focus().insertTable({
- rows: size.rows,
- cols: size.columns,
- }).run();
- (_a = props.onClick) === null || _a === void 0 ? void 0 : _a.call(props);
- } })); },
- },
- ],
+ menu: {
+ title: "Insert a table",
+ items: [
+ {
+ key: "table-size-selector",
+ type: "popup",
+ component: function (props) { return (_jsx(TablePopup, { onInsertTable: function (size) {
+ var _a;
+ editor === null || editor === void 0 ? void 0 : editor.chain().focus().insertTable({
+ rows: size.rows,
+ cols: size.columns,
+ }).run();
+ (_a = props.onClick) === null || _a === void 0 ? void 0 : _a.call(props);
+ } })); },
+ },
+ ],
+ },
}); };
-var embedActionSheet = function (editor) { return ({
+var embedMobile = function (editor) { return ({
key: "embed",
- type: "menuitem",
+ type: "button",
title: "Embed",
icon: "embed",
- items: [
- {
- key: "table-size-selector",
- type: "menuitem",
- component: function (_a) {
- var onClick = _a.onClick;
- var _b = __read(useState(true), 2), isOpen = _b[0], setIsOpen = _b[1];
- return (_jsx(ActionSheetPresenter, __assign({ isOpen: isOpen, onClose: function () { return setIsOpen(false); }, items: [] }, { children: _jsx(EmbedPopup, { title: "Insert embed", icon: "check", onClose: function (embed) {
+ menu: {
+ title: "Insert an embed",
+ items: [
+ {
+ key: "embed-popup",
+ type: "popup",
+ component: function (_a) {
+ var onClick = _a.onClick;
+ return (_jsx(EmbedPopup, { title: "Insert embed", onClose: function (embed) {
+ if (!embed)
+ return onClick === null || onClick === void 0 ? void 0 : onClick();
editor === null || editor === void 0 ? void 0 : editor.chain().insertEmbed(embed).run();
- setIsOpen(false);
onClick === null || onClick === void 0 ? void 0 : onClick();
- } }) })));
+ } }));
+ },
},
- },
- ],
+ ],
+ },
}); };
-var tableActionSheet = function (editor) { return ({
- key: "table",
- type: "menuitem",
- title: "Table",
- icon: "table",
- items: [
- {
- key: "table-size-selector",
- type: "menuitem",
- component: function (_a) {
- var onClick = _a.onClick;
- var _b = __read(useState(true), 2), isOpen = _b[0], setIsOpen = _b[1];
- return (_jsx(ActionSheetPresenter, __assign({ isOpen: isOpen, onClose: function () { return setIsOpen(false); }, items: [] }, { children: _jsx(TablePopup, { cellSize: 30, autoExpand: false, onInsertTable: function (size) {
- editor === null || editor === void 0 ? void 0 : editor.chain().focus().insertTable({
- rows: size.rows,
- cols: size.columns,
- }).run();
- setIsOpen(false);
- onClick === null || onClick === void 0 ? void 0 : onClick();
- } }) })));
- },
- },
- ],
+var embedDesktop = function (editor) { return ({
+ key: "embed",
+ type: "button",
+ title: "Embed",
+ icon: "embed",
+ onClick: function () {
+ if (!editor)
+ return;
+ showPopup({
+ theme: editor.storage.theme,
+ popup: function (hide) { return (_jsx(EmbedPopup, { title: "Insert embed", onClose: function (embed) {
+ if (!embed)
+ return hide();
+ editor === null || editor === void 0 ? void 0 : editor.chain().insertEmbed(embed).run();
+ hide();
+ } })); },
+ });
+ },
}); };
var attachment = function (editor) { return ({
key: "attachment",
- type: "menuitem",
+ type: "button",
title: "Attachment",
icon: "attachment",
isChecked: editor === null || editor === void 0 ? void 0 : editor.isActive("attachment"),
@@ -239,7 +195,7 @@ var attachment = function (editor) { return ({
}); };
var tasklist = function (editor) { return ({
key: "tasklist",
- type: "menuitem",
+ type: "button",
title: "Task list",
icon: "checkbox",
isChecked: editor === null || editor === void 0 ? void 0 : editor.isActive("taskList"),
diff --git a/packages/editor/dist/toolbar/tools/colors.d.ts b/packages/editor/dist/toolbar/tools/colors.d.ts
index 2b501e6fc..97271d99e 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 { ToolProps } from "../types";
-export declare const DEFAULT_COLORS: string[];
+import { Editor } from "@tiptap/core";
+declare type ColorToolProps = ToolProps & {
+ onColorChange: (editor: Editor, color?: string) => void;
+ isActive: (editor: Editor) => boolean;
+ getActiveColor: (editor: Editor) => string;
+ title: string;
+};
+export declare function ColorTool(props: ColorToolProps): JSX.Element;
export declare function Highlight(props: ToolProps): JSX.Element;
export declare function TextColor(props: ToolProps): JSX.Element;
-declare type ColorPickerProps = {
- colors: string[];
- color: string;
- onClear: () => void;
- onChange: (color: string) => void;
-};
-export declare function ColorPicker(props: ColorPickerProps): JSX.Element;
export {};
diff --git a/packages/editor/dist/toolbar/tools/colors.js b/packages/editor/dist/toolbar/tools/colors.js
index 20cd3828d..d2b308cc8 100644
--- a/packages/editor/dist/toolbar/tools/colors.js
+++ b/packages/editor/dist/toolbar/tools/colors.js
@@ -36,126 +36,57 @@ var __read = (this && this.__read) || function (o, n) {
}
return ar;
};
-import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
-import { Button, Flex } from "rebass";
-import { Input } from "@rebass/forms";
-import { Icon } from "../components/icon";
-import { Icons } from "../icons";
+import { jsx as _jsx } from "react/jsx-runtime";
import { SplitButton } from "../components/split-button";
import { useState } from "react";
import tinycolor from "tinycolor2";
-import { HexColorPicker } from "react-colorful";
-export var DEFAULT_COLORS = [
- "#e91e63",
- "#9c27b0",
- "#673ab7",
- "#3f51b5",
- "#2196f3",
- "#03a9f4",
- "#00bcd4",
- "#009688",
- "#4caf50",
- "#8bc34a",
- "#cddc39",
- "#ffeb3b",
- "#ffc107",
- "#f44336",
-];
-function ColorTool(props) {
- var editor = props.editor, onColorChange = props.onColorChange, isActive = props.isActive, getActiveColor = props.getActiveColor, toolProps = __rest(props, ["editor", "onColorChange", "isActive", "getActiveColor"]);
+import { getToolbarElement } from "../utils/dom";
+import { useToolbarLocation } from "../stores/toolbar-store";
+import { ColorPicker } from "../popups/color-picker";
+import { useEditorContext } from "../../components/popup-presenter/popuprenderer";
+import { PopupWrapper } from "../../components/popup-presenter";
+export function ColorTool(props) {
+ var onColorChange = props.onColorChange, isActive = props.isActive, getActiveColor = props.getActiveColor, title = props.title, toolProps = __rest(props, ["onColorChange", "isActive", "getActiveColor", "title"]);
+ var editor = useEditorContext();
var activeColor = getActiveColor(editor);
var _isActive = isActive(editor);
var tColor = tinycolor(activeColor);
- return (_jsx(SplitButton, __assign({}, toolProps, { toggled: false, iconColor: _isActive && tColor.isDark() ? "static" : "icon", sx: {
+ var toolbarLocation = useToolbarLocation();
+ var isBottom = toolbarLocation === "bottom";
+ var _a = __read(useState(false), 2), isOpen = _a[0], setIsOpen = _a[1];
+ // const { hide, isOpen, show } = usePopup({
+ // id: title,
+ // group: "color",
+ // theme: editor?.storage.theme,
+ // blocking: false,
+ // focusOnRender: false,
+ // });
+ // console.log("Updating color", editor);
+ return (_jsx(SplitButton, __assign({}, toolProps, { iconColor: _isActive && tColor.isDark() ? "static" : "icon", sx: {
mr: 0,
bg: _isActive ? activeColor : "transparent",
":hover": {
bg: _isActive ? tColor.darken(5).toRgbString() : "transparent",
},
- }, popupPresenterProps: {
- mobile: "sheet",
- desktop: "menu",
- } }, { children: _jsx(Flex, __assign({ sx: {
- bg: "background",
- width: ["auto", "auto", 250],
- flexDirection: "column",
- p: [3, 3, 2],
- boxShadow: ["none", "none", "menu"],
- borderRadius: ["none", "none", "dialog"],
- ".react-colorful": {
- width: "auto",
- height: 150,
- },
- } }, { children: _jsx(ColorPicker, { colors: DEFAULT_COLORS, color: activeColor, onClear: function () { return onColorChange(editor); }, onChange: function (color) { return onColorChange(editor, color); } }) })) })));
+ }, onOpen: function () { return setIsOpen(function (s) { return !s; }); }, toggled: isOpen }, { children: _jsx(PopupWrapper, { isOpen: isOpen, id: title, 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 () { return onColorChange(editor); }, onChange: function (color) { return onColorChange(editor, color); }, onClose: close, title: title })); } }) })));
}
export function Highlight(props) {
- return (_jsx(ColorTool, __assign({}, props, { isActive: function (editor) { return editor.isActive("highlight", { color: /\W+/gm }); }, getActiveColor: function (editor) { return editor.getAttributes("highlight").color; }, onColorChange: function (editor, color) {
+ return (_jsx(ColorTool, __assign({}, props, { isActive: function (editor) { return editor.isActive("highlight", { color: /\W+/gm }); }, getActiveColor: function (editor) { return editor.getAttributes("highlight").color; }, title: "Background color", onColorChange: function (editor, color) {
return color
? editor.chain().focus().toggleHighlight({ color: color }).run()
: editor.chain().focus().unsetHighlight().run();
} })));
}
export function TextColor(props) {
- return (_jsx(ColorTool, __assign({}, props, { isActive: function (editor) { return editor.isActive("textStyle", { color: /\W+/gm }); }, getActiveColor: function (editor) { return editor.getAttributes("textStyle").color; }, onColorChange: function (editor, color) {
+ return (_jsx(ColorTool, __assign({}, props, { isActive: function (editor) { return editor.isActive("textStyle", { color: /\W+/gm }); }, getActiveColor: function (editor) { return editor.getAttributes("textStyle").color; }, title: "Text color", onColorChange: function (editor, color) {
return color
? editor.chain().focus().setColor(color).run()
: editor.chain().focus().unsetColor().run();
} })));
}
-var PALETTE_SIZE = [35, 35, 25];
-export function ColorPicker(props) {
- var colors = props.colors, color = props.color, onClear = props.onClear, onChange = props.onChange;
- var _a = __read(useState(false), 2), isPickerOpen = _a[0], setIsPickerOpen = _a[1];
- var tColor = tinycolor(color || colors[0]);
- var _b = __read(useState(tColor.toHexString()), 2), currentColor = _b[0], setCurrentColor = _b[1];
- return (_jsxs(_Fragment, { children: [isPickerOpen && (_jsx(HexColorPicker, { color: currentColor, onChange: onChange })), _jsxs(Flex, __assign({ sx: {
- alignItems: "center",
- justifyContent: "center",
- mt: isPickerOpen ? 2 : 0,
- } }, { children: [_jsx(Button, __assign({ variant: "secondary", sx: {
- flexShrink: 0,
- bg: currentColor,
- width: PALETTE_SIZE,
- height: PALETTE_SIZE,
- mr: 2,
- borderRadius: 50,
- boxShadow: "menu",
- p: 0,
- }, onClick: function () { return setIsPickerOpen(function (s) { return !s; }); } }, { children: _jsx(Icon, { path: Icons.palette, color: tColor.isDark() ? "static" : "icon", size: 18 }) })), _jsx(Input, { variant: "clean", placeholder: "#000000", spellCheck: false, sx: {
- p: 0,
- borderRadius: 0,
- fontSize: ["title", "title", "body"],
- color: "fontTertiary",
- textAlign: "left",
- letterSpacing: 1.5,
- }, value: currentColor.toUpperCase(), maxLength: 7, onChange: function (e) {
- var value = e.target.value;
- if (!value)
- return;
- setCurrentColor(value);
- } }), _jsx(Button, __assign({ variant: "icon", sx: {
- flexShrink: 0,
- bg: "transparent",
- width: PALETTE_SIZE,
- height: PALETTE_SIZE,
- mr: 2,
- borderRadius: 50,
- p: 0,
- }, onClick: onClear }, { children: _jsx(Icon, { path: Icons.colorClear, color: "text", size: 15 }) }))] })), _jsx(Flex, __assign({ sx: {
- borderTop: "1px solid var(--border)",
- mt: 2,
- pt: 4,
- flexWrap: "wrap",
- } }, { children: colors.map(function (color) { return (_jsx(Button, { variant: "secondary", sx: {
- bg: color,
- width: PALETTE_SIZE,
- height: PALETTE_SIZE,
- ml: [2, 2, 1],
- mb: [2, 2, 1],
- borderRadius: 50,
- boxShadow: "menu",
- }, onClick: function () {
- setCurrentColor(color);
- onChange(color);
- } })); }) }))] }));
-}
diff --git a/packages/editor/dist/toolbar/tools/font.js b/packages/editor/dist/toolbar/tools/font.js
index b8a097341..862745874 100644
--- a/packages/editor/dist/toolbar/tools/font.js
+++ b/packages/editor/dist/toolbar/tools/font.js
@@ -1,14 +1,3 @@
-var __assign = (this && this.__assign) || function () {
- __assign = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
@@ -25,11 +14,10 @@ var __read = (this && this.__read) || function (o, n) {
}
return ar;
};
-import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
+import { jsx as _jsx } from "react/jsx-runtime";
import { Dropdown } from "../components/dropdown";
-import { Flex, Text } from "rebass";
-import { ToolButton } from "../components/tool-button";
import { useCallback } from "react";
+import { Counter } from "../components/counter";
var defaultFontSizes = [
8, 12, 14, 16, 18, 20, 24, 28, 32, 36, 42, 48, 60, 72, 100,
];
@@ -40,23 +28,15 @@ export function FontSize(props) {
var decreaseFontSize = useCallback(function () {
return Math.max(8, fontSizeAsNumber - 1);
}, [fontSizeAsNumber]);
- return (_jsxs(Flex, __assign({ sx: {
- alignItems: "center",
- mr: 1,
- ":last-of-type": {
- mr: 0,
- },
- } }, { children: [_jsx(ToolButton, { toggled: false, title: "Decrease font size", icon: "minus", variant: "small", onClick: function () {
- editor.chain().focus().setFontSize("".concat(decreaseFontSize(), "px")).run();
- } }), _jsx(Text, __assign({ variant: "body", sx: { fontSize: "subBody", mx: 1, textAlign: "center" }, title: "Reset font size", onClick: function () {
- editor.chain().focus().setFontSize("16px").run();
- } }, { children: fontSize })), _jsx(ToolButton, { toggled: false, title: "Increase font size", icon: "plus", variant: "small", onClick: function () {
- editor
- .chain()
- .focus()
- .setFontSize("".concat(fontSizeAsNumber + 1, "px"))
- .run();
- } })] })));
+ return (_jsx(Counter, { title: "font size", onDecrease: function () {
+ return editor.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 fontFamilies = {
System: "Open Sans",
@@ -79,7 +59,7 @@ function toMenuItems(editor, currentFontFamily) {
var value = fontFamilies[key];
menuItems.push({
key: key,
- type: "menuitem",
+ type: "button",
title: key,
isChecked: key === currentFontFamily,
onClick: function () { return editor.chain().focus().setFontFamily(value).run(); },
diff --git a/packages/editor/dist/toolbar/tools/headings.js b/packages/editor/dist/toolbar/tools/headings.js
index 41ed1ae6b..7fd6aac40 100644
--- a/packages/editor/dist/toolbar/tools/headings.js
+++ b/packages/editor/dist/toolbar/tools/headings.js
@@ -35,7 +35,7 @@ export function Headings(props) {
}
function toMenuItems(editor, currentHeadingLevel) {
var menuItems = defaultLevels.map(function (level) { return ({
- type: "menuitem",
+ type: "button",
key: "heading-".concat(level),
title: "Heading ".concat(level),
isChecked: level === currentHeadingLevel,
@@ -49,7 +49,7 @@ function toMenuItems(editor, currentHeadingLevel) {
}); });
var paragraph = {
key: "paragraph",
- type: "menuitem",
+ type: "button",
title: "Paragraph",
isChecked: !currentHeadingLevel,
onClick: function () { return editor.chain().focus().setParagraph().run(); },
diff --git a/packages/editor/dist/toolbar/tools/index.d.ts b/packages/editor/dist/toolbar/tools/index.d.ts
index 5c7fd2c4d..f51c43898 100644
--- a/packages/editor/dist/toolbar/tools/index.d.ts
+++ b/packages/editor/dist/toolbar/tools/index.d.ts
@@ -8,6 +8,8 @@ import { Headings } from "./headings";
import { NumberedList, BulletList } from "./lists";
import { LeftToRight, RightToLeft } from "./text-direction";
import { Highlight, TextColor } from "./colors";
+import { TableSettings, ColumnProperties, RowProperties, CellProperties, CellBackgroundColor, CellBorderColor, CellTextColor, CellBorderWidth } from "./table";
+export declare type ToolId = keyof typeof tools;
declare const tools: {
bold: typeof Bold;
italic: typeof Italic;
@@ -32,7 +34,27 @@ declare const tools: {
rtl: typeof RightToLeft;
textColor: typeof TextColor;
highlight: typeof Highlight;
+ tableSettings: typeof TableSettings;
+ columnProperties: typeof ColumnProperties;
+ rowProperties: typeof RowProperties;
+ cellProperties: typeof CellProperties;
+ insertColumnLeft: (props: ToolProps) => JSX.Element;
+ insertColumnRight: (props: ToolProps) => JSX.Element;
+ moveColumnLeft: (props: ToolProps) => JSX.Element;
+ moveColumnRight: (props: ToolProps) => JSX.Element;
+ deleteColumn: (props: ToolProps) => JSX.Element;
+ splitCells: (props: ToolProps) => JSX.Element;
+ mergeCells: (props: ToolProps) => JSX.Element;
+ cellBackgroundColor: typeof CellBackgroundColor;
+ cellBorderColor: typeof CellBorderColor;
+ cellTextColor: typeof CellTextColor;
+ cellBorderWidth: typeof CellBorderWidth;
+ insertRowAbove: (props: ToolProps) => JSX.Element;
+ insertRowBelow: (props: ToolProps) => JSX.Element;
+ moveRowUp: (props: ToolProps) => JSX.Element;
+ moveRowDown: (props: ToolProps) => JSX.Element;
+ deleteRow: (props: ToolProps) => JSX.Element;
+ deleteTable: (props: ToolProps) => JSX.Element;
};
-export declare type ToolId = keyof typeof tools;
-export declare function findToolById(id: ToolId): React.FunctionComponent<ToolProps>;
+export declare function findTool(id: ToolId): React.FunctionComponent<ToolProps>;
export {};
diff --git a/packages/editor/dist/toolbar/tools/index.js b/packages/editor/dist/toolbar/tools/index.js
index 6aaf4f495..77a2f2152 100644
--- a/packages/editor/dist/toolbar/tools/index.js
+++ b/packages/editor/dist/toolbar/tools/index.js
@@ -2,38 +2,11 @@ import { Bold, Italic, Underline, Strikethrough, Code, Subscript, Superscript, C
import { InsertBlock } from "./block";
import { FontSize, FontFamily } from "./font";
import { AlignCenter, AlignLeft, AlignRight, AlignJustify } from "./alignment";
-// import {
-// Blockquote,
-// CodeBlock,
-// HorizontalRule,
-// Image,
-// Table,
-// Embed,
-// } from "./block";
import { Headings } from "./headings";
import { NumberedList, BulletList } from "./lists";
import { LeftToRight, RightToLeft } from "./text-direction";
import { Highlight, TextColor } from "./colors";
-// const tools = {
-// bold: new Bold(),
-// italic: new Italic(),
-// underline: new Underline(),
-// strikethrough: new Strikethrough(),
-// code: new Code(),
-// formatClear: new ClearFormatting(),
-// subscript: new Subscript(),
-// superscript: new Superscript(),
-// horizontalRule: new HorizontalRule(),
-// codeblock: new CodeBlock(),
-// blockquote: new Blockquote(),
-// headings: new Headings(),
-// checklist: new Checklist(),
-// link: new Link(),
-// image: new Image(),
-// attachment: new Attachment(),
-// table: new Table(),
-// embed: new Embed(),
-// };
+import { TableSettings, ColumnProperties, RowProperties, CellProperties, InsertColumnLeft, InsertColumnRight, MoveColumnLeft, MoveColumnRight, DeleteColumn, SplitCells, MergeCells, InsertRowAbove, InsertRowBelow, MoveRowUp, MoveRowDown, DeleteRow, DeleteTable, CellBackgroundColor, CellBorderColor, CellTextColor, CellBorderWidth, } from "./table";
var tools = {
bold: Bold,
italic: Italic,
@@ -58,7 +31,28 @@ var tools = {
rtl: RightToLeft,
textColor: TextColor,
highlight: Highlight,
+ tableSettings: TableSettings,
+ columnProperties: ColumnProperties,
+ rowProperties: RowProperties,
+ cellProperties: CellProperties,
+ insertColumnLeft: InsertColumnLeft,
+ insertColumnRight: InsertColumnRight,
+ moveColumnLeft: MoveColumnLeft,
+ moveColumnRight: MoveColumnRight,
+ deleteColumn: DeleteColumn,
+ splitCells: SplitCells,
+ mergeCells: MergeCells,
+ cellBackgroundColor: CellBackgroundColor,
+ cellBorderColor: CellBorderColor,
+ cellTextColor: CellTextColor,
+ cellBorderWidth: CellBorderWidth,
+ insertRowAbove: InsertRowAbove,
+ insertRowBelow: InsertRowBelow,
+ moveRowUp: MoveRowUp,
+ moveRowDown: MoveRowDown,
+ deleteRow: DeleteRow,
+ deleteTable: DeleteTable,
};
-export function findToolById(id) {
+export function findTool(id) {
return tools[id];
}
diff --git a/packages/editor/dist/toolbar/tools/inline.js b/packages/editor/dist/toolbar/tools/inline.js
index 01d5aa5bf..6d12b196a 100644
--- a/packages/editor/dist/toolbar/tools/inline.js
+++ b/packages/editor/dist/toolbar/tools/inline.js
@@ -25,11 +25,11 @@ var __read = (this && this.__read) || function (o, n) {
}
return ar;
};
-import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
+import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { ToolButton } from "../components/tool-button";
-import { PopupPresenter } from "../../components/menu/menu";
-import { useRef, useState } from "react";
-import { Flex } from "rebass";
+import { useCallback, useRef, useState } from "react";
+import { ResponsivePresenter } from "../../components/responsive";
+import { Button, Flex } from "rebass";
import { Input } from "@rebass/forms";
import { Popup } from "../components/popup";
function InlineTool(props) {
@@ -71,7 +71,20 @@ export function Link(props) {
var _c = __read(useState(), 2), text = _c[0], setText = _c[1];
var currentUrl = editor.getAttributes("link").href;
var isEditing = !!currentUrl;
- return (_jsxs(_Fragment, { children: [_jsx(ToolButton, { id: icon, ref: buttonRef, title: title, icon: icon, onClick: function () {
+ var onDone = useCallback(function (href, text) {
+ if (!href)
+ return;
+ var commandChain = editor
+ .chain()
+ .focus()
+ .extendMarkRange("link")
+ .setLink({ href: href, target: "_blank" });
+ if (text)
+ commandChain = commandChain.insertContent(text).focus();
+ commandChain.run();
+ setIsOpen(false);
+ }, []);
+ return (_jsxs(_Fragment, { children: [_jsx(ToolButton, { id: icon, buttonRef: buttonRef, title: title, icon: icon, onClick: function () {
if (isEditing)
setHref(currentUrl);
var _a = editor.state.selection, from = _a.from, to = _a.to, $from = _a.$from;
@@ -84,31 +97,27 @@ export function Link(props) {
: editor.state.doc.textBetween(from, to);
setText(selectedText);
setIsOpen(true);
- }, toggled: isOpen || !!isEditing }), _jsx(PopupPresenter, __assign({ mobile: "sheet", desktop: "menu", options: {
- type: "menu",
- position: {
- target: targetRef.current || buttonRef.current || undefined,
- isTargetAbsolute: true,
- location: "below",
- yOffset: 5,
- },
- }, isOpen: isOpen, items: [], onClose: function () {
+ }, toggled: isOpen || !!isEditing }), _jsx(ResponsivePresenter, __assign({ mobile: "sheet", desktop: "menu", position: {
+ target: targetRef.current || 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);
- } }, { children: _jsx(Popup, __assign({ title: isEditing ? "Edit link" : "Insert link", action: {
- text: isEditing ? "Edit" : "Insert",
- onClick: function () {
- if (!href)
- return;
- var commandChain = editor
- .chain()
- .focus()
- .extendMarkRange("link")
- .setLink({ href: href, target: "_blank" });
- if (text)
- commandChain = commandChain.insertContent(text).focus();
- commandChain.run();
- setIsOpen(false);
- },
- } }, { children: _jsxs(Flex, __assign({ sx: { p: 1, flexDirection: "column" } }, { children: [_jsx(Input, { type: "text", placeholder: "Link text", value: text, onChange: function (e) { return setText(e.target.value); } }), _jsx(Input, { type: "url", sx: { mt: 1 }, autoFocus: true, placeholder: "https://example.com/", value: href, onChange: function (e) { return setHref(e.target.value); } })] })) })) }))] }));
+ }, 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);
+ } }) })) }))] }));
+}
+function LinkPopup(props) {
+ var _text = props.text, _href = props.href, _a = props.isEditing, isEditing = _a === void 0 ? false : _a, onDone = props.onDone;
+ var _b = __read(useState(_href || ""), 2), href = _b[0], setHref = _b[1];
+ var _c = __read(useState(_text || ""), 2), text = _c[0], setText = _c[1];
+ return (_jsxs(Flex, __assign({ sx: { p: 1, flexDirection: "column", width: ["auto", 250] } }, { children: [_jsx(Input, { type: "text", placeholder: "Link text", value: text, onChange: function (e) { return setText(e.target.value); } }), _jsx(Input, { type: "url", sx: { mt: 1 }, autoFocus: true, placeholder: "https://example.com/", value: href, onChange: function (e) { return setHref(e.target.value); } }), _jsx(Button, __assign({ variant: "primary", sx: {
+ alignSelf: ["stretch", "end", "end"],
+ my: 1,
+ mr: 1,
+ }, onClick: function () { return onDone({ text: text, href: href }); } }, { children: isEditing ? "Save edits" : "Insert link" }))] })));
}
diff --git a/packages/editor/dist/toolbar/tools/lists.js b/packages/editor/dist/toolbar/tools/lists.js
index 15b66ef8e..82c20fae4 100644
--- a/packages/editor/dist/toolbar/tools/lists.js
+++ b/packages/editor/dist/toolbar/tools/lists.js
@@ -20,36 +20,54 @@ var __rest = (this && this.__rest) || function (s, e) {
}
return t;
};
+var __read = (this && this.__read) || function (o, n) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
+ if (!m) return o;
+ var i = m.call(o), r, ar = [], e;
+ try {
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
+ }
+ catch (error) { e = { error: error }; }
+ finally {
+ try {
+ if (r && !r.done && (m = i["return"])) m.call(i);
+ }
+ finally { if (e) throw e.error; }
+ }
+ return ar;
+};
import { jsx as _jsx } from "react/jsx-runtime";
import { Box, Button, Flex } from "rebass";
+import { 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);
- return (_jsx(SplitButton, __assign({}, toolProps, { onClick: function () { return options.onClick(editor); }, toggled: isActive, sx: { mr: 0 }, popupPresenterProps: {
- items: options.subTypes.map(function (item) { return ({
- key: item.type,
- tooltip: item.title,
- type: "menuitem",
- component: function (_a) {
- var onClick = _a.onClick;
- return (_jsx(Button, __assign({ variant: "menuitem", onClick: onClick }, { children: _jsx(ListThumbnail, { listStyleType: item.type }) })));
- },
- onClick: function () {
- var chain = editor.chain().focus();
- if (!isActive) {
- if (options.type === "bulletList")
- chain = chain.toggleBulletList();
- else
- chain = chain.toggleOrderedList();
- }
- return chain
- .updateAttributes(options.type, { listType: item.type })
- .run();
- },
- }); }),
- sx: { display: "grid", gridTemplateColumns: "1fr 1fr 1fr", p: 1 },
- } })));
+ 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: {
+ 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();
+ if (!isActive) {
+ if (options.type === "bulletList")
+ chain = chain.toggleBulletList();
+ else
+ chain = chain.toggleOrderedList();
+ }
+ return chain
+ .updateAttributes(options.type, { listType: item.type })
+ .run();
+ } }, { children: _jsx(ListThumbnail, { listStyleType: item.type }) }), item.title)); }) }))); } }) })));
}
export function NumberedList(props) {
var options = {
@@ -95,7 +113,7 @@ function ListThumbnail(props) {
flex: 1,
p: 0,
listStyleType: listStyleType,
- } }, { children: [0, 0, 0].map(function () { return (_jsx(Box, __assign({ as: "li", sx: {
+ } }, { children: [0, 1, 2].map(function (i) { return (_jsx(Box, __assign({ as: "li", sx: {
display: "list-item",
color: "text",
fontSize: 8,
@@ -108,5 +126,5 @@ function ListThumbnail(props) {
height: 4,
bg: "#cbcbcb",
borderRadius: "small",
- } }) })) }))); }) })));
+ } }) })) }), i.toString())); }) })));
}
diff --git a/packages/editor/dist/toolbar/tools/table.d.ts b/packages/editor/dist/toolbar/tools/table.d.ts
new file mode 100644
index 000000000..8a7280fd5
--- /dev/null
+++ b/packages/editor/dist/toolbar/tools/table.d.ts
@@ -0,0 +1,24 @@
+/// <reference types="react" />
+import { ToolProps } from "../types";
+export declare function TableSettings(props: ToolProps): JSX.Element | null;
+export declare function RowProperties(props: ToolProps): JSX.Element;
+export declare function ColumnProperties(props: ToolProps): JSX.Element;
+export declare function TableProperties(props: ToolProps): JSX.Element;
+export declare function CellProperties(props: ToolProps): JSX.Element;
+export declare function CellBackgroundColor(props: ToolProps): JSX.Element;
+export declare function CellTextColor(props: ToolProps): JSX.Element;
+export declare function CellBorderColor(props: ToolProps): JSX.Element;
+export declare function CellBorderWidth(props: ToolProps): JSX.Element;
+export declare const InsertColumnLeft: (props: ToolProps) => JSX.Element;
+export declare const InsertColumnRight: (props: ToolProps) => JSX.Element;
+export declare const MoveColumnLeft: (props: ToolProps) => JSX.Element;
+export declare const MoveColumnRight: (props: ToolProps) => JSX.Element;
+export declare const DeleteColumn: (props: ToolProps) => JSX.Element;
+export declare const SplitCells: (props: ToolProps) => JSX.Element;
+export declare const MergeCells: (props: ToolProps) => JSX.Element;
+export declare const InsertRowAbove: (props: ToolProps) => JSX.Element;
+export declare const InsertRowBelow: (props: ToolProps) => JSX.Element;
+export declare const MoveRowUp: (props: ToolProps) => JSX.Element;
+export declare const MoveRowDown: (props: ToolProps) => JSX.Element;
+export declare const DeleteRow: (props: ToolProps) => JSX.Element;
+export declare const DeleteTable: (props: ToolProps) => JSX.Element;
diff --git a/packages/editor/dist/toolbar/tools/table.js b/packages/editor/dist/toolbar/tools/table.js
new file mode 100644
index 000000000..680788fe9
--- /dev/null
+++ b/packages/editor/dist/toolbar/tools/table.js
@@ -0,0 +1,179 @@
+var __assign = (this && this.__assign) || function () {
+ __assign = Object.assign || function(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+};
+var __read = (this && this.__read) || function (o, n) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
+ if (!m) return o;
+ var i = m.call(o), r, ar = [], e;
+ try {
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
+ }
+ catch (error) { e = { error: error }; }
+ finally {
+ try {
+ if (r && !r.done && (m = i["return"])) m.call(i);
+ }
+ finally { if (e) throw e.error; }
+ }
+ return ar;
+};
+import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
+import { ToolButton } from "../components/tool-button";
+import { useCallback, useMemo, useState } from "react";
+import { Flex, Text } from "rebass";
+import { ResponsivePresenter } from "../../components/responsive";
+import { MoreTools } from "../components/more-tools";
+import { menuButtonToTool } from "./utils";
+import { getToolDefinition } from "../tool-definitions";
+import { CellProperties as CellPropertiesPopup } from "../popups/cell-properties";
+import { ColorTool } from "./colors";
+import { Counter } from "../components/counter";
+import { useToolbarLocation } from "../stores/toolbar-store";
+import { showPopup } from "../../components/popup-presenter";
+export function TableSettings(props) {
+ var editor = props.editor;
+ var isBottom = useToolbarLocation() === "bottom";
+ if (!editor.isActive("table") || !isBottom)
+ return null;
+ return (_jsx(MoreTools, __assign({}, props, { popupId: "tableSettings", tools: [
+ "insertColumnLeft",
+ "insertColumnRight",
+ "insertRowAbove",
+ "insertRowBelow",
+ "cellProperties",
+ "columnProperties",
+ "rowProperties",
+ "deleteRow",
+ "deleteColumn",
+ "deleteTable",
+ ] })));
+}
+export function RowProperties(props) {
+ var editor = props.editor;
+ var _a = __read(useState(false), 2), isMenuOpen = _a[0], setIsMenuOpen = _a[1];
+ var items = useMemo(function () { return [
+ insertRowAbove(editor),
+ insertRowBelow(editor),
+ moveRowUp(editor),
+ moveRowDown(editor),
+ deleteRow(editor),
+ ]; }, []);
+ return (_jsxs(_Fragment, { children: [_jsx(ToolButton, __assign({}, props, { toggled: isMenuOpen, onClick: function () { return setIsMenuOpen(true); } })), _jsx(ResponsivePresenter, { title: "Row properties", mobile: "sheet", desktop: "menu", isOpen: isMenuOpen, onClose: function () { return setIsMenuOpen(false); }, position: {}, items: items })] }));
+}
+export function ColumnProperties(props) {
+ var editor = props.editor;
+ var _a = __read(useState(false), 2), isMenuOpen = _a[0], setIsMenuOpen = _a[1];
+ var items = useMemo(function () { return [
+ insertColumnLeft(editor),
+ insertColumnRight(editor),
+ moveColumnLeft(editor),
+ moveColumnRight(editor),
+ deleteColumn(editor),
+ ]; }, []);
+ return (_jsxs(_Fragment, { children: [_jsx(ToolButton, __assign({}, props, { toggled: isMenuOpen, onClick: function () { return setIsMenuOpen(true); } })), _jsx(ResponsivePresenter, { title: "Column properties", mobile: "sheet", desktop: "menu", isOpen: isMenuOpen, onClose: function () { return setIsMenuOpen(false); }, position: {}, items: items })] }));
+}
+export function TableProperties(props) {
+ var editor = props.editor;
+ var _a = __read(useState(false), 2), isMenuOpen = _a[0], setIsMenuOpen = _a[1];
+ var items = useMemo(function () { return [
+ insertColumnLeft(editor),
+ insertColumnRight(editor),
+ moveColumnLeft(editor),
+ moveColumnRight(editor),
+ deleteColumn(editor),
+ { type: "separator", key: "cellSeperator" },
+ mergeCells(editor),
+ splitCells(editor),
+ cellProperties(editor),
+ { type: "separator", key: "tableSeperator" },
+ deleteTable(editor),
+ ]; }, []);
+ return (_jsxs(_Fragment, { children: [_jsx(ToolButton, __assign({}, props, { toggled: isMenuOpen, onClick: function () { return setIsMenuOpen(true); } })), _jsx(ResponsivePresenter, { title: "Table properties", mobile: "sheet", desktop: "menu", isOpen: isMenuOpen, onClose: function () { return setIsMenuOpen(false); }, position: {}, items: items })] }));
+}
+export function CellProperties(props) {
+ return (_jsx(_Fragment, { children: _jsx(MoreTools, __assign({}, props, { popupId: "cellProperties", tools: [
+ "mergeCells",
+ "splitCells",
+ "cellBackgroundColor",
+ "cellTextColor",
+ "cellBorderColor",
+ "cellBorderWidth",
+ ] })) }));
+}
+export function CellBackgroundColor(props) {
+ return (_jsx(ColorTool, __assign({}, props, { isActive: function (editor) {
+ return editor.isActive("tableCell", { backgroundColor: /\W+/gm });
+ }, getActiveColor: function (editor) {
+ return editor.getAttributes("tableCell").backgroundColor;
+ }, title: "Cell background color", onColorChange: function (editor, color) {
+ return editor.chain().setCellAttribute("backgroundColor", color).run();
+ } })));
+}
+export function CellTextColor(props) {
+ return (_jsx(ColorTool, __assign({}, props, { isActive: function (editor) { return editor.isActive("tableCell", { color: /\W+/gm }); }, getActiveColor: function (editor) { return editor.getAttributes("tableCell").color; }, title: "Cell text color", onColorChange: function (editor, color) {
+ return editor.chain().focus().setCellAttribute("color", color).run();
+ } })));
+}
+export function CellBorderColor(props) {
+ return (_jsx(ColorTool, __assign({}, props, { isActive: function (editor) {
+ return editor.isActive("tableCell", { borderColor: /\W+/gm });
+ }, getActiveColor: function (editor) { return editor.getAttributes("tableCell").borderColor; }, title: "Cell border color", onColorChange: function (editor, color) {
+ return editor.chain().focus().setCellAttribute("borderColor", color).run();
+ } })));
+}
+export function CellBorderWidth(props) {
+ var editor = props.editor;
+ var _borderWidth = editor.getAttributes("tableCell").borderWidth;
+ var borderWidth = _borderWidth ? _borderWidth : 1;
+ var decreaseBorderWidth = useCallback(function () {
+ return Math.max(1, borderWidth - 1);
+ }, [borderWidth]);
+ var increaseBorderWidth = useCallback(function () {
+ return Math.min(10, borderWidth + 1);
+ }, [borderWidth]);
+ return (_jsxs(Flex, __assign({ sx: { justifyContent: "center", alignItems: "center" } }, { children: [_jsx(Text, __assign({ variant: "subBody", sx: { mx: 1 } }, { children: "Border width:" })), _jsx(Counter, { title: "cell border width", onDecrease: function () {
+ return editor.commands.setCellAttribute("borderWidth", decreaseBorderWidth());
+ }, onIncrease: function () {
+ 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 moveColumnLeft = function (editor) { return (__assign(__assign({}, getToolDefinition("moveColumnLeft")), { key: "moveColumnLeft", type: "button", onClick: function () { return moveColumnLeft(editor); } })); };
+var moveColumnRight = function (editor) { return (__assign(__assign({}, getToolDefinition("moveColumnRight")), { key: "moveColumnRight", type: "button", onClick: function () { return moveColumnRight(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 moveRowUp = function (editor) { return (__assign(__assign({}, getToolDefinition("moveRowUp")), { key: "moveRowUp", type: "button", onClick: function () { } })); };
+var moveRowDown = function (editor) { return (__assign(__assign({}, getToolDefinition("moveRowDown")), { key: "moveRowDown", type: "button", onClick: function () { } })); };
+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 cellProperties = function (editor) { return (__assign(__assign({}, getToolDefinition("cellProperties")), { key: "cellProperties", type: "button", onClick: function () {
+ showPopup({
+ theme: editor.storage.theme,
+ popup: function (hide) { return _jsx(CellPropertiesPopup, { onClose: hide, editor: editor }); },
+ });
+ } })); };
+export var InsertColumnLeft = menuButtonToTool(insertColumnLeft);
+export var InsertColumnRight = menuButtonToTool(insertColumnRight);
+export var MoveColumnLeft = menuButtonToTool(moveColumnLeft);
+export var MoveColumnRight = menuButtonToTool(moveColumnRight);
+export var DeleteColumn = menuButtonToTool(deleteColumn);
+export var SplitCells = menuButtonToTool(splitCells);
+export var MergeCells = menuButtonToTool(mergeCells);
+export var InsertRowAbove = menuButtonToTool(insertRowAbove);
+export var InsertRowBelow = menuButtonToTool(insertRowBelow);
+export var MoveRowUp = menuButtonToTool(moveRowUp);
+export var MoveRowDown = menuButtonToTool(moveRowDown);
+export var DeleteRow = menuButtonToTool(deleteRow);
+export var DeleteTable = menuButtonToTool(deleteTable);
diff --git a/packages/editor/dist/toolbar/tools/utils.d.ts b/packages/editor/dist/toolbar/tools/utils.d.ts
new file mode 100644
index 000000000..2aaf4fe1f
--- /dev/null
+++ b/packages/editor/dist/toolbar/tools/utils.d.ts
@@ -0,0 +1,5 @@
+/// <reference types="react" />
+import { Editor } from "@tiptap/core";
+import { MenuButton } from "../../components/menu/types";
+import { ToolProps } from "../types";
+export declare function menuButtonToTool(constructItem: (editor: Editor) => MenuButton): (props: ToolProps) => JSX.Element;
diff --git a/packages/editor/dist/toolbar/tools/utils.js b/packages/editor/dist/toolbar/tools/utils.js
new file mode 100644
index 000000000..3e649ff2b
--- /dev/null
+++ b/packages/editor/dist/toolbar/tools/utils.js
@@ -0,0 +1,19 @@
+var __assign = (this && this.__assign) || function () {
+ __assign = Object.assign || function(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+};
+import { jsx as _jsx } from "react/jsx-runtime";
+import { ToolButton } from "../components/tool-button";
+export function menuButtonToTool(constructItem) {
+ return function (props) {
+ var item = constructItem(props.editor);
+ return (_jsx(ToolButton, __assign({}, props, { icon: item.icon || props.icon, toggled: item.isChecked || false, title: item.title, onClick: item.onClick })));
+ };
+}
diff --git a/packages/editor/dist/toolbar/types.d.ts b/packages/editor/dist/toolbar/types.d.ts
index 19ce4f691..20bbc1c61 100644
--- a/packages/editor/dist/toolbar/types.d.ts
+++ b/packages/editor/dist/toolbar/types.d.ts
@@ -1,10 +1,15 @@
import { Editor } from "@tiptap/core";
import { IconNames } from "./icons";
+import { ToolId } from "./tools";
export declare type ToolProps = ToolDefinition & {
editor: Editor;
+ variant?: "small" | "normal";
};
export declare type ToolDefinition = {
icon: IconNames;
title: string;
+ conditional?: boolean;
description?: string;
};
+export declare type ToolbarGroupDefinition = (ToolId | ToolId[])[];
+export declare type ToolbarDefinition = ToolbarGroupDefinition[];
diff --git a/packages/editor/dist/toolbar/utils/dom.d.ts b/packages/editor/dist/toolbar/utils/dom.d.ts
index ad25b37e2..03ae30042 100644
--- a/packages/editor/dist/toolbar/utils/dom.d.ts
+++ b/packages/editor/dist/toolbar/utils/dom.d.ts
@@ -1 +1,2 @@
export declare function getToolbarElement(): HTMLElement;
+export declare function getPopupContainer(): HTMLElement;
diff --git a/packages/editor/dist/toolbar/utils/dom.js b/packages/editor/dist/toolbar/utils/dom.js
index aab1dc4d5..a8c8fb214 100644
--- a/packages/editor/dist/toolbar/utils/dom.js
+++ b/packages/editor/dist/toolbar/utils/dom.js
@@ -1,3 +1,6 @@
export function getToolbarElement() {
return (document.querySelector(".editor-toolbar") || undefined);
}
+export function getPopupContainer() {
+ return (document.getElementById("popup-container") || undefined);
+}
diff --git a/packages/editor/dist/components/menu/useMenu.d.ts b/packages/editor/dist/utils/position.d.ts
similarity index 82%
rename from packages/editor/dist/components/menu/useMenu.d.ts
rename to packages/editor/dist/utils/position.d.ts
index 18974886d..85bee69bf 100644
--- a/packages/editor/dist/components/menu/useMenu.d.ts
+++ b/packages/editor/dist/utils/position.d.ts
@@ -6,11 +6,7 @@ declare type PositionData = {
width?: number;
height?: number;
};
-export declare type MenuOptions = {
- type: "autocomplete" | "menu";
- position?: PositionOptions;
-};
-declare type PositionOptions = {
+export declare type PositionOptions = {
target?: HTMLElement | "mouse";
isTargetAbsolute?: boolean;
location?: "right" | "left" | "below" | "top";
diff --git a/packages/editor/dist/components/menu/useMenu.js b/packages/editor/dist/utils/position.js
similarity index 65%
rename from packages/editor/dist/components/menu/useMenu.js
rename to packages/editor/dist/utils/position.js
index b4db2445e..519292baf 100644
--- a/packages/editor/dist/components/menu/useMenu.js
+++ b/packages/editor/dist/utils/position.js
@@ -102,61 +102,3 @@ export function getElementPosition(element, absolute) {
}
return position;
}
-// function mapMenuItems<TData>(
-// items: MenuItem<TData>[],
-// data: TData
-// ): ResolvedMenuItem<TData>[] {
-// return items.reduce((prev, item) => {
-// const { key, onClick: _onClick, disabled, hidden, checked, type } = item;
-// const isHidden = resolveProp(hidden, data, item);
-// if (isHidden) return prev;
-// const isSeperator = type === "seperator";
-// if (isSeperator) {
-// prev.push({ isSeperator: true });
-// return prev;
-// }
-// const title = resolveProp(item.title, data, item);
-// const icon = resolveProp(item.icon, data, item);
-// const isChecked = resolveProp(checked, data, item);
-// const isDisabled = resolveProp(disabled, data, item);
-// const items = resolveProp(item.items, data, item);
-// const modifier = resolveProp(item.modifier, data, item);
-// const onClick =
-// typeof _onClick === "function" && _onClick.bind(this, data, item);
-// const tooltip =
-// isDisabled || resolveProp(item.tooltip, data, item) || title;
-// const hasSubmenu = items?.length > 0;
-// const menuItem: ResolvedMenuItem<TData> = {
-// type,
-// title,
-// key,
-// onClick,
-// tooltip,
-// isChecked,
-// isDisabled: !!isDisabled,
-// isHidden,
-// hasSubmenu,
-// icon,
-// modifier: modifier?.join("+"),
-// };
-// if (hasSubmenu)
-// menuItem.items = mapMenuItems(items, { ...data, parent: menuItem });
-// prev.push(menuItem);
-// return prev;
-// }, []);
-// }
-// function resolveProp<T, TData>(
-// prop: Resolvable<T, TData>,
-// data: any,
-// item: MenuItem<TData>
-// ): T {
-// if (typeof prop === "function" && (prop as any).isReactComponent) {
-// return prop as T;
-// }
-// return isResolverFunction<T, TData>(prop) ? prop(data, item) : prop;
-// }
-// function isResolverFunction<T, TData>(
-// prop: any
-// ): prop is ResolverFunction<T, TData> {
-// return typeof prop === "function";
-// }
diff --git a/packages/editor/src/components/action-sheet/index.tsx b/packages/editor/src/components/action-sheet/index.tsx
new file mode 100644
index 000000000..021062937
--- /dev/null
+++ b/packages/editor/src/components/action-sheet/index.tsx
@@ -0,0 +1,196 @@
+import React, { PropsWithChildren, useCallback, useRef, useState } from "react";
+import { MenuItem } from "../menu/types";
+import { useTheme } from "emotion-theming";
+import Sheet from "react-modal-sheet";
+import { Theme } from "@notesnook/theme";
+import { Button, Flex, Text } from "rebass";
+import { Icon } from "../../toolbar/components/icon";
+import { Icons } from "../../toolbar/icons";
+import { MenuButton } from "../menu/menu-button";
+import { MenuSeparator } from "../menu/menu-separator";
+
+type ActionSheetHistoryItem = {
+ title?: string;
+ items?: MenuItem[];
+};
+
+function useHistory<T>(initial: T) {
+ const [current, setCurrent] = useState<T | undefined>(initial);
+ const [canGoBack, setCanGoBack] = useState(false);
+ const stack = useRef<T[]>([initial]);
+
+ const goBack = useCallback(() => {
+ if (!canGoBack) return;
+ const prev = stack.current.pop();
+ setCurrent(prev);
+ if (stack.current.length <= 1) setCanGoBack(false);
+ }, [canGoBack]);
+
+ const navigate = useCallback((state: T) => {
+ console.log("NAVI", state);
+ setCurrent((prev) => {
+ if (prev) stack.current.push(prev);
+ return state;
+ });
+
+ setCanGoBack(true);
+ }, []);
+
+ return { current, goBack, navigate, canGoBack };
+}
+
+export type ActionSheetPresenterProps = {
+ items?: MenuItem[];
+ isOpen: boolean;
+ onClose?: () => void;
+ blocking?: boolean;
+ focusOnRender?: boolean;
+ title?: string;
+};
+
+export function ActionSheetPresenter(
+ props: PropsWithChildren<ActionSheetPresenterProps>
+) {
+ const {
+ isOpen,
+ title,
+ items,
+ onClose,
+ blocking = true,
+ focusOnRender = true,
+ children,
+ } = props;
+ const theme: Theme = useTheme();
+ const contentRef = useRef<HTMLDivElement>();
+ const focusedElement = useRef<HTMLElement>();
+
+ // hijack the back button temporarily for a more native experience
+ // on mobile phones.
+ const onPopState = useCallback(
+ (e: PopStateEvent | BeforeUnloadEvent) => {
+ if (onClose) {
+ onClose();
+ e.preventDefault();
+ return true;
+ }
+ },
+ [isOpen, onClose]
+ );
+
+ return (
+ <Sheet
+ isOpen={isOpen}
+ onClose={onClose || (() => {})}
+ springConfig={{
+ stiffness: 300,
+ damping: 30,
+ mass: 0.2,
+ duration: 300,
+ }}
+ onOpenStart={() => {
+ window.addEventListener("popstate", onPopState);
+ window.addEventListener("beforeunload", onPopState);
+
+ if (focusOnRender) {
+ focusedElement.current =
+ (document.activeElement as HTMLElement) || undefined;
+ contentRef.current?.focus({ preventScroll: true });
+ }
+ }}
+ onCloseEnd={() => {
+ window.removeEventListener("popstate", onPopState);
+ window.removeEventListener("beforeunload", onPopState);
+ if (focusOnRender) {
+ focusedElement.current?.focus({ preventScroll: true });
+ }
+ }}
+ >
+ <Sheet.Container
+ style={{
+ borderTopLeftRadius: 20,
+ borderTopRightRadius: 20,
+ boxShadow: theme.shadows.menu,
+ }}
+ >
+ <Sheet.Header disableDrag={!onClose} />
+ <Sheet.Content>
+ <div
+ id="action-sheet-focus"
+ ref={(ref) => (contentRef.current = ref || undefined)}
+ tabIndex={-1}
+ />
+ <ContentContainer items={items} title={title} onClose={onClose}>
+ {children}
+ </ContentContainer>
+ </Sheet.Content>
+ </Sheet.Container>
+
+ {blocking ? (
+ <Sheet.Backdrop style={{ border: "none" }} onTap={onClose} />
+ ) : (
+ <></>
+ )}
+ </Sheet>
+ );
+}
+
+type ContentContainerProps = {
+ title?: string;
+ items?: MenuItem[];
+ onClose?: () => void;
+};
+function ContentContainer(props: PropsWithChildren<ContentContainerProps>) {
+ const { title, items, onClose, children } = props;
+
+ const { current, goBack, canGoBack, navigate } =
+ useHistory<ActionSheetHistoryItem>({
+ title,
+ items,
+ });
+
+ return (
+ <Flex sx={{ flexDirection: "column" }}>
+ <Flex id="header" sx={{ alignItems: "center", mx: 2, mb: 2 }}>
+ {canGoBack && (
+ <Button variant={"icon"} sx={{ p: 1, mr: 2 }} onClick={goBack}>
+ <Icon path={Icons.chevronLeft} size={"big"} />
+ </Button>
+ )}
+ {current?.title && (
+ <Text variant={"title"} sx={{ ml: 1, fontSize: "title" }}>
+ {current?.title}
+ </Text>
+ )}
+ </Flex>
+ {children
+ ? children
+ : current?.items?.map((item) => {
+ switch (item.type) {
+ case "separator":
+ return <MenuSeparator key={item.key} />;
+ case "button":
+ return (
+ <MenuButton
+ key={item.key}
+ item={item}
+ onClick={(e) => {
+ if (item.menu) {
+ navigate(item.menu);
+ } else if (item.onClick) {
+ item.onClick();
+ onClose?.();
+ }
+ }}
+ />
+ );
+ case "popup":
+ return (
+ <React.Fragment key={item.key}>
+ <item.component onClick={onClose} />
+ </React.Fragment>
+ );
+ }
+ })}
+ </Flex>
+ );
+}
diff --git a/packages/editor/src/components/inline-input/index.tsx b/packages/editor/src/components/inline-input/index.tsx
new file mode 100644
index 000000000..4026b621f
--- /dev/null
+++ b/packages/editor/src/components/inline-input/index.tsx
@@ -0,0 +1,40 @@
+import { Input, InputProps } from "@rebass/forms";
+import { Flex, FlexProps, Text } from "rebass";
+
+type LabelInputProps = InputProps & {
+ label: string;
+ containerProps?: FlexProps;
+};
+export function InlineInput(props: LabelInputProps) {
+ const { label, containerProps, sx, ...inputProps } = props;
+
+ return (
+ <Flex
+ {...containerProps}
+ sx={{
+ flex: 1,
+ ...containerProps?.sx,
+ outline: "1px solid var(--border)",
+ p: 2,
+ borderRadius: "default",
+ ":focus-within": {
+ outlineColor: "primary",
+ outlineWidth: "1.8px",
+ },
+ }}
+ >
+ <Input variant={"clean"} sx={{ ...sx, p: 0 }} {...inputProps} />
+ <Text
+ variant={"body"}
+ sx={{
+ flexShrink: 0,
+ color: "fontTertiary",
+ borderLeft: "1px solid var(--border)",
+ pl: 1,
+ }}
+ >
+ {label}
+ </Text>
+ </Flex>
+ );
+}
diff --git a/packages/editor/src/components/menu/index.ts b/packages/editor/src/components/menu/index.ts
deleted file mode 100644
index c6bb7b61b..000000000
--- a/packages/editor/src/components/menu/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { MenuPresenter } from "./menu";
diff --git a/packages/editor/src/components/menu/index.tsx b/packages/editor/src/components/menu/index.tsx
new file mode 100644
index 000000000..05c036c62
--- /dev/null
+++ b/packages/editor/src/components/menu/index.tsx
@@ -0,0 +1,191 @@
+import React, {
+ useCallback,
+ useRef,
+ useEffect,
+ PropsWithChildren,
+} from "react";
+import { Box, Flex, FlexProps, Text } from "rebass";
+import { getPosition } from "../../utils/position";
+import { MenuItem, MenuItem as MenuItemType } from "./types";
+import { useFocus } from "./use-focus";
+import { MenuSeparator } from "./menu-separator";
+import { MenuButton } from "./menu-button";
+import {
+ PopupPresenter as _PopupPresenter,
+ PopupPresenterProps as _PopupPresenterProps,
+} from "../popup-presenter";
+
+type MenuProps = MenuContainerProps & {
+ items?: MenuItemType[];
+ onClose: () => void;
+};
+
+export function Menu(props: MenuProps) {
+ const { items = [], title, onClose, ...containerProps } = props;
+ const hoverTimeout = useRef<NodeJS.Timeout>();
+ const onAction = useCallback(
+ (e, item) => {
+ e?.stopPropagation();
+ if (onClose) onClose();
+ if (item.onClick) {
+ item.onClick();
+ }
+ },
+ [onClose]
+ );
+
+ const { focusIndex, setFocusIndex, isSubmenuOpen, setIsSubmenuOpen } =
+ useFocus(
+ items,
+ (e) => {
+ const item = items[focusIndex];
+ if (item) onAction(e, item);
+ },
+ () => onClose()
+ );
+ const focusedItem = items[focusIndex];
+
+ const subMenuRef = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ const item = items[focusIndex];
+ if (!item || !subMenuRef.current) return;
+
+ const menuItemElement = document.getElementById(item.key);
+ if (!menuItemElement) return;
+
+ if (!isSubmenuOpen) {
+ subMenuRef.current.style.visibility = "hidden";
+ return;
+ }
+
+ const { top, left } = getPosition(subMenuRef.current, {
+ // yOffset: menuItemElement.offsetHeight,
+ target: menuItemElement,
+ location: "right",
+ });
+
+ subMenuRef.current.style.visibility = "visible";
+ subMenuRef.current.style.top = `${top}px`;
+ subMenuRef.current.style.left = `${left}px`;
+ }, [isSubmenuOpen, focusIndex, items]);
+
+ return (
+ <>
+ <MenuContainer {...containerProps}>
+ {items.map((item, index) => {
+ switch (item.type) {
+ case "separator":
+ return <MenuSeparator key={item.key} />;
+ case "button":
+ return (
+ <MenuButton
+ key={item.key}
+ item={item}
+ onClick={(e) => {
+ if (item.menu) {
+ setFocusIndex(index);
+ setIsSubmenuOpen(true);
+ } else onAction(e, item);
+ }}
+ isFocused={focusIndex === index}
+ onMouseEnter={() => {
+ if (item.isDisabled) {
+ setFocusIndex(-1);
+ return;
+ }
+
+ if (hoverTimeout.current)
+ clearTimeout(hoverTimeout.current);
+ setFocusIndex(index);
+ setIsSubmenuOpen(false);
+ if (item.menu) {
+ hoverTimeout.current = setTimeout(() => {
+ setIsSubmenuOpen(true);
+ }, 500);
+ }
+ }}
+ onMouseLeave={() => {
+ if (hoverTimeout.current)
+ clearTimeout(hoverTimeout.current);
+ }}
+ />
+ );
+ case "popup":
+ return <item.component onClick={(e) => onAction(e, item)} />;
+ }
+ })}
+ </MenuContainer>
+ {focusedItem?.type === "button" && focusedItem?.menu && isSubmenuOpen && (
+ <Flex
+ ref={subMenuRef}
+ style={{ visibility: "hidden" }}
+ sx={{
+ position: "absolute",
+ }}
+ >
+ <Menu items={focusedItem.menu.items} onClose={onClose} />
+ </Flex>
+ )}
+ </>
+ );
+}
+
+type MenuContainerProps = FlexProps & {
+ title?: string;
+};
+function MenuContainer(props: PropsWithChildren<MenuContainerProps>) {
+ const { children, title, sx, ...flexProps } = props;
+
+ return (
+ <Box
+ className="menuContainer"
+ as="ul"
+ tabIndex={-1}
+ sx={{
+ bg: "background",
+ py: 1,
+ display: "flex",
+ flexDirection: "column",
+ position: "relative",
+ listStyle: "none",
+ padding: 0,
+ margin: 0,
+ borderRadius: "default",
+ boxShadow: "menu",
+ border: "1px solid var(--border)",
+ minWidth: 220,
+ ...sx,
+ }}
+ {...flexProps}
+ >
+ {title && (
+ <Text
+ sx={{
+ fontFamily: "body",
+ fontSize: "subtitle",
+ color: "primary",
+ py: "8px",
+ px: 3,
+ borderBottom: "1px solid",
+ borderBottomColor: "border",
+ wordWrap: "break-word",
+ }}
+ >
+ {title}
+ </Text>
+ )}
+ {children}
+ {/* <FlexScrollContainer>{children}</FlexScrollContainer> */}
+ </Box>
+ );
+}
+
+export type MenuPresenterProps = _PopupPresenterProps & MenuProps;
+export function MenuPresenter(props: PropsWithChildren<MenuPresenterProps>) {
+ const { items = [], ...restProps } = props;
+ return (
+ <_PopupPresenter {...restProps}>
+ {props.children ? props.children : <Menu items={items} {...restProps} />}
+ </_PopupPresenter>
+ );
+}
diff --git a/packages/editor/src/components/menu/menu-button.tsx b/packages/editor/src/components/menu/menu-button.tsx
new file mode 100644
index 000000000..b29ba5da6
--- /dev/null
+++ b/packages/editor/src/components/menu/menu-button.tsx
@@ -0,0 +1,82 @@
+import { useRef } from "react";
+import { Flex, Text, Button } from "rebass";
+import { Icon } from "../../toolbar/components/icon";
+import { Icons } from "../../toolbar/icons";
+import { MenuButton } from "./types";
+
+type MenuButtonProps = {
+ item: MenuButton;
+ isFocused?: boolean;
+ onMouseEnter?: () => void;
+ onMouseLeave?: () => void;
+ onClick: (e?: any) => void;
+};
+
+export function MenuButton(props: MenuButtonProps) {
+ const { item, isFocused, onMouseEnter, onMouseLeave, onClick } = props;
+ const { title, key, icon, tooltip, isDisabled, isChecked, menu, modifier } =
+ item;
+ const itemRef = useRef<HTMLButtonElement>(null);
+
+ return (
+ <Flex
+ as="li"
+ sx={{ flexShrink: 0, flexDirection: "column" }}
+ onMouseEnter={onMouseEnter}
+ onMouseLeave={onMouseLeave}
+ >
+ <Button
+ id={key}
+ data-test-id={`MenuButton-${key}`}
+ key={key}
+ ref={itemRef}
+ tabIndex={-1}
+ variant="menuitem"
+ title={tooltip}
+ disabled={isDisabled}
+ onClick={onClick}
+ sx={{
+ bg: isFocused ? "hover" : "transparent",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "space-between",
+ ":hover": {
+ bg: "hover",
+ },
+ }}
+ >
+ <Flex>
+ {icon && (
+ <Icon
+ path={Icons[icon]}
+ color={"text"}
+ size={"medium"}
+ sx={{ mr: 2 }}
+ />
+ )}
+ <Text as="span" variant={"body"}>
+ {title}
+ </Text>
+ </Flex>
+ {isChecked || menu || modifier ? (
+ <Flex sx={{ ml: 4 }}>
+ {isChecked && <Icon path={Icons.check} size={14} />}
+ {menu && <Icon path={Icons.chevronRight} size={14} />}
+ {modifier && (
+ <Text
+ as="span"
+ sx={{
+ fontFamily: "body",
+ fontSize: "menu",
+ color: "fontTertiary",
+ }}
+ >
+ {modifier}
+ </Text>
+ )}
+ </Flex>
+ ) : null}
+ </Button>
+ </Flex>
+ );
+}
diff --git a/packages/editor/src/components/menu/menu-separator.tsx b/packages/editor/src/components/menu/menu-separator.tsx
new file mode 100644
index 000000000..e76810813
--- /dev/null
+++ b/packages/editor/src/components/menu/menu-separator.tsx
@@ -0,0 +1,16 @@
+import { Box } from "rebass";
+
+export function MenuSeparator() {
+ return (
+ <Box
+ as="li"
+ sx={{
+ width: "95%",
+ height: "0.5px",
+ bg: "border",
+ my: 2,
+ alignSelf: "center",
+ }}
+ />
+ );
+}
diff --git a/packages/editor/src/components/menu/menu.tsx b/packages/editor/src/components/menu/menu.tsx
deleted file mode 100644
index 910fc56dc..000000000
--- a/packages/editor/src/components/menu/menu.tsx
+++ /dev/null
@@ -1,471 +0,0 @@
-import React, {
- useCallback,
- useRef,
- useEffect,
- useState,
- PropsWithChildren,
-} from "react";
-import ReactDOM from "react-dom";
-import { Box, Flex, FlexProps, Text } from "rebass";
-import { getPosition, MenuOptions } from "./useMenu";
-// import { FlexScrollContainer } from "../scrollcontainer";
-import MenuItem from "./menuitem";
-import { MenuItem as MenuItemType /*ResolvedMenuItem*/ } from "./types";
-// import { useMenuTrigger, useMenu, getPosition } from "../../hooks/useMenu";
-import Modal from "react-modal";
-import { ThemeProvider, useTheme } from "emotion-theming";
-import Sheet from "react-modal-sheet";
-import { useIsMobile } from "../../toolbar/stores/toolbar-store";
-import { Theme } from "@notesnook/theme";
-// import { store as selectionStore } from "../../stores/selectionstore";
-
-function useMenuFocus(
- items: MenuItemType[],
- onAction: (event: KeyboardEvent) => void,
- onClose: (event: KeyboardEvent) => void
-) {
- const [focusIndex, setFocusIndex] = useState(-1);
- const [isSubmenuOpen, setIsSubmenuOpen] = useState(false);
-
- const moveItemIntoView = useCallback(
- (index) => {
- const item = items[index];
- if (!item) return;
- const element = document.getElementById(item.key);
- if (!element) return;
- element.scrollIntoView({
- behavior: "auto",
- });
- },
- [items]
- );
-
- const onKeyDown = useCallback(
- (e: KeyboardEvent) => {
- const isSeperator = (i: number) =>
- items && (items[i]?.type === "seperator" || items[i]?.isDisabled);
- const moveDown = (i: number) => (i < items.length - 1 ? ++i : 0);
- const moveUp = (i: number) => (i > 0 ? --i : items.length - 1);
- const hasSubmenu = (i: number) => items && items[i]?.hasSubmenu;
- const openSubmenu = (index: number) => {
- if (!hasSubmenu(index)) return;
- setIsSubmenuOpen(true);
- };
-
- const closeSubmenu = (index: number) => {
- if (!hasSubmenu(index)) return;
- setIsSubmenuOpen(false);
- };
-
- setFocusIndex((i) => {
- let nextIndex = i;
-
- switch (e.key) {
- case "ArrowUp":
- if (isSubmenuOpen) break;
- nextIndex = moveUp(i);
- while (isSeperator(nextIndex)) {
- nextIndex = moveUp(nextIndex);
- }
- break;
- case "ArrowDown":
- if (isSubmenuOpen) break;
- nextIndex = moveDown(i);
- while (isSeperator(nextIndex)) {
- nextIndex = moveDown(nextIndex);
- }
- break;
- case "ArrowRight":
- openSubmenu(i);
- break;
- case "ArrowLeft":
- closeSubmenu(i);
- break;
- case "Enter":
- onAction && onAction(e);
- break;
- case "Escape":
- onClose && onClose(e);
- break;
- default:
- break;
- }
- if (nextIndex !== i) moveItemIntoView(nextIndex);
-
- return nextIndex;
- });
- },
- [items, isSubmenuOpen, moveItemIntoView, onAction]
- );
-
- useEffect(() => {
- window.addEventListener("keydown", onKeyDown);
- return () => {
- window.removeEventListener("keydown", onKeyDown);
- };
- }, [onKeyDown]);
-
- return { focusIndex, setFocusIndex, isSubmenuOpen, setIsSubmenuOpen };
-}
-
-type MenuProps = MenuContainerProps & {
- items: MenuItemType[];
- closeMenu: () => void;
-};
-
-export function Menu(props: MenuProps) {
- const { items, title, closeMenu, ...containerProps } = props;
- const hoverTimeout = useRef<NodeJS.Timeout>();
- const onAction = useCallback(
- (e, item) => {
- e?.stopPropagation();
- if (closeMenu) closeMenu();
- if (item.onClick) {
- item.onClick();
- }
- },
- [closeMenu]
- );
-
- const { focusIndex, setFocusIndex, isSubmenuOpen, setIsSubmenuOpen } =
- useMenuFocus(
- items,
- (e) => {
- const item = items[focusIndex];
- if (item) onAction(e, item);
- },
- () => closeMenu()
- );
-
- const subMenuRef = useRef<HTMLDivElement>(null);
- useEffect(() => {
- const item = items[focusIndex];
- if (!item || !subMenuRef.current) return;
-
- const menuItemElement = document.getElementById(item.key);
- if (!menuItemElement) return;
-
- if (!isSubmenuOpen) {
- subMenuRef.current.style.visibility = "hidden";
- return;
- }
-
- const { top, left } = getPosition(subMenuRef.current, {
- // yOffset: menuItemElement.offsetHeight,
- target: menuItemElement,
- location: "right",
- });
-
- subMenuRef.current.style.visibility = "visible";
- subMenuRef.current.style.top = `${top}px`;
- subMenuRef.current.style.left = `${left}px`;
- }, [isSubmenuOpen, focusIndex, items]);
-
- return (
- <>
- <MenuContainer {...containerProps}>
- {items.map((item, index) => (
- <MenuItem
- key={item.key}
- item={item}
- onClick={(e) => {
- if (item.items?.length) {
- setFocusIndex(index);
- setIsSubmenuOpen(true);
- } else onAction(e, item);
- }}
- isFocused={focusIndex === index}
- onMouseEnter={() => {
- if (item.isDisabled) {
- setFocusIndex(-1);
- return;
- }
-
- if (hoverTimeout.current) clearTimeout(hoverTimeout.current);
- setFocusIndex(index);
- setIsSubmenuOpen(false);
- if (item.items?.length) {
- hoverTimeout.current = setTimeout(() => {
- setIsSubmenuOpen(true);
- }, 500);
- }
- }}
- onMouseLeave={() => {
- if (hoverTimeout.current) clearTimeout(hoverTimeout.current);
- }}
- />
- ))}
- </MenuContainer>
- {isSubmenuOpen && (
- <Flex
- ref={subMenuRef}
- style={{ visibility: "hidden" }}
- sx={{
- position: "absolute",
- }}
- >
- <Menu items={items[focusIndex]?.items || []} closeMenu={closeMenu} />
- </Flex>
- )}
- </>
- );
-}
-
-type MenuContainerProps = FlexProps & {
- title?: string;
-};
-function MenuContainer(props: PropsWithChildren<MenuContainerProps>) {
- const { children, title, sx, ...flexProps } = props;
-
- return (
- <Box
- className="menuContainer"
- as="ul"
- tabIndex={-1}
- sx={{
- bg: "background",
- py: 1,
- display: "flex",
- flexDirection: "column",
- position: "relative",
- listStyle: "none",
- padding: 0,
- margin: 0,
- borderRadius: "default",
- boxShadow: "menu",
- border: "1px solid var(--border)",
- minWidth: 220,
- ...sx,
- }}
- {...flexProps}
- >
- {title && (
- <Text
- sx={{
- fontFamily: "body",
- fontSize: "subtitle",
- color: "primary",
- py: "8px",
- px: 3,
- borderBottom: "1px solid",
- borderBottomColor: "border",
- wordWrap: "break-word",
- }}
- >
- {title}
- </Text>
- )}
- {children}
- {/* <FlexScrollContainer>{children}</FlexScrollContainer> */}
- </Box>
- );
-}
-
-export type PopupType = "sheet" | "menu" | "none";
-export type PopupPresenterProps = MenuPresenterProps &
- ActionSheetPresenterProps & {
- mobile?: PopupType;
- desktop?: PopupType;
- };
-export function PopupPresenter(props: PropsWithChildren<PopupPresenterProps>) {
- const { mobile = "menu", desktop = "menu", ...restProps } = props;
- const isMobile = useIsMobile();
- if (isMobile && mobile === "sheet")
- return <ActionSheetPresenter {...restProps} />;
- else if (mobile === "menu" || desktop === "menu")
- return <MenuPresenter {...restProps} />;
- else return props.isOpen ? <>{props.children}</> : null;
-}
-
-export type MenuPresenterProps = MenuContainerProps & {
- items?: MenuItemType[];
- onClose?: () => void;
- isOpen: boolean;
- options?: MenuOptions;
-};
-export function MenuPresenter(props: PropsWithChildren<MenuPresenterProps>) {
- const {
- className,
- options = { type: "menu", position: {} },
- items = [],
- isOpen,
- onClose = () => {},
- children,
- ...containerProps
- } = props;
- const { position, type } = options;
- const isAutocomplete = type === "autocomplete";
- const contentRef = useRef<HTMLDivElement>();
-
- const repositionMenu = useCallback((position: MenuOptions["position"]) => {
- if (!contentRef.current || !position) return;
- const menu = contentRef.current;
- const menuPosition = getPosition(menu, position);
- menu.style.top = menuPosition.top + "px";
- menu.style.left = menuPosition.left + "px";
- }, []);
-
- useEffect(() => {
- repositionMenu(position);
- }, [position]);
-
- useEffect(() => {
- function onWindowResize() {
- repositionMenu(position);
- }
- window.addEventListener("resize", onWindowResize);
- return () => {
- window.removeEventListener("resize", onWindowResize);
- };
- }, [position]);
-
- return (
- <Modal
- contentRef={(ref) => (contentRef.current = ref)}
- className={className || "menuContainer"}
- role="menu"
- isOpen={isOpen}
- appElement={document.body}
- shouldCloseOnEsc
- shouldReturnFocusAfterClose
- shouldCloseOnOverlayClick
- shouldFocusAfterRender={!isAutocomplete}
- ariaHideApp={!isAutocomplete}
- preventScroll={!isAutocomplete}
- onRequestClose={onClose}
- portalClassName={className || "menuPresenter"}
- onAfterOpen={(obj) => {
- if (!obj || !position) return;
- repositionMenu(position);
- }}
- overlayElement={(props, contentEl) => {
- return (
- <Box
- {...props}
- //@ts-ignore
- style={{
- ...props.style,
- position: isAutocomplete ? "initial" : "fixed",
- zIndex: 1000,
- backgroundColor: isAutocomplete ? "transparent" : "unset",
- }}
- // onClick={(e) => {
- // if (!(e.target instanceof HTMLElement)) return;
- // console.log(e.target.closest(".ReactModal__Content"));
- // if (e.target.closest(".ReactModal__Content")) return;
- // onClose();
- // }}
- // onContextMenu={(e) => {
- // e.preventDefault();
- // onClose();
- // }}
- >
- {contentEl}
- </Box>
- );
- }}
- contentElement={(props, children) => (
- <Box
- {...props}
- style={{}}
- sx={{
- top: 0,
- left: 0,
- right: 0,
- bottom: 0,
- display: "flex",
- width: "fit-content",
- height: "fit-content",
- position: "absolute",
- backgroundColor: undefined,
- padding: 0,
- zIndex: 0,
- outline: 0,
- isolation: "isolate",
- }}
- >
- {children}
- </Box>
- )}
- style={{
- content: {},
- overlay: {
- zIndex: 999,
- background: "transparent",
- },
- }}
- >
- {props.children ? (
- props.children
- ) : (
- <Menu items={items} closeMenu={onClose} {...containerProps} />
- )}
- </Modal>
- );
-}
-
-export type ActionSheetPresenterProps = MenuContainerProps & {
- items?: MenuItemType[];
- isOpen: boolean;
- onClose?: () => void;
- blocking?: boolean;
-};
-export function ActionSheetPresenter(
- props: PropsWithChildren<ActionSheetPresenterProps>
-) {
- const {
- items = [],
- isOpen,
- onClose = () => {},
- children,
- sx,
- blocking = true,
- ...containerProps
- } = props;
- const theme: Theme = useTheme();
-
- return (
- <Sheet
- isOpen={isOpen}
- onClose={onClose}
- springConfig={{
- stiffness: 300,
- damping: 30,
- mass: 0.2,
- duration: 300,
- }}
- >
- <Sheet.Container
- style={{
- borderTopLeftRadius: 20,
- borderTopRightRadius: 20,
- boxShadow: theme.shadows.menu,
- }}
- >
- <Sheet.Header />
- <Sheet.Content>
- {props.children ? (
- props.children
- ) : (
- <Menu
- items={items}
- closeMenu={onClose}
- sx={{
- flex: 1,
- boxShadow: "none",
- border: "none",
- ...sx,
- }}
- {...containerProps}
- />
- )}
- </Sheet.Content>
- </Sheet.Container>
-
- <Sheet.Backdrop
- style={{ backgroundColor: "transparent", border: "none" }}
- onTap={onClose}
- />
- </Sheet>
- );
-}
diff --git a/packages/editor/src/components/menu/menuitem.tsx b/packages/editor/src/components/menu/menuitem.tsx
deleted file mode 100644
index 06aadfa41..000000000
--- a/packages/editor/src/components/menu/menuitem.tsx
+++ /dev/null
@@ -1,111 +0,0 @@
-// import { Check, ChevronRight, Pro } from "../icons";
-import { useRef } from "react";
-import { Flex, Box, Text, Button } from "rebass";
-import { Icon } from "../../toolbar/components/icon";
-import { Icons } from "../../toolbar/icons";
-import { MenuItem /*ResolvedMenuItem*/ } from "./types";
-
-type MenuItemProps = {
- // item: ResolvedMenuItem;
- item: MenuItem;
- isFocused: boolean;
- onMouseEnter: () => void;
- onMouseLeave: () => void;
- onClick: (e?: any) => void;
-};
-
-function MenuItem(props: MenuItemProps) {
- const { item, isFocused, onMouseEnter, onMouseLeave, onClick } = props;
- const {
- title,
- key,
- // color,
- icon,
- // iconColor,
- type,
- tooltip,
- isDisabled,
- isChecked,
- items,
- component: Component,
- modifier,
- } = item;
- const itemRef = useRef<HTMLButtonElement>(null);
-
- if (type === "seperator")
- return (
- <Box
- as="li"
- key={key}
- sx={{
- width: "95%",
- height: "0.5px",
- bg: "border",
- my: 2,
- alignSelf: "center",
- }}
- />
- );
-
- return (
- <Flex
- as="li"
- sx={{ flex: 1, flexDirection: "column" }}
- onMouseEnter={onMouseEnter}
- onMouseLeave={onMouseLeave}
- >
- {Component ? (
- <Component onClick={onClick} />
- ) : (
- <Button
- id={key}
- data-test-id={`menuitem-${key}`}
- key={key}
- ref={itemRef}
- tabIndex={-1}
- variant="menuitem"
- title={tooltip}
- disabled={isDisabled}
- onClick={onClick}
- sx={{
- bg: isFocused ? "hover" : "transparent",
- display: "flex",
- alignItems: "center",
- justifyContent: "space-between",
- }}
- >
- <Flex>
- {icon && (
- <Icon
- path={Icons[icon]}
- color={"text"}
- size={"medium"}
- sx={{ mr: 2 }}
- />
- )}
- <Text as="span" variant={"body"}>
- {title}
- </Text>
- </Flex>
- <Flex>
- {isChecked && <Icon path={Icons.check} size={14} />}
- {items?.length && <Icon path={Icons.chevronRight} size={14} />}
- {modifier && (
- <Text
- as="span"
- sx={{
- fontFamily: "body",
- fontSize: "menu",
- color: "fontTertiary",
- }}
- >
- {modifier}
- </Text>
- )}
- </Flex>
- </Button>
- )}
- </Flex>
- );
-}
-export default MenuItem;
diff --git a/packages/editor/src/components/menu/types.ts b/packages/editor/src/components/menu/types.ts
index 4438c8d57..30858eba8 100644
--- a/packages/editor/src/components/menu/types.ts
+++ b/packages/editor/src/components/menu/types.ts
@@ -1,40 +1,31 @@
-// export type ResolverFunction<T, TData> = (
-// data: any,
-// item: MenuItem<TData>
-// ) => T;
-// export type Resolvable<T, TData> = T | ResolverFunction<T, TData>;
-// export type MenuItem<TData> = {
-// type: "menuitem" | "seperator";
-// key: string;
-// component?: Resolvable<(props: any) => JSX.Element, TData>;
-// onClick?: (data: TData, item: MenuItem<TData>) => void;
-// title?: Resolvable<string, TData>;
-// icon?: Resolvable<string, TData>;
-// tooltip?: Resolvable<string, TData>;
-// disabled?: Resolvable<string, TData>;
-// hidden?: Resolvable<boolean, TData>;
-// checked?: Resolvable<boolean, TData>;
-// modifier?: Resolvable<string[], TData>;
-// items?: Resolvable<MenuItem<TData>[], TData>;
-// };
-
import { IconNames } from "../../toolbar/icons";
type MenuItemComponentProps = {
onClick?: (e?: any) => void;
};
-export type MenuItem = {
- type: "menuitem" | "seperator";
+
+export type MenuItemTypes = "button" | "separator" | "popup";
+export type BaseMenuItem<TType extends MenuItemTypes> = {
+ type: TType;
key: string;
- component?: (props: MenuItemComponentProps) => JSX.Element;
+ isHidden?: boolean;
+};
+
+export type MenuSeperator = BaseMenuItem<"separator">;
+
+export type MenuPopup = BaseMenuItem<"popup"> & {
+ component: (props: MenuItemComponentProps) => JSX.Element;
+};
+
+export type MenuButton = BaseMenuItem<"button"> & {
onClick?: () => void;
- title?: string;
+ title: string;
icon?: IconNames;
tooltip?: string;
isDisabled?: boolean;
- isHidden?: boolean;
isChecked?: boolean;
- hasSubmenu?: boolean;
modifier?: string;
- items?: MenuItem[];
+ menu?: { title: string; items: MenuItem[] };
};
+
+export type MenuItem = MenuButton | MenuSeperator | MenuPopup;
diff --git a/packages/editor/src/components/menu/use-focus.ts b/packages/editor/src/components/menu/use-focus.ts
new file mode 100644
index 000000000..a6eac7434
--- /dev/null
+++ b/packages/editor/src/components/menu/use-focus.ts
@@ -0,0 +1,93 @@
+import { useCallback, useEffect, useState } from "react";
+import { MenuButton, MenuItem } from "./types";
+
+export function useFocus(
+ items: MenuItem[],
+ onAction: (event: KeyboardEvent) => void,
+ onClose: (event: KeyboardEvent) => void
+) {
+ const [focusIndex, setFocusIndex] = useState(-1);
+ const [isSubmenuOpen, setIsSubmenuOpen] = useState(false);
+
+ const moveItemIntoView = useCallback(
+ (index) => {
+ const item = items[index];
+ if (!item) return;
+ const element = document.getElementById(item.key);
+ if (!element) return;
+ element.scrollIntoView({
+ behavior: "auto",
+ });
+ },
+ [items]
+ );
+
+ const onKeyDown = useCallback(
+ (e: KeyboardEvent) => {
+ const as = <T>(i: number) => items[i] as unknown as T;
+ const isSeperator = (i: number) =>
+ items &&
+ (items[i]?.type === "separator" || as<MenuButton>(i)?.isDisabled);
+ const moveDown = (i: number) => (i < items.length - 1 ? ++i : 0);
+ const moveUp = (i: number) => (i > 0 ? --i : items.length - 1);
+ const hasSubmenu = (i: number) => items && as<MenuButton>(i).menu;
+ const openSubmenu = (index: number) => {
+ if (!hasSubmenu(index)) return;
+ setIsSubmenuOpen(true);
+ };
+
+ const closeSubmenu = (index: number) => {
+ if (!hasSubmenu(index)) return;
+ setIsSubmenuOpen(false);
+ };
+
+ setFocusIndex((i) => {
+ let nextIndex = i;
+
+ switch (e.key) {
+ case "ArrowUp":
+ if (isSubmenuOpen) break;
+ nextIndex = moveUp(i);
+ while (isSeperator(nextIndex)) {
+ nextIndex = moveUp(nextIndex);
+ }
+ break;
+ case "ArrowDown":
+ if (isSubmenuOpen) break;
+ nextIndex = moveDown(i);
+ while (isSeperator(nextIndex)) {
+ nextIndex = moveDown(nextIndex);
+ }
+ break;
+ case "ArrowRight":
+ openSubmenu(i);
+ break;
+ case "ArrowLeft":
+ closeSubmenu(i);
+ break;
+ case "Enter":
+ onAction && onAction(e);
+ break;
+ case "Escape":
+ onClose && onClose(e);
+ break;
+ default:
+ break;
+ }
+ if (nextIndex !== i) moveItemIntoView(nextIndex);
+
+ return nextIndex;
+ });
+ },
+ [items, isSubmenuOpen, moveItemIntoView, onAction]
+ );
+
+ useEffect(() => {
+ window.addEventListener("keydown", onKeyDown);
+ return () => {
+ window.removeEventListener("keydown", onKeyDown);
+ };
+ }, [onKeyDown]);
+
+ return { focusIndex, setFocusIndex, isSubmenuOpen, setIsSubmenuOpen };
+}
diff --git a/packages/editor/src/components/menu/useMenu.ts b/packages/editor/src/components/menu/useMenu.ts
deleted file mode 100644
index 6dbdc86f5..000000000
--- a/packages/editor/src/components/menu/useMenu.ts
+++ /dev/null
@@ -1,297 +0,0 @@
-import create from "zustand";
-import shallow from "zustand/shallow";
-import {
- MenuItem,
- // Resolvable,
- // ResolvedMenuItem,
- // ResolverFunction,
-} from "./types";
-
-type PositionData = {
- x: number;
- y: number;
- actualX: number;
- actualY: number;
- width?: number;
- height?: number;
-};
-
-const mousePosition: PositionData = { x: 0, y: 0, actualX: 0, actualY: 0 };
-window.addEventListener("mousemove", (e) => {
- const { x, y, actualX, actualY } = getMousePosition(e);
- mousePosition.x = x;
- mousePosition.y = y;
- mousePosition.actualX = actualX;
- mousePosition.actualY = actualY;
-});
-
-export type MenuOptions = {
- type: "autocomplete" | "menu";
- position?: PositionOptions;
-};
-// interface IMenuStore {
-// isOpen?: boolean;
-// // items?: ResolvedMenuItem[];
-// items?: MenuItem[];
-// title?: string;
-// options?: MenuOptions;
-// //data?: any;
-
-// // open: <TData>(items: MenuItem<TData>[], data: TData) => void;
-// open: (items: MenuItem[]) => void;
-// close: () => void;
-// }
-
-// const useMenuStore = create<IMenuStore>((set) => ({
-// isOpen: false,
-// items: [],
-// title: undefined,
-// options: undefined,
-// // data: undefined,
-// // open: <TData>(items: MenuItem<TData>[], data: TData) =>
-// // set((state) => {
-// // state.isOpen = true;
-// // state.items = mapMenuItems(items, data);
-// // // state.data = data;
-// // }),
-// open: (items: MenuItem[], options?: MenuOptions) =>
-// set((state) => {
-// state.isOpen = true;
-// state.items = items.filter((item) => !item.isHidden);
-// state.options = options;
-// // state.data = data;
-// }),
-// close: () =>
-// set((state) => {
-// state.isOpen = false;
-// state.items = [];
-// state.options = undefined;
-// // state.data = undefined;
-// state.title = undefined;
-// }),
-// }));
-
-// export function useMenuTrigger() {
-// const isOpen = useMenuStore((store) => store.isOpen);
-// const [open, close] = useMenuStore(
-// (store) => [store.open, store.close],
-// shallow
-// );
-
-// return {
-// openMenu: open,
-// closeMenu: close,
-// isOpen,
-// };
-// }
-
-// export function useMenu() {
-// const [items, options] = useMenuStore((store) => [
-// store.items,
-// store.options,
-// ]);
-// return { items, options };
-// }
-
-type PositionOptions = {
- target?: HTMLElement | "mouse";
- isTargetAbsolute?: boolean;
- location?: "right" | "left" | "below" | "top";
- align?: "center" | "start" | "end";
- yOffset?: number;
- xOffset?: number;
- yAnchor?: HTMLElement;
- parent?: HTMLElement | Element;
-};
-export function getPosition(
- element: HTMLElement,
- options: PositionOptions
-): { top: number; left: number } {
- const {
- target = "mouse",
- isTargetAbsolute = false,
- location = undefined,
- yOffset = 0,
- xOffset = 0,
- align = "start",
- parent = document.body,
- yAnchor,
- } = options || {};
-
- const { x, y, width, height, actualX, actualY } =
- target === "mouse"
- ? mousePosition
- : getElementPosition(target, isTargetAbsolute);
-
- const elementWidth = element.offsetWidth;
- const elementHeight = element.offsetHeight;
-
- const windowWidth = parent.clientWidth;
- const windowHeight = parent.clientHeight;
-
- let position = { top: 0, left: 0 };
-
- if (windowWidth - actualX < elementWidth) {
- const xDiff = actualX - x;
- position.left = windowWidth - elementWidth;
- position.left -= xDiff;
- } else {
- position.left = x;
- }
-
- if (width) {
- if (location === "right") position.left += width;
- else if (location === "left") position.left -= elementWidth;
- }
-
- if (actualY + elementHeight > windowHeight) {
- position.top = windowHeight - elementHeight;
- } else {
- position.top = y;
- }
-
- if (height) {
- if (location === "below") position.top += height;
- else if (location === "top") position.top = y - elementHeight;
- }
-
- if (target !== "mouse" && align === "center" && elementWidth > 0) {
- position.left -= elementWidth / 2 - target.clientWidth / 2;
- } else if (target !== "mouse" && align === "end" && elementWidth > 0) {
- position.left -= elementWidth - target.clientWidth;
- }
-
- // Adjust menu height
- if (elementHeight > windowHeight - position.top) {
- element.style.maxHeight = `${windowHeight - 20}px`;
- }
-
- if (yAnchor) {
- const anchorY = getElementPosition(yAnchor, isTargetAbsolute);
- position.top = anchorY.actualY - elementHeight;
- }
-
- position.top = position.top < 0 ? 0 : position.top;
- position.left = position.left < 0 ? 0 : position.left;
- position.top += location === "below" ? yOffset : -yOffset;
- position.left += xOffset;
-
- return position;
-}
-
-function getMousePosition(e: MouseEvent) {
- var posx = 0;
- var posy = 0;
-
- if (!e && window.event) e = window.event as MouseEvent;
-
- if (e.pageX || e.pageY) {
- posx = e.pageX;
- posy = e.pageY;
- } else if (e.clientX || e.clientY) {
- posx =
- e.clientX +
- document.body.scrollLeft +
- document.documentElement.scrollLeft;
- posy =
- e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
- }
-
- return {
- x: posx,
- y: posy,
- actualY: posy,
- actualX: posx,
- };
-}
-
-export function getElementPosition(
- element: HTMLElement,
- absolute: boolean
-): PositionData {
- const rect = element.getBoundingClientRect();
- const position: PositionData = {
- x: element.offsetLeft,
- y: element.offsetTop,
- width: rect.width,
- height: rect.height,
- actualY: rect.y,
- actualX: rect.x,
- };
- if (absolute) {
- position.x = position.actualX;
- position.y = position.actualY;
- }
-
- return position;
-}
-
-// function mapMenuItems<TData>(
-// items: MenuItem<TData>[],
-// data: TData
-// ): ResolvedMenuItem<TData>[] {
-// return items.reduce((prev, item) => {
-// const { key, onClick: _onClick, disabled, hidden, checked, type } = item;
-
-// const isHidden = resolveProp(hidden, data, item);
-// if (isHidden) return prev;
-
-// const isSeperator = type === "seperator";
-// if (isSeperator) {
-// prev.push({ isSeperator: true });
-// return prev;
-// }
-
-// const title = resolveProp(item.title, data, item);
-// const icon = resolveProp(item.icon, data, item);
-// const isChecked = resolveProp(checked, data, item);
-// const isDisabled = resolveProp(disabled, data, item);
-// const items = resolveProp(item.items, data, item);
-// const modifier = resolveProp(item.modifier, data, item);
-// const onClick =
-// typeof _onClick === "function" && _onClick.bind(this, data, item);
-
-// const tooltip =
-// isDisabled || resolveProp(item.tooltip, data, item) || title;
-// const hasSubmenu = items?.length > 0;
-
-// const menuItem: ResolvedMenuItem<TData> = {
-// type,
-// title,
-// key,
-// onClick,
-// tooltip,
-
-// isChecked,
-// isDisabled: !!isDisabled,
-// isHidden,
-// hasSubmenu,
-// icon,
-// modifier: modifier?.join("+"),
-// };
-
-// if (hasSubmenu)
-// menuItem.items = mapMenuItems(items, { ...data, parent: menuItem });
-
-// prev.push(menuItem);
-
-// return prev;
-// }, []);
-// }
-
-// function resolveProp<T, TData>(
-// prop: Resolvable<T, TData>,
-// data: any,
-// item: MenuItem<TData>
-// ): T {
-// if (typeof prop === "function" && (prop as any).isReactComponent) {
-// return prop as T;
-// }
-// return isResolverFunction<T, TData>(prop) ? prop(data, item) : prop;
-// }
-
-// function isResolverFunction<T, TData>(
-// prop: any
-// ): prop is ResolverFunction<T, TData> {
-// return typeof prop === "function";
-// }
diff --git a/packages/editor/src/components/popup-presenter/index.tsx b/packages/editor/src/components/popup-presenter/index.tsx
new file mode 100644
index 000000000..389e5b131
--- /dev/null
+++ b/packages/editor/src/components/popup-presenter/index.tsx
@@ -0,0 +1,328 @@
+import {
+ useCallback,
+ useRef,
+ useEffect,
+ PropsWithChildren,
+ ReactNode,
+} from "react";
+import { Box } from "rebass";
+import { getPosition, PositionOptions } from "../../utils/position";
+import Modal from "react-modal";
+import ReactDOM from "react-dom";
+import { Editor } from "@tiptap/core";
+import { ThemeProvider } from "emotion-theming";
+import { getPopupContainer, getToolbarElement } from "../../toolbar/utils/dom";
+import { Theme } from "@notesnook/theme";
+import { useToolbarStore } from "../../toolbar/stores/toolbar-store";
+import React from "react";
+import {
+ EditorContext,
+ PopupRenderer,
+ usePopupRenderer,
+} from "./popuprenderer";
+
+export type PopupPresenterProps = {
+ isOpen: boolean;
+ onClose: () => void;
+ position: PositionOptions;
+ blocking?: boolean;
+ focusOnRender?: boolean;
+ movable?: boolean;
+};
+
+export function PopupPresenter(props: PropsWithChildren<PopupPresenterProps>) {
+ const {
+ isOpen,
+ position,
+ onClose,
+ blocking = true,
+ focusOnRender = true,
+ children,
+ } = props;
+
+ const contentRef = useRef<HTMLDivElement>();
+ const observerRef = useRef<ResizeObserver>();
+
+ const repositionPopup = useCallback((position: PositionOptions) => {
+ if (!contentRef.current || !position) return;
+ const popup = contentRef.current;
+ const popupPosition = getPosition(popup, position);
+ popup.style.top = popupPosition.top + "px";
+ popup.style.left = popupPosition.left + "px";
+ }, []);
+
+ useEffect(() => {
+ repositionPopup(position);
+ }, [position]);
+
+ useEffect(() => {
+ function onWindowResize() {
+ repositionPopup(position);
+ }
+ window.addEventListener("resize", onWindowResize);
+ return () => {
+ window.removeEventListener("resize", onWindowResize);
+ };
+ }, [position]);
+
+ const attachMoveHandlers = useCallback(() => {
+ if (!contentRef.current || !isOpen) return;
+ const movableBar = contentRef.current.querySelector(
+ ".movable"
+ ) as HTMLElement;
+
+ if (!movableBar) return;
+ const popup = contentRef.current;
+
+ var offset = { x: 0, y: 0 };
+ function mouseDown(e: MouseEvent) {
+ offset.x = e.clientX - popup.offsetLeft;
+ offset.y = e.clientY - popup.offsetTop;
+ window.addEventListener("mousemove", mouseMove);
+ }
+
+ function mouseMove(e: MouseEvent) {
+ if (!e.buttons) mouseUp();
+ var top = e.clientY - offset.y;
+ var left = e.clientX - offset.x;
+ requestAnimationFrame(() => {
+ popup.style.top = top + "px";
+ popup.style.left = left + "px";
+ });
+ }
+
+ function mouseUp() {
+ window.removeEventListener("mousemove", mouseMove);
+ }
+
+ movableBar.addEventListener("mousedown", mouseDown);
+ window.addEventListener("mouseup", mouseUp);
+ }, [isOpen]);
+
+ const handleResize = useCallback(() => {
+ const popup = contentRef.current;
+ if (!popup) return;
+
+ let oldHeight: number = popup.offsetHeight;
+ observerRef.current = new ResizeObserver((e) => {
+ const { height, y } = popup.getBoundingClientRect();
+ const delta = height - oldHeight;
+ if (delta > 0) {
+ // means the new size is bigger so we need to adjust the position
+ // if required. We only do this in case the newly resized popup
+ // is going out of the window.
+
+ const windowHeight = document.body.clientHeight - 20;
+ if (y + height > windowHeight) {
+ popup.style.top = windowHeight - height + "px";
+ }
+ }
+ oldHeight = height;
+ });
+ observerRef.current.observe(popup, { box: "border-box" });
+ }, []);
+
+ return (
+ <Modal
+ contentRef={(ref) => (contentRef.current = ref)}
+ className={"popup-presenter"}
+ role="menu"
+ isOpen={isOpen}
+ appElement={document.body}
+ shouldCloseOnEsc
+ shouldReturnFocusAfterClose
+ shouldCloseOnOverlayClick
+ shouldFocusAfterRender={focusOnRender}
+ ariaHideApp={blocking}
+ preventScroll={blocking}
+ onRequestClose={onClose}
+ portalClassName={"popup-presenter-portal"}
+ onAfterOpen={(obj) => {
+ if (!obj || !position) return;
+ repositionPopup(position);
+
+ handleResize();
+ attachMoveHandlers();
+ }}
+ onAfterClose={() => observerRef.current?.disconnect()}
+ overlayElement={(props, contentEl) => {
+ return (
+ <Box
+ {...props}
+ //@ts-ignore
+ style={{
+ ...props.style,
+ position: !blocking ? "initial" : "fixed",
+ zIndex: 1000,
+ backgroundColor: !blocking ? "transparent" : "unset",
+ }}
+ // onClick={(e) => {
+ // if (!(e.target instanceof HTMLElement)) return;
+ // console.log(e.target.closest(".ReactModal__Content"));
+ // if (e.target.closest(".ReactModal__Content")) return;
+ // onClose();
+ // }}
+ // onContextMenu={(e) => {
+ // e.preventDefault();
+ // onClose();
+ // }}
+ >
+ {contentEl}
+ </Box>
+ );
+ }}
+ contentElement={(props, children) => (
+ <Box
+ {...props}
+ style={{}}
+ sx={{
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ display: "flex",
+ width: "fit-content",
+ height: "fit-content",
+ position: "absolute",
+ backgroundColor: undefined,
+ padding: 0,
+ zIndex: 0,
+ outline: 0,
+ isolation: "isolate",
+ }}
+ >
+ {children}
+ </Box>
+ )}
+ style={{
+ content: {},
+ overlay: {
+ zIndex: 999,
+ background: "transparent",
+ },
+ }}
+ >
+ {children}
+ </Modal>
+ );
+}
+
+export type PopupWrapperProps = {
+ id: string;
+ group: string;
+ position: PositionOptions;
+ isOpen: boolean;
+ onClosed?: () => void;
+ renderPopup: (closePopup: () => void) => React.ReactNode;
+} & Partial<Omit<PopupPresenterProps, "onClose">>;
+export function PopupWrapper(props: PopupWrapperProps) {
+ let {
+ id,
+ group,
+ position,
+ renderPopup,
+ isOpen,
+ onClosed,
+ ...presenterProps
+ } = props;
+ const closePopup = useToolbarStore((store) => store.closePopup);
+ const openPopup = useToolbarStore((store) => store.openPopup);
+ const closePopupGroup = useToolbarStore((store) => store.closePopupGroup);
+ const isPopupOpen = useToolbarStore((store) => !!store.openedPopups[id]);
+ const PopupRenderer = usePopupRenderer();
+ const isBottom = useToolbarStore(
+ (store) => store.toolbarLocation === "bottom"
+ );
+ if (isBottom) group = "popup";
+
+ useEffect(() => {
+ if (isPopupOpen) {
+ closePopupGroup(group, [id]);
+ }
+ }, [onClosed, isPopupOpen, closePopupGroup, id, group]);
+
+ useEffect(() => {
+ if (!isPopupOpen) onClosed?.();
+ }, [isPopupOpen]);
+
+ useEffect(() => {
+ console.log("Opening popup", id, isOpen);
+ if (isOpen) openPopup({ id, group });
+ else closePopup(id);
+ }, [isOpen, id, group, openPopup]);
+
+ useEffect(() => {
+ return () => {
+ PopupRenderer?.closePopup(id);
+ };
+ }, [id]);
+
+ useEffect(() => {
+ if (PopupRenderer && isPopupOpen) {
+ PopupRenderer.openPopup(id, () => (
+ <PopupPresenter
+ key={id}
+ isOpen={isPopupOpen}
+ onClose={() => closePopup(id)}
+ position={position}
+ blocking
+ focusOnRender
+ {...presenterProps}
+ >
+ <Box
+ sx={{
+ boxShadow: "menu",
+ borderRadius: "default",
+ overflow: "hidden",
+ // width,
+ }}
+ >
+ <EditorContext.Consumer>
+ {() => {
+ return renderPopup(() => PopupRenderer.closePopup(id));
+ }}
+ </EditorContext.Consumer>
+ </Box>
+ </PopupPresenter>
+ ));
+ } else if (PopupRenderer && !isPopupOpen) {
+ PopupRenderer.closePopup(id);
+ }
+ }, [PopupRenderer, isPopupOpen]);
+
+ return null;
+}
+
+type ShowPopupOptions = {
+ theme: Theme;
+ popup: (closePopup: () => void) => React.ReactNode;
+} & Partial<PopupPresenterProps>;
+export function showPopup(options: ShowPopupOptions) {
+ const { theme, popup, ...props } = options;
+
+ function hide() {
+ ReactDOM.unmountComponentAtNode(getPopupContainer());
+ }
+
+ ReactDOM.render(
+ <ThemeProvider theme={theme}>
+ <PopupPresenter
+ isOpen
+ onClose={hide}
+ position={{
+ target: getToolbarElement(),
+ isTargetAbsolute: true,
+ location: "below",
+ align: "end",
+ yOffset: 10,
+ }}
+ blocking
+ focusOnRender
+ {...props}
+ >
+ {popup(hide)}
+ </PopupPresenter>
+ </ThemeProvider>,
+ getPopupContainer()
+ );
+}
diff --git a/packages/editor/src/components/popup-presenter/popuprenderer.tsx b/packages/editor/src/components/popup-presenter/popuprenderer.tsx
new file mode 100644
index 000000000..37da8868e
--- /dev/null
+++ b/packages/editor/src/components/popup-presenter/popuprenderer.tsx
@@ -0,0 +1,48 @@
+import React, { PropsWithChildren, useContext } from "react";
+import { Editor } from "@tiptap/core";
+import ReactDOM from "react-dom";
+import { PopupPresenter } from ".";
+
+export const PopupRendererContext = React.createContext<PopupRenderer | null>(
+ null
+);
+export const EditorContext = React.createContext<Editor | null>(null);
+
+export type PopupRendererProps = PropsWithChildren<{ editor: Editor }>;
+type PopupRendererState = { popups: Record<string, React.FunctionComponent> };
+export class PopupRenderer extends React.Component<PopupRendererProps> {
+ popupContainer: HTMLDivElement | null = null;
+ state: PopupRendererState = {
+ popups: {} as Record<string, React.FunctionComponent>,
+ };
+
+ openPopup(id: string, popup: React.FunctionComponent) {
+ this.setState({ popups: { ...this.state.popups, [id]: popup } });
+ }
+
+ closePopup(id: string) {
+ this.setState({ popups: { ...this.state.popups, [id]: null } });
+ }
+
+ render(): React.ReactNode {
+ return (
+ <PopupRendererContext.Provider value={this}>
+ {this.props.children}
+ <EditorContext.Provider value={this.props.editor}>
+ {Object.entries(this.state.popups).map(([id, Popup]) => {
+ if (!Popup) return null;
+ return <Popup key={id} />;
+ })}
+ <div id="popup-container" />
+ </EditorContext.Provider>
+ </PopupRendererContext.Provider>
+ );
+ }
+}
+
+export function usePopupRenderer() {
+ return useContext(PopupRendererContext);
+}
+export function useEditorContext() {
+ return useContext(EditorContext)!;
+}
diff --git a/packages/editor/src/components/responsive/index.tsx b/packages/editor/src/components/responsive/index.tsx
index e2c454aa9..50caef28d 100644
--- a/packages/editor/src/components/responsive/index.tsx
+++ b/packages/editor/src/components/responsive/index.tsx
@@ -1,5 +1,13 @@
import React, { PropsWithChildren } from "react";
-import { useToolbarStore } from "../../toolbar/stores/toolbar-store";
+import {
+ useIsMobile,
+ useToolbarStore,
+} from "../../toolbar/stores/toolbar-store";
+import {
+ ActionSheetPresenter,
+ ActionSheetPresenterProps,
+} from "../action-sheet";
+import { MenuPresenter, MenuPresenterProps } from "../menu";
type ResponsiveContainerProps = {
mobile?: JSX.Element;
@@ -7,7 +15,7 @@ type ResponsiveContainerProps = {
};
export function ResponsiveContainer(props: ResponsiveContainerProps) {
- const isMobile = useToolbarStore((store) => store.isMobile);
+ const isMobile = useIsMobile();
if (isMobile) return props.mobile || null;
else return props.desktop || null;
}
@@ -19,3 +27,22 @@ export function DesktopOnly(props: PropsWithChildren<{}>) {
export function MobileOnly(props: PropsWithChildren<{}>) {
return <ResponsiveContainer mobile={<>{props.children}</>} />;
}
+
+export type PopupType = "sheet" | "menu" | "none";
+export type ResponsivePresenterProps = MenuPresenterProps &
+ ActionSheetPresenterProps & {
+ mobile?: PopupType;
+ desktop?: PopupType;
+ };
+
+export function ResponsivePresenter(
+ props: PropsWithChildren<ResponsivePresenterProps>
+) {
+ const { mobile = "menu", desktop = "menu", ...restProps } = props;
+ const isMobile = useIsMobile();
+ if (isMobile && mobile === "sheet")
+ return <ActionSheetPresenter {...restProps} />;
+ else if (mobile === "menu" || desktop === "menu")
+ return <MenuPresenter {...restProps} />;
+ else return props.isOpen ? <>{props.children}</> : null;
+}
diff --git a/packages/editor/src/components/tabs/index.tsx b/packages/editor/src/components/tabs/index.tsx
new file mode 100644
index 000000000..d1794d142
--- /dev/null
+++ b/packages/editor/src/components/tabs/index.tsx
@@ -0,0 +1,67 @@
+import React, { Children, PropsWithChildren, useMemo, useState } from "react";
+import { Button, Flex, FlexProps } from "rebass";
+
+export type TabProps = { title: string | React.ReactElement };
+export function Tab(props: PropsWithChildren<TabProps>) {
+ return <>{props.children}</>;
+}
+
+export type TabsProps = {
+ activeIndex: number;
+ containerProps?: FlexProps;
+ onTabChanged?: (index: number) => void;
+};
+export function Tabs(props: PropsWithChildren<TabsProps>) {
+ const { activeIndex, children, containerProps, onTabChanged } = props;
+ const [activeTab, setActiveTab] = useState(activeIndex || 0);
+
+ const tabs = useMemo(
+ () =>
+ Children.map(children, (child) => {
+ if (React.isValidElement(child))
+ return { title: child.props.title, component: child };
+ }),
+ [children]
+ );
+
+ return (
+ <Flex sx={{ flexDirection: "column" }}>
+ <Flex
+ sx={{
+ mb: 1,
+ }}
+ >
+ {tabs?.map((tab, index) => (
+ <Button
+ key={index.toString()}
+ sx={{
+ flex: 1,
+ p: 0,
+ py: 1,
+ borderRadius: 0,
+ borderTopLeftRadius: "default",
+ borderTopRightRadius: "default",
+ bg: activeTab === index ? "bgSecondary" : "transparent",
+ fontWeight: activeTab === index ? "bold" : "normal",
+ color: "text",
+ ":last-of-type": { mr: 0 },
+ borderBottom: "2px solid",
+ borderBottomColor:
+ activeTab === index ? "primary" : "transparent",
+ ":hover": {
+ bg: "hover",
+ },
+ }}
+ onClick={() => {
+ setActiveTab(index);
+ onTabChanged?.(index);
+ }}
+ >
+ {tab.title}
+ </Button>
+ ))}
+ </Flex>
+ <Flex {...containerProps}>{tabs && tabs[activeTab].component}</Flex>
+ </Flex>
+ );
+}
diff --git a/packages/editor/src/extensions/attachment/component.tsx b/packages/editor/src/extensions/attachment/component.tsx
index 4212080db..0b246e978 100644
--- a/packages/editor/src/extensions/attachment/component.tsx
+++ b/packages/editor/src/extensions/attachment/component.tsx
@@ -3,7 +3,7 @@ import { Attachment } from "./attachment";
import { ToolButton } from "../../toolbar/components/tool-button";
import { Editor } from "@tiptap/core";
import { useRef } from "react";
-import { MenuPresenter } from "../../components/menu/menu";
+// import { MenuPresenter } from "../../components/menu/menu";
import { Icon } from "../../toolbar/components/icon";
import { Icons } from "../../toolbar/icons";
import { ReactNodeViewProps } from "../react";
@@ -74,7 +74,7 @@ export function AttachmentComponent(props: ReactNodeViewProps<Attachment>) {
{formatBytes(size)}
</Text>
</Box>
- <MenuPresenter
+ {/* <MenuPresenter
isOpen={isActive}
onClose={() => {}}
items={[]}
@@ -90,7 +90,7 @@ export function AttachmentComponent(props: ReactNodeViewProps<Attachment>) {
}}
>
<AttachmentToolbar editor={editor} />
- </MenuPresenter>
+ </MenuPresenter> */}
</>
);
}
diff --git a/packages/editor/src/extensions/code-block/component.tsx b/packages/editor/src/extensions/code-block/component.tsx
index d36d36b97..d95f32c00 100644
--- a/packages/editor/src/extensions/code-block/component.tsx
+++ b/packages/editor/src/extensions/code-block/component.tsx
@@ -4,12 +4,13 @@ import { refractor } from "refractor/lib/core";
import "prism-themes/themes/prism-dracula.min.css";
import { Button, Flex, Text } from "rebass";
import Languages from "./languages.json";
-import { PopupPresenter } from "../../components/menu/menu";
import { Input } from "@rebass/forms";
import { Icon } from "../../toolbar/components/icon";
import { Icons } from "../../toolbar/icons";
import { CodeBlockAttributes } from "./code-block";
import { ReactNodeViewProps } from "../react/types";
+import { ResponsivePresenter } from "../../components/responsive";
+import { Popup } from "../../toolbar/components/popup";
export function CodeblockComponent(
props: ReactNodeViewProps<CodeBlockAttributes>
@@ -127,30 +128,29 @@ export function CodeblockComponent(
</Button>
</Flex>
</Flex>
- <PopupPresenter
+ <ResponsivePresenter
isOpen={isOpen}
- onClose={() => {
- setIsOpen(false);
- editor.commands.focus();
- }}
+ onClose={() => setIsOpen(false)}
mobile="sheet"
desktop="menu"
- options={{
- type: "menu",
- position: {
- target: toolbarRef.current || undefined,
- align: "end",
- isTargetAbsolute: true,
- location: "top",
- yOffset: 5,
- },
+ position={{
+ target: toolbarRef.current || undefined,
+ align: "end",
+ isTargetAbsolute: true,
+ location: "top",
+ yOffset: 5,
}}
+ title="Change code block language"
>
<LanguageSelector
selectedLanguage={languageDefinition?.filename || "Plaintext"}
- onLanguageSelected={(language) => updateAttributes({ language })}
+ onLanguageSelected={(language) => {
+ updateAttributes({ language });
+ setIsOpen(false);
+ }}
+ onClose={() => setIsOpen(false)}
/>
- </PopupPresenter>
+ </ResponsivePresenter>
</>
);
}
@@ -158,80 +158,82 @@ export function CodeblockComponent(
type LanguageSelectorProps = {
onLanguageSelected: (language: string) => void;
selectedLanguage: string;
+ onClose: () => void;
};
function LanguageSelector(props: LanguageSelectorProps) {
- const { onLanguageSelected, selectedLanguage } = props;
+ const { onLanguageSelected, selectedLanguage, onClose } = props;
const [languages, setLanguages] = useState(Languages);
return (
- <Flex
- sx={{
- flexDirection: "column",
- height: 200,
- width: 300,
- boxShadow: "menu",
- borderRadius: "default",
- overflowY: "auto",
- bg: "background",
- marginRight: 2,
- }}
- >
- <Input
- autoFocus
- placeholder="Search languages"
- sx={{
- width: "auto",
- position: "sticky",
- top: 2,
- bg: "background",
- mx: 2,
- p: "7px",
- }}
- onChange={(e) => {
- if (!e.target.value) return setLanguages(Languages);
- const query = e.target.value.toLowerCase();
- setLanguages(
- Languages.filter((lang) => {
- return (
- lang.title.toLowerCase().indexOf(query) > -1 ||
- lang.alias?.some(
- (alias) => alias.toLowerCase().indexOf(query) > -1
- )
- );
- })
- );
- }}
- />
+ <Popup title="Select language" onClose={onClose}>
<Flex
sx={{
flexDirection: "column",
- pt: 2,
- mt: 1,
+ height: 200,
+ width: ["auto", 300],
+ overflowY: "auto",
+ bg: "background",
}}
>
- {languages.map((lang) => (
- <Button
- variant={"menuitem"}
- sx={{
- textAlign: "left",
- py: 1,
- display: "flex",
- justifyContent: "space-between",
- alignItems: "center",
- }}
- onClick={() => onLanguageSelected(lang.filename)}
- >
- <Text variant={"body"}>{lang.title}</Text>
- {selectedLanguage === lang.filename ? (
- <Icon path={Icons.check} size="small" />
- ) : lang.alias ? (
- <Text variant={"subBody"} sx={{ fontSize: "10px" }}>
- {lang.alias.slice(0, 3).join(", ")}
- </Text>
- ) : null}
- </Button>
- ))}
+ <Input
+ autoFocus
+ placeholder="Search languages"
+ sx={{
+ width: "auto",
+ position: "sticky",
+ top: 0,
+ bg: "background",
+ mx: 2,
+ p: "7px",
+ zIndex: 999,
+ }}
+ onChange={(e) => {
+ if (!e.target.value) return setLanguages(Languages);
+ const query = e.target.value.toLowerCase();
+ setLanguages(
+ Languages.filter((lang) => {
+ return (
+ lang.title.toLowerCase().indexOf(query) > -1 ||
+ lang.alias?.some(
+ (alias) => alias.toLowerCase().indexOf(query) > -1
+ )
+ );
+ })
+ );
+ }}
+ />
+ <Flex
+ sx={{
+ flexDirection: "column",
+ pt: 1,
+ mt: 1,
+ }}
+ >
+ {languages.map((lang) => (
+ <Button
+ key={lang.title}
+ variant={"menuitem"}
+ sx={{
+ textAlign: "left",
+ py: 1,
+ display: "flex",
+ justifyContent: "space-between",
+ alignItems: "center",
+ }}
+ onClick={() => onLanguageSelected(lang.filename)}
+ >
+ <Text variant={"body"}>{lang.title}</Text>
+ {selectedLanguage === lang.filename ? (
+ <Icon path={Icons.check} size="small" />
+ ) : lang.alias ? (
+ <Text variant={"subBody"} sx={{ fontSize: "10px" }}>
+ {lang.alias.slice(0, 3).join(", ")}
+ </Text>
+ ) : null}
+ </Button>
+ ))}
+ </Flex>
</Flex>
- </Flex>
+ </Popup>
);
}
diff --git a/packages/editor/src/extensions/embed/component.tsx b/packages/editor/src/extensions/embed/component.tsx
index e9af8d4d7..5ba98c1cd 100644
--- a/packages/editor/src/extensions/embed/component.tsx
+++ b/packages/editor/src/extensions/embed/component.tsx
@@ -5,25 +5,19 @@ import { Resizable } from "re-resizable";
import { ToolButton } from "../../toolbar/components/tool-button";
import { Editor } from "@tiptap/core";
import { useEffect, useRef, useState } from "react";
-import { PopupPresenter } from "../../components/menu/menu";
import { EmbedAlignmentOptions, EmbedAttributes } from "./embed";
import { EmbedPopup } from "../../toolbar/popups/embed-popup";
-import { ReactNodeViewProps } from "../react";
+import { SelectionBasedReactNodeViewProps } from "../react";
+import { ResponsivePresenter } from "../../components/responsive";
export function EmbedComponent(
- props: ReactNodeViewProps<EmbedAttributes & EmbedAlignmentOptions>
+ props: SelectionBasedReactNodeViewProps<
+ EmbedAttributes & EmbedAlignmentOptions
+ >
) {
- const { src, width, height, align } = props.node.attrs;
-
- const { editor, updateAttributes } = props;
+ const { editor, updateAttributes, selected, node } = props;
const embedRef = useRef<HTMLIFrameElement>();
- const isActive = editor.isActive("embed", { src });
- const [isToolbarVisible, setIsToolbarVisible] = useState<boolean>();
- const theme = editor.storage.theme as Theme;
-
- useEffect(() => {
- setIsToolbarVisible(isActive);
- }, [isActive]);
+ const { src, width, height, align } = node.attrs;
return (
<>
@@ -60,14 +54,14 @@ export function EmbedComponent(
// borderLeft: "20px solid var(--bgSecondary)",
borderTopLeftRadius: "default",
borderTopRightRadius: "default",
- borderColor: isActive ? "border" : "bgSecondary",
+ borderColor: selected ? "border" : "bgSecondary",
cursor: "pointer",
":hover": {
borderColor: "border",
},
}}
>
- {isToolbarVisible && (
+ {selected && (
<EmbedToolbar
editor={editor}
align={align}
@@ -106,9 +100,11 @@ type ImageToolbarProps = Required<EmbedAttributes> &
function EmbedToolbar(props: ImageToolbarProps) {
const { editor, height, width, src } = props;
const [isOpen, setIsOpen] = useState(false);
+ const ref = useRef<HTMLDivElement>();
return (
<Flex
+ ref={ref}
sx={{
flexDirection: "column",
position: "absolute",
@@ -188,23 +184,29 @@ function EmbedToolbar(props: ImageToolbarProps) {
/>
</Flex>
</Flex>
-
- <PopupPresenter
+ <ResponsivePresenter
isOpen={isOpen}
- desktop="none"
+ desktop="menu"
mobile="sheet"
onClose={() => setIsOpen(false)}
- blocking={true}
+ blocking
+ focusOnRender={false}
+ position={{
+ target: ref.current || "mouse",
+ align: "start",
+ location: "below",
+ yOffset: 10,
+ isTargetAbsolute: true,
+ }}
>
<EmbedPopup
title="Embed properties"
- icon="close"
onClose={() => setIsOpen(false)}
embed={props}
onSourceChanged={(src) => {}}
onSizeChanged={(size) => editor.commands.setEmbedSize(size)}
/>
- </PopupPresenter>
+ </ResponsivePresenter>
</Flex>
);
}
diff --git a/packages/editor/src/extensions/embed/embed.ts b/packages/editor/src/extensions/embed/embed.ts
index 431981fd9..e50ad998e 100644
--- a/packages/editor/src/extensions/embed/embed.ts
+++ b/packages/editor/src/extensions/embed/embed.ts
@@ -1,5 +1,9 @@
import { Node, mergeAttributes } from "@tiptap/core";
-import { createNodeView } from "../react";
+import {
+ createNodeView,
+ createSelectionBasedNodeView,
+ NodeViewSelectionNotifierPlugin,
+} from "../react";
import { EmbedComponent } from "./component";
export interface EmbedOptions {
@@ -74,8 +78,12 @@ export const EmbedNode = Node.create<EmbedOptions>({
];
},
+ addProseMirrorPlugins() {
+ return [NodeViewSelectionNotifierPlugin];
+ },
+
addNodeView() {
- return createNodeView(EmbedComponent);
+ return createSelectionBasedNodeView(EmbedComponent);
},
addCommands() {
diff --git a/packages/editor/src/extensions/image/component.tsx b/packages/editor/src/extensions/image/component.tsx
index 60af32062..5f035ce64 100644
--- a/packages/editor/src/extensions/image/component.tsx
+++ b/packages/editor/src/extensions/image/component.tsx
@@ -4,31 +4,24 @@ import {
ImageAttributes,
ImageSizeOptions,
} from "./image";
-import { ThemeProvider } from "emotion-theming";
import { Theme } from "@notesnook/theme";
import { Resizable } from "re-resizable";
import { ToolButton } from "../../toolbar/components/tool-button";
import { Editor } from "@tiptap/core";
import { useEffect, useRef, useState } from "react";
-import { PopupPresenter } from "../../components/menu/menu";
-import { Popup } from "../../toolbar/components/popup";
+import { ReactNodeViewProps, SelectionBasedReactNodeViewProps } from "../react";
+import { ResponsivePresenter } from "../../components/responsive";
import { ImageProperties } from "../../toolbar/popups/image-properties";
-import { ReactNodeViewProps } from "../react";
+import { Popup } from "../../toolbar/components/popup";
export function ImageComponent(
- props: ReactNodeViewProps<ImageAttributes & ImageAlignmentOptions>
+ props: SelectionBasedReactNodeViewProps<
+ ImageAttributes & ImageAlignmentOptions
+ >
) {
- const { src, alt, title, width, height, align, float } = props.node.attrs;
-
- const { editor, updateAttributes } = props;
+ const { editor, updateAttributes, node, selected } = props;
+ const { src, alt, title, width, height, align, float } = node.attrs;
const imageRef = useRef<HTMLImageElement>();
- const isActive = editor.isActive("image", { src });
- const [isToolbarVisible, setIsToolbarVisible] = useState<boolean>();
- const theme = editor.storage.theme as Theme;
-
- useEffect(() => {
- setIsToolbarVisible(isActive);
- }, [isActive]);
return (
<>
@@ -61,8 +54,8 @@ export function ImageComponent(
}}
lockAspectRatio={true}
>
- <Flex sx={{ position: "relative", justifyContent: "end" }}>
- {isToolbarVisible && (
+ {selected && (
+ <Flex sx={{ position: "relative", justifyContent: "end" }}>
<ImageToolbar
editor={editor}
float={float}
@@ -70,8 +63,8 @@ export function ImageComponent(
height={height || 0}
width={width || 0}
/>
- )}
- </Flex>
+ </Flex>
+ )}
<Image
ref={imageRef}
src={src}
@@ -80,7 +73,7 @@ export function ImageComponent(
width={"100%"}
height={"100%"}
sx={{
- border: isActive
+ border: selected
? "2px solid var(--primary)"
: "2px solid transparent",
borderRadius: "default",
@@ -101,9 +94,11 @@ type ImageToolbarProps = ImageAlignmentOptions &
function ImageToolbar(props: ImageToolbarProps) {
const { editor, float, height, width } = props;
const [isOpen, setIsOpen] = useState(false);
+ const ref = useRef<HTMLDivElement>();
return (
<Flex
+ ref={ref}
sx={{
flexDirection: "column",
position: "absolute",
@@ -184,25 +179,30 @@ function ImageToolbar(props: ImageToolbarProps) {
</Flex>
</Flex>
- <PopupPresenter
- mobile="sheet"
- desktop="none"
+ <ResponsivePresenter
isOpen={isOpen}
+ desktop="menu"
+ mobile="sheet"
onClose={() => setIsOpen(false)}
- blocking={false}
+ blocking
+ focusOnRender={false}
+ position={{
+ target: ref.current || "mouse",
+ align: "start",
+ location: "below",
+ yOffset: 10,
+ isTargetAbsolute: true,
+ }}
>
<Popup
title="Image properties"
- action={{
- icon: "close",
- onClick: () => {
- setIsOpen(false);
- },
+ onClose={() => {
+ setIsOpen(false);
}}
>
<ImageProperties {...props} />
</Popup>
- </PopupPresenter>
+ </ResponsivePresenter>
</Flex>
);
}
diff --git a/packages/editor/src/extensions/image/image.ts b/packages/editor/src/extensions/image/image.ts
index 67b7fa284..03749f48a 100644
--- a/packages/editor/src/extensions/image/image.ts
+++ b/packages/editor/src/extensions/image/image.ts
@@ -1,5 +1,9 @@
import { Node, nodeInputRule, mergeAttributes } from "@tiptap/core";
-import { createNodeView } from "../react";
+import {
+ createNodeView,
+ createSelectionBasedNodeView,
+ NodeViewSelectionNotifierPlugin,
+} from "../react";
import { ImageComponent } from "./component";
export interface ImageOptions {
@@ -98,7 +102,11 @@ export const ImageNode = Node.create<ImageOptions>({
},
addNodeView() {
- return createNodeView(ImageComponent);
+ return createSelectionBasedNodeView(ImageComponent);
+ },
+
+ addProseMirrorPlugins() {
+ return [NodeViewSelectionNotifierPlugin];
},
addCommands() {
diff --git a/packages/editor/src/extensions/react/plugin.ts b/packages/editor/src/extensions/react/plugin.ts
index 6d0f0139d..9592bfafa 100644
--- a/packages/editor/src/extensions/react/plugin.ts
+++ b/packages/editor/src/extensions/react/plugin.ts
@@ -25,7 +25,7 @@ export class ReactNodeViewState {
export const stateKey = new PluginKey("reactNodeView");
-export const plugin = new Plugin({
+export const NodeViewSelectionNotifierPlugin = new Plugin({
state: {
init() {
return new ReactNodeViewState();
@@ -46,7 +46,3 @@ export const plugin = new Plugin({
};
},
});
-
-const plugins = () => [plugin];
-
-export default plugins;
diff --git a/packages/editor/src/styles.css b/packages/editor/src/styles.css
index 44350d7a0..fdc35f548 100644
--- a/packages/editor/src/styles.css
+++ b/packages/editor/src/styles.css
@@ -212,3 +212,7 @@ pre *::selection {
background-color: var(--codeSelection) !important;
color: currentColor;
}
+
+.hide-scrollbar::-webkit-scrollbar {
+ display: none;
+}
diff --git a/packages/editor/src/toolbar/components/counter.tsx b/packages/editor/src/toolbar/components/counter.tsx
new file mode 100644
index 000000000..14828a932
--- /dev/null
+++ b/packages/editor/src/toolbar/components/counter.tsx
@@ -0,0 +1,48 @@
+import { Flex, Text } from "rebass";
+import { ToolButton } from "./tool-button";
+
+export type CounterProps = {
+ title: string;
+ onIncrease: () => void;
+ onDecrease: () => void;
+ onReset: () => void;
+ value: string;
+};
+export function Counter(props: CounterProps) {
+ const { title, onDecrease, onIncrease, onReset, value } = props;
+
+ return (
+ <Flex
+ sx={{
+ alignItems: "center",
+ mr: 1,
+ ":last-of-type": {
+ mr: 0,
+ },
+ }}
+ >
+ <ToolButton
+ toggled={false}
+ title={`Decrease ${title}`}
+ icon="minus"
+ variant={"small"}
+ onClick={onDecrease}
+ />
+ <Text
+ variant={"body"}
+ sx={{ fontSize: "subBody", mx: 1, textAlign: "center" }}
+ title={`Reset ${title}`}
+ onClick={onReset}
+ >
+ {value}
+ </Text>
+ <ToolButton
+ toggled={false}
+ title={`Increase ${title}`}
+ icon="plus"
+ variant={"small"}
+ onClick={onIncrease}
+ />
+ </Flex>
+ );
+}
diff --git a/packages/editor/src/toolbar/components/dropdown.tsx b/packages/editor/src/toolbar/components/dropdown.tsx
index 17fcff733..fc18b3492 100644
--- a/packages/editor/src/toolbar/components/dropdown.tsx
+++ b/packages/editor/src/toolbar/components/dropdown.tsx
@@ -2,10 +2,11 @@ import { useRef, useState } from "react";
import { Button, Flex, Text } from "rebass";
import { Icon } from "./icon";
import { Icons } from "../icons";
-import { MenuPresenter, MenuPresenterProps } from "../../components/menu/menu";
+// import { MenuPresenter, MenuPresenterProps } from "../../components/menu/menu";
import { MenuItem } from "../../components/menu/types";
-import { useToolbarContext } from "../hooks/useToolbarContext";
-import { useToolbarLocation } from "../stores/toolbar-store";
+import { useIsMobile, useToolbarLocation } from "../stores/toolbar-store";
+import { MenuPresenter } from "../../components/menu";
+import { getToolbarElement } from "../utils/dom";
type DropdownProps = {
selectedItem: string | JSX.Element;
@@ -18,6 +19,8 @@ export function Dropdown(props: DropdownProps) {
const internalRef = useRef<any>();
const [isOpen, setIsOpen] = useState(false);
const toolbarLocation = useToolbarLocation();
+ const isMobile = useIsMobile();
+ const isBottom = toolbarLocation === "bottom";
return (
<>
@@ -49,27 +52,34 @@ export function Dropdown(props: DropdownProps) {
selectedItem
)}
<Icon
- path={
- toolbarLocation === "bottom" ? Icons.chevronUp : Icons.chevronDown
- }
+ path={isBottom ? Icons.chevronUp : Icons.chevronDown}
size={"small"}
color={"text"}
/>
</Button>
+
<MenuPresenter
- options={{
- type: "menu",
- position: {
- target: internalRef.current || undefined,
- isTargetAbsolute: true,
- location: toolbarLocation === "bottom" ? "top" : "below",
- yOffset: 5,
- },
- }}
isOpen={isOpen}
items={items}
onClose={() => setIsOpen(false)}
- sx={{ minWidth: menuWidth }}
+ position={{
+ target: isBottom
+ ? getToolbarElement()
+ : internalRef.current || "mouse",
+ isTargetAbsolute: true,
+ location: isBottom ? "top" : "below",
+ align: "center",
+ yOffset: 5,
+ }}
+ blocking={!isMobile}
+ focusOnRender={!isMobile}
+ sx={{
+ minWidth: menuWidth,
+ maxWidth: isBottom ? "95vw" : "auto",
+ p: isBottom ? 1 : 0,
+ flexDirection: isBottom ? "row" : "column",
+ overflowX: isBottom ? "auto" : "hidden",
+ }}
/>
</>
);
diff --git a/packages/editor/src/toolbar/components/more-tools.tsx b/packages/editor/src/toolbar/components/more-tools.tsx
new file mode 100644
index 000000000..262a0aa24
--- /dev/null
+++ b/packages/editor/src/toolbar/components/more-tools.tsx
@@ -0,0 +1,62 @@
+import { useEffect, useRef, useState } from "react";
+import { PopupWrapper } from "../../components/popup-presenter";
+import { ToolButton } from "../components/tool-button";
+import { useToolbarLocation } from "../stores/toolbar-store";
+import { ToolProps } from "../types";
+import { getToolbarElement } from "../utils/dom";
+import { ToolId } from "../tools";
+import { ToolbarGroup } from "./toolbar-group";
+
+type MoreToolsProps = ToolProps & {
+ popupId: string;
+ tools: ToolId[];
+};
+export function MoreTools(props: MoreToolsProps) {
+ const { popupId, editor, tools } = props;
+ const toolbarLocation = useToolbarLocation();
+ const isBottom = toolbarLocation === "bottom";
+ const buttonRef = useRef<HTMLButtonElement | null>();
+ const [isOpen, setIsOpen] = useState(false);
+
+ return (
+ <>
+ <ToolButton
+ {...props}
+ toggled={isOpen}
+ buttonRef={buttonRef}
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => setIsOpen((s) => !s)}
+ />
+ <PopupWrapper
+ isOpen={isOpen}
+ group={"toolbarGroup"}
+ id={popupId}
+ onClosed={() => setIsOpen(false)}
+ position={{
+ isTargetAbsolute: true,
+ target: isBottom ? getToolbarElement() : buttonRef.current || "mouse",
+ align: "center",
+ location: isBottom ? "top" : "below",
+ yOffset: isBottom ? 10 : 5,
+ }}
+ focusOnRender={false}
+ blocking={false}
+ renderPopup={() => (
+ <ToolbarGroup
+ tools={tools}
+ editor={editor}
+ sx={{
+ flex: 1,
+ p: 1,
+ boxShadow: "menu",
+ bg: "background",
+ borderRadius: "default",
+ overflowX: "auto",
+ maxWidth: "95vw",
+ }}
+ />
+ )}
+ />
+ </>
+ );
+}
diff --git a/packages/editor/src/toolbar/components/popup.tsx b/packages/editor/src/toolbar/components/popup.tsx
index 896041e0e..094492f2a 100644
--- a/packages/editor/src/toolbar/components/popup.tsx
+++ b/packages/editor/src/toolbar/components/popup.tsx
@@ -3,67 +3,53 @@ import { Icon } from "./icon";
import { IconNames, Icons } from "../icons";
import { PropsWithChildren } from "react";
import { SchemeColors } from "@notesnook/theme/dist/theme/colorscheme";
+import { DesktopOnly, MobileOnly } from "../../components/responsive";
export type PopupProps = {
title?: string;
- action?: PopupButtonProps;
+ onClose: () => void;
};
export function Popup(props: PropsWithChildren<PopupProps>) {
- const { title, action, children } = props;
+ const { title, onClose, children } = props;
return (
- <Flex
- sx={{
- bg: "background",
- flexDirection: "column",
- // borderRadius: "default",
- // border: "1px solid var(--border)",
- // boxShadow: "menu",
- }}
- >
- {title && (
+ <>
+ <DesktopOnly>
<Flex
sx={{
- justifyContent: "space-between",
- alignItems: "center",
- mx: 1,
- mt: 1,
+ overflow: "hidden",
+ bg: "background",
+ flexDirection: "column",
+ borderRadius: "default",
+ // border: "1px solid var(--border)",
+ boxShadow: "menu",
+ minWidth: 200,
}}
>
- <Text variant={"subtitle"}>{title}</Text>
- {action && (
- <PopupButton data-test-id="popup-no" color="text" {...action} />
- )}
+ <Flex
+ className="movable"
+ sx={{
+ bg: "bgSecondary",
+ justifyContent: "space-between",
+ alignItems: "center",
+ p: 1,
+ mb: 1,
+ }}
+ >
+ <Text variant={"body"}>{title}</Text>
+ <Button
+ variant={"tool"}
+ sx={{ p: 0, bg: "transparent" }}
+ onClick={onClose}
+ >
+ <Icon path={Icons.close} size={16} />
+ </Button>
+ </Flex>
+ {children}
</Flex>
- )}
- {children}
- </Flex>
- );
-}
-
-type PopupButtonProps = ButtonProps & {
- text?: string;
- loading?: boolean;
- icon?: IconNames;
- iconSize?: number;
- iconColor?: keyof SchemeColors;
-};
-function PopupButton(props: PopupButtonProps) {
- const { text, loading, icon, iconColor, iconSize, ...restProps } = props;
- return (
- <Button variant="icon" sx={{ p: 1, px: 2 }} {...restProps}>
- {loading ? (
- <Icon path={Icons.loading} size={16} rotate color="primary" />
- ) : icon ? (
- <Icon
- path={Icons[icon]}
- size={iconSize || 18}
- color={iconColor || "icon"}
- />
- ) : (
- text
- )}
- </Button>
+ </DesktopOnly>
+ <MobileOnly>{children}</MobileOnly>
+ </>
);
}
diff --git a/packages/editor/src/toolbar/components/split-button.tsx b/packages/editor/src/toolbar/components/split-button.tsx
index 7381a430e..efab204e3 100644
--- a/packages/editor/src/toolbar/components/split-button.tsx
+++ b/packages/editor/src/toolbar/components/split-button.tsx
@@ -1,23 +1,19 @@
-import { SchemeColors } from "@notesnook/theme/dist/theme/colorscheme";
-import React, { PropsWithChildren, useRef, useState } from "react";
-import { Button, ButtonProps, Flex } from "rebass";
-import { IconNames, Icons } from "../icons";
+import { PropsWithChildren, useRef, useState } from "react";
+import { Button, Flex } from "rebass";
+import { Icons } from "../icons";
import { Icon } from "./icon";
import { ToolButton, ToolButtonProps } from "./tool-button";
-import {
- PopupPresenter,
- PopupPresenterProps,
-} from "../../components/menu/menu";
-import { useToolbarContext } from "../hooks/useToolbarContext";
import { useToolbarLocation } from "../stores/toolbar-store";
+import {
+ PopupWrapper,
+ PopupWrapperProps,
+} from "../../components/popup-presenter";
+import { PositionOptions } from "../../utils/position";
-type SplitButtonProps = ToolButtonProps & {
- popupPresenterProps?: Partial<PopupPresenterProps>;
-};
+export type SplitButtonProps = ToolButtonProps & { onOpen: () => void };
export function SplitButton(props: PropsWithChildren<SplitButtonProps>) {
- const { popupPresenterProps, children, ...toolButtonProps } = props;
+ const { children, toggled, onOpen, ...toolButtonProps } = props;
- const [isOpen, setIsOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
const toolbarLocation = useToolbarLocation();
@@ -27,22 +23,22 @@ export function SplitButton(props: PropsWithChildren<SplitButtonProps>) {
ref={ref}
sx={{
borderRadius: "default",
- bg: isOpen ? "hover" : "transparent",
+ bg: toggled ? "hover" : "transparent",
":hover": { bg: "hover" },
}}
>
- <ToolButton {...toolButtonProps} />
+ <ToolButton {...toolButtonProps} toggled={toggled} />
<Button
sx={{
p: 0,
m: 0,
- bg: "transparent",
+ bg: toggled ? "hover" : "transparent",
":hover": { bg: "hover" },
":last-of-type": {
mr: 0,
},
}}
- onClick={() => setIsOpen((s) => !s)}
+ onClick={onOpen}
onMouseDown={(e) => e.preventDefault()}
>
<Icon
@@ -54,24 +50,7 @@ export function SplitButton(props: PropsWithChildren<SplitButtonProps>) {
/>
</Button>
</Flex>
- <PopupPresenter
- isOpen={isOpen}
- onClose={() => setIsOpen(false)}
- options={{
- type: "menu",
- position: {
- target: ref.current || undefined,
- isTargetAbsolute: true,
- location: toolbarLocation === "bottom" ? "top" : "below",
- yOffset: 5,
- align: "center",
- },
- }}
- items={[]}
- {...popupPresenterProps}
- >
- {children}
- </PopupPresenter>
+ {children}
</>
);
}
diff --git a/packages/editor/src/toolbar/components/tool-button.tsx b/packages/editor/src/toolbar/components/tool-button.tsx
index 2d6b14f80..23ca430e7 100644
--- a/packages/editor/src/toolbar/components/tool-button.tsx
+++ b/packages/editor/src/toolbar/components/tool-button.tsx
@@ -33,6 +33,7 @@ export function ToolButton(props: ToolButtonProps) {
tabIndex={-1}
id={`tool-${id}`}
sx={{
+ flexShrink: 0,
p: variant === "small" ? "small" : 1,
borderRadius: variant === "small" ? "small" : "default",
m: 0,
diff --git a/packages/editor/src/toolbar/components/toolbar-group.tsx b/packages/editor/src/toolbar/components/toolbar-group.tsx
new file mode 100644
index 000000000..bf5a220e8
--- /dev/null
+++ b/packages/editor/src/toolbar/components/toolbar-group.tsx
@@ -0,0 +1,43 @@
+import { ToolbarGroupDefinition } from "../types";
+import { findTool } from "../tools";
+import { Flex, FlexProps } from "rebass";
+import { Editor } from "@tiptap/core";
+import { MoreTools } from "./more-tools";
+import { getToolDefinition } from "../tool-definitions";
+
+export type ToolbarGroupProps = FlexProps & {
+ tools: ToolbarGroupDefinition;
+ editor: Editor;
+};
+export function ToolbarGroup(props: ToolbarGroupProps) {
+ const { tools, editor, ...flexProps } = props;
+ return (
+ <Flex className="toolbar-group" {...flexProps}>
+ {tools.map((toolId) => {
+ if (Array.isArray(toolId)) {
+ return (
+ <MoreTools
+ key={"more-tools"}
+ title="More"
+ icon="more"
+ popupId={toolId.join("")}
+ tools={toolId}
+ editor={editor}
+ />
+ );
+ } else {
+ const Component = findTool(toolId);
+ const toolDefinition = getToolDefinition(toolId);
+ if (toolId === "textColor") console.log("Rendering", toolId);
+ return (
+ <Component
+ key={toolDefinition.title}
+ editor={editor}
+ {...toolDefinition}
+ />
+ );
+ }
+ })}
+ </Flex>
+ );
+}
diff --git a/packages/editor/src/toolbar/floating-menus/search-replace.tsx b/packages/editor/src/toolbar/floating-menus/search-replace.tsx
index 26ff90af1..80a2dd803 100644
--- a/packages/editor/src/toolbar/floating-menus/search-replace.tsx
+++ b/packages/editor/src/toolbar/floating-menus/search-replace.tsx
@@ -1,8 +1,3 @@
-import {
- ActionSheetPresenter,
- MenuPresenter,
- PopupPresenter,
-} from "../../components/menu/menu";
import { SearchStorage } from "../../extensions/search-replace";
import { FloatingMenuProps } from "./types";
import { SearchReplacePopup } from "../popups/search-replace";
@@ -13,26 +8,27 @@ export function SearchReplaceFloatingMenu(props: FloatingMenuProps) {
const { isSearching } = editor.storage.searchreplace as SearchStorage;
if (!isSearching) return null;
- return (
- <>
- <PopupPresenter
- mobile="sheet"
- desktop="menu"
- isOpen
- onClose={() => editor.commands.endSearch()}
- options={{
- type: "autocomplete",
- position: {
- target:
- document.querySelector<HTMLElement>(".editor-toolbar") || "mouse",
- isTargetAbsolute: true,
- location: "below",
- align: "end",
- },
- }}
- >
- <SearchReplacePopup editor={editor} />
- </PopupPresenter>
- </>
- );
+ return null;
+ // return (
+ // <>
+ // <PopupPresenter
+ // mobile="sheet"
+ // desktop="menu"
+ // isOpen
+ // onClose={() => editor.commands.endSearch()}
+ // options={{
+ // type: "autocomplete",
+ // position: {
+ // target:
+ // document.querySelector<HTMLElement>(".editor-toolbar") || "mouse",
+ // isTargetAbsolute: true,
+ // location: "below",
+ // align: "end",
+ // },
+ // }}
+ // >
+ // <SearchReplacePopup editor={editor} />
+ // </PopupPresenter>
+ // </>
+ // );
}
diff --git a/packages/editor/src/toolbar/floating-menus/table/table.tsx b/packages/editor/src/toolbar/floating-menus/table/table.tsx
index e9ddf912c..41a145bf0 100644
--- a/packages/editor/src/toolbar/floating-menus/table/table.tsx
+++ b/packages/editor/src/toolbar/floating-menus/table/table.tsx
@@ -1,25 +1,24 @@
import { useEffect, useState } from "react";
import { Flex } from "rebass";
-import { MenuPresenter } from "../../../components/menu/menu";
-import { MenuOptions } from "../../../components/menu/useMenu";
// import { ColorPicker, DEFAULT_COLORS } from "../tools/colors";
import { FloatingMenuProps } from "../types";
+import { useToolbarLocation } from "../../stores/toolbar-store";
+import { PositionOptions } from "../../../utils/position";
+import { PopupPresenter } from "../../../components/popup-presenter";
+import { getToolbarElement } from "../../utils/dom";
import {
ColumnProperties,
InsertColumnRight,
InsertRowBelow,
RowProperties,
-} from "./tools";
-import { getToolbarElement } from "../../utils/dom";
-import { useToolbarContext } from "../../hooks/useToolbarContext";
-import { useToolbarLocation } from "../../stores/toolbar-store";
+ TableProperties,
+} from "../../tools/table";
+import { getToolDefinition } from "../../tool-definitions";
export function TableRowFloatingMenu(props: FloatingMenuProps) {
const { editor } = props;
// const theme = editor.storage.theme as Theme;
- const [position, setPosition] = useState<MenuOptions["position"] | null>(
- null
- );
+ const [position, setPosition] = useState<PositionOptions | null>(null);
useEffect(() => {
if (
@@ -54,14 +53,12 @@ export function TableRowFloatingMenu(props: FloatingMenuProps) {
if (!position) return null;
return (
- <MenuPresenter
+ <PopupPresenter
isOpen
- items={[]}
+ blocking={false}
+ focusOnRender={false}
onClose={() => {}}
- options={{
- type: "autocomplete",
- position,
- }}
+ position={position}
>
<Flex
sx={{
@@ -75,27 +72,24 @@ export function TableRowFloatingMenu(props: FloatingMenuProps) {
}}
>
<RowProperties
- title="Row properties"
- editor={editor}
- variant="small"
+ {...getToolDefinition("rowProperties")}
icon="more"
+ variant="small"
+ editor={editor}
/>
<InsertRowBelow
- title="Insert row below"
- icon="insertRowBelow"
+ {...getToolDefinition("insertRowBelow")}
editor={editor}
variant="small"
/>
</Flex>
- </MenuPresenter>
+ </PopupPresenter>
);
}
export function TableColumnFloatingMenu(props: FloatingMenuProps) {
const { editor } = props;
- const [position, setPosition] = useState<MenuOptions["position"] | null>(
- null
- );
+ const [position, setPosition] = useState<PositionOptions | null>(null);
useEffect(() => {
if (
@@ -135,14 +129,12 @@ export function TableColumnFloatingMenu(props: FloatingMenuProps) {
if (!position) return null;
return (
- <MenuPresenter
+ <PopupPresenter
isOpen
- items={[]}
onClose={() => {}}
- options={{
- type: "autocomplete",
- position,
- }}
+ blocking={false}
+ position={position}
+ focusOnRender={false}
>
<Flex
sx={{
@@ -156,21 +148,20 @@ export function TableColumnFloatingMenu(props: FloatingMenuProps) {
},
}}
>
- <ColumnProperties
- currentCell={position.target as HTMLElement}
- title="Column properties"
+ <TableProperties
editor={editor}
+ title="tableProperties"
icon="more"
variant={"small"}
/>
<InsertColumnRight
+ {...getToolDefinition("insertColumnRight")}
editor={editor}
- title="Insert column right"
variant={"small"}
icon="plus"
/>
</Flex>
- </MenuPresenter>
+ </PopupPresenter>
);
}
@@ -179,18 +170,16 @@ export function TableFloatingMenu(props: FloatingMenuProps) {
const toolbarLocation = useToolbarLocation();
if (!editor.isActive("table")) return null;
return (
- <MenuPresenter
+ <PopupPresenter
isOpen
- items={[]}
onClose={() => {}}
- options={{
- type: "autocomplete",
- position: {
- isTargetAbsolute: true,
- target: getToolbarElement(),
- location: toolbarLocation === "bottom" ? "top" : "below",
- },
+ blocking={false}
+ position={{
+ isTargetAbsolute: true,
+ target: getToolbarElement(),
+ location: toolbarLocation === "bottom" ? "top" : "below",
}}
+ focusOnRender={false}
>
<Flex
sx={{
@@ -204,7 +193,7 @@ export function TableFloatingMenu(props: FloatingMenuProps) {
},
}}
>
- <RowProperties
+ {/* <RowProperties
title="Row properties"
editor={editor}
variant="normal"
@@ -227,8 +216,8 @@ export function TableFloatingMenu(props: FloatingMenuProps) {
title="Insert column right"
variant={"normal"}
icon="insertColumnRight"
- />
+ /> */}
</Flex>
- </MenuPresenter>
+ </PopupPresenter>
);
}
diff --git a/packages/editor/src/toolbar/floating-menus/table/tools.tsx b/packages/editor/src/toolbar/floating-menus/table/tools.tsx
deleted file mode 100644
index 8ab555f03..000000000
--- a/packages/editor/src/toolbar/floating-menus/table/tools.tsx
+++ /dev/null
@@ -1,262 +0,0 @@
-import { Theme } from "@notesnook/theme";
-import { Slider } from "@rebass/forms";
-import { Editor, findParentNodeClosestToPos } from "@tiptap/core";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { Flex, Text } from "rebass";
-import {
- ActionSheetPresenter,
- MenuPresenter,
- PopupPresenter,
-} from "../../../components/menu/menu";
-import {
- getElementPosition,
- MenuOptions,
-} from "../../../components/menu/useMenu";
-import { Popup } from "../../components/popup";
-import { ToolButton, ToolButtonProps } from "../../components/tool-button";
-import { IconNames } from "../../icons";
-// import { ColorPicker, DEFAULT_COLORS } from "../tools/colors";
-import { FloatingMenuProps } from "../types";
-import { selectedRect, TableMap, TableRect } from "prosemirror-tables";
-import { Transaction } from "prosemirror-state";
-import { MenuItem } from "../../../components/menu/types";
-import { DesktopOnly, MobileOnly } from "../../../components/responsive";
-import { ToolProps } from "../../types";
-import { CellProperties } from "../../popups/cell-properties";
-import {
- moveColumnLeft,
- moveColumnRight,
- moveRowDown,
- moveRowUp,
-} from "./actions";
-
-type TableToolProps = ToolProps & { variant: ToolButtonProps["variant"] };
-
-export function RowProperties(props: TableToolProps) {
- const { editor, ...toolProps } = props;
- const [isMenuOpen, setIsMenuOpen] = useState(false);
- return (
- <>
- <ToolButton
- toggled={isMenuOpen}
- {...toolProps}
- onClick={() => setIsMenuOpen(true)}
- // iconSize={16}
- // sx={{ mr: 0, p: "3px", borderRadius: "small" }}
- />
- <MenuPresenter
- isOpen={isMenuOpen}
- onClose={() => {
- setIsMenuOpen(false);
- editor.commands.focus();
- }}
- options={{
- type: "menu",
- position: {},
- }}
- items={[
- {
- key: "addRowAbove",
- type: "menuitem",
- title: "Add row above",
- onClick: () => editor.chain().focus().addRowBefore().run(),
- icon: "insertRowAbove",
- },
- {
- key: "moveRowUp",
- type: "menuitem",
- title: "Move row up",
- onClick: () => moveRowUp(editor),
- icon: "moveRowUp",
- },
- {
- key: "moveRowDown",
- type: "menuitem",
- title: "Move row down",
- onClick: () => moveRowDown(editor),
- icon: "moveRowDown",
- },
- {
- key: "deleteRow",
- type: "menuitem",
- title: "Delete row",
- onClick: () => editor.chain().focus().deleteRow().run(),
- icon: "deleteRow",
- },
- ]}
- />
- </>
- );
-}
-
-export function InsertRowBelow(props: TableToolProps) {
- const { editor, ...toolProps } = props;
- return (
- <ToolButton
- toggled={false}
- {...toolProps}
- onClick={() => editor.chain().focus().addRowAfter().run()}
- // sx={{ mr: 0, p: "3px", borderRadius: "small" }}
- // iconSize={16}
- />
- );
-}
-
-type ColumnPropertiesProps = TableToolProps & {
- currentCell?: HTMLElement;
-};
-export function ColumnProperties(props: ColumnPropertiesProps) {
- const { editor, currentCell, ...toolProps } = props;
- const [isMenuOpen, setIsMenuOpen] = useState(false);
- const isInsideCellSelection =
- !editor.state.selection.empty &&
- editor.state.selection.$anchor.node().type.name === "tableCell";
-
- const [showCellProps, setShowCellProps] = useState(false);
- const [menuPosition, setMenuPosition] = useState<
- MenuOptions["position"] | null
- >(null);
-
- const columnProperties: MenuItem[] = [
- {
- key: "addColumnLeft",
- type: "menuitem",
- title: "Add column left",
- onClick: () => editor.chain().focus().addColumnBefore().run(),
- icon: "insertColumnLeft",
- },
- {
- key: "addColumnRight",
- type: "menuitem",
- title: "Add column right",
- onClick: () => editor.chain().focus().addColumnAfter().run(),
- icon: "insertColumnRight",
- },
- {
- key: "moveColumnLeft",
- type: "menuitem",
- title: "Move column left",
- onClick: () => moveColumnLeft(editor),
- icon: "moveColumnLeft",
- },
- {
- key: "moveColumnRight",
- type: "menuitem",
- title: "Move column right",
- onClick: () => moveColumnRight(editor),
- icon: "moveColumnRight",
- },
- {
- key: "deleteColumn",
- type: "menuitem",
- title: "Delete column",
- onClick: () => editor.chain().focus().deleteColumn().run(),
- icon: "deleteColumn",
- },
- ];
-
- const mergeSplitProperties: MenuItem[] = [
- {
- key: "splitCells",
- type: "menuitem",
- title: "Split cells",
- onClick: () => editor.chain().focus().splitCell().run(),
- icon: "splitCells",
- },
- {
- key: "mergeCells",
- type: "menuitem",
- title: "Merge cells",
- onClick: () => editor.chain().focus().mergeCells().run(),
- icon: "mergeCells",
- },
- ];
-
- const cellProperties: MenuItem[] = [
- {
- key: "cellProperties",
- type: "menuitem",
- title: "Cell properties",
- onClick: () => {
- setShowCellProps(true);
- setMenuPosition({
- target: currentCell || undefined,
- isTargetAbsolute: true,
- yOffset: 10,
- location: "below",
- });
- },
- icon: "cellProperties",
- },
- ];
-
- const tableProperties: MenuItem[] = [
- {
- key: "deleteTable",
- type: "menuitem",
- title: "Delete table",
- icon: "deleteTable",
- onClick: () => editor.chain().focus().deleteTable().run(),
- },
- ];
-
- return (
- <>
- <ToolButton
- toggled={isMenuOpen}
- {...toolProps}
- onClick={async () => setIsMenuOpen(true)}
- />
- <PopupPresenter
- isOpen={isMenuOpen}
- onClose={() => {
- setIsMenuOpen(false);
- editor.commands.focus();
- }}
- mobile="sheet"
- items={
- isInsideCellSelection
- ? [...mergeSplitProperties, ...cellProperties]
- : [
- ...columnProperties,
- { type: "seperator", key: "cellSeperator" },
- ...cellProperties,
- { type: "seperator", key: "tableSeperator" },
- ...tableProperties,
- ]
- }
- />
-
- <PopupPresenter
- isOpen={showCellProps}
- onClose={() => {
- setShowCellProps(false);
- editor.commands.focus();
- }}
- options={{
- type: "menu",
- position: menuPosition || {},
- }}
- mobile="sheet"
- >
- <CellProperties
- editor={editor}
- onClose={() => setShowCellProps(false)}
- />
- </PopupPresenter>
- </>
- );
-}
-
-export function InsertColumnRight(props: TableToolProps) {
- const { editor, ...toolProps } = props;
- return (
- <ToolButton
- {...toolProps}
- toggled={false}
- onClick={() => editor.chain().focus().addColumnAfter().run()}
- // sx={{ mr: 0, p: "3px", borderRadius: "small" }}
- // iconSize={16}
- />
- );
-}
diff --git a/packages/editor/src/toolbar/hooks/useToolbarContext.ts b/packages/editor/src/toolbar/hooks/useToolbarContext.ts
deleted file mode 100644
index e3d80629f..000000000
--- a/packages/editor/src/toolbar/hooks/useToolbarContext.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import React, { useContext } from "react";
-
-export const ToolbarContext = React.createContext<{
- currentPopup?: string;
- setCurrentPopup?: React.Dispatch<React.SetStateAction<string | undefined>>;
-}>({});
-
-export function useToolbarContext() {
- return useContext(ToolbarContext);
-}
diff --git a/packages/editor/src/toolbar/icons.ts b/packages/editor/src/toolbar/icons.ts
index 9de82677e..75ccc5ffc 100644
--- a/packages/editor/src/toolbar/icons.ts
+++ b/packages/editor/src/toolbar/icons.ts
@@ -85,6 +85,13 @@ import {
mdiMinus,
mdiPaletteOutline,
mdiCircle,
+ mdiChevronLeft,
+ mdiTableCog,
+ mdiVectorRectangle,
+ mdiSquareOutline,
+ mdiTableOff,
+ mdiRectangleOutline,
+ mdiRectangle,
} from "@mdi/js";
export const Icons = {
@@ -133,11 +140,14 @@ export const Icons = {
moveColumnRight: mdiArrowExpandRight,
moveColumnLeft: mdiArrowExpandLeft,
deleteColumn: mdiTableColumnRemove,
- cellProperties: mdiSquareRoundedBadgeOutline,
+ cellProperties: mdiRectangle,
+ cellBorderColor:
+ "M4 24q-.825 0-1.412-.587Q2 22.825 2 22q0-.825.588-1.413Q3.175 20 4 20h16q.825 0 1.413.587Q22 21.175 22 22q0 .825-.587 1.413Q20.825 24 20 24Zm1-6q-.425 0-.713-.288Q4 17.425 4 17v-2.325q0-.2.075-.388q.075-.187.225-.337l8.75-8.75l3.75 3.75l-8.75 8.75q-.15.15-.337.225q-.188.075-.388.075Zm1-2h.9L14 8.95L13.05 8L6 15.1Zm11.925-8.15l-3.75-3.75l1.8-1.8q.275-.3.7-.288q.425.013.7.288l2.35 2.35q.275.275.275.688q0 .412-.275.712ZM6 16Z",
backgroundColor: mdiFormatColorFill,
- borderColor: mdiBorderAllVariant,
+ borderColor:
+ "M4 24q-.825 0-1.412-.587Q2 22.825 2 22q0-.825.588-1.413Q3.175 20 4 20h16q.825 0 1.413.587Q22 21.175 22 22q0 .825-.587 1.413Q20.825 24 20 24Zm1-6q-.425 0-.713-.288Q4 17.425 4 17v-2.325q0-.2.075-.388q.075-.187.225-.337l8.75-8.75l3.75 3.75l-8.75 8.75q-.15.15-.337.225q-.188.075-.388.075Zm1-2h.9L14 8.95L13.05 8L6 15.1Zm11.925-8.15l-3.75-3.75l1.8-1.8q.275-.3.7-.288q.425.013.7.288l2.35 2.35q.275.275.275.688q0 .412-.275.712ZM6 16Z",
sortDesc: mdiSortDescending,
- deleteTable: mdiTrashCanOutline,
+ deleteTable: mdiTableOff,
mergeCells: mdiTableMergeCells,
splitCells: mdiTableSplitCell,
checklist: mdiFormatListCheckbox,
@@ -153,6 +163,7 @@ export const Icons = {
regex: mdiRegex,
embed: mdiMoviePlusOutline,
palette: mdiPaletteOutline,
+ tableSettings: mdiTableCog,
plus: mdiPlus,
minus: mdiMinus,
@@ -162,6 +173,7 @@ export const Icons = {
chevronDown: mdiChevronDown,
chevronUp: mdiChevronUp,
chevronRight: mdiChevronRight,
+ chevronLeft: mdiChevronLeft,
circle: mdiCircle,
none: "",
diff --git a/packages/editor/src/toolbar/popups/cell-properties.tsx b/packages/editor/src/toolbar/popups/cell-properties.tsx
index 50f2d3ee5..bbe9fb5e6 100644
--- a/packages/editor/src/toolbar/popups/cell-properties.tsx
+++ b/packages/editor/src/toolbar/popups/cell-properties.tsx
@@ -1,26 +1,82 @@
import { Slider } from "@rebass/forms";
import { Editor } from "@tiptap/core";
import { useRef, useState } from "react";
-import { Flex, Text } from "rebass";
-import { MenuPresenter } from "../../components/menu/menu";
+import { Box, Flex, Text } from "rebass";
+import { Tab, Tabs } from "../../components/tabs";
+import { Counter } from "../components/counter";
+import { Icon } from "../components/icon";
+// import { MenuPresenter } from "../../components/menu/menu";
import { Popup } from "../components/popup";
import { ToolButton } from "../components/tool-button";
-import { IconNames } from "../icons";
+import { IconNames, Icons } from "../icons";
+import { ColorPicker } from "./color-picker";
type CellPropertiesProps = { editor: Editor; onClose: () => void };
export function CellProperties(props: CellPropertiesProps) {
const { editor, onClose } = props;
const attributes = editor.getAttributes("tableCell");
return (
- <Popup
- title="Cell properties"
- action={{
- icon: "close",
- iconColor: "error",
- onClick: onClose,
- }}
- >
- <Flex sx={{ flexDirection: "column", px: 1, mb: 2 }}>
+ <Popup title="Cell properties" onClose={onClose}>
+ <Tabs activeIndex={0}>
+ <Tab
+ title={
+ <Icon
+ title="Cell background color"
+ path={Icons.backgroundColor}
+ size={16}
+ />
+ }
+ >
+ <Box mt={2} />
+ <ColorPicker
+ expanded={true}
+ color={attributes.backgroundColor}
+ onChange={(color) =>
+ editor.commands.setCellAttribute("backgroundColor", color)
+ }
+ onClear={() =>
+ editor.commands.setCellAttribute("backgroundColor", undefined)
+ }
+ />
+ </Tab>
+ <Tab
+ title={
+ <Icon title="Cell text color" path={Icons.textColor} size={16} />
+ }
+ >
+ <Box mt={2} />
+ <ColorPicker
+ expanded={true}
+ color={attributes.color}
+ onChange={(color) =>
+ editor.commands.setCellAttribute("color", color)
+ }
+ onClear={() => editor.commands.setCellAttribute("color", undefined)}
+ />
+ </Tab>
+ <Tab
+ title={
+ <Icon
+ title="Cell border color"
+ path={Icons.cellBorderColor}
+ size={16}
+ />
+ }
+ >
+ <Box mt={2} />
+ <ColorPicker
+ expanded={true}
+ color={attributes.borderColor}
+ onChange={(color) =>
+ editor.commands.setCellAttribute("borderColor", color)
+ }
+ onClear={() =>
+ editor.commands.setCellAttribute("borderColor", undefined)
+ }
+ />
+ </Tab>
+ </Tabs>
+ {/* <Flex sx={{ flexDirection: "column", px: 1, mb: 2 }}>
<ColorPickerTool
color={attributes.backgroundColor}
title="Background color"
@@ -56,19 +112,8 @@ export function CellProperties(props: CellPropertiesProps) {
<Text variant={"body"}>Border width</Text>
<Text variant={"body"}>{attributes.borderWidth || 1}px</Text>
</Flex>
- <Slider
- min={1}
- max={5}
- value={attributes.borderWidth || 1}
- onChange={(e) => {
- editor.commands.setCellAttribute(
- "borderWidth",
- e.target.valueAsNumber
- );
- }}
- />
</Flex>
- </Flex>
+ </Flex> */}
</Popup>
);
}
@@ -105,7 +150,7 @@ function ColorPickerTool(props: ColorPickerToolProps) {
/>
</Flex>
- <MenuPresenter
+ {/* <MenuPresenter
isOpen={isOpen}
onClose={() => setIsOpen(false)}
items={[]}
@@ -136,9 +181,9 @@ function ColorPickerTool(props: ColorPickerToolProps) {
color={color}
onClear={() => onColorChange()}
onChange={(color) => onColorChange(color)}
- /> */}
+ />
</Flex>
- </MenuPresenter>
+ </MenuPresenter> */}
</>
);
}
diff --git a/packages/editor/src/toolbar/popups/color-picker.tsx b/packages/editor/src/toolbar/popups/color-picker.tsx
new file mode 100644
index 000000000..eb2fd3f44
--- /dev/null
+++ b/packages/editor/src/toolbar/popups/color-picker.tsx
@@ -0,0 +1,191 @@
+import { Box, Button, Flex, Text } from "rebass";
+import { Input } from "@rebass/forms";
+import { Icon } from "../components/icon";
+import { Icons } from "../icons";
+import { useState } from "react";
+import tinycolor from "tinycolor2";
+import { HexColorPicker } from "react-colorful";
+
+export const DEFAULT_COLORS = [
+ "#e91e63",
+ "#9c27b0",
+ "#673ab7",
+ "#3f51b5",
+ "#2196f3",
+ "#03a9f4",
+ "#00bcd4",
+ "#009688",
+ "#4caf50",
+ "#8bc34a",
+ "#cddc39",
+ "#ffeb3b",
+ "#ffc107",
+ "#f44336",
+];
+
+type ColorPickerProps = {
+ colors?: string[];
+ color: string;
+ onClear: () => void;
+ expanded?: boolean;
+ onChange: (color: string) => void;
+ onClose?: () => void;
+ title?: string;
+};
+const PALETTE_SIZE = [35, 35, 25];
+export function ColorPicker(props: ColorPickerProps) {
+ const {
+ colors = DEFAULT_COLORS,
+ color,
+ onClear,
+ onChange,
+ title,
+ onClose,
+ expanded,
+ } = props;
+ const [isPickerOpen, setIsPickerOpen] = useState(expanded || false);
+ const tColor = tinycolor(color || colors[0]);
+ const [currentColor, setCurrentColor] = useState<string>(
+ tColor.toHexString()
+ );
+
+ return (
+ <Flex
+ sx={{
+ bg: "background",
+ flexDirection: "column",
+ ".react-colorful": {
+ width: "auto",
+ height: 150,
+ },
+ ".react-colorful__saturation": {
+ borderRadius: ["default", 0],
+ },
+ width: ["calc(100vw - 20px)", 250],
+ // width: ["auto", 250],
+ }}
+ >
+ {onClose && (
+ <Box
+ sx={{
+ display: ["none", "flex"],
+ justifyContent: "space-between",
+ p: 2,
+ pb: isPickerOpen ? 2 : 0,
+ //pb: 0,
+ alignItems: "center",
+ }}
+ onClick={onClose}
+ >
+ <Text variant={"title"}>{title}</Text>
+ <Button variant={"icon"} sx={{ p: 0 }}>
+ <Icon path={Icons.close} size="big" />
+ </Button>
+ </Box>
+ )}
+
+ {isPickerOpen ? (
+ <>
+ <HexColorPicker color={currentColor} onChange={onChange} />
+ <Input
+ variant={"clean"}
+ placeholder="#000000"
+ spellCheck={false}
+ sx={{
+ my: 2,
+ p: 0,
+ borderRadius: 0,
+ fontSize: ["title", "title", "body"],
+ color: "fontTertiary",
+ textAlign: "center",
+ letterSpacing: 1.5,
+ }}
+ value={currentColor.toUpperCase()}
+ maxLength={7}
+ onChange={(e) => {
+ const { value } = e.target;
+ if (!value) return;
+ setCurrentColor(value);
+ }}
+ />
+ </>
+ ) : null}
+ <Flex>
+ <Flex
+ className="hide-scrollbar"
+ sx={{
+ flex: 1,
+ p: 1,
+ overflowX: ["auto", "hidden"],
+ flexWrap: ["nowrap", "wrap"],
+ }}
+ >
+ <Button
+ variant={"icon"}
+ sx={{
+ flexShrink: 0,
+ width: PALETTE_SIZE,
+ height: PALETTE_SIZE,
+ borderRadius: 50,
+ boxShadow: "menu",
+ p: 0,
+ ml: [2, 2, 1],
+ }}
+ onClick={onClear}
+ >
+ <Icon path={Icons.colorClear} color="text" size={15} />
+ </Button>
+ <Button
+ variant={"secondary"}
+ sx={{
+ flexShrink: 0,
+ bg: currentColor,
+ width: PALETTE_SIZE,
+ height: PALETTE_SIZE,
+ borderRadius: 50,
+ // boxShadow: "menu",
+ p: 0,
+ ml: [2, 2, 1],
+ }}
+ onClick={() => setIsPickerOpen((s) => !s)}
+ >
+ <Icon
+ path={Icons.palette}
+ color={tColor.isDark() ? "static" : "icon"}
+ size={18}
+ />
+ </Button>
+ {colors.map((color) => (
+ <Button
+ key={color}
+ variant={"secondary"}
+ sx={{
+ flex: "0 0 auto",
+ bg: color,
+ width: PALETTE_SIZE,
+ height: PALETTE_SIZE,
+ ml: [2, 1, 1],
+ mb: [0, 1, 1],
+ borderRadius: 50,
+ // boxShadow: "menu",
+ }}
+ onClick={() => {
+ setCurrentColor(color);
+ onChange(color);
+ }}
+ />
+ ))}
+ </Flex>
+ {onClose && (
+ <Button
+ variant={"icon"}
+ sx={{ display: ["block", "none"], px: 2 }}
+ onClick={onClose}
+ >
+ <Icon path={Icons.close} size="big" />
+ </Button>
+ )}
+ </Flex>
+ </Flex>
+ );
+}
diff --git a/packages/editor/src/toolbar/popups/embed-popup.tsx b/packages/editor/src/toolbar/popups/embed-popup.tsx
index dfcfe7ed1..4e071664d 100644
--- a/packages/editor/src/toolbar/popups/embed-popup.tsx
+++ b/packages/editor/src/toolbar/popups/embed-popup.tsx
@@ -11,13 +11,14 @@ import {
import { IconNames } from "../icons";
import { ToolButton } from "../components/tool-button";
import { convertUrlToEmbedUrl } from "@social-embed/lib";
+import { InlineInput } from "../../components/inline-input";
+import { Tabs, Tab } from "../../components/tabs";
type Embed = Required<EmbedAttributes> & EmbedAlignmentOptions;
type EmbedSource = "url" | "code";
export type EmbedPopupProps = {
- onClose: (embed: Embed) => void;
+ onClose: (embed?: Embed) => void;
title?: string;
- icon?: IconNames;
embed?: Embed;
onSizeChanged?: (size: EmbedSizeOptions) => void;
@@ -25,7 +26,7 @@ export type EmbedPopupProps = {
};
export function EmbedPopup(props: EmbedPopupProps) {
- const { onClose, onSizeChanged, onSourceChanged, title, icon, embed } = props;
+ const { onClose, onSizeChanged, onSourceChanged, title, embed } = props;
const [width, setWidth] = useState(embed?.width || 300);
const [height, setHeight] = useState(embed?.height || 150);
const [src, setSrc] = useState(embed?.src || "");
@@ -60,47 +61,8 @@ export function EmbedPopup(props: EmbedPopupProps) {
}, [onSourceChanged, src]);
return (
- <Popup
- title={title}
- action={{
- icon,
- onClick: () => {
- setError(null);
- let _src = src;
- let _width = width;
- let _height = height;
- if (embedSource === "code") {
- const document = new DOMParser().parseFromString(src, "text/html");
- if (document.getElementsByTagName("iframe").length <= 0)
- return setError("Embed code must include an iframe.");
-
- const srcValue = getAttribute(document, "src");
- if (!srcValue)
- return setError(
- "Embed code must include an iframe with an src attribute."
- );
-
- _src = srcValue;
-
- const widthValue = getAttribute(document, "width");
- if (widthValue && !isNaN(parseInt(widthValue)))
- _width = parseInt(widthValue);
-
- const heightValue = getAttribute(document, "height");
- if (heightValue && !isNaN(parseInt(heightValue)))
- _height = parseInt(heightValue);
- }
- const convertedUrl = convertUrlToEmbedUrl(_src);
- if (!!convertedUrl) _src = convertedUrl;
- onClose({
- height: _height,
- width: _width,
- src: _src,
- });
- },
- }}
- >
- <Flex sx={{ flexDirection: "column", p: 1 }}>
+ <Popup title={title} onClose={() => onClose()}>
+ <Flex sx={{ flexDirection: "column", width: ["auto", 300] }}>
{error && (
<Text
variant={"error"}
@@ -114,77 +76,104 @@ export function EmbedPopup(props: EmbedPopupProps) {
Error: {error}
</Text>
)}
- {/* <Flex sx={{ position: "relative", alignItems: "center" }}> */}
- <Flex sx={{ mb: 1 }}>
- <Button
- variant={"dialog"}
- sx={{
- pb: 1,
- mr: 1,
- borderRadius: 0,
- color: embedSource === "url" ? "primary" : "text",
- borderBottom: "2px solid",
- borderBottomColor:
- embedSource === "url" ? "primary" : "transparent",
- }}
- onClick={() => setEmbedSource("url")}
- >
- From URL
- </Button>
- <Button
- variant={"dialog"}
- sx={{
- pb: 1,
- borderRadius: 0,
- color: embedSource === "code" ? "primary" : "text",
- borderBottom: "2px solid",
- borderBottomColor:
- embedSource === "code" ? "primary" : "transparent",
- }}
- onClick={() => setEmbedSource("code")}
- >
- From code
- </Button>
- </Flex>
- {embedSource === "url" ? (
- <Input
- placeholder="Enter embed source URL"
- value={src}
- autoFocus
- onChange={(e) => setSrc(e.target.value)}
- sx={{ mt: 1, fontSize: "body" }}
- />
- ) : (
- <Textarea
- autoFocus
- variant={"forms.input"}
- sx={{ fontSize: "subBody", fontFamily: "monospace", mt: 1 }}
- minHeight={[200, 100]}
- onChange={(e) => setSrc(e.target.value)}
- placeholder="Paste embed code here. Only iframes are supported."
- />
- )}
- {embedSource === "url" ? (
- <Flex sx={{ alignItems: "center", mt: 1 }}>
- <Input
- type="number"
- placeholder="Width"
- value={width}
- sx={{
- mr: 1,
- fontSize: "body",
- }}
- onChange={(e) => onSizeChange(e.target.valueAsNumber)}
- />
+
+ <Tabs
+ activeIndex={0}
+ containerProps={{ sx: { mx: 1, mb: 1, flexDirection: "column" } }}
+ onTabChanged={(index) => setEmbedSource(index === 0 ? "url" : "code")}
+ >
+ <Tab title="From URL">
<Input
- type="number"
- placeholder="Height"
- value={height}
+ placeholder="Enter embed source URL"
+ value={src}
+ autoFocus
+ onChange={(e) => setSrc(e.target.value)}
sx={{ fontSize: "body" }}
- onChange={(e) => onSizeChange(undefined, e.target.valueAsNumber)}
/>
- </Flex>
- ) : null}
+ <Flex sx={{ alignItems: "center", mt: 1 }}>
+ <InlineInput
+ containerProps={{ sx: { mr: 1 } }}
+ label="width"
+ type="number"
+ placeholder="Width"
+ value={width}
+ sx={{
+ mr: 1,
+ fontSize: "body",
+ }}
+ onChange={(e) => onSizeChange(e.target.valueAsNumber)}
+ />
+ <InlineInput
+ label="height"
+ type="number"
+ placeholder="Height"
+ value={height}
+ sx={{ fontSize: "body" }}
+ onChange={(e) =>
+ onSizeChange(undefined, e.target.valueAsNumber)
+ }
+ />
+ </Flex>
+ </Tab>
+ <Tab title="From code">
+ <Textarea
+ autoFocus
+ variant={"forms.input"}
+ sx={{ fontSize: "subBody", fontFamily: "monospace" }}
+ minHeight={[200, 100]}
+ onChange={(e) => setSrc(e.target.value)}
+ placeholder="Paste embed code here. Only iframes are supported."
+ />
+ </Tab>
+ </Tabs>
+
+ <Button
+ variant={"primary"}
+ sx={{
+ alignSelf: ["stretch", "end", "end"],
+ my: 1,
+ mr: 1,
+ }}
+ onClick={() => {
+ setError(null);
+ let _src = src;
+ let _width = width;
+ let _height = height;
+ if (embedSource === "code") {
+ const document = new DOMParser().parseFromString(
+ src,
+ "text/html"
+ );
+ if (document.getElementsByTagName("iframe").length <= 0)
+ return setError("Embed code must include an iframe.");
+
+ const srcValue = getAttribute(document, "src");
+ if (!srcValue)
+ return setError(
+ "Embed code must include an iframe with an src attribute."
+ );
+
+ _src = srcValue;
+
+ const widthValue = getAttribute(document, "width");
+ if (widthValue && !isNaN(parseInt(widthValue)))
+ _width = parseInt(widthValue);
+
+ const heightValue = getAttribute(document, "height");
+ if (heightValue && !isNaN(parseInt(heightValue)))
+ _height = parseInt(heightValue);
+ }
+ const convertedUrl = convertUrlToEmbedUrl(_src);
+ if (!!convertedUrl) _src = convertedUrl;
+ onClose({
+ height: _height,
+ width: _width,
+ src: _src,
+ });
+ }}
+ >
+ {title}
+ </Button>
</Flex>
</Popup>
);
diff --git a/packages/editor/src/toolbar/popups/table-popup.tsx b/packages/editor/src/toolbar/popups/table-popup.tsx
index af4c1f6ae..caf54db03 100644
--- a/packages/editor/src/toolbar/popups/table-popup.tsx
+++ b/packages/editor/src/toolbar/popups/table-popup.tsx
@@ -4,6 +4,8 @@ import { Popup } from "../components/popup";
import { Input } from "@rebass/forms";
import { Icon } from "../components/icon";
import { Icons } from "../icons";
+import { useIsMobile } from "../stores/toolbar-store";
+import { InlineInput } from "../../components/inline-input";
const MAX_COLUMNS = 20;
const MAX_ROWS = 20;
@@ -15,11 +17,13 @@ type TableSize = { columns: number; rows: number };
export type TablePopupProps = {
onInsertTable: (size: TableSize) => void;
- cellSize?: number;
- autoExpand?: boolean;
};
export function TablePopup(props: TablePopupProps) {
- const { onInsertTable, cellSize, autoExpand } = props;
+ const isMobile = useIsMobile();
+ const autoExpand = !isMobile;
+ const cellSize = isMobile ? 30 : 15;
+
+ const { onInsertTable } = props;
const [cellLocation, setCellLocation] = useState<CellLocation>({
column: 0,
row: 0,
@@ -52,106 +56,115 @@ export function TablePopup(props: TablePopupProps) {
}, [cellLocation, autoExpand]);
return (
- <Popup
- title="Insert table"
- action={{
- icon: "check",
- onClick: () => {
- onInsertTable({
- columns: cellLocation.column,
- rows: cellLocation.row,
- });
- },
- }}
- >
- <Flex sx={{ p: 1, flexDirection: "column", alignItems: "center" }}>
- <Box
- sx={{
- display: "grid",
- gridTemplateColumns: `repeat(${tableSize.columns}, minmax(${
- cellSize || 15
- }px, 1fr))`, // "1fr ".repeat(tableSize.columns),
- gap: "small",
- bg: "background",
- width: "100%",
+ <Flex sx={{ p: 1, flexDirection: "column", alignItems: "center" }}>
+ <Box
+ sx={{
+ display: "grid",
+ gridTemplateColumns: `repeat(${tableSize.columns}, minmax(${cellSize}px, 1fr))`, // "1fr ".repeat(tableSize.columns),
+ gap: "small",
+ bg: "background",
+ width: "100%",
+ }}
+ onTouchMove={(e) => {
+ const touch = e.touches.item(0);
+ const element = document.elementFromPoint(
+ touch.pageX,
+ touch.pageY
+ ) as HTMLElement;
+ if (!element) return;
+ const index = element.dataset.index;
+ if (!index) return;
+ setCellLocation(getCellLocation(parseInt(index), tableSize));
+ }}
+ >
+ {Array(tableSize.columns * tableSize.rows)
+ .fill(0)
+ .map((_, index) => (
+ <Box
+ data-index={index}
+ height={cellSize || 15}
+ sx={{
+ border: "1px solid var(--disabled)",
+ borderRadius: "small",
+ bg: isCellHighlighted(index, cellLocation, tableSize)
+ ? "disabled"
+ : "transparent",
+ }}
+ onTouchStart={() => {
+ setCellLocation(getCellLocation(index, tableSize));
+ }}
+ onMouseEnter={() => {
+ setCellLocation(getCellLocation(index, tableSize));
+ }}
+ onClick={() => {
+ onInsertTable({
+ columns: cellLocation.column,
+ rows: cellLocation.row,
+ });
+ }}
+ />
+ ))}
+ </Box>
+ <Flex
+ sx={{
+ display: ["flex", "none", "none"],
+ my: 1,
+ alignItems: "center",
+ justifyContent: "center",
+ }}
+ >
+ <InlineInput
+ containerProps={{ sx: { mr: 1 } }}
+ label="columns"
+ placeholder={`${cellLocation.column} columns`}
+ type="number"
+ value={cellLocation.column}
+ onChange={(e) => {
+ setCellLocation((l) => ({
+ ...l,
+ column: e.target.valueAsNumber || 0,
+ }));
}}
- onTouchMove={(e) => {
- const touch = e.touches.item(0);
- const element = document.elementFromPoint(
- touch.pageX,
- touch.pageY
- ) as HTMLElement;
- if (!element) return;
- const index = element.dataset.index;
- if (!index) return;
- setCellLocation(getCellLocation(parseInt(index), tableSize));
+ />
+ <InlineInput
+ label="rows"
+ placeholder={`${cellLocation.row} rows`}
+ type="number"
+ value={cellLocation.row}
+ onChange={(e) => {
+ setCellLocation((l) => ({
+ ...l,
+ row: e.target.valueAsNumber || 0,
+ }));
}}
- >
- {Array(tableSize.columns * tableSize.rows)
- .fill(0)
- .map((_, index) => (
- <Box
- data-index={index}
- height={cellSize || 15}
- sx={{
- border: "1px solid var(--disabled)",
- borderRadius: "small",
- bg: isCellHighlighted(index, cellLocation, tableSize)
- ? "disabled"
- : "transparent",
- }}
- onTouchStart={() => {
- setCellLocation(getCellLocation(index, tableSize));
- }}
- onMouseEnter={() => {
- setCellLocation(getCellLocation(index, tableSize));
- }}
- onClick={() => {
- onInsertTable({
- columns: cellLocation.column,
- rows: cellLocation.row,
- });
- }}
- />
- ))}
- </Box>
- <Flex
- sx={{
- display: ["flex", "none"],
- my: 1,
- alignItems: "center",
- justifyContent: "center",
- }}
- >
- <Input
- placeholder={`${cellLocation.column} columns`}
- sx={{ mr: 1 }}
- type="number"
- value={cellLocation.column}
- onChange={(e) => {
- setCellLocation((l) => ({
- ...l,
- column: e.target.valueAsNumber || 0,
- }));
- }}
- />
- <Input
- placeholder={`${cellLocation.row} rows`}
- type="number"
- value={cellLocation.row}
- onChange={(e) => {
- setCellLocation((l) => ({
- ...l,
- row: e.target.valueAsNumber || 0,
- }));
- }}
- />
- </Flex>
- <Text variant={"body"} sx={{ mt: 1, display: ["none", "block"] }}>
- {cellLocation.column}x{cellLocation.row}
- </Text>
+ />
</Flex>
- </Popup>
+ <Text
+ variant={"body"}
+ sx={{ mt: 1, display: ["none", "block", "block"] }}
+ >
+ {cellLocation.column} x {cellLocation.row}
+ </Text>
+ <Button
+ variant={"primary"}
+ sx={{
+ display: ["block", "none", "none"],
+ alignSelf: ["stretch", "end", "end"],
+ py: 2,
+ }}
+ onClick={() =>
+ onInsertTable({
+ columns: cellLocation.column,
+ rows: cellLocation.row,
+ })
+ }
+ disabled={!cellLocation.column || !cellLocation.row}
+ >
+ {!cellLocation.column || !cellLocation.row
+ ? "Please set a table size"
+ : `Insert a ${cellLocation.column} x ${cellLocation.row} table`}
+ </Button>
+ </Flex>
);
}
diff --git a/packages/editor/src/toolbar/stores/toolbar-store.ts b/packages/editor/src/toolbar/stores/toolbar-store.ts
index d6aa1f094..1328db36e 100644
--- a/packages/editor/src/toolbar/stores/toolbar-store.ts
+++ b/packages/editor/src/toolbar/stores/toolbar-store.ts
@@ -1,16 +1,24 @@
+import { Editor } from "@tiptap/core";
import create from "zustand";
export type ToolbarLocation = "top" | "bottom";
+export type PopupRef = { id: string; group: string };
interface ToolbarState {
isMobile: boolean;
+ openedPopups: Record<string, PopupRef | false>;
setIsMobile: (isMobile: boolean) => void;
toolbarLocation: ToolbarLocation;
setToolbarLocation: (location: ToolbarLocation) => void;
+ isPopupOpen: (popupId: string) => boolean;
+ openPopup: (ref: PopupRef) => void;
+ closePopup: (popupId: string) => void;
+ closePopupGroup: (groupId: string, excluded: string[]) => void;
}
-export const useToolbarStore = create<ToolbarState>((set) => ({
+export const useToolbarStore = create<ToolbarState>((set, get) => ({
isMobile: false,
+ openedPopups: {},
setIsMobile: (isMobile) =>
set((state) => {
state.isMobile = isMobile;
@@ -20,6 +28,30 @@ export const useToolbarStore = create<ToolbarState>((set) => ({
set((state) => {
state.toolbarLocation = location;
}),
+ closePopup: (id) =>
+ set((state) => {
+ state.openedPopups = {
+ ...state.openedPopups,
+ [id]: false,
+ };
+ }),
+ isPopupOpen: (id) => !!get().openedPopups[id],
+ openPopup: (ref) =>
+ set((state) => {
+ state.openedPopups = {
+ ...state.openedPopups,
+ [ref.id]: ref,
+ };
+ }),
+ closePopupGroup: (group, excluded) =>
+ set((state) => {
+ for (const key in state.openedPopups) {
+ const ref = state.openedPopups[key];
+ if (ref && ref.group === group && !excluded.includes(ref.id)) {
+ state.openedPopups[key] = false;
+ }
+ }
+ }),
}));
export function useToolbarLocation() {
diff --git a/packages/editor/src/toolbar/tool-definitions.ts b/packages/editor/src/toolbar/tool-definitions.ts
index f09c592b4..83dc739ea 100644
--- a/packages/editor/src/toolbar/tool-definitions.ts
+++ b/packages/editor/src/toolbar/tool-definitions.ts
@@ -94,6 +94,112 @@ const tools: Record<ToolId, ToolDefinition> = {
icon: "textColor",
title: "Text color",
},
+
+ tableSettings: {
+ icon: "tableSettings",
+ title: "Table settings",
+ conditional: true,
+ },
+ columnProperties: {
+ icon: "columnProperties",
+ title: "Column properties",
+ conditional: true,
+ },
+ rowProperties: {
+ icon: "rowProperties",
+ title: "Row properties",
+ conditional: true,
+ },
+ cellProperties: {
+ icon: "cellProperties",
+ title: "Cell properties",
+ conditional: true,
+ },
+ insertColumnLeft: {
+ icon: "insertColumnLeft",
+ title: "Insert column left",
+ conditional: true,
+ },
+ insertColumnRight: {
+ icon: "insertColumnRight",
+ title: "Insert column right",
+ conditional: true,
+ },
+ moveColumnLeft: {
+ icon: "moveColumnLeft",
+ title: "Move column left",
+ conditional: true,
+ },
+ moveColumnRight: {
+ icon: "moveColumnLeft",
+ title: "Move column right",
+ conditional: true,
+ },
+ deleteColumn: {
+ icon: "deleteColumn",
+ title: "Delete column",
+ conditional: true,
+ },
+ splitCells: {
+ icon: "splitCells",
+ title: "Split cells",
+ conditional: true,
+ },
+ mergeCells: {
+ icon: "mergeCells",
+ title: "Merge cells",
+ conditional: true,
+ },
+ insertRowAbove: {
+ icon: "insertRowAbove",
+ title: "Insert row above",
+ conditional: true,
+ },
+ insertRowBelow: {
+ icon: "insertRowBelow",
+ title: "Insert row below",
+ conditional: true,
+ },
+ moveRowUp: {
+ icon: "moveRowUp",
+ title: "Move row up",
+ conditional: true,
+ },
+ moveRowDown: {
+ icon: "moveRowDown",
+ title: "Move row down",
+ conditional: true,
+ },
+ deleteRow: {
+ icon: "deleteRow",
+ title: "Delete row",
+ conditional: true,
+ },
+ deleteTable: {
+ icon: "deleteTable",
+ title: "Delete table",
+ conditional: true,
+ },
+ cellBackgroundColor: {
+ icon: "backgroundColor",
+ title: "Cell background color",
+ conditional: true,
+ },
+ cellBorderColor: {
+ icon: "cellBorderColor",
+ title: "Cell border color",
+ conditional: true,
+ },
+ cellTextColor: {
+ icon: "textColor",
+ title: "Cell text color",
+ conditional: true,
+ },
+ cellBorderWidth: {
+ icon: "none",
+ title: "Cell border width",
+ conditional: true,
+ },
};
export function getToolDefinition(id: ToolId) {
diff --git a/packages/editor/src/toolbar/toolbar.tsx b/packages/editor/src/toolbar/toolbar.tsx
index 4c7ebe5ef..2a88f4af6 100644
--- a/packages/editor/src/toolbar/toolbar.tsx
+++ b/packages/editor/src/toolbar/toolbar.tsx
@@ -2,22 +2,27 @@ import { Theme, useTheme } from "@notesnook/theme";
import { ThemeConfig } from "@notesnook/theme/dist/theme/types";
import { Editor } from "@tiptap/core";
import { Flex, FlexProps } from "rebass";
-import { findToolById, ToolId } from "./tools";
+import { findTool, ToolId } from "./tools";
import { ThemeProvider } from "emotion-theming";
import { EditorFloatingMenus } from "./floating-menus";
import { getToolDefinition } from "./tool-definitions";
import { Dropdown } from "./components/dropdown";
import { ToolButton } from "./components/tool-button";
import { useContext, useEffect, useRef, useState } from "react";
-import { MenuPresenter } from "../components/menu";
+// import { MenuPresenter } from "../components/menu";
import { Popup } from "./components/popup";
-import { ToolbarContext, useToolbarContext } from "./hooks/useToolbarContext";
import {
ToolbarLocation,
useToolbarLocation,
useToolbarStore,
} from "./stores/toolbar-store";
-
+import { getToolbarElement } from "./utils/dom";
+import { ToolbarDefinition, ToolProps } from "./types";
+import { ToolbarGroup } from "./components/toolbar-group";
+import {
+ EditorContext,
+ PopupRenderer,
+} from "../components/popup-presenter/popuprenderer";
// type Colors = {
// text: string;
// background: string;
@@ -27,9 +32,6 @@ import {
// border: string;
// };
-type ToolbarGroupDefinition = (ToolId | ToolId[])[];
-type ToolbarDefinition = ToolbarGroupDefinition[];
-
type ToolbarProps = {
theme: Theme;
editor: Editor | null;
@@ -38,8 +40,10 @@ type ToolbarProps = {
};
export function Toolbar(props: ToolbarProps) {
const { editor, theme, location, isMobile } = props;
- const [currentPopup, setCurrentPopup] = useState<string | undefined>();
- const { setIsMobile, setToolbarLocation } = useToolbarStore();
+ const setIsMobile = useToolbarStore((store) => store.setIsMobile);
+ const setToolbarLocation = useToolbarStore(
+ (store) => store.setToolbarLocation
+ );
useEffect(() => {
setIsMobile(isMobile || false);
@@ -47,7 +51,7 @@ export function Toolbar(props: ToolbarProps) {
}, [isMobile, location]);
const tools: ToolbarDefinition = [
- ["insertBlock"],
+ ["insertBlock", "tableSettings"],
[
"bold",
"italic",
@@ -72,117 +76,32 @@ export function Toolbar(props: ToolbarProps) {
if (!editor) return null;
return (
<ThemeProvider theme={theme}>
- <ToolbarContext.Provider
- value={{
- setCurrentPopup,
- currentPopup,
- }}
- >
- <Flex
- className="editor-toolbar"
- sx={{ flexWrap: ["nowrap", "wrap"], overflowX: ["auto", "hidden"] }}
- >
- {tools.map((tools) => {
- return (
- <ToolbarGroup
- tools={tools}
- editor={editor}
- sx={{
- flexShrink: 0,
- pr: 2,
- mr: 2,
- borderRight: "1px solid var(--border)",
- ":last-of-type": { mr: 0, pr: 0, borderRight: "none" },
- }}
- />
- );
- })}
- </Flex>
- </ToolbarContext.Provider>
- <EditorFloatingMenus editor={editor} />
+ <EditorContext.Provider value={editor}>
+ <PopupRenderer editor={editor}>
+ <Flex
+ className="editor-toolbar"
+ sx={{ flexWrap: ["nowrap", "wrap"], overflowX: ["auto", "hidden"] }}
+ >
+ {tools.map((tools) => {
+ return (
+ <ToolbarGroup
+ key={tools.join("")}
+ tools={tools}
+ editor={editor}
+ sx={{
+ flexShrink: 0,
+ pr: 2,
+ mr: 2,
+ borderRight: "1px solid var(--border)",
+ ":last-of-type": { mr: 0, pr: 0, borderRight: "none" },
+ }}
+ />
+ );
+ })}
+ </Flex>
+ <EditorFloatingMenus editor={editor} />
+ </PopupRenderer>
+ </EditorContext.Provider>
</ThemeProvider>
);
}
-
-type ToolbarGroupProps = FlexProps & {
- tools: ToolbarGroupDefinition;
- editor: Editor;
-};
-function ToolbarGroup(props: ToolbarGroupProps) {
- const { tools, editor, ...flexProps } = props;
-
- return (
- <Flex className="toolbar-group" {...flexProps}>
- {tools.map((toolId) => {
- if (Array.isArray(toolId)) {
- return (
- <MoreTools
- popupId={toolId.join("")}
- tools={toolId}
- editor={editor}
- />
- );
- } else {
- const Component = findToolById(toolId);
- const toolDefinition = getToolDefinition(toolId);
- return <Component editor={editor} {...toolDefinition} />;
- }
- })}
- </Flex>
- );
-}
-
-type MoreToolsProps = {
- popupId: string;
- tools: ToolId[];
- editor: Editor;
-};
-function MoreTools(props: MoreToolsProps) {
- const { popupId } = props;
- const { currentPopup, setCurrentPopup } = useToolbarContext();
- const toolbarLocation = useToolbarLocation();
-
- const buttonRef = useRef<HTMLButtonElement | null>();
-
- const show = popupId === currentPopup;
- const setShow = (state: boolean) =>
- setCurrentPopup?.(state ? popupId : undefined);
-
- return (
- <>
- <ToolButton
- icon="more"
- title="More"
- toggled={show}
- buttonRef={buttonRef}
- onMouseDown={(e) => e.preventDefault()}
- onClick={() => setShow(!show)}
- />
- <MenuPresenter
- isOpen={show}
- onClose={() => setShow(false)}
- items={[]}
- options={{
- type: "autocomplete",
- position: {
- isTargetAbsolute: true,
- target: buttonRef.current || "mouse",
- align: "center",
- location: toolbarLocation === "bottom" ? "top" : "below",
- yOffset: 5,
- },
- }}
- >
- <Popup>
- <ToolbarGroup
- tools={props.tools}
- editor={props.editor}
- sx={{
- p: 1,
- }}
- />
- </Popup>
- </MenuPresenter>
- </>
- );
-}
diff --git a/packages/editor/src/toolbar/tools/block.tsx b/packages/editor/src/toolbar/tools/block.tsx
index 1e86313bb..a8a00b072 100644
--- a/packages/editor/src/toolbar/tools/block.tsx
+++ b/packages/editor/src/toolbar/tools/block.tsx
@@ -3,11 +3,7 @@ import { Editor } from "@tiptap/core";
import { ToolButton } from "../components/tool-button";
import { ToolId } from ".";
import { IconNames, Icons } from "../icons";
-import {
- ActionSheetPresenter,
- MenuPresenter,
-} from "../../components/menu/menu";
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { Dropdown } from "../components/dropdown";
import { Icon } from "../components/icon";
import { Box, Button, Flex, Text } from "rebass";
@@ -15,13 +11,34 @@ import { Popup } from "../components/popup";
import { EmbedPopup } from "../popups/embed-popup";
import { TablePopup } from "../popups/table-popup";
import { MenuItem } from "../../components/menu/types";
-import { useToolbarLocation } from "../stores/toolbar-store";
-import { DesktopOnly, MobileOnly } from "../../components/responsive";
+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 { showPopup } from "../../components/popup-presenter";
export function InsertBlock(props: ToolProps) {
const buttonRef = useRef<HTMLButtonElement | null>();
const [isOpen, setIsOpen] = useState(false);
const toolbarLocation = useToolbarLocation();
+ const isMobile = useIsMobile();
+
+ const menuItems = useMemo(() => {
+ return [
+ tasklist(editor),
+ horizontalRule(editor),
+ codeblock(editor),
+ blockquote(editor),
+ image(editor),
+ attachment(editor),
+ isMobile ? embedMobile(editor) : embedDesktop(editor),
+ table(editor),
+ ];
+ }, [isMobile]);
return (
<>
@@ -45,54 +62,27 @@ export function InsertBlock(props: ToolProps) {
<Icon path={Icons.plus} size={18} color={"primary"} />
</Button>
- <DesktopOnly>
- <MenuPresenter
- options={{
- type: "menu",
- position: {
- target: buttonRef.current || undefined,
- isTargetAbsolute: true,
- location: toolbarLocation === "bottom" ? "top" : "below",
- yOffset: 5,
- },
- }}
- isOpen={isOpen}
- items={[
- tasklist(editor),
- horizontalRule(editor),
- codeblock(editor),
- blockquote(editor),
- image(editor),
- attachment(editor),
- embed(editor),
- table(editor),
- ]}
- onClose={() => setIsOpen(false)}
- />
- </DesktopOnly>
- <MobileOnly>
- <ActionSheetPresenter
- isOpen={isOpen}
- items={[
- tasklist(editor),
- horizontalRule(editor),
- codeblock(editor),
- blockquote(editor),
- imageActionSheet(editor),
- attachment(editor),
- embedActionSheet(editor),
- tableActionSheet(editor),
- ]}
- onClose={() => setIsOpen(false)}
- />
- </MobileOnly>
+ <ResponsivePresenter
+ desktop="menu"
+ mobile="sheet"
+ title="Choose a block to insert"
+ isOpen={isOpen}
+ items={menuItems}
+ onClose={() => setIsOpen(false)}
+ position={{
+ target: buttonRef.current || undefined,
+ isTargetAbsolute: true,
+ location: toolbarLocation === "bottom" ? "top" : "below",
+ yOffset: 5,
+ }}
+ />
</>
);
}
const horizontalRule = (editor: Editor | null): MenuItem => ({
key: "hr",
- type: "menuitem",
+ type: "button",
title: "Horizontal rule",
icon: "horizontalRule",
isChecked: editor?.isActive("horizontalRule"),
@@ -101,7 +91,7 @@ const horizontalRule = (editor: Editor | null): MenuItem => ({
const codeblock = (editor: Editor | null): MenuItem => ({
key: "codeblock",
- type: "menuitem",
+ type: "button",
title: "Code block",
icon: "codeblock",
isChecked: editor?.isActive("codeBlock"),
@@ -110,7 +100,7 @@ const codeblock = (editor: Editor | null): MenuItem => ({
const blockquote = (editor: Editor | null): MenuItem => ({
key: "blockquote",
- type: "menuitem",
+ type: "button",
title: "Quote",
icon: "blockquote",
isChecked: editor?.isActive("blockQuote"),
@@ -119,180 +109,115 @@ const blockquote = (editor: Editor | null): MenuItem => ({
const image = (editor: Editor | null): MenuItem => ({
key: "image",
- type: "menuitem",
+ type: "button",
title: "Image",
icon: "image",
- items: [
- {
- key: "upload-from-disk",
- type: "menuitem",
- title: "Upload from disk",
- icon: "upload",
- onClick: () => {},
- },
- {
- key: "upload-from-url",
- type: "menuitem",
- title: "Attach from URL",
- icon: "link",
- onClick: () => {},
- },
- ],
-});
-
-const imageActionSheet = (editor: Editor | null): MenuItem => ({
- key: "image",
- type: "menuitem",
- title: "Image",
- icon: "image",
- items: [
- {
- key: "imageOptions",
- type: "menuitem",
- component: function ({ onClick }) {
- const [isOpen, setIsOpen] = useState(true);
- return (
- <ActionSheetPresenter
- isOpen={isOpen}
- onClose={() => setIsOpen(false)}
- items={[
- {
- key: "upload-from-disk",
- type: "menuitem",
- title: "Upload from disk",
- icon: "upload",
- onClick: () =>
- editor?.chain().focus().openAttachmentPicker("image").run(),
- },
- {
- key: "upload-from-url",
- type: "menuitem",
- title: "Attach from URL",
- icon: "link",
- onClick: () => {},
- },
- ]}
- />
- );
+ menu: {
+ title: "Insert an image",
+ items: [
+ {
+ key: "upload-from-disk",
+ type: "button",
+ title: "Upload from disk",
+ icon: "upload",
+ onClick: () => {},
},
- },
- ],
-});
-
-const embed = (editor: Editor | null): MenuItem => ({
- key: "embed",
- type: "menuitem",
- title: "Embed",
- icon: "embed",
+ {
+ key: "upload-from-url",
+ type: "button",
+ title: "Attach from URL",
+ icon: "link",
+ onClick: () => {},
+ },
+ ],
+ },
});
const table = (editor: Editor | null): MenuItem => ({
key: "table",
- type: "menuitem",
+ type: "button",
title: "Table",
icon: "table",
- items: [
- {
- key: "table-size-selector",
- type: "menuitem",
- component: (props) => (
- <TablePopup
- onInsertTable={(size) => {
- editor
- ?.chain()
- .focus()
- .insertTable({
- rows: size.rows,
- cols: size.columns,
- })
- .run();
- props.onClick?.();
- }}
- />
- ),
- },
- ],
+ menu: {
+ title: "Insert a table",
+ items: [
+ {
+ key: "table-size-selector",
+ type: "popup",
+ component: (props) => (
+ <TablePopup
+ onInsertTable={(size) => {
+ editor
+ ?.chain()
+ .focus()
+ .insertTable({
+ rows: size.rows,
+ cols: size.columns,
+ })
+ .run();
+ props.onClick?.();
+ }}
+ />
+ ),
+ },
+ ],
+ },
});
-const embedActionSheet = (editor: Editor | null): MenuItem => ({
+const embedMobile = (editor: Editor | null): MenuItem => ({
key: "embed",
- type: "menuitem",
+ type: "button",
title: "Embed",
icon: "embed",
- items: [
- {
- key: "table-size-selector",
- type: "menuitem",
- component: function ({ onClick }) {
- const [isOpen, setIsOpen] = useState(true);
- return (
- <ActionSheetPresenter
- isOpen={isOpen}
- onClose={() => setIsOpen(false)}
- items={[]}
- >
+ menu: {
+ title: "Insert an embed",
+ items: [
+ {
+ key: "embed-popup",
+ type: "popup",
+ component: function ({ onClick }) {
+ return (
<EmbedPopup
title="Insert embed"
- icon="check"
onClose={(embed) => {
+ if (!embed) return onClick?.();
editor?.chain().insertEmbed(embed).run();
- setIsOpen(false);
onClick?.();
}}
- // embed={props}
- // onSourceChanged={(src) => {}}
- // onSizeChanged={(size) => editor.commands.setEmbedSize(size)}
/>
- </ActionSheetPresenter>
- );
+ );
+ },
},
- },
- ],
+ ],
+ },
});
-const tableActionSheet = (editor: Editor | null): MenuItem => ({
- key: "table",
- type: "menuitem",
- title: "Table",
- icon: "table",
- items: [
- {
- key: "table-size-selector",
- type: "menuitem",
- component: function ({ onClick }) {
- const [isOpen, setIsOpen] = useState(true);
- return (
- <ActionSheetPresenter
- isOpen={isOpen}
- onClose={() => setIsOpen(false)}
- items={[]}
- >
- <TablePopup
- cellSize={30}
- autoExpand={false}
- onInsertTable={(size) => {
- editor
- ?.chain()
- .focus()
- .insertTable({
- rows: size.rows,
- cols: size.columns,
- })
- .run();
- setIsOpen(false);
- onClick?.();
- }}
- />
- </ActionSheetPresenter>
- );
- },
- },
- ],
+const embedDesktop = (editor: Editor | null): MenuItem => ({
+ key: "embed",
+ type: "button",
+ title: "Embed",
+ icon: "embed",
+ onClick: () => {
+ if (!editor) return;
+ showPopup({
+ theme: editor.storage.theme,
+ popup: (hide) => (
+ <EmbedPopup
+ title="Insert embed"
+ onClose={(embed) => {
+ if (!embed) return hide();
+ editor?.chain().insertEmbed(embed).run();
+ hide();
+ }}
+ />
+ ),
+ });
+ },
});
const attachment = (editor: Editor | null): MenuItem => ({
key: "attachment",
- type: "menuitem",
+ type: "button",
title: "Attachment",
icon: "attachment",
isChecked: editor?.isActive("attachment"),
@@ -301,7 +226,7 @@ const attachment = (editor: Editor | null): MenuItem => ({
const tasklist = (editor: Editor | null): MenuItem => ({
key: "tasklist",
- type: "menuitem",
+ type: "button",
title: "Task list",
icon: "checkbox",
isChecked: editor?.isActive("taskList"),
diff --git a/packages/editor/src/toolbar/tools/colors.tsx b/packages/editor/src/toolbar/tools/colors.tsx
index 261f5b180..3225f9575 100644
--- a/packages/editor/src/toolbar/tools/colors.tsx
+++ b/packages/editor/src/toolbar/tools/colors.tsx
@@ -6,43 +6,43 @@ import { Icon } from "../components/icon";
import { Icons } from "../icons";
import { ToolButton } from "../components/tool-button";
import { SplitButton } from "../components/split-button";
-import { MenuPresenter } from "../../components/menu/menu";
-import { useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import tinycolor from "tinycolor2";
import { HexColorPicker, HexColorInput } from "react-colorful";
+import { getToolbarElement } from "../utils/dom";
+import { useToolbarLocation } from "../stores/toolbar-store";
+import { ColorPicker } from "../popups/color-picker";
+import { useEditorContext } from "../../components/popup-presenter/popuprenderer";
+import { PopupWrapper } from "../../components/popup-presenter";
-export const DEFAULT_COLORS = [
- "#e91e63",
- "#9c27b0",
- "#673ab7",
- "#3f51b5",
- "#2196f3",
- "#03a9f4",
- "#00bcd4",
- "#009688",
- "#4caf50",
- "#8bc34a",
- "#cddc39",
- "#ffeb3b",
- "#ffc107",
- "#f44336",
-];
type ColorToolProps = ToolProps & {
onColorChange: (editor: Editor, color?: string) => void;
isActive: (editor: Editor) => boolean;
getActiveColor: (editor: Editor) => string;
+ title: string;
};
-function ColorTool(props: ColorToolProps) {
- const { editor, onColorChange, isActive, getActiveColor, ...toolProps } =
+export function ColorTool(props: ColorToolProps) {
+ const { onColorChange, isActive, getActiveColor, title, ...toolProps } =
props;
+ const editor = useEditorContext();
const activeColor = getActiveColor(editor);
const _isActive = isActive(editor);
const tColor = tinycolor(activeColor);
+ const toolbarLocation = useToolbarLocation();
+ const isBottom = toolbarLocation === "bottom";
+ const [isOpen, setIsOpen] = useState<boolean>(false);
+ // const { hide, isOpen, show } = usePopup({
+ // id: title,
+ // group: "color",
+ // theme: editor?.storage.theme,
+ // blocking: false,
+ // focusOnRender: false,
+ // });
+ // console.log("Updating color", editor);
return (
<SplitButton
{...toolProps}
- toggled={false}
iconColor={_isActive && tColor.isDark() ? "static" : "icon"}
sx={{
mr: 0,
@@ -51,32 +51,32 @@ function ColorTool(props: ColorToolProps) {
bg: _isActive ? tColor.darken(5).toRgbString() : "transparent",
},
}}
- popupPresenterProps={{
- mobile: "sheet",
- desktop: "menu",
- }}
+ onOpen={() => setIsOpen((s) => !s)}
+ toggled={isOpen}
>
- <Flex
- sx={{
- bg: "background",
- width: ["auto", "auto", 250],
- flexDirection: "column",
- p: [3, 3, 2],
- boxShadow: ["none", "none", "menu"],
- borderRadius: ["none", "none", "dialog"],
- ".react-colorful": {
- width: "auto",
- height: 150,
- },
+ <PopupWrapper
+ isOpen={isOpen}
+ id={title}
+ group={"color"}
+ position={{
+ isTargetAbsolute: true,
+ target: getToolbarElement(),
+ align: isBottom ? "center" : "end",
+ location: isBottom ? "top" : "below",
+ yOffset: 10,
}}
- >
- <ColorPicker
- colors={DEFAULT_COLORS}
- color={activeColor}
- onClear={() => onColorChange(editor)}
- onChange={(color) => onColorChange(editor, color)}
- />
- </Flex>
+ focusOnRender={false}
+ blocking={false}
+ renderPopup={(close) => (
+ <ColorPicker
+ color={activeColor}
+ onClear={() => onColorChange(editor)}
+ onChange={(color) => onColorChange(editor, color)}
+ onClose={close}
+ title={title}
+ />
+ )}
+ />
</SplitButton>
);
}
@@ -87,6 +87,7 @@ export function Highlight(props: ToolProps) {
{...props}
isActive={(editor) => editor.isActive("highlight", { color: /\W+/gm })}
getActiveColor={(editor) => editor.getAttributes("highlight").color}
+ title={"Background color"}
onColorChange={(editor, color) =>
color
? editor.chain().focus().toggleHighlight({ color }).run()
@@ -102,6 +103,7 @@ export function TextColor(props: ToolProps) {
{...props}
isActive={(editor) => editor.isActive("textStyle", { color: /\W+/gm })}
getActiveColor={(editor) => editor.getAttributes("textStyle").color}
+ title="Text color"
onColorChange={(editor, color) =>
color
? editor.chain().focus().setColor(color).run()
@@ -110,117 +112,3 @@ export function TextColor(props: ToolProps) {
/>
);
}
-
-type ColorPickerProps = {
- colors: string[];
- color: string;
- onClear: () => void;
- onChange: (color: string) => void;
-};
-const PALETTE_SIZE = [35, 35, 25];
-export function ColorPicker(props: ColorPickerProps) {
- const { colors, color, onClear, onChange } = props;
- const [isPickerOpen, setIsPickerOpen] = useState(false);
- const tColor = tinycolor(color || colors[0]);
- const [currentColor, setCurrentColor] = useState<string>(
- tColor.toHexString()
- );
-
- return (
- <>
- {isPickerOpen && (
- <HexColorPicker color={currentColor} onChange={onChange} />
- )}
- <Flex
- sx={{
- alignItems: "center",
- justifyContent: "center",
- mt: isPickerOpen ? 2 : 0,
- }}
- >
- <Button
- variant={"secondary"}
- sx={{
- flexShrink: 0,
- bg: currentColor,
- width: PALETTE_SIZE,
- height: PALETTE_SIZE,
- mr: 2,
- borderRadius: 50,
- boxShadow: "menu",
- p: 0,
- }}
- onClick={() => setIsPickerOpen((s) => !s)}
- >
- <Icon
- path={Icons.palette}
- color={tColor.isDark() ? "static" : "icon"}
- size={18}
- />
- </Button>
- <Input
- variant={"clean"}
- placeholder="#000000"
- spellCheck={false}
- sx={{
- p: 0,
- borderRadius: 0,
- fontSize: ["title", "title", "body"],
- color: "fontTertiary",
- textAlign: "left",
- letterSpacing: 1.5,
- }}
- value={currentColor.toUpperCase()}
- maxLength={7}
- onChange={(e) => {
- const { value } = e.target;
- if (!value) return;
- setCurrentColor(value);
- }}
- />
- <Button
- variant={"icon"}
- sx={{
- flexShrink: 0,
- bg: "transparent",
- width: PALETTE_SIZE,
- height: PALETTE_SIZE,
- mr: 2,
- borderRadius: 50,
- p: 0,
- }}
- onClick={onClear}
- >
- <Icon path={Icons.colorClear} color="text" size={15} />
- </Button>
- </Flex>
- <Flex
- sx={{
- borderTop: "1px solid var(--border)",
- mt: 2,
- pt: 4,
- flexWrap: "wrap",
- }}
- >
- {colors.map((color) => (
- <Button
- variant={"secondary"}
- sx={{
- bg: color,
- width: PALETTE_SIZE,
- height: PALETTE_SIZE,
- ml: [2, 2, 1],
- mb: [2, 2, 1],
- borderRadius: 50,
- boxShadow: "menu",
- }}
- onClick={() => {
- setCurrentColor(color);
- onChange(color);
- }}
- />
- ))}
- </Flex>
- </>
- );
-}
diff --git a/packages/editor/src/toolbar/tools/font.tsx b/packages/editor/src/toolbar/tools/font.tsx
index 2ffc8e543..fa1de27bd 100644
--- a/packages/editor/src/toolbar/tools/font.tsx
+++ b/packages/editor/src/toolbar/tools/font.tsx
@@ -1,12 +1,9 @@
import { ToolProps } from "../types";
import { Dropdown } from "../components/dropdown";
-import { ToolId } from ".";
import { MenuItem } from "../../components/menu/types";
import { Editor } from "@tiptap/core";
-import { Box, Button, Flex, Text } from "rebass";
-import { Slider } from "@rebass/forms";
-import { ToolButton } from "../components/tool-button";
import { useCallback } from "react";
+import { Counter } from "../components/counter";
const defaultFontSizes = [
8, 12, 14, 16, 18, 20, 24, 28, 32, 36, 42, 48, 60, 72, 100,
@@ -21,48 +18,21 @@ export function FontSize(props: ToolProps) {
}, [fontSizeAsNumber]);
return (
- <Flex
- sx={{
- alignItems: "center",
- mr: 1,
- ":last-of-type": {
- mr: 0,
- },
- }}
- >
- <ToolButton
- toggled={false}
- title="Decrease font size"
- icon="minus"
- variant={"small"}
- onClick={() => {
- editor.chain().focus().setFontSize(`${decreaseFontSize()}px`).run();
- }}
- />
- <Text
- variant={"body"}
- sx={{ fontSize: "subBody", mx: 1, textAlign: "center" }}
- title="Reset font size"
- onClick={() => {
- editor.chain().focus().setFontSize(`16px`).run();
- }}
- >
- {fontSize}
- </Text>
- <ToolButton
- toggled={false}
- title="Increase font size"
- icon="plus"
- variant={"small"}
- onClick={() => {
- editor
- .chain()
- .focus()
- .setFontSize(`${fontSizeAsNumber + 1}px`)
- .run();
- }}
- />
- </Flex>
+ <Counter
+ title="font size"
+ onDecrease={() =>
+ editor.chain().focus().setFontSize(`${decreaseFontSize()}px`).run()
+ }
+ onIncrease={() =>
+ editor
+ .chain()
+ .focus()
+ .setFontSize(`${fontSizeAsNumber + 1}px`)
+ .run()
+ }
+ onReset={() => editor.chain().focus().setFontSize(`16px`).run()}
+ value={fontSize}
+ />
);
}
@@ -97,7 +67,7 @@ function toMenuItems(editor: Editor, currentFontFamily: string): MenuItem[] {
const value = fontFamilies[key as keyof typeof fontFamilies];
menuItems.push({
key,
- type: "menuitem",
+ type: "button",
title: key,
isChecked: key === currentFontFamily,
onClick: () => editor.chain().focus().setFontFamily(value).run(),
diff --git a/packages/editor/src/toolbar/tools/headings.tsx b/packages/editor/src/toolbar/tools/headings.tsx
index 458837fe3..3257fc9ab 100644
--- a/packages/editor/src/toolbar/tools/headings.tsx
+++ b/packages/editor/src/toolbar/tools/headings.tsx
@@ -25,7 +25,7 @@ export function Headings(props: ToolProps) {
function toMenuItems(editor: Editor, currentHeadingLevel?: number): MenuItem[] {
const menuItems: MenuItem[] = defaultLevels.map((level) => ({
- type: "menuitem",
+ type: "button",
key: `heading-${level}`,
title: `Heading ${level}`,
isChecked: level === currentHeadingLevel,
@@ -38,7 +38,7 @@ function toMenuItems(editor: Editor, currentHeadingLevel?: number): MenuItem[] {
}));
const paragraph: MenuItem = {
key: "paragraph",
- type: "menuitem",
+ type: "button",
title: "Paragraph",
isChecked: !currentHeadingLevel,
onClick: () => editor.chain().focus().setParagraph().run(),
diff --git a/packages/editor/src/toolbar/tools/index.ts b/packages/editor/src/toolbar/tools/index.ts
index 9aced6d22..2a19185df 100644
--- a/packages/editor/src/toolbar/tools/index.ts
+++ b/packages/editor/src/toolbar/tools/index.ts
@@ -14,44 +14,35 @@ import {
import { InsertBlock } from "./block";
import { FontSize, FontFamily } from "./font";
import { AlignCenter, AlignLeft, AlignRight, AlignJustify } from "./alignment";
-// import {
-// Blockquote,
-// CodeBlock,
-// HorizontalRule,
-// Image,
-// Table,
-// Embed,
-// } from "./block";
import { Headings } from "./headings";
import { NumberedList, BulletList } from "./lists";
import { LeftToRight, RightToLeft } from "./text-direction";
import { Highlight, TextColor } from "./colors";
+import {
+ TableSettings,
+ ColumnProperties,
+ RowProperties,
+ CellProperties,
+ InsertColumnLeft,
+ InsertColumnRight,
+ MoveColumnLeft,
+ MoveColumnRight,
+ DeleteColumn,
+ SplitCells,
+ MergeCells,
+ InsertRowAbove,
+ InsertRowBelow,
+ MoveRowUp,
+ MoveRowDown,
+ DeleteRow,
+ DeleteTable,
+ CellBackgroundColor,
+ CellBorderColor,
+ CellTextColor,
+ CellBorderWidth,
+} from "./table";
-// const tools = {
-// bold: new Bold(),
-// italic: new Italic(),
-// underline: new Underline(),
-// strikethrough: new Strikethrough(),
-// code: new Code(),
-// formatClear: new ClearFormatting(),
-
-// subscript: new Subscript(),
-// superscript: new Superscript(),
-
-// horizontalRule: new HorizontalRule(),
-// codeblock: new CodeBlock(),
-// blockquote: new Blockquote(),
-// headings: new Headings(),
-
-// checklist: new Checklist(),
-
-// link: new Link(),
-// image: new Image(),
-// attachment: new Attachment(),
-// table: new Table(),
-// embed: new Embed(),
-// };
-
+export type ToolId = keyof typeof tools;
const tools = {
bold: Bold,
italic: Italic,
@@ -76,9 +67,30 @@ const tools = {
rtl: RightToLeft,
textColor: TextColor,
highlight: Highlight,
+
+ tableSettings: TableSettings,
+ columnProperties: ColumnProperties,
+ rowProperties: RowProperties,
+ cellProperties: CellProperties,
+ insertColumnLeft: InsertColumnLeft,
+ insertColumnRight: InsertColumnRight,
+ moveColumnLeft: MoveColumnLeft,
+ moveColumnRight: MoveColumnRight,
+ deleteColumn: DeleteColumn,
+ splitCells: SplitCells,
+ mergeCells: MergeCells,
+ cellBackgroundColor: CellBackgroundColor,
+ cellBorderColor: CellBorderColor,
+ cellTextColor: CellTextColor,
+ cellBorderWidth: CellBorderWidth,
+ insertRowAbove: InsertRowAbove,
+ insertRowBelow: InsertRowBelow,
+ moveRowUp: MoveRowUp,
+ moveRowDown: MoveRowDown,
+ deleteRow: DeleteRow,
+ deleteTable: DeleteTable,
};
-export type ToolId = keyof typeof tools;
-export function findToolById(id: ToolId): React.FunctionComponent<ToolProps> {
+export function findTool(id: ToolId): React.FunctionComponent<ToolProps> {
return tools[id];
}
diff --git a/packages/editor/src/toolbar/tools/inline.tsx b/packages/editor/src/toolbar/tools/inline.tsx
index ef2a58ece..4a0f21110 100644
--- a/packages/editor/src/toolbar/tools/inline.tsx
+++ b/packages/editor/src/toolbar/tools/inline.tsx
@@ -1,9 +1,9 @@
import { ToolProps } from "../types";
import { Editor } from "@tiptap/core";
import { ToolButton } from "../components/tool-button";
-import { MenuPresenter, PopupPresenter } from "../../components/menu/menu";
-import { useRef, useState } from "react";
-import { Flex } from "rebass";
+import { useCallback, useRef, useState } from "react";
+import { ResponsivePresenter } from "../../components/responsive";
+import { Button, Flex } from "rebass";
import { Input } from "@rebass/forms";
import { Popup } from "../components/popup";
@@ -111,16 +111,31 @@ export function Link(props: ToolProps) {
const buttonRef = useRef<HTMLButtonElement>(null);
const targetRef = useRef<HTMLElement>();
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
+ .chain()
+ .focus()
+ .extendMarkRange("link")
+ .setLink({ href, target: "_blank" });
+ if (text) commandChain = commandChain.insertContent(text).focus();
+
+ commandChain.run();
+ setIsOpen(false);
+ }, []);
+
return (
<>
<ToolButton
id={icon}
- ref={buttonRef}
+ buttonRef={buttonRef}
title={title}
icon={icon}
onClick={() => {
@@ -143,63 +158,81 @@ export function Link(props: ToolProps) {
}}
toggled={isOpen || !!isEditing}
/>
- <PopupPresenter
+ <ResponsivePresenter
mobile="sheet"
desktop="menu"
- options={{
- type: "menu",
- position: {
- target: targetRef.current || buttonRef.current || undefined,
- isTargetAbsolute: true,
- location: "below",
- yOffset: 5,
- },
+ position={{
+ target: targetRef.current || buttonRef.current || undefined,
+ isTargetAbsolute: true,
+ location: "below",
+ align: "center",
+ yOffset: 5,
}}
+ title={isEditing ? "Edit link" : "Insert link"}
isOpen={isOpen}
items={[]}
onClose={() => {
editor.commands.focus();
setIsOpen(false);
}}
+ focusOnRender={false}
>
<Popup
title={isEditing ? "Edit link" : "Insert link"}
- action={{
- text: isEditing ? "Edit" : "Insert",
- onClick: () => {
- if (!href) return;
-
- let commandChain = editor
- .chain()
- .focus()
- .extendMarkRange("link")
- .setLink({ href, target: "_blank" });
- if (text) commandChain = commandChain.insertContent(text).focus();
-
- commandChain.run();
- setIsOpen(false);
- },
- }}
- // negativeButton={{ text: "Cancel", onClick: () => setIsOpen(false) }}
+ onClose={() => setIsOpen(false)}
>
- <Flex sx={{ p: 1, flexDirection: "column" }}>
- <Input
- type="text"
- placeholder="Link text"
- value={text}
- onChange={(e) => setText(e.target.value)}
- />
- <Input
- type="url"
- sx={{ mt: 1 }}
- autoFocus
- placeholder="https://example.com/"
- value={href}
- onChange={(e) => setHref(e.target.value)}
- />
- </Flex>
+ <LinkPopup
+ href={href}
+ text={text}
+ isEditing={isEditing}
+ onDone={({ href, text }) => {
+ onDone(href, text);
+ }}
+ />
</Popup>
- </PopupPresenter>
+ </ResponsivePresenter>
</>
);
}
+
+type LinkPopupProps = {
+ text?: string;
+ href?: string;
+ isEditing?: boolean;
+ onDone: (link: { text: string; href: string }) => void;
+};
+function LinkPopup(props: LinkPopupProps) {
+ const { text: _text, href: _href, isEditing = false, onDone } = props;
+ const [href, setHref] = useState<string>(_href || "");
+ const [text, setText] = useState<string>(_text || "");
+
+ return (
+ <Flex sx={{ p: 1, flexDirection: "column", width: ["auto", 250] }}>
+ <Input
+ type="text"
+ placeholder="Link text"
+ value={text}
+ onChange={(e) => setText(e.target.value)}
+ />
+ <Input
+ type="url"
+ sx={{ mt: 1 }}
+ autoFocus
+ placeholder="https://example.com/"
+ value={href}
+ onChange={(e) => setHref(e.target.value)}
+ />
+ <Button
+ variant={"primary"}
+ sx={{
+ alignSelf: ["stretch", "end", "end"],
+ my: 1,
+ mr: 1,
+ }}
+ onClick={() => onDone({ text, href })}
+ >
+ {isEditing ? "Save edits" : "Insert link"}
+ </Button>
+ </Flex>
+ );
+}
diff --git a/packages/editor/src/toolbar/tools/lists.tsx b/packages/editor/src/toolbar/tools/lists.tsx
index 6dfe6fcf6..1c28ab721 100644
--- a/packages/editor/src/toolbar/tools/lists.tsx
+++ b/packages/editor/src/toolbar/tools/lists.tsx
@@ -1,15 +1,12 @@
import { ToolProps } from "../types";
import { Editor } from "@tiptap/core";
-import { ToolId } from ".";
-import { Dropdown } from "../components/dropdown";
-import { MenuItem } from "../../components/menu/types";
-import { Box, Button, Flex, Text } from "rebass";
-import { Icon } from "../components/icon";
-import { IconNames, Icons } from "../icons";
-import { ToolButton } from "../components/tool-button";
-import { MenuPresenter } from "../../components/menu/menu";
+import { Box, Button, Flex } from "rebass";
+import { IconNames } from "../icons";
import { 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";
type ListSubType<TListStyleTypes> = {
items: string[];
@@ -31,40 +28,63 @@ function ListTool<TListStyleTypes extends string>(
) {
const { editor, options, ...toolProps } = props;
const isActive = editor.isActive(options.type);
+ const toolbarLocation = useToolbarLocation();
+ const isBottom = toolbarLocation === "bottom";
+ const [isOpen, setIsOpen] = useState(false);
+ const buttonRef = useRef<HTMLButtonElement>();
return (
<SplitButton
{...toolProps}
+ buttonRef={buttonRef}
onClick={() => options.onClick(editor)}
- toggled={isActive}
+ toggled={isActive || isOpen}
sx={{ mr: 0 }}
- popupPresenterProps={{
- items: options.subTypes.map((item) => ({
- key: item.type,
- tooltip: item.title,
- type: "menuitem",
- component: ({ onClick }) => (
- <Button variant={"menuitem"} onClick={onClick}>
- <ListThumbnail listStyleType={item.type} />
- </Button>
- ),
- onClick: () => {
- let chain = editor.chain().focus();
+ onOpen={() => setIsOpen((s) => !s)}
+ >
+ <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={() => (
+ <Box
+ sx={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", p: 1 }}
+ >
+ {options.subTypes.map((item) => (
+ <Button
+ key={item.title}
+ variant={"menuitem"}
+ sx={{ width: 80 }}
+ onClick={() => {
+ let chain = editor.chain().focus();
- if (!isActive) {
- if (options.type === "bulletList")
- chain = chain.toggleBulletList();
- else chain = chain.toggleOrderedList();
- }
+ if (!isActive) {
+ if (options.type === "bulletList")
+ chain = chain.toggleBulletList();
+ else chain = chain.toggleOrderedList();
+ }
- return chain
- .updateAttributes(options.type, { listType: item.type })
- .run();
- },
- })),
- sx: { display: "grid", gridTemplateColumns: "1fr 1fr 1fr", p: 1 },
- }}
- />
+ return chain
+ .updateAttributes(options.type, { listType: item.type })
+ .run();
+ }}
+ >
+ <ListThumbnail listStyleType={item.type} />
+ </Button>
+ ))}
+ </Box>
+ )}
+ />
+ </SplitButton>
);
}
@@ -129,8 +149,9 @@ function ListThumbnail(props: ListThumbnailProps) {
listStyleType,
}}
>
- {[0, 0, 0].map(() => (
+ {[0, 1, 2].map((i) => (
<Box
+ key={i.toString()}
as="li"
sx={{
display: "list-item",
diff --git a/packages/editor/src/toolbar/tools/table.tsx b/packages/editor/src/toolbar/tools/table.tsx
new file mode 100644
index 000000000..8e25c6264
--- /dev/null
+++ b/packages/editor/src/toolbar/tools/table.tsx
@@ -0,0 +1,375 @@
+import { ToolProps } from "../types";
+import { Editor } from "@tiptap/core";
+import { ToolButton } from "../components/tool-button";
+import { useCallback, useMemo, useRef, useState } from "react";
+import { Flex, Text } from "rebass";
+import { Input } from "@rebass/forms";
+import { Popup } from "../components/popup";
+import { ResponsivePresenter } from "../../components/responsive";
+import { MenuButton, MenuItem } from "../../components/menu/types";
+import {
+ moveColumnLeft as moveColumnLeftAction,
+ moveColumnRight as moveColumnRightAction,
+ moveRowDown as moveRowDownAction,
+ moveRowUp as moveRowUpAction,
+} from "../floatingmenus/table/actions";
+import { MoreTools } from "../components/more-tools";
+import { menuButtonToTool } from "./utils";
+import { getToolDefinition } from "../tool-definitions";
+import { CellProperties as CellPropertiesPopup } from "../popups/cell-properties";
+import { ColorTool } from "./colors";
+import { Counter } from "../components/counter";
+import { useToolbarLocation } from "../stores/toolbar-store";
+import { showPopup } from "../../components/popup-presenter";
+
+export function TableSettings(props: ToolProps) {
+ const { editor } = props;
+ const isBottom = useToolbarLocation() === "bottom";
+ if (!editor.isActive("table") || !isBottom) return null;
+ return (
+ <MoreTools
+ {...props}
+ popupId="tableSettings"
+ tools={[
+ "insertColumnLeft",
+ "insertColumnRight",
+ "insertRowAbove",
+ "insertRowBelow",
+ "cellProperties",
+ "columnProperties",
+ "rowProperties",
+ "deleteRow",
+ "deleteColumn",
+ "deleteTable",
+ ]}
+ />
+ );
+}
+
+export function RowProperties(props: ToolProps) {
+ const { editor } = props;
+ const [isMenuOpen, setIsMenuOpen] = useState(false);
+ const items = useMemo(
+ () => [
+ insertRowAbove(editor),
+ insertRowBelow(editor),
+ moveRowUp(editor),
+ moveRowDown(editor),
+ deleteRow(editor),
+ ],
+ []
+ );
+
+ return (
+ <>
+ <ToolButton
+ {...props}
+ toggled={isMenuOpen}
+ onClick={() => setIsMenuOpen(true)}
+ />
+ <ResponsivePresenter
+ title="Row properties"
+ mobile="sheet"
+ desktop="menu"
+ isOpen={isMenuOpen}
+ onClose={() => setIsMenuOpen(false)}
+ position={{}}
+ items={items}
+ />
+ </>
+ );
+}
+
+export function ColumnProperties(props: ToolProps) {
+ const { editor } = props;
+ const [isMenuOpen, setIsMenuOpen] = useState(false);
+
+ const items = useMemo(
+ () => [
+ insertColumnLeft(editor),
+ insertColumnRight(editor),
+ moveColumnLeft(editor),
+ moveColumnRight(editor),
+ deleteColumn(editor),
+ ],
+ []
+ );
+
+ return (
+ <>
+ <ToolButton
+ {...props}
+ toggled={isMenuOpen}
+ onClick={() => setIsMenuOpen(true)}
+ />
+ <ResponsivePresenter
+ title="Column properties"
+ mobile="sheet"
+ desktop="menu"
+ isOpen={isMenuOpen}
+ onClose={() => setIsMenuOpen(false)}
+ position={{}}
+ items={items}
+ />
+ </>
+ );
+}
+
+export function TableProperties(props: ToolProps) {
+ const { editor } = props;
+ const [isMenuOpen, setIsMenuOpen] = useState(false);
+
+ const items = useMemo<MenuItem[]>(
+ () => [
+ insertColumnLeft(editor),
+ insertColumnRight(editor),
+ moveColumnLeft(editor),
+ moveColumnRight(editor),
+ deleteColumn(editor),
+ { type: "separator", key: "cellSeperator" },
+ mergeCells(editor),
+ splitCells(editor),
+ cellProperties(editor),
+ { type: "separator", key: "tableSeperator" },
+ deleteTable(editor),
+ ],
+ []
+ );
+
+ return (
+ <>
+ <ToolButton
+ {...props}
+ toggled={isMenuOpen}
+ onClick={() => setIsMenuOpen(true)}
+ />
+ <ResponsivePresenter
+ title="Table properties"
+ mobile="sheet"
+ desktop="menu"
+ isOpen={isMenuOpen}
+ onClose={() => setIsMenuOpen(false)}
+ position={{}}
+ items={items}
+ />
+ </>
+ );
+}
+
+export function CellProperties(props: ToolProps) {
+ return (
+ <>
+ <MoreTools
+ {...props}
+ popupId="cellProperties"
+ tools={[
+ "mergeCells",
+ "splitCells",
+ "cellBackgroundColor",
+ "cellTextColor",
+ "cellBorderColor",
+ "cellBorderWidth",
+ ]}
+ />
+ </>
+ );
+}
+
+export function CellBackgroundColor(props: ToolProps) {
+ return (
+ <ColorTool
+ {...props}
+ isActive={(editor) =>
+ editor.isActive("tableCell", { backgroundColor: /\W+/gm })
+ }
+ getActiveColor={(editor) =>
+ editor.getAttributes("tableCell").backgroundColor
+ }
+ title={"Cell background color"}
+ onColorChange={(editor, color) =>
+ editor.chain().setCellAttribute("backgroundColor", color).run()
+ }
+ />
+ );
+}
+
+export function CellTextColor(props: ToolProps) {
+ return (
+ <ColorTool
+ {...props}
+ isActive={(editor) => editor.isActive("tableCell", { color: /\W+/gm })}
+ getActiveColor={(editor) => editor.getAttributes("tableCell").color}
+ title={"Cell text color"}
+ onColorChange={(editor, color) =>
+ editor.chain().focus().setCellAttribute("color", color).run()
+ }
+ />
+ );
+}
+
+export function CellBorderColor(props: ToolProps) {
+ return (
+ <ColorTool
+ {...props}
+ isActive={(editor) =>
+ editor.isActive("tableCell", { borderColor: /\W+/gm })
+ }
+ getActiveColor={(editor) => editor.getAttributes("tableCell").borderColor}
+ title={"Cell border color"}
+ onColorChange={(editor, color) =>
+ editor.chain().focus().setCellAttribute("borderColor", color).run()
+ }
+ />
+ );
+}
+
+export function CellBorderWidth(props: ToolProps) {
+ const { editor } = props;
+ const { borderWidth: _borderWidth } = editor.getAttributes("tableCell");
+ const borderWidth: number = _borderWidth ? _borderWidth : 1;
+
+ const decreaseBorderWidth = useCallback(() => {
+ return Math.max(1, borderWidth - 1);
+ }, [borderWidth]);
+
+ const increaseBorderWidth = useCallback(() => {
+ return Math.min(10, borderWidth + 1);
+ }, [borderWidth]);
+
+ return (
+ <Flex sx={{ justifyContent: "center", alignItems: "center" }}>
+ <Text variant={"subBody"} sx={{ mx: 1 }}>
+ Border width:
+ </Text>
+ <Counter
+ title="cell border width"
+ onDecrease={() =>
+ editor.commands.setCellAttribute("borderWidth", decreaseBorderWidth())
+ }
+ onIncrease={() =>
+ editor.commands.setCellAttribute("borderWidth", increaseBorderWidth())
+ }
+ onReset={() => editor.commands.setCellAttribute("borderWidth", 1)}
+ value={borderWidth + "px"}
+ />
+ </Flex>
+ );
+}
+
+const insertColumnLeft = (editor: Editor): MenuButton => ({
+ ...getToolDefinition("insertColumnLeft"),
+ key: "addColumnLeft",
+ type: "button",
+ onClick: () => editor.chain().focus().addColumnBefore().run(),
+});
+
+const insertColumnRight = (editor: Editor): MenuButton => ({
+ ...getToolDefinition("insertColumnRight"),
+ key: "addColumnRight",
+ type: "button",
+ title: "Add column right",
+ onClick: () => editor.chain().focus().addColumnAfter().run(),
+ icon: "insertColumnRight",
+});
+
+const moveColumnLeft = (editor: Editor): MenuButton => ({
+ ...getToolDefinition("moveColumnLeft"),
+ key: "moveColumnLeft",
+ type: "button",
+ onClick: () => moveColumnLeft(editor),
+});
+
+const moveColumnRight = (editor: Editor): MenuButton => ({
+ ...getToolDefinition("moveColumnRight"),
+ key: "moveColumnRight",
+ type: "button",
+ onClick: () => moveColumnRight(editor),
+});
+
+const deleteColumn = (editor: Editor): MenuButton => ({
+ ...getToolDefinition("deleteColumn"),
+ key: "deleteColumn",
+ type: "button",
+ onClick: () => editor.chain().focus().deleteColumn().run(),
+});
+
+const splitCells = (editor: Editor): MenuButton => ({
+ ...getToolDefinition("splitCells"),
+ key: "splitCells",
+ type: "button",
+ onClick: () => editor.chain().focus().splitCell().run(),
+});
+
+const mergeCells = (editor: Editor): MenuButton => ({
+ ...getToolDefinition("mergeCells"),
+ key: "mergeCells",
+ type: "button",
+ onClick: () => editor.chain().focus().mergeCells().run(),
+});
+
+const insertRowAbove = (editor: Editor): MenuButton => ({
+ ...getToolDefinition("insertRowAbove"),
+ key: "insertRowAbove",
+ type: "button",
+ onClick: () => editor.chain().focus().addRowBefore().run(),
+});
+
+const insertRowBelow = (editor: Editor): MenuButton => ({
+ ...getToolDefinition("insertRowBelow"),
+ key: "insertRowBelow",
+ type: "button",
+ onClick: () => editor.chain().focus().addRowAfter().run(),
+});
+
+const moveRowUp = (editor: Editor): MenuButton => ({
+ ...getToolDefinition("moveRowUp"),
+ key: "moveRowUp",
+ type: "button",
+ onClick: () => {},
+});
+const moveRowDown = (editor: Editor): MenuButton => ({
+ ...getToolDefinition("moveRowDown"),
+ key: "moveRowDown",
+ type: "button",
+ onClick: () => {},
+});
+
+const deleteRow = (editor: Editor): MenuButton => ({
+ ...getToolDefinition("deleteRow"),
+ key: "deleteRow",
+ type: "button",
+ onClick: () => editor.chain().focus().deleteRow().run(),
+});
+
+const deleteTable = (editor: Editor): MenuButton => ({
+ ...getToolDefinition("deleteTable"),
+ key: "deleteTable",
+ type: "button",
+ onClick: () => editor.chain().focus().deleteTable().run(),
+});
+
+const cellProperties = (editor: Editor): MenuButton => ({
+ ...getToolDefinition("cellProperties"),
+ key: "cellProperties",
+ type: "button",
+ onClick: () => {
+ showPopup({
+ theme: editor.storage.theme,
+ popup: (hide) => <CellPropertiesPopup onClose={hide} editor={editor} />,
+ });
+ },
+});
+
+export const InsertColumnLeft = menuButtonToTool(insertColumnLeft);
+export const InsertColumnRight = menuButtonToTool(insertColumnRight);
+export const MoveColumnLeft = menuButtonToTool(moveColumnLeft);
+export const MoveColumnRight = menuButtonToTool(moveColumnRight);
+export const DeleteColumn = menuButtonToTool(deleteColumn);
+export const SplitCells = menuButtonToTool(splitCells);
+export const MergeCells = menuButtonToTool(mergeCells);
+export const InsertRowAbove = menuButtonToTool(insertRowAbove);
+export const InsertRowBelow = menuButtonToTool(insertRowBelow);
+export const MoveRowUp = menuButtonToTool(moveRowUp);
+export const MoveRowDown = menuButtonToTool(moveRowDown);
+export const DeleteRow = menuButtonToTool(deleteRow);
+export const DeleteTable = menuButtonToTool(deleteTable);
diff --git a/packages/editor/src/toolbar/tools/utils.tsx b/packages/editor/src/toolbar/tools/utils.tsx
new file mode 100644
index 000000000..84a1fb122
--- /dev/null
+++ b/packages/editor/src/toolbar/tools/utils.tsx
@@ -0,0 +1,21 @@
+import { Editor } from "@tiptap/core";
+import { MenuButton } from "../../components/menu/types";
+import { ToolButton } from "../components/tool-button";
+import { ToolProps } from "../types";
+
+export function menuButtonToTool(
+ constructItem: (editor: Editor) => MenuButton
+) {
+ return function (props: ToolProps) {
+ const item = constructItem(props.editor);
+ return (
+ <ToolButton
+ {...props}
+ icon={item.icon || props.icon}
+ toggled={item.isChecked || false}
+ title={item.title}
+ onClick={item.onClick}
+ />
+ );
+ };
+}
diff --git a/packages/editor/src/toolbar/types.ts b/packages/editor/src/toolbar/types.ts
index b58738281..2325228ab 100644
--- a/packages/editor/src/toolbar/types.ts
+++ b/packages/editor/src/toolbar/types.ts
@@ -1,12 +1,19 @@
import { Editor } from "@tiptap/core";
import { IconNames } from "./icons";
+import { ToolId } from "./tools";
export type ToolProps = ToolDefinition & {
editor: Editor;
+ variant?: "small" | "normal";
};
export type ToolDefinition = {
icon: IconNames;
title: string;
+ conditional?: boolean;
description?: string;
};
+
+export type ToolbarGroupDefinition = (ToolId | ToolId[])[];
+
+export type ToolbarDefinition = ToolbarGroupDefinition[];
diff --git a/packages/editor/src/toolbar/utils/dom.ts b/packages/editor/src/toolbar/utils/dom.ts
index 9c5b0011d..ad87837e4 100644
--- a/packages/editor/src/toolbar/utils/dom.ts
+++ b/packages/editor/src/toolbar/utils/dom.ts
@@ -3,3 +3,9 @@ export function getToolbarElement() {
(document.querySelector(".editor-toolbar") as HTMLElement) || undefined
);
}
+
+export function getPopupContainer() {
+ return (
+ (document.getElementById("popup-container") as HTMLElement) || undefined
+ );
+}
diff --git a/packages/editor/src/utils/position.ts b/packages/editor/src/utils/position.ts
new file mode 100644
index 000000000..392534554
--- /dev/null
+++ b/packages/editor/src/utils/position.ts
@@ -0,0 +1,150 @@
+type PositionData = {
+ x: number;
+ y: number;
+ actualX: number;
+ actualY: number;
+ width?: number;
+ height?: number;
+};
+
+const mousePosition: PositionData = { x: 0, y: 0, actualX: 0, actualY: 0 };
+window.addEventListener("mousemove", (e) => {
+ const { x, y, actualX, actualY } = getMousePosition(e);
+ mousePosition.x = x;
+ mousePosition.y = y;
+ mousePosition.actualX = actualX;
+ mousePosition.actualY = actualY;
+});
+
+export type PositionOptions = {
+ target?: HTMLElement | "mouse";
+ isTargetAbsolute?: boolean;
+ location?: "right" | "left" | "below" | "top";
+ align?: "center" | "start" | "end";
+ yOffset?: number;
+ xOffset?: number;
+ yAnchor?: HTMLElement;
+ parent?: HTMLElement | Element;
+};
+export function getPosition(
+ element: HTMLElement,
+ options: PositionOptions
+): { top: number; left: number } {
+ const {
+ target = "mouse",
+ isTargetAbsolute = false,
+ location = undefined,
+ yOffset = 0,
+ xOffset = 0,
+ align = "start",
+ parent = document.body,
+ yAnchor,
+ } = options || {};
+
+ const { x, y, width, height, actualX, actualY } =
+ target === "mouse"
+ ? mousePosition
+ : getElementPosition(target, isTargetAbsolute);
+
+ const elementWidth = element.offsetWidth;
+ const elementHeight = element.offsetHeight;
+
+ const windowWidth = parent.clientWidth;
+ const windowHeight = parent.clientHeight;
+
+ let position = { top: 0, left: 0 };
+
+ if (windowWidth - actualX < elementWidth) {
+ const xDiff = actualX - x;
+ position.left = windowWidth - elementWidth;
+ position.left -= xDiff;
+ } else {
+ position.left = x;
+ }
+
+ if (width) {
+ if (location === "right") position.left += width;
+ else if (location === "left") position.left -= elementWidth;
+ }
+
+ if (actualY + elementHeight > windowHeight) {
+ position.top = windowHeight - elementHeight;
+ } else {
+ position.top = y;
+ }
+
+ if (height) {
+ if (location === "below") position.top += height;
+ else if (location === "top") position.top = y - elementHeight;
+ }
+
+ if (target !== "mouse" && align === "center" && elementWidth > 0) {
+ position.left -= elementWidth / 2 - target.clientWidth / 2;
+ } else if (target !== "mouse" && align === "end" && elementWidth > 0) {
+ position.left -= elementWidth - target.clientWidth;
+ }
+
+ // Adjust menu height
+ if (elementHeight > windowHeight - position.top) {
+ element.style.maxHeight = `${windowHeight - 20}px`;
+ }
+
+ if (yAnchor) {
+ const anchorY = getElementPosition(yAnchor, isTargetAbsolute);
+ position.top = anchorY.actualY - elementHeight;
+ }
+
+ position.top = position.top < 0 ? 0 : position.top;
+ position.left = position.left < 0 ? 0 : position.left;
+ position.top += location === "below" ? yOffset : -yOffset;
+ position.left += xOffset;
+
+ return position;
+}
+
+function getMousePosition(e: MouseEvent) {
+ var posx = 0;
+ var posy = 0;
+
+ if (!e && window.event) e = window.event as MouseEvent;
+
+ if (e.pageX || e.pageY) {
+ posx = e.pageX;
+ posy = e.pageY;
+ } else if (e.clientX || e.clientY) {
+ posx =
+ e.clientX +
+ document.body.scrollLeft +
+ document.documentElement.scrollLeft;
+ posy =
+ e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
+ }
+
+ return {
+ x: posx,
+ y: posy,
+ actualY: posy,
+ actualX: posx,
+ };
+}
+
+export function getElementPosition(
+ element: HTMLElement,
+ absolute: boolean
+): PositionData {
+ const rect = element.getBoundingClientRect();
+ const position: PositionData = {
+ x: element.offsetLeft,
+ y: element.offsetTop,
+ width: rect.width,
+ height: rect.height,
+ actualY: rect.y,
+ actualX: rect.x,
+ };
+ if (absolute) {
+ position.x = position.actualX;
+ position.y = position.actualY;
+ }
+
+ return position;
+}