UNPKG

tldraw

Version:

A tiny little drawing editor.

344 lines (343 loc) • 12.3 kB
import { jsx } from "react/jsx-runtime"; import { getMarkRange } from "@tiptap/core"; import { Box, clamp, debounce, tltime, track, useAtom, useEditor, useQuickReactor, useReactor, useValue, Vec } from "@tldraw/editor"; import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; import { useTranslation } from "../../hooks/useTranslation/useTranslation.mjs"; import { TldrawUiContextualToolbar } from "../primitives/TldrawUiContextualToolbar.mjs"; import { DefaultRichTextToolbarContent } from "./DefaultRichTextToolbarContent.mjs"; import { LinkEditor } from "./LinkEditor.mjs"; const MOVE_TIMEOUT = 150; const HIDE_VISIBILITY_TIMEOUT = 16; const SHOW_VISIBILITY_TIMEOUT = 16; const TOOLBAR_GAP = 8; const SCREEN_MARGIN = 16; const MIN_DISTANCE_TO_REPOSITION_SQUARED = 16 ** 2; const HIDE_TOOLBAR_WHEN_CAMERA_IS_MOVING = true; const CHANGE_ONLY_WHEN_Y_CHANGES = true; const LEFT_ALIGN_TOOLBAR = false; const DefaultRichTextToolbar = track(function DefaultRichTextToolbar2({ children }) { const editor = useEditor(); const textEditor = useValue("textEditor", () => editor.getRichTextEditor(), [editor]); if (editor.getInstanceState().isCoarsePointer || !textEditor) return null; return /* @__PURE__ */ jsx(ContextualToolbarInner, { textEditor, children }); }); function ContextualToolbarInner({ textEditor, children }) { const editor = useEditor(); const msg = useTranslation(); const rToolbar = useRef(null); const { isVisible, isInteractive, hide, show, position, move } = useToolbarVisibilityStateMachine(); const { isEditingLink, onEditLinkStart, onEditLinkComplete } = useEditingLinkBehavior(textEditor); const forcePositionUpdateAtom = useAtom("force toolbar position update", 0); useEffect( function forceUpdateWhenSelectionUpdates() { function handleSelectionUpdate() { forcePositionUpdateAtom.update((t) => t + 1); } tltime.requestAnimationFrame("first forced update", handleSelectionUpdate); textEditor.on("selectionUpdate", handleSelectionUpdate); return () => { textEditor.off("selectionUpdate", handleSelectionUpdate); }; }, [textEditor, forcePositionUpdateAtom] ); useReactor( "shape change", function forceUpdateOnNextFrameWhenShapeChanges() { editor.getEditingShape(); forcePositionUpdateAtom.update((t) => t + 1); }, [editor] ); const rCouldShowToolbar = useRef(false); const [hasValidToolbarPosition, setHasValidToolbarPosition] = useState(false); useQuickReactor( "toolbar position", function updateToolbarPositionAndDisplay() { const toolbarElm = rToolbar.current; if (!toolbarElm) return; editor.getCamera(); forcePositionUpdateAtom.get(); const position2 = getToolbarScreenPosition(editor, toolbarElm); if (!position2) { if (rCouldShowToolbar.current) { rCouldShowToolbar.current = false; setHasValidToolbarPosition(false); } return; } const cameraState2 = editor.getCameraState(); if (cameraState2 === "moving") { const elm = rToolbar.current; elm.style.setProperty("transform", `translate(${position2.x}px, ${position2.y}px)`); } else { move(position2.x, position2.y); } if (!rCouldShowToolbar.current) { rCouldShowToolbar.current = true; setHasValidToolbarPosition(true); } }, [editor, textEditor, forcePositionUpdateAtom] ); const cameraState = useValue("camera state", () => editor.getCameraState(), [editor]); const isMousingDown = useIsMousingDownOnTextEditor(textEditor); useEffect(() => { if (cameraState === "moving" && HIDE_TOOLBAR_WHEN_CAMERA_IS_MOVING) { hide(true); return; } if (isMousingDown || !hasValidToolbarPosition) { hide(); return; } show(); }, [hasValidToolbarPosition, cameraState, isMousingDown, show, hide]); useLayoutEffect(() => { const elm = rToolbar.current; if (!elm) return; elm.dataset.visible = `${isVisible}`; }, [isVisible, position]); useLayoutEffect(() => { const elm = rToolbar.current; if (!elm) return; elm.style.setProperty("transform", `translate(${position.x}px, ${position.y}px)`); }, [position]); useLayoutEffect(() => { const elm = rToolbar.current; if (!elm) return; elm.dataset.interactive = `${isInteractive}`; }, [isInteractive]); return /* @__PURE__ */ jsx( TldrawUiContextualToolbar, { ref: rToolbar, className: "tlui-rich-text__toolbar", "data-interactive": false, "data-visible": false, label: msg("tool.rich-text-toolbar-title"), children: children ? children : isEditingLink ? /* @__PURE__ */ jsx( LinkEditor, { textEditor, value: textEditor.isActive("link") ? textEditor.getAttributes("link").href : "", onComplete: onEditLinkComplete } ) : /* @__PURE__ */ jsx(DefaultRichTextToolbarContent, { textEditor, onEditLinkStart }) } ); } function rectToBox(rect) { return new Box(rect.x, rect.y, rect.width, rect.height); } function getToolbarScreenPosition(editor, toolbarElm) { const selection = window.getSelection(); if (!selection || selection.rangeCount === 0 || selection.isCollapsed) return; const rangeBoxes = []; for (let i = 0; i < selection.rangeCount; i++) { const range = selection.getRangeAt(i); rangeBoxes.push(rectToBox(range.getBoundingClientRect())); } const selectionBounds = Box.Common(rangeBoxes); const vsb = editor.getViewportScreenBounds(); selectionBounds.x -= vsb.x; selectionBounds.y -= vsb.y; if (selectionBounds.midY < SCREEN_MARGIN || selectionBounds.midY > vsb.h - SCREEN_MARGIN || selectionBounds.midX < SCREEN_MARGIN || selectionBounds.midX > vsb.w - SCREEN_MARGIN) { return; } const toolbarBounds = rectToBox(toolbarElm.getBoundingClientRect()); if (!toolbarBounds.width || !toolbarBounds.height) return; const { scrollLeft, scrollTop } = editor.getContainer(); let x = LEFT_ALIGN_TOOLBAR ? selectionBounds.x : selectionBounds.midX - toolbarBounds.w / 2; let y = selectionBounds.y - toolbarBounds.h - TOOLBAR_GAP; x = clamp(x, SCREEN_MARGIN, vsb.w - toolbarBounds.w - SCREEN_MARGIN); y = clamp(y, SCREEN_MARGIN, vsb.h - toolbarBounds.h - SCREEN_MARGIN); x += scrollLeft; y += scrollTop; x = Math.round(x); y = Math.round(y); return { x, y }; } function useEditingLinkBehavior(textEditor) { const [isEditingLink, setIsEditingLink] = useState(false); useEffect(() => { if (!textEditor) { setIsEditingLink(false); return; } const handleClick = () => { const isLinkActive = textEditor.isActive("link"); setIsEditingLink(isLinkActive); }; textEditor.view.dom.addEventListener("click", handleClick); return () => { textEditor.view.dom.removeEventListener("click", handleClick); }; }, [textEditor, isEditingLink]); useEffect(() => { if (!textEditor) { return; } if (textEditor.isActive("link")) { try { const { from, to } = getMarkRange( textEditor.state.doc.resolve(textEditor.state.selection.from), textEditor.schema.marks.link ); if (textEditor.state.selection.empty) { textEditor.commands.setTextSelection({ from, to }); } } catch { } } }, [textEditor, isEditingLink]); const onEditLinkStart = useCallback(() => { setIsEditingLink(true); }, []); const onEditLinkCancel = useCallback(() => { setIsEditingLink(false); }, []); const onEditLinkComplete = useCallback(() => { setIsEditingLink(false); if (!textEditor) return; const from = textEditor.state.selection.from; textEditor.commands.setTextSelection({ from, to: from }); }, [textEditor]); return { isEditingLink, onEditLinkStart, onEditLinkComplete, onEditLinkCancel }; } function sufficientlyDistant(curr, next) { if (CHANGE_ONLY_WHEN_Y_CHANGES) { return Vec.Sub(next, curr).y ** 2 >= MIN_DISTANCE_TO_REPOSITION_SQUARED; } return Vec.Len2(Vec.Sub(next, curr)) >= MIN_DISTANCE_TO_REPOSITION_SQUARED; } function useToolbarVisibilityStateMachine() { const editor = useEditor(); const rState = useRef({ name: "hidden" }); const [isInteractive, setIsInteractive] = useState(false); const [isVisible, setIsVisible] = useState(false); const [position, setPosition] = useState({ x: -1e3, y: -1e3 }); const rCurrPosition = useRef(new Vec(-1e3, -1e3)); const rNextPosition = useRef(new Vec(-1e3, -1e3)); const rStableVisibilityTimeout = useRef(-1); const rStablePositionTimeout = useRef(-1); const move = useCallback( (x, y) => { rNextPosition.current.x = x; rNextPosition.current.y = y; if (rState.current.name === "hidden" || rState.current.name === "showing") return; clearTimeout(rStablePositionTimeout.current); rStablePositionTimeout.current = editor.timers.setTimeout(() => { if (rState.current.name === "shown" && sufficientlyDistant(rNextPosition.current, rCurrPosition.current)) { const { x: x2, y: y2 } = rNextPosition.current; rCurrPosition.current = new Vec(x2, y2); setPosition({ x: x2, y: y2 }); } }, MOVE_TIMEOUT); }, [editor] ); const hide = useCallback( (immediate = false) => { switch (rState.current.name) { case "showing": { clearTimeout(rStableVisibilityTimeout.current); rState.current = { name: "hidden" }; break; } case "shown": { rState.current = { name: "hiding" }; setIsInteractive(false); if (immediate) { rState.current = { name: "hidden" }; setIsVisible(false); } else { rStableVisibilityTimeout.current = editor.timers.setTimeout(() => { rState.current = { name: "hidden" }; setIsVisible(false); }, HIDE_VISIBILITY_TIMEOUT); } break; } default: { } } }, [editor] ); const show = useCallback(() => { switch (rState.current.name) { case "hidden": { rState.current = { name: "showing" }; rStableVisibilityTimeout.current = editor.timers.setTimeout(() => { const { x, y } = rNextPosition.current; rCurrPosition.current = new Vec(x, y); setPosition({ x, y }); rState.current = { name: "shown" }; setIsVisible(true); setIsInteractive(true); }, SHOW_VISIBILITY_TIMEOUT); break; } case "hiding": { clearTimeout(rStableVisibilityTimeout.current); rState.current = { name: "shown" }; setIsInteractive(true); move(rNextPosition.current.x, rNextPosition.current.y); break; } default: { } } }, [editor, move]); return { isVisible, isInteractive, show, hide, move, position }; } function useIsMousingDownOnTextEditor(textEditor) { const [isMousingDown, setIsMousingDown] = useState(false); useEffect(() => { if (!textEditor) return; const handlePointingStateChange = debounce(({ isPointing }) => { setIsMousingDown(isPointing); }, 16); const handlePointingDown = () => handlePointingStateChange({ isPointing: true }); const handlePointingUp = () => handlePointingStateChange({ isPointing: false }); const touchDownEvents = ["touchstart", "pointerdown", "mousedown"]; const touchUpEvents = ["touchend", "pointerup", "mouseup"]; touchDownEvents.forEach((eventName) => { textEditor.view.dom.addEventListener(eventName, handlePointingDown); }); touchUpEvents.forEach((eventName) => { document.body.addEventListener(eventName, handlePointingUp); }); return () => { touchDownEvents.forEach((eventName) => { textEditor.view.dom.removeEventListener(eventName, handlePointingDown); }); touchUpEvents.forEach((eventName) => { document.body.removeEventListener(eventName, handlePointingUp); }); }; }, [textEditor]); return isMousingDown; } export { DefaultRichTextToolbar }; //# sourceMappingURL=DefaultRichTextToolbar.mjs.map