chore: export as es & cjs both

This commit is contained in:
thecodrr
2022-07-01 18:02:53 +05:00
parent ba2248e06b
commit 286a76da81
636 changed files with 16003 additions and 7951 deletions

View File

@@ -1,15 +1,4 @@
"use strict";
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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -33,39 +22,23 @@ var __importStar = (this && this.__importStar) || function (mod) {
__setModuleDefault(result, mod);
return result;
};
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 __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ActionSheetPresenter = void 0;
var jsx_runtime_1 = require("react/jsx-runtime");
var react_1 = __importStar(require("react"));
var emotion_theming_1 = require("emotion-theming");
var rebass_1 = require("rebass");
var icon_1 = require("../../toolbar/components/icon");
var icons_1 = require("../../toolbar/icons");
var menubutton_1 = require("../menu/menubutton");
var menuseparator_1 = require("../menu/menuseparator");
var react_modal_1 = __importDefault(require("react-modal"));
var framer_motion_1 = require("framer-motion");
var AnimatedFlex = (0, framer_motion_1.motion)(rebass_1.Flex);
var TRANSITION = {
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = __importStar(require("react"));
const emotion_theming_1 = require("emotion-theming");
const rebass_1 = require("rebass");
const icon_1 = require("../../toolbar/components/icon");
const icons_1 = require("../../toolbar/icons");
const menubutton_1 = require("../menu/menubutton");
const menuseparator_1 = require("../menu/menuseparator");
const react_modal_1 = __importDefault(require("react-modal"));
const framer_motion_1 = require("framer-motion");
const AnimatedFlex = (0, framer_motion_1.motion)(rebass_1.Flex);
const TRANSITION = {
type: "spring",
stiffness: 300,
damping: 30,
@@ -73,40 +46,40 @@ var TRANSITION = {
duration: 300,
};
function useHistory(initial) {
var _a = __read((0, react_1.useState)(initial), 2), current = _a[0], setCurrent = _a[1];
var _b = __read((0, react_1.useState)(false), 2), canGoBack = _b[0], setCanGoBack = _b[1];
var stack = (0, react_1.useRef)([initial]);
var goBack = (0, react_1.useCallback)(function () {
const [current, setCurrent] = (0, react_1.useState)(initial);
const [canGoBack, setCanGoBack] = (0, react_1.useState)(false);
const stack = (0, react_1.useRef)([initial]);
const goBack = (0, react_1.useCallback)(() => {
if (!canGoBack)
return;
var prev = stack.current.pop();
const prev = stack.current.pop();
setCurrent(prev);
if (stack.current.length <= 1)
setCanGoBack(false);
}, [canGoBack]);
var navigate = (0, react_1.useCallback)(function (state) {
const navigate = (0, react_1.useCallback)((state) => {
console.log("NAVI", state);
setCurrent(function (prev) {
setCurrent((prev) => {
if (prev)
stack.current.push(prev);
return state;
});
setCanGoBack(true);
}, []);
return { current: current, goBack: goBack, navigate: navigate, canGoBack: canGoBack };
return { current, goBack, navigate, canGoBack };
}
function ActionSheetPresenter(props) {
var _a;
var isOpen = props.isOpen, title = props.title, items = props.items, onClose = props.onClose, _b = props.blocking, blocking = _b === void 0 ? true : _b, _c = props.focusOnRender, focusOnRender = _c === void 0 ? true : _c, _d = props.draggable, draggable = _d === void 0 ? true : _d, children = props.children;
var theme = (0, emotion_theming_1.useTheme)();
var contentRef = (0, react_1.useRef)();
var y = (0, framer_motion_1.useMotionValue)(0);
var opacity = (0, framer_motion_1.useTransform)(y, [0, ((_a = contentRef.current) === null || _a === void 0 ? void 0 : _a.offsetHeight) || window.innerHeight], [1, 0]);
var animation = (0, framer_motion_1.useAnimation)();
var onBeforeClose = (0, react_1.useCallback)(function () {
const { isOpen, title, items, onClose, blocking = true, focusOnRender = true, draggable = true, children, } = props;
const theme = (0, emotion_theming_1.useTheme)();
const contentRef = (0, react_1.useRef)();
const y = (0, framer_motion_1.useMotionValue)(0);
const opacity = (0, framer_motion_1.useTransform)(y, [0, ((_a = contentRef.current) === null || _a === void 0 ? void 0 : _a.offsetHeight) || window.innerHeight], [1, 0]);
const animation = (0, framer_motion_1.useAnimation)();
const onBeforeClose = (0, react_1.useCallback)(() => {
var _a;
var height = ((_a = contentRef.current) === null || _a === void 0 ? void 0 : _a.offsetHeight) || window.innerHeight;
setTimeout(function () {
const height = ((_a = contentRef.current) === null || _a === void 0 ? void 0 : _a.offsetHeight) || window.innerHeight;
setTimeout(() => {
onClose === null || onClose === void 0 ? void 0 : onClose();
}, TRANSITION.duration - 50);
animation.start({
@@ -114,35 +87,35 @@ function ActionSheetPresenter(props) {
y: height + 100,
});
}, [animation, onClose, contentRef.current]);
var handleBackPress = (0, react_1.useCallback)(function (event) {
const handleBackPress = (0, react_1.useCallback)((event) => {
if (!isOpen)
return;
event.preventDefault();
onBeforeClose();
}, [isOpen, onBeforeClose]);
(0, react_1.useEffect)(function () {
(0, react_1.useEffect)(() => {
// Note: this is a custom event implemented on the React Native
// side to handle back button when action sheet is opened.
window.addEventListener("handleBackPress", handleBackPress);
return function () {
return () => {
window.removeEventListener("handleBackPress", handleBackPress);
};
}, [handleBackPress]);
if (!isOpen)
return null;
return ((0, jsx_runtime_1.jsx)(react_modal_1.default, __assign({ contentRef: function (ref) { return (contentRef.current = ref); }, className: "bottom-sheet-presenter", role: "menu", isOpen: isOpen, appElement: document.body, shouldCloseOnEsc: blocking, shouldReturnFocusAfterClose: focusOnRender, shouldCloseOnOverlayClick: blocking, shouldFocusAfterRender: focusOnRender, ariaHideApp: blocking, preventScroll: blocking, onRequestClose: function () { return onBeforeClose(); }, portalClassName: "bottom-sheet-presenter-portal", onAfterOpen: function () {
return ((0, jsx_runtime_1.jsx)(react_modal_1.default, Object.assign({ contentRef: (ref) => (contentRef.current = ref), className: "bottom-sheet-presenter", role: "menu", isOpen: isOpen, appElement: document.body, shouldCloseOnEsc: blocking, shouldReturnFocusAfterClose: focusOnRender, shouldCloseOnOverlayClick: blocking, shouldFocusAfterRender: focusOnRender, ariaHideApp: blocking, preventScroll: blocking, onRequestClose: () => onBeforeClose(), portalClassName: "bottom-sheet-presenter-portal", onAfterOpen: () => {
animation.start({ transition: TRANSITION, y: 0 });
}, overlayElement: function (props, contentEl) {
return ((0, jsx_runtime_1.jsxs)(rebass_1.Box, __assign({}, props, {
}, overlayElement: (props, contentEl) => {
return ((0, jsx_runtime_1.jsxs)(rebass_1.Box, Object.assign({}, props, {
//@ts-ignore
style: __assign(__assign({}, props.style), { position: blocking ? "fixed" : "sticky", zIndex: 1000, backgroundColor: !blocking ? "transparent" : "unset" }), tabIndex: -1 }, { children: [blocking && ((0, jsx_runtime_1.jsx)(framer_motion_1.motion.div, { id: "action-sheet-overlay", style: {
style: Object.assign(Object.assign({}, props.style), { position: blocking ? "fixed" : "sticky", zIndex: 1000, backgroundColor: !blocking ? "transparent" : "unset" }), tabIndex: -1 }, { children: [blocking && ((0, jsx_runtime_1.jsx)(framer_motion_1.motion.div, { id: "action-sheet-overlay", style: {
height: "100%",
width: "100%",
opacity: opacity,
opacity,
position: "absolute",
backgroundColor: "var(--overlay)",
}, tabIndex: -1 })), contentEl] })));
}, contentElement: function (props, children) { return ((0, jsx_runtime_1.jsx)(rebass_1.Box, __assign({}, props, { style: {}, sx: {
}, contentElement: (props, children) => ((0, jsx_runtime_1.jsx)(rebass_1.Box, Object.assign({}, props, { style: {}, sx: {
// top: 0,
left: 0,
right: 0,
@@ -156,30 +129,28 @@ function ActionSheetPresenter(props) {
zIndex: 0,
outline: 0,
isolation: "isolate",
} }, { children: children }))); } }, { children: (0, jsx_runtime_1.jsxs)(AnimatedFlex, __assign({ animate: animation, style: { y: y }, initial: { y: 1000 }, sx: {
} }, { children: children }))) }, { children: (0, jsx_runtime_1.jsxs)(AnimatedFlex, Object.assign({ animate: animation, style: { y }, initial: { y: 1000 }, sx: {
bg: "background",
borderTopLeftRadius: 15,
borderTopRightRadius: 15,
boxShadow: theme.shadows.menu,
flex: 1,
flexDirection: "column",
} }, { children: [draggable && ((0, jsx_runtime_1.jsx)(AnimatedFlex, __assign({ drag: "y",
} }, { children: [draggable && ((0, jsx_runtime_1.jsx)(AnimatedFlex, Object.assign({ drag: "y",
// @ts-ignore
onDrag: function (_, _a) {
var delta = _a.delta;
onDrag: (_, { delta }) => {
y.set(Math.max(y.get() + delta.y, 0));
},
// @ts-ignore
onDragEnd: function (_, _a) {
var velocity = _a.velocity;
onDragEnd: (_, { velocity }) => {
if (velocity.y >= 500) {
onClose === null || onClose === void 0 ? void 0 : onClose();
return;
}
var sheetEl = contentRef.current;
var contentHeight = sheetEl.offsetHeight;
var threshold = 30;
var closingHeight = (contentHeight * threshold) / 100;
const sheetEl = contentRef.current;
const contentHeight = sheetEl.offsetHeight;
const threshold = 30;
const closingHeight = (contentHeight * threshold) / 100;
if (y.get() >= closingHeight) {
onBeforeClose();
}
@@ -196,32 +167,32 @@ function ActionSheetPresenter(props) {
width: 60,
height: 8,
borderRadius: 100,
} }) }))), (0, jsx_runtime_1.jsx)(ContentContainer, __assign({ items: items, title: title, onClose: onClose }, { children: children }))] })) })));
} }) }))), (0, jsx_runtime_1.jsx)(ContentContainer, Object.assign({ items: items, title: title, onClose: onClose }, { children: children }))] })) })));
}
exports.ActionSheetPresenter = ActionSheetPresenter;
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 ((0, jsx_runtime_1.jsxs)(rebass_1.Flex, __assign({ sx: { flexDirection: "column" } }, { children: [canGoBack || (current === null || current === void 0 ? void 0 : current.title) ? ((0, jsx_runtime_1.jsxs)(rebass_1.Flex, __assign({ id: "header", sx: { alignItems: "center", mx: 0, mb: 1 } }, { children: [canGoBack && ((0, jsx_runtime_1.jsx)(rebass_1.Button, __assign({ variant: "icon", sx: { p: 1, ml: 1 }, onClick: goBack }, { children: (0, jsx_runtime_1.jsx)(icon_1.Icon, { path: icons_1.Icons.arrowLeft, size: "big" }) }))), (current === null || current === void 0 ? void 0 : current.title) && ((0, jsx_runtime_1.jsx)(rebass_1.Text, __assign({ variant: "title", sx: { ml: 1, fontSize: "title" } }, { children: current === null || current === void 0 ? void 0 : current.title })))] }))) : null, children
const { title, items, onClose, children } = props;
const { current, goBack, canGoBack, navigate } = useHistory({
title,
items,
});
return ((0, jsx_runtime_1.jsxs)(rebass_1.Flex, Object.assign({ sx: { flexDirection: "column" } }, { children: [canGoBack || (current === null || current === void 0 ? void 0 : current.title) ? ((0, jsx_runtime_1.jsxs)(rebass_1.Flex, Object.assign({ id: "header", sx: { alignItems: "center", mx: 0, mb: 1 } }, { children: [canGoBack && ((0, jsx_runtime_1.jsx)(rebass_1.Button, Object.assign({ variant: "icon", sx: { p: 1, ml: 1 }, onClick: goBack }, { children: (0, jsx_runtime_1.jsx)(icon_1.Icon, { path: icons_1.Icons.arrowLeft, size: "big" }) }))), (current === null || current === void 0 ? void 0 : current.title) && ((0, jsx_runtime_1.jsx)(rebass_1.Text, Object.assign({ variant: "title", sx: { ml: 1, fontSize: "title" } }, { children: current === null || current === void 0 ? void 0 : current.title })))] }))) : null, children
? children
: (_a = current === null || current === void 0 ? void 0 : current.items) === null || _a === void 0 ? void 0 : _a.map(function (item) {
: (_a = current === null || current === void 0 ? void 0 : current.items) === null || _a === void 0 ? void 0 : _a.map((item) => {
if (item.isHidden)
return null;
switch (item.type) {
case "separator":
return (0, jsx_runtime_1.jsx)(menuseparator_1.MenuSeparator, {}, item.key);
case "button":
return ((0, jsx_runtime_1.jsx)(menubutton_1.MenuButton, { item: item, onClick: function (e) {
return ((0, jsx_runtime_1.jsx)(menubutton_1.MenuButton, { item: item, onClick: (e) => {
if (item.menu) {
navigate(item.menu);
}
else if (item.onClick) {
onClose === null || onClose === void 0 ? void 0 : onClose();
setTimeout(function () {
setTimeout(() => {
var _a;
(_a = item.onClick) === null || _a === void 0 ? void 0 : _a.call(item);
}, 300);

View File

@@ -0,0 +1,34 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Button = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const react_2 = require("react");
const rebass_1 = require("rebass");
exports.Button = (0, react_1.forwardRef)((props, forwardedRef) => {
const buttonRef = (0, react_1.useRef)();
(0, react_2.useEffect)(() => {
if (!buttonRef.current)
return;
buttonRef.current.addEventListener("mousedown", onMouseDown, {
passive: false,
capture: true,
});
return () => {
var _a;
(_a = buttonRef.current) === null || _a === void 0 ? void 0 : _a.removeEventListener("mousedown", onMouseDown, {
capture: true,
});
};
}, []);
const onMouseDown = (0, react_1.useCallback)((e) => {
e.preventDefault();
}, []);
return ((0, jsx_runtime_1.jsx)(rebass_1.Button, Object.assign({}, props, { ref: (ref) => {
buttonRef.current = ref;
if (typeof forwardedRef === "function")
forwardedRef(ref);
else if (forwardedRef)
forwardedRef.current = ref;
}, onClick: props.onClick, onMouseDown: () => { } })));
});

View File

@@ -0,0 +1,30 @@
"use strict";
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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.InlineInput = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const forms_1 = require("@rebass/forms");
const rebass_1 = require("rebass");
function InlineInput(props) {
const { label, containerProps, sx } = props, inputProps = __rest(props, ["label", "containerProps", "sx"]);
return ((0, jsx_runtime_1.jsxs)(rebass_1.Flex, Object.assign({}, containerProps, { sx: Object.assign(Object.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: [(0, jsx_runtime_1.jsx)(forms_1.Input, Object.assign({ variant: "clean", sx: Object.assign(Object.assign({}, sx), { p: 0 }) }, inputProps)), (0, jsx_runtime_1.jsx)(rebass_1.Text, Object.assign({ variant: "body", sx: {
flexShrink: 0,
color: "fontTertiary",
borderLeft: "1px solid var(--border)",
pl: 1,
} }, { children: label }))] })));
}
exports.InlineInput = InlineInput;

View File

@@ -1,15 +1,4 @@
"use strict";
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)
@@ -23,18 +12,18 @@ var __rest = (this && this.__rest) || function (s, e) {
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MenuPresenter = exports.Menu = void 0;
var jsx_runtime_1 = require("react/jsx-runtime");
var react_1 = require("react");
var rebass_1 = require("rebass");
var position_1 = require("../../utils/position");
var usefocus_1 = require("./usefocus");
var menuseparator_1 = require("./menuseparator");
var menubutton_1 = require("./menubutton");
var popuppresenter_1 = require("../popuppresenter");
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const rebass_1 = require("rebass");
const position_1 = require("../../utils/position");
const usefocus_1 = require("./usefocus");
const menuseparator_1 = require("./menuseparator");
const menubutton_1 = require("./menubutton");
const popuppresenter_1 = require("../popuppresenter");
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 = (0, react_1.useRef)();
var onAction = (0, react_1.useCallback)(function (e, item) {
const { items = [], title, onClose } = props, containerProps = __rest(props, ["items", "title", "onClose"]);
const hoverTimeout = (0, react_1.useRef)();
const onAction = (0, react_1.useCallback)((e, item) => {
e === null || e === void 0 ? void 0 : e.stopPropagation();
if (item === null || item === void 0 ? void 0 : item.onClick) {
item.onClick();
@@ -42,48 +31,48 @@ function Menu(props) {
if (onClose)
onClose();
}, [onClose]);
var _b = (0, usefocus_1.useFocus)(items, function (e) {
var item = items[focusIndex];
const { focusIndex, setFocusIndex, isSubmenuOpen, setIsSubmenuOpen } = (0, usefocus_1.useFocus)(items, (e) => {
const item = items[focusIndex];
if (item && item.type === "button")
onAction(e, item);
}, function () { return onClose(); }), focusIndex = _b.focusIndex, setFocusIndex = _b.setFocusIndex, isSubmenuOpen = _b.isSubmenuOpen, setIsSubmenuOpen = _b.setIsSubmenuOpen;
var focusedItem = items[focusIndex];
var subMenuRef = (0, react_1.useRef)(null);
(0, react_1.useEffect)(function () {
var item = items[focusIndex];
}, () => onClose());
const focusedItem = items[focusIndex];
const subMenuRef = (0, react_1.useRef)(null);
(0, react_1.useEffect)(() => {
const item = items[focusIndex];
if (!item || !subMenuRef.current)
return;
var menuItemElement = document.getElementById(item.key);
const menuItemElement = document.getElementById(item.key);
if (!menuItemElement)
return;
if (!isSubmenuOpen) {
subMenuRef.current.style.visibility = "hidden";
return;
}
var _a = (0, position_1.getPosition)(subMenuRef.current, {
const { top, left } = (0, position_1.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");
subMenuRef.current.style.top = `${top}px`;
subMenuRef.current.style.left = `${left}px`;
}, [isSubmenuOpen, focusIndex, items]);
return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(MenuContainer, __assign({}, containerProps, { children: items.map(function (item, index) {
return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(MenuContainer, Object.assign({}, containerProps, { children: items.map((item, index) => {
if (item.isHidden)
return null;
switch (item.type) {
case "separator":
return (0, jsx_runtime_1.jsx)(menuseparator_1.MenuSeparator, {}, item.key);
case "button":
return ((0, jsx_runtime_1.jsx)(menubutton_1.MenuButton, { item: item, onClick: function (e) {
return ((0, jsx_runtime_1.jsx)(menubutton_1.MenuButton, { item: item, onClick: (e) => {
if (item.menu) {
setFocusIndex(index);
setIsSubmenuOpen(true);
}
else
onAction(e, item);
}, isFocused: focusIndex === index, onMouseEnter: function () {
}, isFocused: focusIndex === index, onMouseEnter: () => {
if (item.isDisabled) {
setFocusIndex(-1);
return;
@@ -93,25 +82,25 @@ function Menu(props) {
setFocusIndex(index);
setIsSubmenuOpen(false);
if (item.menu) {
hoverTimeout.current = setTimeout(function () {
hoverTimeout.current = setTimeout(() => {
setIsSubmenuOpen(true);
}, 500);
}
}, onMouseLeave: function () {
}, onMouseLeave: () => {
if (hoverTimeout.current)
clearTimeout(hoverTimeout.current);
} }, item.key));
case "popup":
return (0, jsx_runtime_1.jsx)(item.component, { onClick: function (e) { return onAction(e); } });
return (0, jsx_runtime_1.jsx)(item.component, { onClick: (e) => onAction(e) });
}
}) })), (focusedItem === null || focusedItem === void 0 ? void 0 : focusedItem.type) === "button" && (focusedItem === null || focusedItem === void 0 ? void 0 : focusedItem.menu) && isSubmenuOpen && ((0, jsx_runtime_1.jsx)(rebass_1.Flex, __assign({ ref: subMenuRef, style: { visibility: "hidden" }, sx: {
}) })), (focusedItem === null || focusedItem === void 0 ? void 0 : focusedItem.type) === "button" && (focusedItem === null || focusedItem === void 0 ? void 0 : focusedItem.menu) && isSubmenuOpen && ((0, jsx_runtime_1.jsx)(rebass_1.Flex, Object.assign({ ref: subMenuRef, style: { visibility: "hidden" }, sx: {
position: "absolute",
} }, { children: (0, jsx_runtime_1.jsx)(Menu, { items: focusedItem.menu.items, onClose: onClose }) })))] }));
}
exports.Menu = Menu;
function MenuContainer(props) {
var children = props.children, title = props.title, sx = props.sx, flexProps = __rest(props, ["children", "title", "sx"]);
return ((0, jsx_runtime_1.jsxs)(rebass_1.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 && ((0, jsx_runtime_1.jsx)(rebass_1.Text, __assign({ sx: {
const { children, title, sx } = props, flexProps = __rest(props, ["children", "title", "sx"]);
return ((0, jsx_runtime_1.jsxs)(rebass_1.Box, Object.assign({ className: "menuContainer", as: "ul", tabIndex: -1, sx: Object.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 && ((0, jsx_runtime_1.jsx)(rebass_1.Text, Object.assign({ sx: {
fontFamily: "body",
fontSize: "subtitle",
color: "primary",
@@ -123,7 +112,7 @@ function MenuContainer(props) {
} }, { children: title }))), children] })));
}
function MenuPresenter(props) {
var _a = props.items, items = _a === void 0 ? [] : _a, restProps = __rest(props, ["items"]);
return ((0, jsx_runtime_1.jsx)(popuppresenter_1.PopupPresenter, __assign({}, restProps, { children: props.children ? props.children : (0, jsx_runtime_1.jsx)(Menu, __assign({ items: items }, restProps)) })));
const { items = [] } = props, restProps = __rest(props, ["items"]);
return ((0, jsx_runtime_1.jsx)(popuppresenter_1.PopupPresenter, Object.assign({}, restProps, { children: props.children ? props.children : (0, jsx_runtime_1.jsx)(Menu, Object.assign({ items: items }, restProps)) })));
}
exports.MenuPresenter = MenuPresenter;

View File

@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MenuButton = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const rebass_1 = require("rebass");
const icon_1 = require("../../toolbar/components/icon");
const icons_1 = require("../../toolbar/icons");
const toolbarstore_1 = require("../../toolbar/stores/toolbarstore");
const button_1 = require("../button");
function MenuButton(props) {
const { item, isFocused, onMouseEnter, onMouseLeave, onClick } = props;
const { title, key, icon, tooltip, isDisabled, isChecked, menu, modifier } = item;
const itemRef = (0, react_1.useRef)(null);
const toolbarLocation = (0, toolbarstore_1.useToolbarLocation)();
const isBottom = toolbarLocation === "bottom";
return ((0, jsx_runtime_1.jsx)(rebass_1.Flex, Object.assign({ as: "li", sx: { flexShrink: 0, flexDirection: "column" }, onMouseEnter: onMouseEnter, onMouseLeave: onMouseLeave }, { children: (0, jsx_runtime_1.jsxs)(button_1.Button, Object.assign({ id: key, "data-test-id": `MenuButton-${key}`, ref: itemRef, tabIndex: -1, variant: "menuitem", title: tooltip, disabled: isDisabled, onClick: onClick, sx: {
bg: isFocused && !isBottom ? "hover" : "transparent",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
":hover": {
bg: isBottom ? "transparent" : "hover",
},
} }, { children: [(0, jsx_runtime_1.jsxs)(rebass_1.Flex, { children: [icon && ((0, jsx_runtime_1.jsx)(icon_1.Icon, { path: icons_1.Icons[icon], color: "text", size: "medium", sx: { mr: 2 } })), (0, jsx_runtime_1.jsx)(rebass_1.Text, Object.assign({ as: "span", variant: "body", sx: { fontSize: "inherit" } }, { children: title }))] }), isChecked || menu || modifier ? ((0, jsx_runtime_1.jsxs)(rebass_1.Flex, Object.assign({ sx: { ml: 4 } }, { children: [isChecked && (0, jsx_runtime_1.jsx)(icon_1.Icon, { path: icons_1.Icons.check, size: 14 }), menu && (0, jsx_runtime_1.jsx)(icon_1.Icon, { path: icons_1.Icons.chevronRight, size: 14 }), modifier && ((0, jsx_runtime_1.jsx)(rebass_1.Text, Object.assign({ as: "span", sx: {
fontFamily: "body",
fontSize: "menu",
color: "fontTertiary",
} }, { children: modifier })))] }))) : null] }), key) })));
}
exports.MenuButton = MenuButton;

View File

@@ -1,8 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MenuSeparator = void 0;
var jsx_runtime_1 = require("react/jsx-runtime");
var rebass_1 = require("rebass");
const jsx_runtime_1 = require("react/jsx-runtime");
const rebass_1 = require("rebass");
function MenuSeparator() {
return ((0, jsx_runtime_1.jsx)(rebass_1.Box, { as: "li", sx: {
width: "95%",

View File

@@ -1,59 +1,43 @@
"use strict";
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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useFocus = void 0;
var react_1 = require("react");
const react_1 = require("react");
function useFocus(items, onAction, onClose) {
var _a = __read((0, react_1.useState)(-1), 2), focusIndex = _a[0], setFocusIndex = _a[1];
var _b = __read((0, react_1.useState)(false), 2), isSubmenuOpen = _b[0], setIsSubmenuOpen = _b[1];
var moveItemIntoView = (0, react_1.useCallback)(function (index) {
var item = items[index];
const [focusIndex, setFocusIndex] = (0, react_1.useState)(-1);
const [isSubmenuOpen, setIsSubmenuOpen] = (0, react_1.useState)(false);
const moveItemIntoView = (0, react_1.useCallback)((index) => {
const item = items[index];
if (!item)
return;
var element = document.getElementById(item.key);
const element = document.getElementById(item.key);
if (!element)
return;
element.scrollIntoView({
behavior: "auto",
});
}, [items]);
var onKeyDown = (0, react_1.useCallback)(function (e) {
var as = function (i) { return items[i]; };
var isSeperator = function (i) {
const onKeyDown = (0, react_1.useCallback)((e) => {
const as = (i) => items[i];
const isSeperator = (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) {
const moveDown = (i) => (i < items.length - 1 ? ++i : 0);
const moveUp = (i) => (i > 0 ? --i : items.length - 1);
const hasSubmenu = (i) => items && as(i).menu;
const openSubmenu = (index) => {
if (!hasSubmenu(index))
return;
setIsSubmenuOpen(true);
};
var closeSubmenu = function (index) {
const closeSubmenu = (index) => {
if (!hasSubmenu(index))
return;
setIsSubmenuOpen(false);
};
setFocusIndex(function (i) {
var nextIndex = i;
setFocusIndex((i) => {
let nextIndex = i;
switch (e.key) {
case "ArrowUp":
if (isSubmenuOpen)
@@ -91,12 +75,12 @@ function useFocus(items, onAction, onClose) {
return nextIndex;
});
}, [items, isSubmenuOpen, moveItemIntoView, onAction]);
(0, react_1.useEffect)(function () {
(0, react_1.useEffect)(() => {
window.addEventListener("keydown", onKeyDown);
return function () {
return () => {
window.removeEventListener("keydown", onKeyDown);
};
}, [onKeyDown]);
return { focusIndex: focusIndex, setFocusIndex: setFocusIndex, isSubmenuOpen: isSubmenuOpen, setIsSubmenuOpen: setIsSubmenuOpen };
return { focusIndex, setFocusIndex, isSubmenuOpen, setIsSubmenuOpen };
}
exports.useFocus = useFocus;

View File

@@ -1,15 +1,4 @@
"use strict";
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)
@@ -26,49 +15,49 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.showPopup = exports.PopupWrapper = exports.PopupPresenter = void 0;
var jsx_runtime_1 = require("react/jsx-runtime");
var react_1 = require("react");
var rebass_1 = require("rebass");
var position_1 = require("../../utils/position");
var react_modal_1 = __importDefault(require("react-modal"));
var react_dom_1 = __importDefault(require("react-dom"));
var emotion_theming_1 = require("emotion-theming");
var dom_1 = require("../../toolbar/utils/dom");
var toolbarstore_1 = require("../../toolbar/stores/toolbarstore");
var popuprenderer_1 = require("./popuprenderer");
var responsive_1 = require("../responsive");
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const rebass_1 = require("rebass");
const position_1 = require("../../utils/position");
const react_modal_1 = __importDefault(require("react-modal"));
const react_dom_1 = __importDefault(require("react-dom"));
const emotion_theming_1 = require("emotion-theming");
const dom_1 = require("../../toolbar/utils/dom");
const toolbarstore_1 = require("../../toolbar/stores/toolbarstore");
const popuprenderer_1 = require("./popuprenderer");
const responsive_1 = require("../responsive");
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 isMobile = (0, toolbarstore_1.useIsMobile)();
var contentRef = (0, react_1.useRef)();
var observerRef = (0, react_1.useRef)();
var repositionPopup = (0, react_1.useCallback)(function () {
const { isOpen, position, onClose, blocking = true, focusOnRender = true, children, } = props;
const isMobile = (0, toolbarstore_1.useIsMobile)();
const contentRef = (0, react_1.useRef)();
const observerRef = (0, react_1.useRef)();
const repositionPopup = (0, react_1.useCallback)(() => {
if (!contentRef.current || !position)
return;
var popup = contentRef.current;
var popupPosition = (0, position_1.getPosition)(popup, position);
const popup = contentRef.current;
const popupPosition = (0, position_1.getPosition)(popup, position);
popup.style.top = popupPosition.top + "px";
popup.style.left = popupPosition.left + "px";
}, [position]);
(0, react_1.useEffect)(function () {
(0, react_1.useEffect)(() => {
repositionPopup();
}, [position]);
(0, react_1.useEffect)(function () {
(0, react_1.useEffect)(() => {
function onWindowResize() {
repositionPopup();
}
window.addEventListener("resize", onWindowResize);
return function () {
return () => {
window.removeEventListener("resize", onWindowResize);
};
}, []);
var attachMoveHandlers = (0, react_1.useCallback)(function () {
const attachMoveHandlers = (0, react_1.useCallback)(() => {
if (!contentRef.current || !isOpen)
return;
var movableBar = contentRef.current.querySelector(".movable");
const movableBar = contentRef.current.querySelector(".movable");
if (!movableBar)
return;
var popup = contentRef.current;
const popup = contentRef.current;
var offset = { x: 0, y: 0 };
function mouseDown(e) {
offset.x = e.clientX - popup.offsetLeft;
@@ -80,7 +69,7 @@ function _PopupPresenter(props) {
mouseUp();
var top = e.clientY - offset.y;
var left = e.clientX - offset.x;
requestAnimationFrame(function () {
requestAnimationFrame(() => {
popup.style.top = top + "px";
popup.style.left = left + "px";
});
@@ -91,23 +80,23 @@ function _PopupPresenter(props) {
movableBar.addEventListener("mousedown", mouseDown);
window.addEventListener("mouseup", mouseUp);
}, [isOpen]);
var handleResize = (0, react_1.useCallback)(function () {
var popup = contentRef.current;
const handleResize = (0, react_1.useCallback)(() => {
const popup = contentRef.current;
if (!popup)
return;
var oldHeight = popup.offsetHeight;
observerRef.current = new ResizeObserver(function (e) {
let oldHeight = popup.offsetHeight;
observerRef.current = new ResizeObserver((e) => {
if (isMobile) {
repositionPopup();
}
else {
var _a = popup.getBoundingClientRect(), height = _a.height, y = _a.y;
var delta = height - oldHeight;
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.
var windowHeight = document.body.clientHeight - 20;
const windowHeight = document.body.clientHeight - 20;
if (y + height > windowHeight) {
popup.style.top = windowHeight - height + "px";
}
@@ -117,17 +106,17 @@ function _PopupPresenter(props) {
});
observerRef.current.observe(popup, { box: "border-box" });
}, [isMobile]);
return ((0, jsx_runtime_1.jsx)(react_modal_1.default, __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) {
return ((0, jsx_runtime_1.jsx)(react_modal_1.default, Object.assign({ contentRef: (ref) => (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: (obj) => {
if (!obj || !position)
return;
repositionPopup();
handleResize();
attachMoveHandlers();
}, onAfterClose: function () { var _a; return (_a = observerRef.current) === null || _a === void 0 ? void 0 : _a.disconnect(); }, overlayElement: function (props, contentEl) {
return ((0, jsx_runtime_1.jsx)(rebass_1.Box, __assign({}, props, {
}, onAfterClose: () => { var _a; return (_a = observerRef.current) === null || _a === void 0 ? void 0 : _a.disconnect(); }, overlayElement: (props, contentEl) => {
return ((0, jsx_runtime_1.jsx)(rebass_1.Box, Object.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 ((0, jsx_runtime_1.jsx)(rebass_1.Box, __assign({}, props, { style: {},
style: Object.assign(Object.assign({}, props.style), { position: !blocking ? "initial" : "fixed", zIndex: 1000, backgroundColor: !blocking ? "transparent" : "unset" }) }, { children: contentEl })));
}, contentElement: (props, children) => ((0, jsx_runtime_1.jsx)(rebass_1.Box, Object.assign({}, props, { style: {},
// TODO onMouseDown={(e) => {
// console.log(e);
// }}
@@ -145,7 +134,7 @@ function _PopupPresenter(props) {
zIndex: 0,
outline: 0,
isolation: "isolate",
} }, { children: children }))); }, style: {
} }, { children: children }))), style: {
content: {},
overlay: {
zIndex: 999,
@@ -159,62 +148,61 @@ function PopupPresenter(props) {
// if the popup is closed.
if (!props.isOpen)
return null;
return (0, jsx_runtime_1.jsx)(_PopupPresenter, __assign({}, props));
return (0, jsx_runtime_1.jsx)(_PopupPresenter, Object.assign({}, props));
}
exports.PopupPresenter = PopupPresenter;
function PopupWrapper(props) {
var id = props.id, group = props.group, position = props.position, renderPopup = props.renderPopup, isOpen = props.isOpen, onClosed = props.onClosed, autoCloseOnUnmount = props.autoCloseOnUnmount, presenterProps = __rest(props, ["id", "group", "position", "renderPopup", "isOpen", "onClosed", "autoCloseOnUnmount"]);
var PopupRenderer = (0, popuprenderer_1.usePopupRenderer)();
var isPopupOpen = (0, toolbarstore_1.useToolbarStore)(function (store) { return !!store.openedPopups[id]; });
var openPopup = (0, toolbarstore_1.useToolbarStore)(function (store) { return store.openPopup; });
var closePopup = (0, toolbarstore_1.useToolbarStore)(function (store) { return store.closePopup; });
var closePopupGroup = (0, toolbarstore_1.useToolbarStore)(function (store) { return store.closePopupGroup; });
var isBottom = (0, toolbarstore_1.useToolbarStore)(function (store) { return store.toolbarLocation === "bottom"; });
let { id, group, position, renderPopup, isOpen, onClosed, autoCloseOnUnmount } = props, presenterProps = __rest(props, ["id", "group", "position", "renderPopup", "isOpen", "onClosed", "autoCloseOnUnmount"]);
const PopupRenderer = (0, popuprenderer_1.usePopupRenderer)();
const isPopupOpen = (0, toolbarstore_1.useToolbarStore)((store) => !!store.openedPopups[id]);
const openPopup = (0, toolbarstore_1.useToolbarStore)((store) => store.openPopup);
const closePopup = (0, toolbarstore_1.useToolbarStore)((store) => store.closePopup);
const closePopupGroup = (0, toolbarstore_1.useToolbarStore)((store) => store.closePopupGroup);
const isBottom = (0, toolbarstore_1.useToolbarStore)((store) => store.toolbarLocation === "bottom");
if (isBottom)
group = "popup";
(0, react_1.useEffect)(function () {
(0, react_1.useEffect)(() => {
if (isOpen)
openPopup({ id: id, group: group });
openPopup({ id, group });
else
closePopup(id);
}, [isOpen, id, group, openPopup, closePopup]);
(0, react_1.useEffect)(function () {
(0, react_1.useEffect)(() => {
if (!autoCloseOnUnmount)
return;
return function () {
return () => {
PopupRenderer === null || PopupRenderer === void 0 ? void 0 : PopupRenderer.closePopup(id);
};
}, [autoCloseOnUnmount, id]);
(0, react_1.useEffect)(function () {
(0, react_1.useEffect)(() => {
if (!isPopupOpen)
onClosed === null || onClosed === void 0 ? void 0 : onClosed();
}, [isPopupOpen]);
(0, react_1.useEffect)(function () {
(0, react_1.useEffect)(() => {
if (isPopupOpen) {
closePopupGroup(group, [id]);
}
}, [onClosed, isPopupOpen, closePopupGroup, id, group]);
(0, react_1.useEffect)(function () {
(0, react_1.useEffect)(() => {
if (!isOpen)
closePopup(id);
}, [isOpen, id, group, closePopup]);
(0, react_1.useEffect)(function () {
(0, react_1.useEffect)(() => {
if (PopupRenderer && isPopupOpen) {
PopupRenderer.openPopup(id, function Popup(_a) {
var id = _a.id;
var isPopupOpen = (0, toolbarstore_1.useToolbarStore)(function (store) { return !!store.openedPopups[id]; });
(0, react_1.useEffect)(function () {
PopupRenderer.openPopup(id, function Popup({ id }) {
const isPopupOpen = (0, toolbarstore_1.useToolbarStore)((store) => !!store.openedPopups[id]);
(0, react_1.useEffect)(() => {
if (!isPopupOpen) {
PopupRenderer.closePopup(id);
}
}, [isPopupOpen]);
return ((0, jsx_runtime_1.jsx)(PopupPresenter, __assign({ isOpen: isPopupOpen, onClose: function () { return closePopup(id); }, position: position, blocking: true, focusOnRender: true }, presenterProps, { children: (0, jsx_runtime_1.jsx)(rebass_1.Box, __assign({ sx: {
return ((0, jsx_runtime_1.jsx)(PopupPresenter, Object.assign({ isOpen: isPopupOpen, onClose: () => closePopup(id), position: position, blocking: true, focusOnRender: true }, presenterProps, { children: (0, jsx_runtime_1.jsx)(rebass_1.Box, Object.assign({ sx: {
boxShadow: "menu",
borderRadius: "default",
overflow: "hidden",
// width,
} }, { children: (0, jsx_runtime_1.jsx)(popuprenderer_1.EditorContext.Consumer, { children: function () {
return renderPopup(function () { return PopupRenderer.closePopup(id); });
} }, { children: (0, jsx_runtime_1.jsx)(popuprenderer_1.EditorContext.Consumer, { children: () => {
return renderPopup(() => PopupRenderer.closePopup(id));
} }) })) }), id));
});
}
@@ -223,11 +211,11 @@ function PopupWrapper(props) {
}
exports.PopupWrapper = PopupWrapper;
function showPopup(options) {
var theme = options.theme, popup = options.popup, props = __rest(options, ["theme", "popup"]);
const { theme, popup } = options, props = __rest(options, ["theme", "popup"]);
function hide() {
react_dom_1.default.unmountComponentAtNode((0, dom_1.getPopupContainer)());
}
react_dom_1.default.render((0, jsx_runtime_1.jsx)(emotion_theming_1.ThemeProvider, __assign({ theme: theme }, { children: (0, jsx_runtime_1.jsx)(responsive_1.ResponsivePresenter, __assign({ isOpen: true, onClose: hide, position: {
react_dom_1.default.render((0, jsx_runtime_1.jsx)(emotion_theming_1.ThemeProvider, Object.assign({ theme: theme }, { children: (0, jsx_runtime_1.jsx)(responsive_1.ResponsivePresenter, Object.assign({ isOpen: true, onClose: hide, position: {
target: (0, dom_1.getToolbarElement)(),
isTargetAbsolute: true,
location: "below",

View File

@@ -0,0 +1,74 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useEditorContext = exports.usePopupRenderer = exports.PopupRenderer = exports.EditorContext = exports.PopupRendererContext = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = __importStar(require("react"));
exports.PopupRendererContext = react_1.default.createContext(null);
exports.EditorContext = react_1.default.createContext(null);
class PopupRenderer extends react_1.default.Component {
constructor() {
super(...arguments);
this.popupContainer = null;
this.state = {
popups: [],
};
this.openPopup = (id, popup) => {
if (!popup)
return;
this.setState((prev) => {
return {
popups: [...prev.popups, { id, popup }],
};
});
};
this.closePopup = (id) => {
this.setState((prev) => {
const index = prev.popups.findIndex((p) => p.id === id);
if (index <= -1)
return prev;
const clone = prev.popups.slice();
clone.splice(index, 1);
return {
popups: clone,
};
});
};
}
render() {
return ((0, jsx_runtime_1.jsxs)(exports.PopupRendererContext.Provider, Object.assign({ value: this }, { children: [this.props.children, (0, jsx_runtime_1.jsxs)(exports.EditorContext.Provider, Object.assign({ value: this.props.editor }, { children: [this.state.popups.map(({ id, popup: Popup }) => {
return (0, jsx_runtime_1.jsx)(Popup, { id: id }, id);
}), (0, jsx_runtime_1.jsx)("div", { id: "popup-container" })] }))] })));
}
}
exports.PopupRenderer = PopupRenderer;
function usePopupRenderer() {
return (0, react_1.useContext)(exports.PopupRendererContext);
}
exports.usePopupRenderer = usePopupRenderer;
function useEditorContext() {
return (0, react_1.useContext)(exports.EditorContext);
}
exports.useEditorContext = useEditorContext;

View File

@@ -1,15 +1,4 @@
"use strict";
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)
@@ -23,12 +12,12 @@ var __rest = (this && this.__rest) || function (s, e) {
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResponsivePresenter = exports.MobileOnly = exports.DesktopOnly = exports.ResponsiveContainer = void 0;
var jsx_runtime_1 = require("react/jsx-runtime");
var toolbarstore_1 = require("../../toolbar/stores/toolbarstore");
var actionsheet_1 = require("../actionsheet");
var menu_1 = require("../menu");
const jsx_runtime_1 = require("react/jsx-runtime");
const toolbarstore_1 = require("../../toolbar/stores/toolbarstore");
const actionsheet_1 = require("../actionsheet");
const menu_1 = require("../menu");
function ResponsiveContainer(props) {
var isMobile = (0, toolbarstore_1.useIsMobile)();
const isMobile = (0, toolbarstore_1.useIsMobile)();
if (isMobile)
return props.mobile || null;
else
@@ -44,12 +33,12 @@ function MobileOnly(props) {
}
exports.MobileOnly = MobileOnly;
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 = (0, toolbarstore_1.useIsMobile)();
const { mobile = "menu", desktop = "menu" } = props, restProps = __rest(props, ["mobile", "desktop"]);
const isMobile = (0, toolbarstore_1.useIsMobile)();
if (isMobile && mobile === "sheet")
return (0, jsx_runtime_1.jsx)(actionsheet_1.ActionSheetPresenter, __assign({}, restProps));
return (0, jsx_runtime_1.jsx)(actionsheet_1.ActionSheetPresenter, Object.assign({}, restProps));
else if (mobile === "menu" || desktop === "menu")
return (0, jsx_runtime_1.jsx)(menu_1.MenuPresenter, __assign({}, restProps));
return (0, jsx_runtime_1.jsx)(menu_1.MenuPresenter, Object.assign({}, restProps));
else
return props.isOpen ? (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: props.children }) : null;
}

View File

@@ -1,15 +1,4 @@
"use strict";
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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -33,43 +22,25 @@ var __importStar = (this && this.__importStar) || function (mod) {
__setModuleDefault(result, mod);
return result;
};
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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Tabs = exports.Tab = void 0;
var jsx_runtime_1 = require("react/jsx-runtime");
var react_1 = __importStar(require("react"));
var rebass_1 = require("rebass");
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = __importStar(require("react"));
const rebass_1 = require("rebass");
function Tab(props) {
return (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: props.children });
}
exports.Tab = Tab;
function Tabs(props) {
var activeIndex = props.activeIndex, children = props.children, containerProps = props.containerProps, onTabChanged = props.onTabChanged;
var _a = __read((0, react_1.useState)(activeIndex || 0), 2), activeTab = _a[0], setActiveTab = _a[1];
var tabs = (0, react_1.useMemo)(function () {
return react_1.Children.map(children, function (child) {
if (react_1.default.isValidElement(child))
return { title: child.props.title, component: child };
});
}, [children]);
return ((0, jsx_runtime_1.jsxs)(rebass_1.Flex, __assign({ sx: { flexDirection: "column" } }, { children: [(0, jsx_runtime_1.jsx)(rebass_1.Flex, __assign({ sx: {
const { activeIndex, children, containerProps, onTabChanged } = props;
const [activeTab, setActiveTab] = (0, react_1.useState)(activeIndex || 0);
const tabs = (0, react_1.useMemo)(() => react_1.Children.map(children, (child) => {
if (react_1.default.isValidElement(child))
return { title: child.props.title, component: child };
}), [children]);
return ((0, jsx_runtime_1.jsxs)(rebass_1.Flex, Object.assign({ sx: { flexDirection: "column" } }, { children: [(0, jsx_runtime_1.jsx)(rebass_1.Flex, Object.assign({ sx: {
mb: 1,
} }, { children: tabs === null || tabs === void 0 ? void 0 : tabs.map(function (tab, index) { return ((0, jsx_runtime_1.jsx)(rebass_1.Button, __assign({ sx: {
} }, { children: tabs === null || tabs === void 0 ? void 0 : tabs.map((tab, index) => ((0, jsx_runtime_1.jsx)(rebass_1.Button, Object.assign({ sx: {
flex: 1,
p: 0,
py: 1,
@@ -85,9 +56,9 @@ function Tabs(props) {
":hover": {
bg: "hover",
},
}, onClick: function () {
}, onClick: () => {
setActiveTab(index);
onTabChanged === null || onTabChanged === void 0 ? void 0 : onTabChanged(index);
} }, { children: tab.title }), index.toString())); }) })), (0, jsx_runtime_1.jsx)(rebass_1.Flex, __assign({}, containerProps, { children: tabs && tabs[activeTab].component }))] })));
} }, { children: tab.title }), index.toString()))) })), (0, jsx_runtime_1.jsx)(rebass_1.Flex, Object.assign({}, containerProps, { children: tabs && tabs[activeTab].component }))] })));
}
exports.Tabs = Tabs;

View File

@@ -0,0 +1,113 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDataAttribute = exports.AttachmentNode = void 0;
const core_1 = require("@tiptap/core");
const react_1 = require("../react");
const component_1 = require("./component");
exports.AttachmentNode = core_1.Node.create({
name: "attachment",
content: "inline*",
marks: "",
inline: true,
atom: true,
addOptions() {
return {
HTMLAttributes: {},
onDownloadAttachment: () => false,
onOpenAttachmentPicker: () => false,
};
},
group() {
return "inline";
},
draggable: true,
addAttributes() {
return {
progress: {
default: 0,
rendered: false,
},
hash: getDataAttribute("hash"),
filename: getDataAttribute("filename"),
type: getDataAttribute("mime"),
size: getDataAttribute("size"),
};
},
parseHTML() {
return [
{
tag: "span[data-hash]",
},
];
},
renderHTML({ HTMLAttributes }) {
return [
"span",
(0, core_1.mergeAttributes)(this.options.HTMLAttributes, HTMLAttributes),
];
},
addNodeView() {
return (0, react_1.createSelectionBasedNodeView)(component_1.AttachmentComponent, {
shouldUpdate: ({ attrs: prev }, { attrs: next }) => {
return prev.progress !== next.progress;
},
});
},
addCommands() {
return {
insertAttachment: (attachment) => ({ commands }) => {
return commands.insertContent({
type: this.name,
attrs: attachment,
});
},
removeAttachment: () => ({ commands }) => commands.deleteNode(this.name),
downloadAttachment: (attachment) => ({ editor }) => {
return this.options.onDownloadAttachment(editor, attachment);
},
openAttachmentPicker: (type) => ({ editor }) => {
return this.options.onOpenAttachmentPicker(editor, type);
},
setAttachmentProgress: (options) => ({ state, tr, dispatch }) => {
const { hash, progress, type } = options;
const attachments = (0, core_1.findChildren)(state.doc, (node) => (node.type.name === this.name || node.type.name === "image") &&
node.attrs.hash === hash);
for (const attachment of attachments) {
tr.setNodeMarkup(attachment.pos, attachment.node.type, Object.assign(Object.assign({}, attachment.node.attrs), { progress: progress === 100 ? null : progress }));
}
tr.setMeta("preventUpdate", true);
tr.setMeta("addToHistory", false);
if (dispatch)
dispatch(tr);
return true;
},
};
},
// addInputRules() {
// return [
// nodeInputRule({
// find: inputRegex,
// type: this.type,
// getAttributes: (match) => {
// const [, , alt, src, title] = match;
// return { src, alt, title };
// },
// }),
// ];
// },
});
function getDataAttribute(name, def) {
return {
default: def,
parseHTML: (element) => element.dataset[name],
renderHTML: (attributes) => {
if (!attributes[name]) {
return {};
}
return {
[`data-${name}`]: attributes[name],
};
},
};
}
exports.getDataAttribute = getDataAttribute;

View File

@@ -1,30 +1,19 @@
"use strict";
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);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AttachmentComponent = void 0;
var jsx_runtime_1 = require("react/jsx-runtime");
var rebass_1 = require("rebass");
var react_1 = require("react");
const jsx_runtime_1 = require("react/jsx-runtime");
const rebass_1 = require("rebass");
const react_1 = require("react");
// import { MenuPresenter } from "../../components/menu/menu";
var icon_1 = require("../../toolbar/components/icon");
var icons_1 = require("../../toolbar/icons");
var toolbargroup_1 = require("../../toolbar/components/toolbargroup");
var responsive_1 = require("../../components/responsive");
const icon_1 = require("../../toolbar/components/icon");
const icons_1 = require("../../toolbar/icons");
const toolbargroup_1 = require("../../toolbar/components/toolbargroup");
const responsive_1 = require("../../components/responsive");
function AttachmentComponent(props) {
var editor = props.editor, node = props.node, selected = props.selected;
var _a = node.attrs, hash = _a.hash, filename = _a.filename, size = _a.size, progress = _a.progress;
var elementRef = (0, react_1.useRef)();
return ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: (0, jsx_runtime_1.jsxs)(rebass_1.Box, __assign({ ref: elementRef, as: "span", contentEditable: false, variant: "body", sx: {
const { editor, node, selected } = props;
const { hash, filename, size, progress } = node.attrs;
const elementRef = (0, react_1.useRef)();
return ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: (0, jsx_runtime_1.jsxs)(rebass_1.Box, Object.assign({ ref: elementRef, as: "span", contentEditable: false, variant: "body", sx: {
display: "inline-flex",
position: "relative",
justifyContent: "center",
@@ -40,18 +29,18 @@ function AttachmentComponent(props) {
":hover": {
bg: "hover",
},
}, title: filename }, { children: [(0, jsx_runtime_1.jsx)(icon_1.Icon, { path: icons_1.Icons.attachment, size: 14 }), (0, jsx_runtime_1.jsx)(rebass_1.Text, __assign({ as: "span", sx: {
}, title: filename }, { children: [(0, jsx_runtime_1.jsx)(icon_1.Icon, { path: icons_1.Icons.attachment, size: 14 }), (0, jsx_runtime_1.jsx)(rebass_1.Text, Object.assign({ as: "span", sx: {
ml: "small",
fontSize: "body",
whiteSpace: "nowrap",
textOverflow: "ellipsis",
overflow: "hidden",
} }, { children: filename })), (0, jsx_runtime_1.jsx)(rebass_1.Text, __assign({ as: "span", sx: {
} }, { children: filename })), (0, jsx_runtime_1.jsx)(rebass_1.Text, Object.assign({ as: "span", sx: {
ml: 1,
fontSize: "0.65rem",
color: "fontTertiary",
flexShrink: 0,
} }, { children: progress ? "".concat(progress, "%") : formatBytes(size) })), (0, jsx_runtime_1.jsx)(responsive_1.DesktopOnly, { children: selected && ((0, jsx_runtime_1.jsx)(toolbargroup_1.ToolbarGroup, { editor: editor, tools: ["removeAttachment", "downloadAttachment"], sx: {
} }, { children: progress ? `${progress}%` : formatBytes(size) })), (0, jsx_runtime_1.jsx)(responsive_1.DesktopOnly, { children: selected && ((0, jsx_runtime_1.jsx)(toolbargroup_1.ToolbarGroup, { editor: editor, tools: ["removeAttachment", "downloadAttachment"], sx: {
boxShadow: "menu",
borderRadius: "default",
bg: "background",
@@ -60,13 +49,12 @@ function AttachmentComponent(props) {
} })) })] })) }));
}
exports.AttachmentComponent = AttachmentComponent;
function formatBytes(bytes, decimals) {
if (decimals === void 0) { decimals = 1; }
function formatBytes(bytes, decimals = 1) {
if (bytes === 0)
return "0B";
var k = 1024;
var dm = decimals < 0 ? 0 : decimals;
var sizes = ["B", "K", "M", "G", "T", "P", "E", "Z", "Y"];
var i = Math.floor(Math.log(bytes) / Math.log(k));
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ["B", "K", "M", "G", "T", "P", "E", "Z", "Y"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + sizes[i];
}

View File

@@ -4,19 +4,19 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BulletList = void 0;
var extension_bullet_list_1 = __importDefault(require("@tiptap/extension-bullet-list"));
const extension_bullet_list_1 = __importDefault(require("@tiptap/extension-bullet-list"));
exports.BulletList = extension_bullet_list_1.default.extend({
addAttributes: function () {
addAttributes() {
return {
listType: {
default: null,
parseHTML: function (element) { return element.style.listStyleType; },
renderHTML: function (attributes) {
parseHTML: (element) => element.style.listStyleType,
renderHTML: (attributes) => {
if (!attributes.listType) {
return {};
}
return {
style: "list-style-type: ".concat(attributes.listType),
style: `list-style-type: ${attributes.listType}`,
};
},
},

View File

@@ -14,6 +14,6 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
var bulletlist_1 = require("./bulletlist");
const bulletlist_1 = require("./bulletlist");
__exportStar(require("./bulletlist"), exports);
exports.default = bulletlist_1.BulletList;

View File

@@ -0,0 +1,516 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.toCodeLines = exports.getLines = exports.toCaretPosition = exports.CodeBlock = exports.tildeInputRegex = exports.backtickInputRegex = void 0;
const core_1 = require("@tiptap/core");
const core_2 = require("@tiptap/core");
const prosemirror_state_1 = require("prosemirror-state");
const component_1 = require("./component");
const highlighter_1 = require("./highlighter");
const react_1 = require("../react");
const detect_indent_1 = __importDefault(require("detect-indent"));
const redent_1 = __importDefault(require("redent"));
const strip_indent_1 = __importDefault(require("strip-indent"));
exports.backtickInputRegex = /^```([a-z]+)?[\s\n]$/;
exports.tildeInputRegex = /^~~~([a-z]+)?[\s\n]$/;
const ZERO_WIDTH_SPACE = "\u200b";
const NEWLINE = "\n";
exports.CodeBlock = core_2.Node.create({
name: "codeblock",
addOptions() {
return {
languageClassPrefix: "language-",
exitOnTripleEnter: true,
exitOnArrowDown: true,
exitOnArrowUp: true,
HTMLAttributes: {},
};
},
content: "text*",
marks: "",
group: "block",
code: true,
defining: true,
addAttributes() {
return {
caretPosition: {
default: undefined,
rendered: false,
},
lines: {
default: [],
rendered: false,
},
indentType: {
default: "space",
parseHTML: (element) => {
const indentType = element.dataset.indentType;
return indentType;
},
renderHTML: (attributes) => {
if (!attributes.indentType) {
return {};
}
return {
"data-indent-type": attributes.indentType,
};
},
},
indentLength: {
default: 2,
parseHTML: (element) => {
const indentLength = element.dataset.indentLength;
return indentLength;
},
renderHTML: (attributes) => {
if (!attributes.indentLength) {
return {};
}
return {
"data-indent-length": attributes.indentLength,
};
},
},
language: {
default: null,
parseHTML: (element) => {
var _a;
const { languageClassPrefix } = this.options;
const classNames = [
...(element.classList || []),
...(((_a = element === null || element === void 0 ? void 0 : element.firstElementChild) === null || _a === void 0 ? void 0 : _a.classList) || []),
];
const languages = classNames
.filter((className) => className.startsWith(languageClassPrefix))
.map((className) => className.replace(languageClassPrefix, ""));
const language = languages[0];
if (!language) {
return null;
}
return language;
},
renderHTML: (attributes) => {
if (!attributes.language) {
return {};
}
return {
class: `language-${attributes.language}`,
};
},
},
};
},
parseHTML() {
return [
{
tag: "pre",
preserveWhitespace: "full",
// contentElement: (node) => {
// if (node instanceof HTMLElement) {
// node.innerText = node.innerText.replaceAll("\n\u200b\n", "\n\n");
// }
// return node;
// },
},
];
},
renderHTML({ HTMLAttributes }) {
return [
"pre",
(0, core_2.mergeAttributes)(this.options.HTMLAttributes, HTMLAttributes),
["code", {}, 0],
];
},
addCommands() {
return {
setCodeBlock: (attributes) => ({ commands }) => {
return commands.setNode(this.name, attributes);
},
toggleCodeBlock: (attributes) => ({ commands }) => {
console.log("TOGGLING!");
return commands.toggleNode(this.name, "paragraph", attributes);
},
changeCodeBlockIndentation: (options) => ({ editor, tr, commands }) => {
const { state } = editor;
const { selection } = state;
const { $from } = selection;
if ($from.parent.type !== this.type) {
return false;
}
const { lines } = $from.parent.attrs;
for (const line of lines) {
const text = line.text();
const whitespaceLength = text.length - text.trimStart().length;
if (!whitespaceLength)
continue;
const indentLength = whitespaceLength;
const indentToken = indent({
type: options.type,
amount: indentLength,
});
tr.insertText(indentToken, tr.mapping.map(line.from), tr.mapping.map(line.from + whitespaceLength));
}
commands.updateAttributes(this.type, {
indentType: options.type,
indentLength: options.amount,
});
return true;
},
};
},
addKeyboardShortcuts() {
return {
"Mod-Alt-c": () => this.editor.commands.toggleCodeBlock(),
"Mod-a": ({ editor }) => {
const { $anchor } = this.editor.state.selection;
if ($anchor.parent.type.name !== this.name) {
return false;
}
const codeblock = (0, core_1.findParentNodeClosestToPos)($anchor, (node) => node.type.name === this.type.name);
if (!codeblock)
return false;
return editor.commands.setTextSelection({
from: codeblock.pos,
to: codeblock.pos + codeblock.node.nodeSize,
});
},
// remove code block when at start of document or code block is empty
Backspace: () => {
const { empty, $anchor } = this.editor.state.selection;
const isAtStart = $anchor.pos === 1;
if (!empty || $anchor.parent.type.name !== this.name) {
return false;
}
if (isAtStart || !$anchor.parent.textContent.length) {
return this.editor.commands.deleteNode(this.type);
}
return false;
},
// exit node on triple enter
Enter: ({ editor }) => {
const { state } = editor;
const { selection } = state;
const { $from, empty } = selection;
if (!empty || $from.parent.type !== this.type) {
return false;
}
const indentation = parseIndentation($from.parent);
return ((this.options.exitOnTripleEnter &&
exitOnTripleEnter(editor, $from)) ||
indentOnEnter(editor, $from, indentation));
},
// exit node on arrow up
ArrowUp: ({ editor }) => {
if (!this.options.exitOnArrowUp) {
return false;
}
const { state } = editor;
const { selection } = state;
const { $anchor, empty } = selection;
if (!empty || $anchor.parent.type !== this.type) {
return false;
}
const isAtStart = $anchor.pos === 1;
if (!isAtStart) {
return false;
}
return editor.commands.insertContentAt(0, "<p></p>");
},
// exit node on arrow down
ArrowDown: ({ editor }) => {
if (!this.options.exitOnArrowDown) {
return false;
}
const { state } = editor;
const { selection, doc } = state;
const { $from, empty } = selection;
if (!empty || $from.parent.type !== this.type) {
return false;
}
const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2;
if (!isAtEnd) {
return false;
}
const after = $from.after();
if (after === undefined) {
return false;
}
const nodeAfter = doc.nodeAt(after);
if (nodeAfter) {
editor.commands.setNodeSelection($from.before());
return false;
}
return editor.commands.exitCode();
},
"Shift-Tab": ({ editor }) => {
const { state } = editor;
const { selection } = state;
const { $from } = selection;
if ($from.parent.type !== this.type) {
return false;
}
const indentation = parseIndentation($from.parent);
const indentToken = indent(indentation);
const { lines } = $from.parent.attrs;
const selectedLines = getSelectedLines(lines, selection);
return editor
.chain()
.command(({ tr }) => withSelection(tr, (tr) => {
for (const line of selectedLines) {
if (line.text(indentToken.length) !== indentToken)
continue;
tr.delete(tr.mapping.map(line.from), tr.mapping.map(line.from + indentation.amount));
}
}))
.run();
},
Tab: ({ editor }) => {
const { state } = editor;
const { selection } = state;
const { $from } = selection;
if ($from.parent.type !== this.type) {
return false;
}
const { lines } = $from.parent.attrs;
const selectedLines = getSelectedLines(lines, selection);
return editor
.chain()
.command(({ tr }) => withSelection(tr, (tr) => {
const indentToken = indent(parseIndentation($from.parent));
if (selectedLines.length === 1)
return tr.insertText(indentToken, $from.pos);
for (const line of selectedLines) {
tr.insertText(indentToken, tr.mapping.map(line.from));
}
}))
.run();
},
};
},
addInputRules() {
return [
(0, core_2.textblockTypeInputRule)({
find: exports.backtickInputRegex,
type: this.type,
getAttributes: (match) => ({
language: match[1],
}),
}),
(0, core_2.textblockTypeInputRule)({
find: exports.tildeInputRegex,
type: this.type,
getAttributes: (match) => ({
language: match[1],
}),
}),
];
},
addProseMirrorPlugins() {
return [
// this plugin creates a code block for pasted content from VS Code
// we can also detect the copied code language
new prosemirror_state_1.Plugin({
key: new prosemirror_state_1.PluginKey("codeBlockVSCodeHandler"),
props: {
handlePaste: (view, event) => {
if (!event.clipboardData) {
return false;
}
const text = event.clipboardData.getData("text/plain");
const vscode = event.clipboardData.getData("vscode-editor-data");
const vscodeData = vscode ? JSON.parse(vscode) : undefined;
const language = vscodeData === null || vscodeData === void 0 ? void 0 : vscodeData.mode;
if (!text || !language) {
return false;
}
const indent = fixIndentation(text, parseIndentation(view.state.selection.$from.parent));
const { tr } = view.state;
// create an empty code block if not already within one
if (!this.editor.isActive(this.type.name)) {
tr.replaceSelectionWith(this.type.create({
language,
indentType: indent.type,
indentLength: indent.amount,
}));
}
// // put cursor inside the newly created code block
// tr.setSelection(
// TextSelection.near(
// tr.doc.resolve(Math.max(0, tr.selection.from - 2))
// )
// );
// add text to code block
// strip carriage return chars from text pasted as code
// see: https://github.com/ProseMirror/prosemirror-view/commit/a50a6bcceb4ce52ac8fcc6162488d8875613aacd
tr.insertText(indent.code.replace(/\r\n?/g, "\n"));
// store meta information
// this is useful for other plugins that depends on the paste event
// like the paste rule plugin
tr.setMeta("paste", true);
view.dispatch(tr);
return true;
},
},
}),
(0, highlighter_1.HighlighterPlugin)({ name: this.name, defaultLanguage: "txt" }),
];
},
addNodeView() {
return (0, react_1.createNodeView)(component_1.CodeblockComponent, {
contentDOMFactory: () => {
const content = document.createElement("div");
content.classList.add("node-content-wrapper");
content.style.whiteSpace = "inherit";
// caret is not visible if content element width is 0px
content.style.minWidth = `20px`;
return { dom: content };
},
shouldUpdate: ({ attrs: prev }, { attrs: next }) => {
return (compareCaretPosition(prev.caretPosition, next.caretPosition) ||
prev.language !== next.language ||
prev.indentType !== next.indentType);
},
});
},
});
function toCaretPosition(selection, lines) {
const { $from, $to, $head } = selection;
if ($from.parent.type.name !== exports.CodeBlock.name)
return;
lines = lines || getLines($from.parent);
for (const line of lines) {
if ($head.pos >= line.from && $head.pos <= line.to) {
const lineLength = line.length + 1;
return {
line: line.index + 1,
column: lineLength - (line.to - $head.pos),
selected: $to.pos - $from.pos,
total: lines.length,
from: line.from,
};
}
}
return;
}
exports.toCaretPosition = toCaretPosition;
function getLines(node) {
const { lines } = node.attrs;
return lines || [];
}
exports.getLines = getLines;
function exitOnTripleEnter(editor, $from) {
const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2;
const endsWithDoubleNewline = $from.parent.textContent.endsWith("\n\n");
if (!isAtEnd || !endsWithDoubleNewline) {
return false;
}
return editor
.chain()
.command(({ tr }) => {
tr.delete($from.pos - 2, $from.pos);
return true;
})
.exitCode()
.run();
}
function indentOnEnter(editor, $from, options) {
const { indentation, newline } = getNewline($from, options) || {};
if (!newline)
return false;
return editor
.chain()
.insertContent(`${newline}${indentation}`, {
parseOptions: { preserveWhitespace: "full" },
})
.focus()
.run();
}
function getNewline($from, options) {
const { lines } = $from.parent.attrs;
const currentLine = getLineAt(lines, $from.pos);
if (!currentLine)
return false;
const text = currentLine.text();
const indentLength = text.length - text.trimStart().length;
return {
newline: NEWLINE,
indentation: indent({ amount: indentLength, type: options.type }),
};
}
function toCodeLines(code, pos) {
const positions = [];
let start = 0;
let from = pos + 1;
let index = 0;
while (start <= code.length) {
let end = code.indexOf("\n", start);
if (end <= -1)
end = code.length;
const lineLength = end - start;
const to = from + lineLength;
const lineStart = start;
positions.push({
index,
length: lineLength,
from,
to,
text: (length) => {
return code.slice(lineStart, length ? lineStart + length : lineStart + lineLength);
},
});
from = to + 1;
start = end + 1;
++index;
}
return positions;
}
exports.toCodeLines = toCodeLines;
function getSelectedLines(lines, selection) {
const { $from, $to } = selection;
return lines.filter((line) => inRange(line.from, $from.pos, $to.pos) ||
inRange(line.to, $from.pos, $to.pos) ||
inRange($from.pos, line.from, line.to));
}
function parseIndentation(node) {
if (node.type.name !== exports.CodeBlock.name)
return undefined;
const { indentType, indentLength } = node.attrs;
return {
type: indentType,
amount: parseInt(indentLength),
};
}
function getLineAt(lines, pos) {
return lines.find((line) => pos >= line.from && pos <= line.to);
}
function inRange(x, a, b) {
return x >= a && x <= b;
}
function indent(options) {
const char = options.type === "space" ? " " : "\t";
return char.repeat(options.amount);
}
function compareCaretPosition(prev, next) {
return (next === undefined ||
(prev === null || prev === void 0 ? void 0 : prev.column) !== (next === null || next === void 0 ? void 0 : next.column) ||
(prev === null || prev === void 0 ? void 0 : prev.line) !== (next === null || next === void 0 ? void 0 : next.line));
}
/**
* Persist selection between transaction steps
*/
function withSelection(tr, callback) {
const { $anchor, $head } = tr.selection;
callback(tr);
tr.setSelection(new prosemirror_state_1.TextSelection(tr.doc.resolve(tr.mapping.map($anchor.pos)), tr.doc.resolve(tr.mapping.map($head.pos))));
return true;
}
function fixIndentation(code, indent) {
const { amount, type = "space" } = indent || (0, detect_indent_1.default)(code);
const fixed = (0, redent_1.default)(code, amount, {
includeEmptyLines: false,
indent: type === "space" ? " " : "\t",
});
return { code: (0, strip_indent_1.default)(fixed), amount, type };
}

View File

@@ -0,0 +1,149 @@
"use strict";
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 __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeblockComponent = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const loader_1 = require("./loader");
const core_1 = require("refractor/lib/core");
const rebass_1 = require("rebass");
const languages_json_1 = __importDefault(require("./languages.json"));
const forms_1 = require("@rebass/forms");
const icon_1 = require("../../toolbar/components/icon");
const icons_1 = require("../../toolbar/icons");
const responsive_1 = require("../../components/responsive");
const popup_1 = require("../../toolbar/components/popup");
const button_1 = require("../../components/button");
function CodeblockComponent(props) {
const { editor, updateAttributes, node, forwardRef } = props;
const { language, indentLength, indentType, caretPosition } = node === null || node === void 0 ? void 0 : node.attrs;
const [isOpen, setIsOpen] = (0, react_1.useState)(false);
// const [caretPosition, setCaretPosition] = useState<CaretPosition>();
const toolbarRef = (0, react_1.useRef)(null);
const languageDefinition = languages_json_1.default.find((l) => { var _a; return l.filename === language || ((_a = l.alias) === null || _a === void 0 ? void 0 : _a.some((a) => a === language)); });
(0, react_1.useEffect)(() => {
(function () {
return __awaiter(this, void 0, void 0, function* () {
if (!language || !languageDefinition || (0, loader_1.isLanguageLoaded)(language))
return;
const syntax = yield (0, loader_1.loadLanguage)(languageDefinition.filename);
if (!syntax)
return;
core_1.refractor.register(syntax);
updateAttributes({
language: languageDefinition.filename,
});
});
})();
}, [language]);
return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsxs)(rebass_1.Flex, Object.assign({ sx: {
flexDirection: "column",
borderRadius: "default",
overflow: "hidden",
} }, { children: [(0, jsx_runtime_1.jsx)(rebass_1.Text, { ref: forwardRef, as: "pre", sx: {
"div, span.token, span.line-number-widget, span.line-number::before": {
fontFamily: "monospace",
fontSize: "code",
whiteSpace: "pre !important",
tabSize: 1,
},
position: "relative",
lineHeight: "20px",
bg: "codeBg",
color: "static",
overflowX: "auto",
display: "flex",
px: 2,
pt: 2,
pb: 1,
}, spellCheck: false }), (0, jsx_runtime_1.jsxs)(rebass_1.Flex, Object.assign({ ref: toolbarRef, contentEditable: false, sx: {
bg: "codeBg",
alignItems: "center",
justifyContent: "end",
borderTop: "1px solid var(--codeBorder)",
} }, { children: [caretPosition ? ((0, jsx_runtime_1.jsxs)(rebass_1.Text, Object.assign({ variant: "subBody", sx: { mr: 2, color: "codeFg" } }, { children: ["Line ", caretPosition.line, ", Column ", caretPosition.column, " ", caretPosition.selected
? `(${caretPosition.selected} selected)`
: ""] }))) : null, (0, jsx_runtime_1.jsx)(button_1.Button, Object.assign({ variant: "icon", sx: { p: 1, mr: 1, ":hover": { bg: "codeSelection" } }, title: "Toggle indentation mode", onClick: () => {
editor.commands.changeCodeBlockIndentation({
type: indentType === "space" ? "tab" : "space",
amount: indentLength,
});
} }, { children: (0, jsx_runtime_1.jsxs)(rebass_1.Text, Object.assign({ variant: "subBody", sx: { color: "codeFg" } }, { children: [indentType === "space" ? "Spaces" : "Tabs", ": ", indentLength] })) })), (0, jsx_runtime_1.jsx)(button_1.Button, Object.assign({ variant: "icon", sx: {
p: 1,
mr: 1,
bg: isOpen ? "codeSelection" : "transparent",
":hover": { bg: "codeSelection" },
}, onClick: () => {
setIsOpen(true);
}, title: "Change language" }, { children: (0, jsx_runtime_1.jsx)(rebass_1.Text, Object.assign({ variant: "subBody", spellCheck: false, sx: { color: "codeFg" } }, { children: (languageDefinition === null || languageDefinition === void 0 ? void 0 : languageDefinition.title) || "Plaintext" })) }))] }))] })), (0, jsx_runtime_1.jsx)(responsive_1.ResponsivePresenter, Object.assign({ isOpen: isOpen, onClose: () => {
setIsOpen(false);
// NOTE: for some reason the language selection action sheet
// does not return focus to the last focused position after
// closing. We have to set focusOnRender=false & manually
// restore focus. I think this has something to do with custom
// node views.
// TRY: perhaps use SelectionBasedReactNodeView?
editor.commands.focus();
}, focusOnRender: false, mobile: "sheet", desktop: "menu", position: {
target: toolbarRef.current || undefined,
align: "end",
isTargetAbsolute: true,
location: "top",
yOffset: 5,
}, title: "Change code block language" }, { children: (0, jsx_runtime_1.jsx)(LanguageSelector, { selectedLanguage: (languageDefinition === null || languageDefinition === void 0 ? void 0 : languageDefinition.filename) || "Plaintext", onLanguageSelected: (language) => {
updateAttributes({ language });
setIsOpen(false);
}, onClose: () => setIsOpen(false) }) }))] }));
}
exports.CodeblockComponent = CodeblockComponent;
function LanguageSelector(props) {
const { onLanguageSelected, selectedLanguage, onClose } = props;
const [languages, setLanguages] = (0, react_1.useState)(languages_json_1.default);
return ((0, jsx_runtime_1.jsx)(popup_1.Popup, Object.assign({ title: "Select language", onClose: onClose }, { children: (0, jsx_runtime_1.jsxs)(rebass_1.Flex, Object.assign({ sx: {
flexDirection: "column",
height: 200,
width: ["auto", 300],
overflowY: "auto",
bg: "background",
} }, { children: [(0, jsx_runtime_1.jsx)(forms_1.Input, { onFocus: () => {
console.log("EHLLO!");
}, autoFocus: true, 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_json_1.default);
const query = e.target.value.toLowerCase();
setLanguages(languages_json_1.default.filter((lang) => {
var _a;
return (lang.title.toLowerCase().indexOf(query) > -1 ||
((_a = lang.alias) === null || _a === void 0 ? void 0 : _a.some((alias) => alias.toLowerCase().indexOf(query) > -1)));
}));
} }), (0, jsx_runtime_1.jsx)(rebass_1.Flex, Object.assign({ sx: {
flexDirection: "column",
pt: 1,
mt: 1,
} }, { children: languages.map((lang) => ((0, jsx_runtime_1.jsxs)(button_1.Button, Object.assign({ variant: "menuitem", sx: {
textAlign: "left",
py: 1,
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}, onClick: () => onLanguageSelected(lang.filename) }, { children: [(0, jsx_runtime_1.jsx)(rebass_1.Text, Object.assign({ variant: "body" }, { children: lang.title })), selectedLanguage === lang.filename ? ((0, jsx_runtime_1.jsx)(icon_1.Icon, { path: icons_1.Icons.check, size: "small" })) : lang.alias ? ((0, jsx_runtime_1.jsx)(rebass_1.Text, Object.assign({ variant: "subBody", sx: { fontSize: "10px" } }, { children: lang.alias.slice(0, 3).join(", ") }))) : null] }), lang.title))) }))] })) })));
}

View File

@@ -0,0 +1,211 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HighlighterPlugin = void 0;
const prosemirror_state_1 = require("prosemirror-state");
const prosemirror_view_1 = require("prosemirror-view");
const core_1 = require("@tiptap/core");
const core_2 = require("refractor/lib/core");
const codeblock_1 = require("./codeblock");
function parseNodes(nodes, className = []) {
return nodes.reduce((result, node) => {
if (node.type === "comment" || node.type === "doctype")
return result;
const classes = [...className];
if (node.type === "element" && node.properties)
classes.push(...node.properties.className);
// this is required so that even plain text is wrapped in a span
// during highlighting. Without this, Prosemirror's selection acts
// weird for the first highlighted node/span.
else
classes.push("token", "text");
if (node.type === "element") {
result.push(...parseNodes(node.children, classes));
}
else {
result.push({ classes, text: node.value });
}
return result;
}, []);
}
function getHighlightNodes(result) {
return result.children || [];
}
function getLineDecoration(from, line, total, isActive) {
const maxLength = String(total).length;
const attributes = {
class: `line-number ${isActive ? "active" : ""}`,
"data-line": String(line).padEnd(maxLength, " "),
};
const spec = {
line: line,
active: isActive,
total,
from,
};
// Prosemirror has a selection issue with the widget decoration
// on the first line. To work around that we use inline decoration
// for the first line.
if (line === 1 ||
// Android Composition API (aka the virtual keyboard) doesn't behave well
// with Decoration widgets so we have to resort to inline line numbers.
isAndroid()) {
return prosemirror_view_1.Decoration.inline(from, from + 1, attributes, spec);
}
return prosemirror_view_1.Decoration.widget(from, () => {
const element = document.createElement("span");
element.classList.add("line-number-widget");
if (isActive)
element.classList.add("active");
element.innerHTML = attributes["data-line"];
return element;
}, Object.assign(Object.assign({}, spec), {
// should rerender when any of these change:
// 1. line number
// 2. line active state
// 3. the max length of all lines
key: `${line}-${isActive ? "active" : ""}-${maxLength}` }));
}
function getDecorations({ doc, name, defaultLanguage, caretPosition, }) {
const decorations = [];
const languages = core_2.refractor.listLanguages();
(0, core_1.findChildren)(doc, (node) => node.type.name === name).forEach((block) => {
const code = block.node.textContent;
const lines = (0, codeblock_1.toCodeLines)(code, block.pos);
for (const line of lines || []) {
const lineNumber = line.index + 1;
const isActive = lineNumber === (caretPosition === null || caretPosition === void 0 ? void 0 : caretPosition.line) && line.from === (caretPosition === null || caretPosition === void 0 ? void 0 : caretPosition.from);
const decoration = getLineDecoration(line.from, lineNumber, (lines === null || lines === void 0 ? void 0 : lines.length) || 0, isActive);
decorations.push(decoration);
}
const language = block.node.attrs.language || defaultLanguage;
const nodes = languages.includes(language)
? getHighlightNodes(core_2.refractor.highlight(code, language))
: null;
if (!nodes)
return;
let from = block.pos + 1;
parseNodes(nodes).forEach((node) => {
const to = from + node.text.length;
if (node.classes.length) {
const decoration = prosemirror_view_1.Decoration.inline(from, to, {
class: node.classes.join(" "),
});
decorations.push(decoration);
}
from = to;
});
});
return prosemirror_view_1.DecorationSet.create(doc, decorations);
}
function HighlighterPlugin({ name, defaultLanguage, }) {
const key = new prosemirror_state_1.PluginKey("highlighter");
return new prosemirror_state_1.Plugin({
key,
state: {
init: () => {
return prosemirror_view_1.DecorationSet.empty;
},
apply: (transaction, decorationSet, oldState, newState) => {
const oldNodeName = oldState.selection.$head.parent.type.name;
const newNodeName = newState.selection.$head.parent.type.name;
const oldNodes = (0, core_1.findChildren)(oldState.doc, (node) => node.type.name === name);
const newNodes = (0, core_1.findChildren)(newState.doc, (node) => node.type.name === name);
const position = (0, codeblock_1.toCaretPosition)(newState.selection);
// const isDocChanged =
// transaction.docChanged &&
// // TODO
// !transaction.steps.every((step) => step instanceof ReplaceAroundStep);
// console.log("Selection", transaction.docChanged, isDocChanged);
if (transaction.docChanged &&
// Apply decorations if:
// selection includes named node,
([oldNodeName, newNodeName].includes(name) ||
// OR transaction adds/removes named node,
newNodes.length !== oldNodes.length ||
// OR transaction has changes that completely encapsulte a node
// (for example, a transaction that affects the entire document).
// Such transactions can happen during collab syncing via y-prosemirror, for example.
transaction.steps.some((step) => {
return (step.from !== undefined &&
step.to !== undefined &&
oldNodes.some((node) => {
return (node.pos >= step.from &&
node.pos + node.node.nodeSize <= step.to);
}));
}))) {
return getDecorations({
doc: transaction.doc,
name,
defaultLanguage,
caretPosition: position,
});
}
decorationSet = getActiveLineDecorations(transaction.doc, decorationSet, position);
return decorationSet.map(transaction.mapping, transaction.doc);
},
},
props: {
decorations(state) {
return key.getState(state);
},
},
appendTransaction: (transactions, prevState, nextState) => {
const tr = nextState.tr;
let modified = false;
const docChanged = transactions.some((transaction) => transaction.docChanged);
const selectionChanged = (nextState.selection.$from.parent.type.name === name ||
prevState.selection.$from.parent.type.name === name) &&
prevState.selection.$from.pos !== nextState.selection.$from.pos;
(0, core_1.findChildren)(nextState.doc, (node) => node.type.name === name).forEach((block) => {
const { node, pos } = block;
const attributes = Object.assign({}, node.attrs);
if (docChanged) {
const lines = (0, codeblock_1.toCodeLines)(node.textContent, pos);
attributes.lines = lines.slice();
}
if (selectionChanged) {
const position = (0, codeblock_1.toCaretPosition)(nextState.selection, docChanged ? (0, codeblock_1.toCodeLines)(node.textContent, pos) : undefined);
attributes.caretPosition = position;
}
if (docChanged || selectionChanged) {
tr.setNodeMarkup(pos, node.type, attributes);
modified = true;
}
});
return modified ? tr : null;
},
});
}
exports.HighlighterPlugin = HighlighterPlugin;
/**
* When `position` is undefined, all active line decorations
* are reset (e.g. when you focus out of the code block).
*/
function getActiveLineDecorations(doc, decorations, position) {
const lineDecorations = decorations.find(undefined, undefined, ({ line, active, from }) => {
const isSame = position
? line === position.line && from === position.from
: false;
return isSame || active;
});
if (!lineDecorations.length)
return decorations;
// we have to clone because prosemirror operates in-place
const cloned = lineDecorations.slice();
// remove old line decorations which inclue the current line decoration
// and the previous current line decoration. We'll replace these with
// new decorations.
decorations = decorations.remove(lineDecorations);
const newDecorations = [];
for (const decoration of cloned) {
const { from, spec: { line, total }, } = decoration;
const isActive = line === (position === null || position === void 0 ? void 0 : position.line);
const newDecoration = getLineDecoration(from, line, (position === null || position === void 0 ? void 0 : position.total) || total, isActive);
newDecorations.push(newDecoration);
}
return decorations.add(doc, newDecorations);
}
function isAndroid() {
var ua = navigator.userAgent.toLowerCase();
return ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
}

View File

@@ -0,0 +1,50 @@
"use strict";
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());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadLanguage = exports.isLanguageLoaded = void 0;
const loadedLanguages = {};
function isLanguageLoaded(name) {
return !!loadedLanguages[name];
}
exports.isLanguageLoaded = isLanguageLoaded;
function loadLanguage(shortName) {
return __awaiter(this, void 0, void 0, function* () {
if (loadedLanguages[shortName])
return loadedLanguages[shortName];
const url = `https://esm.sh/refractor@4.7.0/lang/${shortName}.js?bundle=true`;
const result = yield loadScript(shortName, url);
loadedLanguages[shortName] = result;
return result;
});
}
exports.loadLanguage = loadLanguage;
function loadScript(id, url) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
const callbackName = `on${id}Loaded`;
const script = document.createElement("script");
script.type = "module";
script.innerHTML = `
import LanguageDefinition from "${url}";
if (window["${callbackName}"]) {
window["${callbackName}"](LanguageDefinition)
}
`;
window[callbackName] = (lang) => {
script.remove();
window[callbackName] = null;
resolve(lang);
};
// Append to the `head` element
document.head.appendChild(script);
});
});
}

View File

@@ -4,11 +4,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Codemark = void 0;
var core_1 = require("@tiptap/core");
var prosemirror_codemark_1 = __importDefault(require("prosemirror-codemark"));
const core_1 = require("@tiptap/core");
const prosemirror_codemark_1 = __importDefault(require("prosemirror-codemark"));
exports.Codemark = core_1.Extension.create({
name: "codemarkPlugin",
addProseMirrorPlugins: function () {
addProseMirrorPlugins() {
return (0, prosemirror_codemark_1.default)({ markType: this.editor.schema.marks.code });
},
});

View File

@@ -1,18 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Dropcursor = void 0;
var core_1 = require("@tiptap/core");
var dropcursor_pm_1 = require("./dropcursor.pm");
const core_1 = require("@tiptap/core");
const dropcursor_pm_1 = require("./dropcursor.pm");
exports.Dropcursor = core_1.Extension.create({
name: "dropCursor",
addOptions: function () {
addOptions() {
return {
color: "currentColor",
width: 1,
class: null,
};
},
addProseMirrorPlugins: function () {
addProseMirrorPlugins() {
return [(0, dropcursor_pm_1.dropCursor)(this.options)];
},
});

View File

@@ -1,8 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dropCursor = void 0;
var prosemirror_state_1 = require("prosemirror-state");
var prosemirror_transform_1 = require("prosemirror-transform");
const prosemirror_state_1 = require("prosemirror-state");
const prosemirror_transform_1 = require("prosemirror-transform");
// :: (options: ?Object) → Plugin
// Create a plugin that, when added to a ProseMirror instance,
// causes a decoration to show up at the drop position when something
@@ -23,18 +23,16 @@ var prosemirror_transform_1 = require("prosemirror-transform");
//
// class:: ?string
// A CSS class name to add to the cursor element.
function dropCursor(options) {
if (options === void 0) { options = {}; }
function dropCursor(options = {}) {
return new prosemirror_state_1.Plugin({
view: function (editorView) {
view(editorView) {
return new DropCursorView(editorView, options);
},
});
}
exports.dropCursor = dropCursor;
var DropCursorView = /** @class */ (function () {
function DropCursorView(editorView, options) {
var _this = this;
class DropCursorView {
constructor(editorView, options) {
this.editorView = editorView;
this.width = options.width || 1;
this.color = options.color || "black";
@@ -42,28 +40,24 @@ var DropCursorView = /** @class */ (function () {
this.cursorPos = null;
this.element = null;
this.timeout = null;
this.handlers = ["dragover", "dragend", "drop", "dragleave"].map(function (name) {
var handler = function (e) { return _this[name](e); };
this.handlers = ["dragover", "dragend", "drop", "dragleave"].map((name) => {
let handler = (e) => this[name](e);
editorView.dom.addEventListener(name, handler);
return { name: name, handler: handler };
return { name, handler };
});
}
DropCursorView.prototype.destroy = function () {
var _this = this;
this.handlers.forEach(function (_a) {
var name = _a.name, handler = _a.handler;
return _this.editorView.dom.removeEventListener(name, handler);
});
};
DropCursorView.prototype.update = function (editorView, prevState) {
destroy() {
this.handlers.forEach(({ name, handler }) => this.editorView.dom.removeEventListener(name, handler));
}
update(editorView, prevState) {
if (this.cursorPos != null && prevState.doc != editorView.state.doc) {
if (this.cursorPos > editorView.state.doc.content.size)
this.setCursor(null);
else
this.updateOverlay();
}
};
DropCursorView.prototype.setCursor = function (pos) {
}
setCursor(pos) {
if (pos == this.cursorPos)
return;
this.cursorPos = pos;
@@ -74,35 +68,35 @@ var DropCursorView = /** @class */ (function () {
else {
this.updateOverlay();
}
};
DropCursorView.prototype.updateOverlay = function () {
}
updateOverlay() {
if (!this.cursorPos)
return;
var $pos = this.editorView.state.doc.resolve(this.cursorPos), rect;
let $pos = this.editorView.state.doc.resolve(this.cursorPos), rect;
if (!$pos.parent.inlineContent) {
var before = $pos.nodeBefore, after = $pos.nodeAfter;
let before = $pos.nodeBefore, after = $pos.nodeAfter;
if (before || after) {
var node = this.editorView.nodeDOM(this.cursorPos - (before ? before.nodeSize : 0));
const node = this.editorView.nodeDOM(this.cursorPos - (before ? before.nodeSize : 0));
if (!node)
return;
var nodeRect = node.getBoundingClientRect();
var top_1 = before ? nodeRect.bottom : nodeRect.top;
let nodeRect = node.getBoundingClientRect();
let top = before ? nodeRect.bottom : nodeRect.top;
if (before && after) {
var cursor = this.editorView.nodeDOM(this.cursorPos);
const cursor = this.editorView.nodeDOM(this.cursorPos);
if (!cursor)
return;
top_1 = (top_1 + cursor.getBoundingClientRect().top) / 2;
top = (top + cursor.getBoundingClientRect().top) / 2;
}
rect = {
left: nodeRect.left,
right: nodeRect.right,
top: top_1 - this.width / 2,
bottom: top_1 + this.width / 2,
top: top - this.width / 2,
bottom: top + this.width / 2,
};
}
}
if (!rect) {
var coords = this.editorView.coordsAtPos(this.cursorPos);
let coords = this.editorView.coordsAtPos(this.cursorPos);
rect = {
left: coords.left - this.width / 2,
right: coords.left + this.width / 2,
@@ -110,7 +104,7 @@ var DropCursorView = /** @class */ (function () {
bottom: coords.bottom,
};
}
var parent = this.editorView.dom.offsetParent;
let parent = this.editorView.dom.offsetParent;
if (!this.element && parent) {
this.element = parent.appendChild(document.createElement("div"));
if (this.class)
@@ -119,16 +113,16 @@ var DropCursorView = /** @class */ (function () {
"position: absolute; z-index: 50; pointer-events: none; background-color: " +
this.color;
}
var parentLeft, parentTop;
let parentLeft, parentTop;
if (!parent ||
(parent == document.body && getComputedStyle(parent).position == "static")) {
parentLeft = -pageXOffset;
parentTop = -pageYOffset;
}
else {
var rect_1 = parent.getBoundingClientRect();
parentLeft = rect_1.left - parent.scrollLeft;
parentTop = rect_1.top - parent.scrollTop;
let rect = parent.getBoundingClientRect();
parentLeft = rect.left - parent.scrollLeft;
parentTop = rect.top - parent.scrollTop;
}
if (!this.element)
return;
@@ -136,28 +130,27 @@ var DropCursorView = /** @class */ (function () {
this.element.style.top = rect.top - parentTop + "px";
this.element.style.width = rect.right - rect.left + "px";
this.element.style.height = rect.bottom - rect.top + "px";
};
DropCursorView.prototype.scheduleRemoval = function (timeout) {
var _this = this;
}
scheduleRemoval(timeout) {
clearTimeout(this.timeout || undefined);
this.timeout = (setTimeout(function () { return _this.setCursor(null); }, timeout));
};
DropCursorView.prototype.dragover = function (event) {
this.timeout = (setTimeout(() => this.setCursor(null), timeout));
}
dragover(event) {
if (!this.editorView.editable)
return;
var pos = this.editorView.posAtCoords({
let pos = this.editorView.posAtCoords({
left: event.clientX,
top: event.clientY,
});
var node = pos && pos.inside >= 0 && this.editorView.state.doc.nodeAt(pos.inside);
var disableDropCursor = node && node.type.spec.disableDropCursor;
var disabled = typeof disableDropCursor == "function"
let node = pos && pos.inside >= 0 && this.editorView.state.doc.nodeAt(pos.inside);
let disableDropCursor = node && node.type.spec.disableDropCursor;
let disabled = typeof disableDropCursor == "function"
? disableDropCursor(this.editorView, pos)
: disableDropCursor;
if (pos && !disabled) {
var target = pos.pos;
let target = pos.pos;
if (this.editorView.dragging && this.editorView.dragging.slice) {
var point = (0, prosemirror_transform_1.dropPoint)(this.editorView.state.doc, target, this.editorView.dragging.slice);
const point = (0, prosemirror_transform_1.dropPoint)(this.editorView.state.doc, target, this.editorView.dragging.slice);
if (!point)
return this.setCursor(null);
target = point;
@@ -165,17 +158,16 @@ var DropCursorView = /** @class */ (function () {
this.setCursor(target);
this.scheduleRemoval(5000);
}
};
DropCursorView.prototype.dragend = function () {
}
dragend() {
this.scheduleRemoval(20);
};
DropCursorView.prototype.drop = function () {
}
drop() {
this.scheduleRemoval(20);
};
DropCursorView.prototype.dragleave = function (event) {
}
dragleave(event) {
if (event.target == this.editorView.dom ||
!this.editorView.dom.contains(event.relatedTarget))
this.setCursor(null);
};
return DropCursorView;
}());
}
}

View File

@@ -14,6 +14,6 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
var dropcursor_1 = require("./dropcursor");
const dropcursor_1 = require("./dropcursor");
__exportStar(require("./dropcursor"), exports);
exports.default = dropcursor_1.Dropcursor;

View File

@@ -1,31 +1,20 @@
"use strict";
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);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EmbedComponent = void 0;
var jsx_runtime_1 = require("react/jsx-runtime");
var rebass_1 = require("rebass");
var re_resizable_1 = require("re-resizable");
var react_1 = require("react");
var responsive_1 = require("../../components/responsive");
var toolbargroup_1 = require("../../toolbar/components/toolbargroup");
const jsx_runtime_1 = require("react/jsx-runtime");
const rebass_1 = require("rebass");
const re_resizable_1 = require("re-resizable");
const react_1 = require("react");
const responsive_1 = require("../../components/responsive");
const toolbargroup_1 = require("../../toolbar/components/toolbargroup");
function EmbedComponent(props) {
var editor = props.editor, updateAttributes = props.updateAttributes, selected = props.selected, node = props.node;
var embedRef = (0, react_1.useRef)();
var _a = node.attrs, src = _a.src, width = _a.width, height = _a.height, align = _a.align;
return ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: (0, jsx_runtime_1.jsx)(rebass_1.Box, __assign({ sx: {
const { editor, updateAttributes, selected, node } = props;
const embedRef = (0, react_1.useRef)();
const { src, width, height, align } = node.attrs;
return ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: (0, jsx_runtime_1.jsx)(rebass_1.Box, Object.assign({ sx: {
display: "flex",
justifyContent: align === "center" ? "center" : align === "left" ? "start" : "end",
} }, { children: (0, jsx_runtime_1.jsxs)(re_resizable_1.Resizable, __assign({ enable: {
} }, { children: (0, jsx_runtime_1.jsxs)(re_resizable_1.Resizable, Object.assign({ enable: {
bottom: editor.isEditable,
left: editor.isEditable,
right: editor.isEditable,
@@ -37,12 +26,12 @@ function EmbedComponent(props) {
}, size: {
height: height || "auto",
width: width || "auto",
}, maxWidth: "100%", onResizeStop: function (e, direction, ref, d) {
}, maxWidth: "100%", onResizeStop: (e, direction, ref, d) => {
updateAttributes({
width: ref.clientWidth,
height: ref.clientHeight,
});
}, lockAspectRatio: true }, { children: [(0, jsx_runtime_1.jsx)(rebass_1.Flex, __assign({ width: "100%", sx: {
}, lockAspectRatio: true }, { children: [(0, jsx_runtime_1.jsx)(rebass_1.Flex, Object.assign({ width: "100%", sx: {
position: "relative",
justifyContent: "end",
borderTop: editor.isEditable
@@ -55,7 +44,7 @@ function EmbedComponent(props) {
":hover": {
borderColor: "border",
},
} }, { children: (0, jsx_runtime_1.jsx)(responsive_1.DesktopOnly, { children: selected && ((0, jsx_runtime_1.jsx)(rebass_1.Flex, __assign({ sx: { position: "relative", justifyContent: "end" } }, { children: (0, jsx_runtime_1.jsx)(rebass_1.Flex, __assign({ sx: {
} }, { children: (0, jsx_runtime_1.jsx)(responsive_1.DesktopOnly, { children: selected && ((0, jsx_runtime_1.jsx)(rebass_1.Flex, Object.assign({ sx: { position: "relative", justifyContent: "end" } }, { children: (0, jsx_runtime_1.jsx)(rebass_1.Flex, Object.assign({ sx: {
position: "absolute",
top: -40,
mb: 2,
@@ -69,7 +58,7 @@ function EmbedComponent(props) {
boxShadow: "menu",
borderRadius: "default",
bg: "background",
} }) })) }))) }) })), (0, jsx_runtime_1.jsx)(rebass_1.Box, __assign({ as: "iframe", ref: embedRef, src: src, width: "100%", height: "100%", sx: {
} }) })) }))) }) })), (0, jsx_runtime_1.jsx)(rebass_1.Box, Object.assign({ as: "iframe", ref: embedRef, src: src, width: "100%", height: "100%", sx: {
border: selected
? "2px solid var(--primary)"
: "2px solid transparent",

View File

@@ -0,0 +1,65 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EmbedNode = void 0;
const core_1 = require("@tiptap/core");
const react_1 = require("../react");
const component_1 = require("./component");
exports.EmbedNode = core_1.Node.create({
name: "embed",
content: "",
marks: "",
draggable: true,
addOptions() {
return {
HTMLAttributes: {},
};
},
group() {
return "block";
},
addAttributes() {
return {
src: {
default: null,
},
width: { default: null },
height: { default: null },
align: { default: "left" },
};
},
parseHTML() {
return [
{
tag: "iframe[src]",
},
];
},
renderHTML({ HTMLAttributes }) {
return [
"iframe",
(0, core_1.mergeAttributes)(this.options.HTMLAttributes, HTMLAttributes),
];
},
addNodeView() {
return (0, react_1.createSelectionBasedNodeView)(component_1.EmbedComponent);
},
addCommands() {
return {
insertEmbed: (options) => ({ commands }) => {
return commands.insertContent({
type: this.name,
attrs: options,
});
},
setEmbedAlignment: (options) => ({ commands }) => {
return commands.updateAttributes(this.name, Object.assign({}, options));
},
setEmbedSize: (options) => ({ commands }) => {
return commands.updateAttributes(this.name, Object.assign({}, options));
},
setEmbedSource: (src) => ({ commands }) => {
return commands.updateAttributes(this.name, { src });
},
};
},
});

View File

@@ -0,0 +1,46 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FontSize = void 0;
const core_1 = require("@tiptap/core");
require("@tiptap/extension-text-style");
exports.FontSize = core_1.Extension.create({
name: "fontSize",
defaultOptions: {
types: ["textStyle"],
defaultFontSize: 16,
},
addGlobalAttributes() {
return [
{
types: this.options.types,
attributes: {
fontSize: {
default: `${this.options.defaultFontSize}px`,
parseHTML: (element) => element.style.fontSize,
renderHTML: (attributes) => {
if (!attributes.fontSize) {
return {};
}
return {
style: `font-size: ${attributes.fontSize}`,
};
},
},
},
},
];
},
addCommands() {
return {
setFontSize: (fontSize) => ({ chain }) => {
return chain().setMark("textStyle", { fontSize }).run();
},
unsetFontSize: () => ({ chain }) => {
return chain()
.setMark("textStyle", { fontSize: null })
.removeEmptyTextStyle()
.run();
},
};
},
});

View File

@@ -14,6 +14,6 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
var fontsize_1 = require("./fontsize");
const fontsize_1 = require("./fontsize");
__exportStar(require("./fontsize"), exports);
exports.default = fontsize_1.FontSize;

View File

@@ -0,0 +1,106 @@
"use strict";
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());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ImageComponent = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const rebass_1 = require("rebass");
const re_resizable_1 = require("re-resizable");
const react_1 = require("react");
const responsive_1 = require("../../components/responsive");
const toolbargroup_1 = require("../../toolbar/components/toolbargroup");
function ImageComponent(props) {
const { editor, updateAttributes, node, selected } = props;
const { src, alt, title, width, height, align, float } = node.attrs;
const imageRef = (0, react_1.useRef)();
(0, react_1.useEffect)(() => {
(() => __awaiter(this, void 0, void 0, function* () {
if (!imageRef.current || !src)
return;
imageRef.current.src = yield dataUriToBlobURL(src);
}))();
}, [src, imageRef]);
return ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: (0, jsx_runtime_1.jsx)(rebass_1.Box, Object.assign({ sx: {
display: float ? "block" : "flex",
justifyContent: float
? "stretch"
: align === "center"
? "center"
: align === "left"
? "start"
: "end",
":hover .drag-handle, :active .drag-handle": {
opacity: 1,
},
} }, { children: (0, jsx_runtime_1.jsxs)(re_resizable_1.Resizable, Object.assign({ enable: {
bottom: editor.isEditable,
left: editor.isEditable,
right: editor.isEditable,
top: editor.isEditable,
bottomLeft: editor.isEditable,
bottomRight: editor.isEditable,
topLeft: editor.isEditable,
topRight: editor.isEditable,
}, style: {
position: "relative",
float: float ? (align === "left" ? "left" : "right") : "none",
}, size: {
height: height || "auto",
width: width || "auto",
}, maxWidth: "100%", onResizeStop: (e, direction, ref, d) => {
updateAttributes({
width: ref.clientWidth,
height: ref.clientHeight,
});
}, lockAspectRatio: true }, { children: [(0, jsx_runtime_1.jsx)(rebass_1.Flex, Object.assign({ width: "100%", "data-drag-handle": true, draggable: true, sx: {
position: "relative",
justifyContent: "end",
borderTop: editor.isEditable
? "20px solid var(--bgSecondary)"
: "none",
borderTopLeftRadius: "default",
borderTopRightRadius: "default",
borderColor: selected ? "border" : "bgSecondary",
cursor: "pointer",
":hover": {
borderColor: "border",
},
} }, { children: (0, jsx_runtime_1.jsx)(responsive_1.DesktopOnly, { children: selected && ((0, jsx_runtime_1.jsx)(rebass_1.Flex, Object.assign({ sx: { position: "relative", justifyContent: "end" } }, { children: (0, jsx_runtime_1.jsx)(rebass_1.Flex, Object.assign({ sx: {
position: "absolute",
top: -40,
mb: 2,
alignItems: "end",
} }, { children: (0, jsx_runtime_1.jsx)(toolbargroup_1.ToolbarGroup, { editor: editor, tools: [
"imageAlignLeft",
"imageAlignCenter",
"imageAlignRight",
"imageProperties",
], sx: {
boxShadow: "menu",
borderRadius: "default",
bg: "background",
} }) })) }))) }) })), (0, jsx_runtime_1.jsx)(rebass_1.Image, Object.assign({ "data-drag-image": true, ref: imageRef, alt: alt, src: "/placeholder.svg", title: title, width: "100%", height: "100%", sx: {
bg: "bgSecondary",
border: selected
? "2px solid var(--primary)"
: "2px solid transparent",
borderRadius: "default",
} }, props))] })) })) }));
}
exports.ImageComponent = ImageComponent;
function dataUriToBlobURL(dataurl) {
return __awaiter(this, void 0, void 0, function* () {
if (!dataurl.startsWith("data:image"))
return dataurl;
const response = yield fetch(dataurl);
const blob = yield response.blob();
return URL.createObjectURL(blob);
});
}

View File

@@ -0,0 +1,109 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ImageNode = exports.inputRegex = void 0;
const core_1 = require("@tiptap/core");
const attachment_1 = require("../attachment");
const react_1 = require("../react");
const component_1 = require("./component");
exports.inputRegex = /(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/;
exports.ImageNode = core_1.Node.create({
name: "image",
addOptions() {
return {
inline: false,
allowBase64: false,
HTMLAttributes: {},
};
},
inline() {
return this.options.inline;
},
group() {
return this.options.inline ? "inline" : "block";
},
draggable: true,
addAttributes() {
return {
src: {
default: null,
},
alt: {
default: null,
},
title: {
default: null,
},
width: { default: null },
height: { default: null },
float: (0, attachment_1.getDataAttribute)("float", false),
align: (0, attachment_1.getDataAttribute)("align", "left"),
hash: (0, attachment_1.getDataAttribute)("hash"),
filename: (0, attachment_1.getDataAttribute)("filename"),
type: (0, attachment_1.getDataAttribute)("mime"),
size: (0, attachment_1.getDataAttribute)("size"),
};
},
parseHTML() {
return [
{
tag: this.options.allowBase64 ? "img" : 'img:not([src^="data:"])',
},
];
},
renderHTML({ HTMLAttributes }) {
return [
"img",
(0, core_1.mergeAttributes)(this.options.HTMLAttributes, HTMLAttributes),
];
},
addNodeView() {
return (0, react_1.createSelectionBasedNodeView)(component_1.ImageComponent);
},
addCommands() {
return {
insertImage: (options) => ({ commands }) => {
return commands.insertContent({
type: this.name,
attrs: options,
});
},
setImageAlignment: (options) => ({ commands }) => {
return commands.updateAttributes(this.name, Object.assign({}, options));
},
setImageSize: (options) => ({ commands }) => {
return commands.updateAttributes(this.name, Object.assign({}, options));
},
updateImage: (options) => ({ state, tr, dispatch }) => {
const query = options.hash
? { key: "hash", value: options.hash }
: options.src
? { key: "src", value: options.src }
: null;
if (!query)
return false;
const images = (0, core_1.findChildren)(state.doc, (node) => node.type.name === this.name &&
node.attrs[query.key] === query.value);
for (const image of images) {
tr.setNodeMarkup(image.pos, image.node.type, Object.assign(Object.assign({}, image.node.attrs), options));
}
tr.setMeta("preventUpdate", true);
tr.setMeta("addToHistory", false);
if (dispatch)
dispatch(tr);
return true;
},
};
},
addInputRules() {
return [
(0, core_1.nodeInputRule)({
find: exports.inputRegex,
type: this.type,
getAttributes: (match) => {
const [, , alt, src, title] = match;
return { src, alt, title };
},
}),
];
},
});

View File

@@ -1,19 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.onBackspacePressed = void 0;
var prosemirror_utils_1 = require("prosemirror-utils");
const prosemirror_utils_1 = require("prosemirror-utils");
// WORKAROUND: if we're at the start of a list item, we need to either
// backspace directly to an empty list item above, or outdent this node
function onBackspacePressed(editor, name, type) {
var selection = editor.state.selection;
var empty = selection.empty, $from = selection.$from;
const { selection } = editor.state;
const { empty, $from } = selection;
if (!empty ||
!isInside(name, type, editor.state) ||
$from.parentOffset !== 0 ||
!isFirstChildOfParent(editor.state) ||
!editor.can().liftListItem(type))
return false;
var isEmpty = isListItemEmpty(type, editor.state);
const isEmpty = isListItemEmpty(type, editor.state);
if (isFirstOfType(type, editor.state)) {
return editor.commands.liftListItem(type);
}
@@ -29,30 +29,30 @@ function onBackspacePressed(editor, name, type) {
}
exports.onBackspacePressed = onBackspacePressed;
function isInside(name, type, state) {
var $from = state.selection.$from;
var node = type || state.schema.nodes[name];
var paragraph = state.schema.nodes.paragraph;
const { $from } = state.selection;
let node = type || state.schema.nodes[name];
const { paragraph } = state.schema.nodes;
return ((0, prosemirror_utils_1.hasParentNodeOfType)(node)(state.selection) &&
$from.parent.type === paragraph);
}
function isFirstChildOfParent(state) {
var $from = state.selection.$from;
const { $from } = state.selection;
return $from.depth > 1
? $from.parentOffset === 0 || $from.index($from.depth - 1) === 0
: true;
}
var isFirstOfType = function (type, state) {
var block = (0, prosemirror_utils_1.findParentNodeOfType)(type)(state.selection);
const isFirstOfType = (type, state) => {
const block = (0, prosemirror_utils_1.findParentNodeOfType)(type)(state.selection);
if (!block)
return false;
var pos = block.pos;
var resolved = state.doc.resolve(pos);
const { pos } = block;
const resolved = state.doc.resolve(pos);
return !resolved.nodeBefore;
};
function isListItemEmpty(type, state) {
var block = (0, prosemirror_utils_1.findParentNodeOfType)(type)(state.selection);
const block = (0, prosemirror_utils_1.findParentNodeOfType)(type)(state.selection);
if (!block)
return false;
var node = block.node;
const { node } = block;
return !node.textContent.length;
}

View File

@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ListItem = void 0;
const extension_list_item_1 = require("@tiptap/extension-list-item");
const commands_1 = require("./commands");
exports.ListItem = extension_list_item_1.ListItem.extend({
addKeyboardShortcuts() {
var _a;
return Object.assign(Object.assign({}, (_a = this.parent) === null || _a === void 0 ? void 0 : _a.call(this)), { Backspace: ({ editor }) => (0, commands_1.onBackspacePressed)(editor, this.name, this.type) });
},
});

View File

@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MathBlock = void 0;
const core_1 = require("@tiptap/core");
const prosemirror_inputrules_1 = require("prosemirror-inputrules");
const plugin_1 = require("./plugin");
exports.MathBlock = core_1.Node.create({
name: "mathBlock",
group: "block math",
content: "text*",
atom: true,
code: true,
parseHTML() {
return [
{
tag: `div[class*='math-block']`, // important!
},
];
},
renderHTML({ HTMLAttributes }) {
return [
"div",
(0, core_1.mergeAttributes)({ class: "math-block math-node" }, HTMLAttributes),
0,
];
},
addCommands() {
return {
insertMathBlock: () => ({ state, dispatch, view }) => {
return (0, plugin_1.insertMathNode)(this.type)(state, dispatch, view);
},
};
},
addProseMirrorPlugins() {
const inputRulePlugin = (0, prosemirror_inputrules_1.inputRules)({
rules: [(0, plugin_1.makeBlockMathInputRule)(plugin_1.REGEX_BLOCK_MATH_DOLLARS, this.type)],
});
return [inputRulePlugin];
},
});

View File

@@ -1,9 +1,9 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MathInline = void 0;
var core_1 = require("@tiptap/core");
var prosemirror_inputrules_1 = require("prosemirror-inputrules");
var plugin_1 = require("./plugin");
const core_1 = require("@tiptap/core");
const prosemirror_inputrules_1 = require("prosemirror-inputrules");
const plugin_1 = require("./plugin");
exports.MathInline = core_1.Node.create({
name: "mathInline",
group: "inline math",
@@ -11,34 +11,29 @@ exports.MathInline = core_1.Node.create({
inline: true,
atom: true,
code: true,
parseHTML: function () {
parseHTML() {
return [
{
tag: "span[class*='math-inline']", // important!,
},
];
},
renderHTML: function (_a) {
var HTMLAttributes = _a.HTMLAttributes;
renderHTML({ HTMLAttributes }) {
return [
"span",
(0, core_1.mergeAttributes)({ class: "math-inline math-node" }, HTMLAttributes),
0,
];
},
addCommands: function () {
var _this = this;
addCommands() {
return {
insertMathInline: function () {
return function (_a) {
var state = _a.state, dispatch = _a.dispatch, view = _a.view;
return (0, plugin_1.insertMathNode)(_this.type)(state, dispatch, view);
};
insertMathInline: () => ({ state, dispatch, view }) => {
return (0, plugin_1.insertMathNode)(this.type)(state, dispatch, view);
},
};
},
addProseMirrorPlugins: function () {
var inputRulePlugin = (0, prosemirror_inputrules_1.inputRules)({
addProseMirrorPlugins() {
const inputRulePlugin = (0, prosemirror_inputrules_1.inputRules)({
rules: [(0, plugin_1.makeInlineMathInputRule)(plugin_1.REGEX_INLINE_MATH_DOLLARS, this.type)],
});
return [plugin_1.mathPlugin, inputRulePlugin];

View File

@@ -1,7 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.collapseMathNode = void 0;
var prosemirror_state_1 = require("prosemirror-state");
const prosemirror_state_1 = require("prosemirror-state");
/**
* A ProseMirror command for determining whether to exit a math block, based on
* specific conditions. Normally called when the user has
@@ -15,24 +15,23 @@ var prosemirror_state_1 = require("prosemirror-state");
* (inner) selection is empty.
* @returns A new ProseMirror command based on the input configuration.
*/
function collapseMathNode(outerView, dir, requireOnBorder, requireEmptySelection) {
if (requireEmptySelection === void 0) { requireEmptySelection = true; }
function collapseMathNode(outerView, dir, requireOnBorder, requireEmptySelection = true) {
// create a new ProseMirror command based on the input conditions
return function (innerState, dispatch) {
return (innerState, dispatch) => {
// get selection info
var outerState = outerView.state;
var _a = outerState.selection, outerTo = _a.to, outerFrom = _a.from;
var _b = innerState.selection, innerTo = _b.to, innerFrom = _b.from;
let outerState = outerView.state;
let { to: outerTo, from: outerFrom } = outerState.selection;
let { to: innerTo, from: innerFrom } = innerState.selection;
// only exit math node when selection is empty
if (requireEmptySelection && innerTo !== innerFrom) {
return false;
}
var currentPos = dir > 0 ? innerTo : innerFrom;
let currentPos = dir > 0 ? innerTo : innerFrom;
// when requireOnBorder is TRUE, collapse only when cursor
// is about to leave the bounds of the math node
if (requireOnBorder) {
// (subtract two from nodeSize to account for start and end tokens)
var nodeSize = innerState.doc.nodeSize - 2;
let nodeSize = innerState.doc.nodeSize - 2;
// early return if exit conditions not met
if (dir > 0 && currentPos < nodeSize) {
return false;
@@ -44,7 +43,7 @@ function collapseMathNode(outerView, dir, requireOnBorder, requireEmptySelection
// all exit conditions met, so close the math node by moving the cursor outside
if (dispatch) {
// set outer selection to be outside of the nodeview
var targetPos = dir > 0 ? outerTo : outerFrom;
let targetPos = dir > 0 ? outerTo : outerFrom;
outerView.dispatch(outerState.tr.setSelection(prosemirror_state_1.TextSelection.create(outerState.doc, targetPos)));
// must return focus to the outer view, otherwise no cursor will appear
outerView.focus();

View File

@@ -1,7 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.insertMathNode = void 0;
var prosemirror_state_1 = require("prosemirror-state");
const prosemirror_state_1 = require("prosemirror-state");
////////////////////////////////////////////////////////////////////////////////
/**
* Returns a new command that can be used to inserts a new math node at the
@@ -12,16 +12,15 @@ var prosemirror_state_1 = require("prosemirror-state");
* NodeType. Must belong to the same schema that your EditorState uses!
* @param initialText (optional) The initial source content for the math editor.
*/
function insertMathNode(mathNodeType, initialText) {
if (initialText === void 0) { initialText = ""; }
function insertMathNode(mathNodeType, initialText = "") {
return function (state, dispatch) {
var $from = state.selection.$from, index = $from.index();
let { $from } = state.selection, index = $from.index();
if (!$from.parent.canReplaceWith(index, index, mathNodeType)) {
return false;
}
if (dispatch) {
var mathNode = mathNodeType.create({}, initialText ? state.schema.text(initialText) : null);
var tr = state.tr.replaceSelectionWith(mathNode);
let mathNode = mathNodeType.create({}, initialText ? state.schema.text(initialText) : null);
let tr = state.tr.replaceSelectionWith(mathNode);
tr = tr.setSelection(prosemirror_state_1.NodeSelection.create(tr.doc, $from.pos));
dispatch(tr);
}

View File

@@ -1,7 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.nudgeCursorBackCmd = exports.nudgeCursorForwardCmd = exports.nudgeCursorCmd = void 0;
var prosemirror_state_1 = require("prosemirror-state");
const prosemirror_state_1 = require("prosemirror-state");
////////////////////////////////////////////////////////////////////////////////
/**
* Some browsers (cough firefox cough) don't properly handle cursor movement on
@@ -10,14 +10,14 @@ var prosemirror_state_1 = require("prosemirror-state");
* @see https://bugzilla.mozilla.org/show_bug.cgi?id=1252108
*/
function nudgeCursorCmd(dir) {
return function (innerState, dispatch) {
var _a = innerState.selection, to = _a.to, from = _a.from;
return (innerState, dispatch) => {
let { to, from } = innerState.selection;
// compute target position
var emptySelection = to === from;
var currentPos = dir < 0 ? from : to;
var increment = emptySelection ? dir : 0;
var nodeSize = innerState.doc.nodeSize;
var targetPos = Math.max(0, Math.min(nodeSize, currentPos + increment));
let emptySelection = to === from;
let currentPos = dir < 0 ? from : to;
let increment = emptySelection ? dir : 0;
let nodeSize = innerState.doc.nodeSize;
let targetPos = Math.max(0, Math.min(nodeSize, currentPos + increment));
if (dispatch) {
dispatch(innerState.tr.setSelection(prosemirror_state_1.TextSelection.create(innerState.doc, targetPos)));
}

View File

@@ -5,13 +5,13 @@
*--------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.MathView = void 0;
var prosemirror_state_1 = require("prosemirror-state");
var prosemirror_view_1 = require("prosemirror-view");
var prosemirror_transform_1 = require("prosemirror-transform");
var prosemirror_keymap_1 = require("prosemirror-keymap");
var prosemirror_commands_1 = require("prosemirror-commands");
var collapsemathnode_1 = require("./commands/collapsemathnode");
var MathView = /** @class */ (function () {
const prosemirror_state_1 = require("prosemirror-state");
const prosemirror_view_1 = require("prosemirror-view");
const prosemirror_transform_1 = require("prosemirror-transform");
const prosemirror_keymap_1 = require("prosemirror-keymap");
const prosemirror_commands_1 = require("prosemirror-commands");
const collapsemathnode_1 = require("./commands/collapsemathnode");
class MathView {
// == Lifecycle ===================================== //
/**
* @param onDestroy Callback for when this NodeView is destroyed.
@@ -22,8 +22,7 @@ var MathView = /** @class */ (function () {
* @option tagName HTML tag name to use for this NodeView. If none is provided,
* will use the node name with underscores converted to hyphens.
*/
function MathView(node, view, getPos, options, mathPluginKey, onDestroy) {
var _this = this;
constructor(node, view, getPos, options, mathPluginKey, onDestroy) {
// store arguments
this.options = options;
this._node = node;
@@ -48,11 +47,11 @@ var MathView = /** @class */ (function () {
this._mathSrcElt.classList.add("math-src");
this.dom.appendChild(this._mathSrcElt);
// ensure
this.dom.addEventListener("click", function () { return _this.ensureFocus(); });
this.dom.addEventListener("click", () => this.ensureFocus());
// render initial content
this.renderMath();
}
MathView.prototype.destroy = function () {
destroy() {
// close the inner editor without rendering
this.closeEditor(false);
// clean up dom elements
@@ -65,29 +64,29 @@ var MathView = /** @class */ (function () {
delete this._mathSrcElt;
}
this.dom.remove();
};
}
/**
* Ensure focus on the inner editor whenever this node has focus.
* This helps to prevent accidental deletions of math blocks.
*/
MathView.prototype.ensureFocus = function () {
ensureFocus() {
if (this._innerView && this._outerView.hasFocus()) {
this._innerView.focus();
}
};
}
// == Updates ======================================= //
MathView.prototype.update = function (node, _decorations, _innerDecorations) {
update(node, _decorations, _innerDecorations) {
if (!node.sameMarkup(this._node))
return false;
this._node = node;
if (this._innerView) {
var state = this._innerView.state;
var start = node.content.findDiffStart(state.doc.content);
let state = this._innerView.state;
let start = node.content.findDiffStart(state.doc.content);
if (start != null) {
var diff = node.content.findDiffEnd(state.doc.content);
let diff = node.content.findDiffEnd(state.doc.content);
if (diff) {
var endA = diff.a, endB = diff.b;
var overlap = start - Math.min(endA, endB);
let { a: endA, b: endB } = diff;
let overlap = start - Math.min(endA, endB);
if (overlap > 0) {
endA += overlap;
endB += overlap;
@@ -102,17 +101,17 @@ var MathView = /** @class */ (function () {
this.renderMath();
}
return true;
};
MathView.prototype.updateCursorPos = function (state) {
var pos = this._getPos();
var size = this._node.nodeSize;
var inPmSelection = state.selection.from < pos + size && pos < state.selection.to;
}
updateCursorPos(state) {
const pos = this._getPos();
const size = this._node.nodeSize;
const inPmSelection = state.selection.from < pos + size && pos < state.selection.to;
if (!inPmSelection) {
this.cursorSide = pos < state.selection.from ? "end" : "start";
}
};
}
// == Events ===================================== //
MathView.prototype.selectNode = function () {
selectNode() {
if (!this._outerView.editable) {
return;
}
@@ -120,29 +119,29 @@ var MathView = /** @class */ (function () {
if (!this._isEditing) {
this.openEditor();
}
};
MathView.prototype.deselectNode = function () {
}
deselectNode() {
this.dom.classList.remove("ProseMirror-selectednode");
if (this._isEditing) {
this.closeEditor();
}
};
MathView.prototype.stopEvent = function (event) {
}
stopEvent(event) {
return (this._innerView !== undefined &&
event.target !== undefined &&
this._innerView.dom.contains(event.target));
};
MathView.prototype.ignoreMutation = function () {
}
ignoreMutation() {
return true;
};
}
// == Rendering ===================================== //
MathView.prototype.renderMath = function () {
renderMath() {
if (!this._mathRenderElt) {
return;
}
// get tex string to render
var content = this._node.content.content;
var texString = "";
let content = this._node.content.content;
let texString = "";
if (content.length > 0 && content[0].textContent !== null) {
texString = content[0].textContent.trim();
}
@@ -172,20 +171,20 @@ var MathView = /** @class */ (function () {
this.dom.setAttribute("title", err.toString());
}
}
};
}
// == Inner Editor ================================== //
MathView.prototype.dispatchInner = function (tr) {
dispatchInner(tr) {
if (!this._innerView) {
return;
}
var _a = this._innerView.state.applyTransaction(tr), state = _a.state, transactions = _a.transactions;
let { state, transactions } = this._innerView.state.applyTransaction(tr);
this._innerView.updateState(state);
if (!tr.getMeta("fromOutside")) {
var outerTr = this._outerView.state.tr, offsetMap = prosemirror_transform_1.StepMap.offset(this._getPos() + 1);
for (var i = 0; i < transactions.length; i++) {
var steps = transactions[i].steps;
for (var j = 0; j < steps.length; j++) {
var mapped = steps[j].map(offsetMap);
let outerTr = this._outerView.state.tr, offsetMap = prosemirror_transform_1.StepMap.offset(this._getPos() + 1);
for (let i = 0; i < transactions.length; i++) {
let steps = transactions[i].steps;
for (let j = 0; j < steps.length; j++) {
let mapped = steps[j].map(offsetMap);
if (!mapped) {
throw Error("step discarded!");
}
@@ -195,9 +194,8 @@ var MathView = /** @class */ (function () {
if (outerTr.docChanged)
this._outerView.dispatch(outerTr);
}
};
MathView.prototype.openEditor = function () {
var _this = this;
}
openEditor() {
var _a;
if (this._innerView) {
throw Error("inner view should not exist!");
@@ -210,24 +208,24 @@ var MathView = /** @class */ (function () {
doc: this._node,
plugins: [
(0, prosemirror_keymap_1.keymap)({
Tab: function (state, dispatch) {
Tab: (state, dispatch) => {
if (dispatch) {
dispatch(state.tr.insertText("\t"));
}
return true;
},
Backspace: (0, prosemirror_commands_1.chainCommands)(prosemirror_commands_1.deleteSelection, function (state, dispatch, tr_inner) {
Backspace: (0, prosemirror_commands_1.chainCommands)(prosemirror_commands_1.deleteSelection, (state, dispatch, tr_inner) => {
// default backspace behavior for non-empty selections
if (!state.selection.empty) {
return false;
}
// default backspace behavior when math node is non-empty
if (_this._node.textContent.length > 0) {
if (this._node.textContent.length > 0) {
return false;
}
// otherwise, we want to delete the empty math node and focus the outer view
_this._outerView.dispatch(_this._outerView.state.tr.insertText(""));
_this._outerView.focus();
this._outerView.dispatch(this._outerView.state.tr.insertText(""));
this._outerView.focus();
return true;
}),
// "Ctrl-Backspace": (state, dispatch, tr_inner) => {
@@ -248,27 +246,26 @@ var MathView = /** @class */ (function () {
dispatchTransaction: this.dispatchInner.bind(this),
});
// focus element
var innerState = this._innerView.state;
let innerState = this._innerView.state;
this._innerView.focus();
// request outer cursor position before math node was selected
var maybePos = (_a = this._mathPluginKey.getState(this._outerView.state)) === null || _a === void 0 ? void 0 : _a.prevCursorPos;
let maybePos = (_a = this._mathPluginKey.getState(this._outerView.state)) === null || _a === void 0 ? void 0 : _a.prevCursorPos;
if (maybePos === null || maybePos === undefined) {
console.error("[prosemirror-math] Error: Unable to fetch math plugin state from key.");
}
var prevCursorPos = maybePos !== null && maybePos !== void 0 ? maybePos : 0;
let prevCursorPos = maybePos !== null && maybePos !== void 0 ? maybePos : 0;
// compute position that cursor should appear within the expanded math node
var innerPos = prevCursorPos <= this._getPos() ? 0 : this._node.nodeSize - 2;
let innerPos = prevCursorPos <= this._getPos() ? 0 : this._node.nodeSize - 2;
this._innerView.dispatch(innerState.tr.setSelection(prosemirror_state_1.TextSelection.create(innerState.doc, innerPos)));
this._isEditing = true;
};
}
/**
* Called when the inner ProseMirror editor should close.
*
* @param render Optionally update the rendered math after closing. (which
* is generally what we want to do, since the user is done editing!)
*/
MathView.prototype.closeEditor = function (render) {
if (render === void 0) { render = true; }
closeEditor(render = true) {
if (this._innerView) {
this._innerView.destroy();
this._innerView = undefined;
@@ -277,7 +274,6 @@ var MathView = /** @class */ (function () {
this.renderMath();
}
this._isEditing = false;
};
return MathView;
}());
}
}
exports.MathView = MathView;

View File

@@ -5,33 +5,33 @@
*--------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.mathPlugin = exports.createMathView = void 0;
var prosemirror_state_1 = require("prosemirror-state");
var math_nodeview_1 = require("./math-nodeview");
var katex_1 = require("./renderers/katex");
const prosemirror_state_1 = require("prosemirror-state");
const math_nodeview_1 = require("./math-nodeview");
const katex_1 = require("./renderers/katex");
// uniquely identifies the prosemirror-math plugin
var MATH_PLUGIN_KEY = new prosemirror_state_1.PluginKey("prosemirror-math");
const MATH_PLUGIN_KEY = new prosemirror_state_1.PluginKey("prosemirror-math");
/**
* Returns a function suitable for passing as a field in `EditorProps.nodeViews`.
* @param inline TRUE for block math, FALSE for inline math.
* @see https://prosemirror.net/docs/ref/#view.EditorProps.nodeViews
*/
function createMathView(inline) {
return function (node, view, getPos) {
return (node, view, getPos) => {
/** @todo is this necessary?
* Docs says that for any function proprs, the current plugin instance
* will be bound to `this`. However, the typings don't reflect this.
*/
var pluginState = MATH_PLUGIN_KEY.getState(view.state);
let pluginState = MATH_PLUGIN_KEY.getState(view.state);
if (!pluginState) {
throw new Error("no math plugin!");
}
var nodeViews = pluginState.activeNodeViews;
let nodeViews = pluginState.activeNodeViews;
// set up NodeView
var nodeView = new math_nodeview_1.MathView(node, view, getPos, {
let nodeView = new math_nodeview_1.MathView(node, view, getPos, {
className: inline ? "math-inline" : "math-block",
renderer: inline ? katex_1.KatexRenderer.inline : katex_1.KatexRenderer.block,
tagName: inline ? "span" : "div",
}, MATH_PLUGIN_KEY, function () {
}, MATH_PLUGIN_KEY, () => {
nodeViews.splice(nodeViews.indexOf(nodeView));
});
nodeViews.push(nodeView);
@@ -39,20 +39,20 @@ function createMathView(inline) {
};
}
exports.createMathView = createMathView;
var mathPluginSpec = {
let mathPluginSpec = {
key: MATH_PLUGIN_KEY,
state: {
init: function (config, instance) {
init(config, instance) {
return {
macros: {},
activeNodeViews: [],
prevCursorPos: 0,
};
},
apply: function (tr, value, oldState, newState) {
apply(tr, value, oldState, newState) {
// produce updated state field for this plugin
var newPos = newState.selection.from;
var oldPos = oldState.selection.from;
const newPos = newState.selection.from;
const oldPos = oldState.selection.from;
return {
// these values are left unchanged
activeNodeViews: value.activeNodeViews,

View File

@@ -3,47 +3,11 @@
* Author: Benjamin R. Bray
* License: MIT (see LICENSE in project root for details)
*--------------------------------------------------------*/
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;
};
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));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.extendMathSchemaSpec = exports.createMathSchema = exports.mathSchemaSpec = void 0;
// prosemirror imports
var prosemirror_model_1 = require("prosemirror-model");
var math_paste_rules_1 = require("./plugins/math-paste-rules");
const prosemirror_model_1 = require("prosemirror-model");
const math_paste_rules_1 = require("./plugins/math-paste-rules");
////////////////////////////////////////////////////////////
// force typescript to infer generic type arguments for SchemaSpec
function createSchemaSpec(spec) {
@@ -60,7 +24,7 @@ exports.mathSchemaSpec = createSchemaSpec({
content: "inline*",
group: "block",
parseDOM: [{ tag: "p" }],
toDOM: function () {
toDOM() {
return ["p", 0];
},
},
@@ -69,16 +33,16 @@ exports.mathSchemaSpec = createSchemaSpec({
content: "text*",
inline: true,
atom: true,
toDOM: function () { return ["math-inline", { class: "math-node" }, 0]; },
parseDOM: __spreadArray([{ tag: "math-inline" }], __read(math_paste_rules_1.defaultInlineMathParseRules), false),
toDOM: () => ["math-inline", { class: "math-node" }, 0],
parseDOM: [{ tag: "math-inline" }, ...math_paste_rules_1.defaultInlineMathParseRules],
},
math_display: {
group: "block math",
content: "text*",
atom: true,
code: true,
toDOM: function () { return ["math-display", { class: "math-node" }, 0]; },
parseDOM: __spreadArray([{ tag: "math-display" }], __read(math_paste_rules_1.defaultBlockMathParseRules), false),
toDOM: () => ["math-display", { class: "math-node" }, 0],
parseDOM: [{ tag: "math-display" }, ...math_paste_rules_1.defaultBlockMathParseRules],
},
text: {
group: "inline",
@@ -86,7 +50,7 @@ exports.mathSchemaSpec = createSchemaSpec({
},
marks: {
math_select: {
toDOM: function () {
toDOM() {
return ["math-select", 0];
},
parseDOM: [{ tag: "math-select" }],
@@ -112,8 +76,8 @@ exports.createMathSchema = createMathSchema;
* must be a raw object (not an OrderedMap).
*/
function extendMathSchemaSpec(baseSpec) {
var nodes = __assign(__assign({}, baseSpec.nodes), exports.mathSchemaSpec.nodes);
var marks = __assign(__assign({}, baseSpec.marks), exports.mathSchemaSpec.marks);
return { nodes: nodes, marks: marks, topNode: baseSpec.topNode };
let nodes = Object.assign(Object.assign({}, baseSpec.nodes), exports.mathSchemaSpec.nodes);
let marks = Object.assign(Object.assign({}, baseSpec.marks), exports.mathSchemaSpec.marks);
return { nodes, marks, topNode: baseSpec.topNode };
}
exports.extendMathSchemaSpec = extendMathSchemaSpec;

Some files were not shown because too many files have changed in this diff Show More