Skip to content

开源白板工具(SaaS),一体化白板,包含思维导图、流程图、自由画等。All in one open-source whiteboard tool with mind, flowchart, freehand and etc.

feat: init dialog and mermaid-to-dialog

pubuzhixing86ff70b972e80
diff --git a/apps/web/src/app/app.tsx b/apps/web/src/app/app.tsx
index 216dec8..823fcd7 100644
--- a/apps/web/src/app/app.tsx
+++ b/apps/web/src/app/app.tsx
@@ -1,12 +1,50 @@
-import { useState } from 'react';
+import { useEffect, useState } from 'react';
import { initializeData } from './initialize-data';
import { Drawnix } from '@drawnix/drawnix';
import { PlaitBoard, PlaitElement, PlaitTheme, Viewport } from '@plait/core';
+import { parseMermaidToDrawnix } from '@drawnix/mermaid-to-drawnix';
const DRAWNIX_LOCAL_DATA_KEY = 'drawnix-local-data';
+const diagramDefinition = `flowchart TB
+ Start([开始恢复指定版本]) -->|"已知参数"| KnownParams["输入参数:
+ - clock: 目标版本
+ - clock_cursor: 基础版本"]
+
+ KnownParams -->|"1. 查询更新数据"| GetUpdates["查询所有更新数据
+ WHERE clock >= clock_cursor
+ AND clock <= clock
+ ORDER BY clock ASC
+
+ (包含基础状态和增量更新)"]
+
+ GetUpdates --> InitDoc["创建新YDoc
+ new Y.Doc()"]
+
+ InitDoc -->|"2. 按序应用"| ApplyUpdates["按clock顺序应用更新
+ for update in updates:
+ doc.applyUpdate(update)"]
+
+ ApplyUpdates -->|"3. 完成"| Complete([得到指定版本])
+
+ %% 补充说明
+ Note["说明:
+ 1. clock_cursor: 基础版本号
+ 2. clock: 目标版本号
+ 3. 单次查询即可获取所需数据
+ 4. 按clock顺序应用可得到目标版本"]
+
+ %% 样式设置
+ style Start fill:#f96,stroke:#333,stroke-width:2px
+ style Complete fill:#9f9,stroke:#333,stroke-width:2px
+ style KnownParams fill:#ff9,stroke:#333,stroke-width:2px
+ style GetUpdates fill:#ff9,stroke:#333,stroke-width:2px
+ style InitDoc fill:#99f,stroke:#333,stroke-width:2px
+ style ApplyUpdates fill:#99f,stroke:#333,stroke-width:2px
+ style Note fill:#fff,stroke:#333,stroke-width:1px`;
+
export function App() {
- const [value] = useState<{
+ const [value, setValue] = useState<{
children: PlaitElement[];
viewport?: Viewport;
theme?: PlaitTheme;
@@ -17,6 +55,23 @@ export function App() {
}
return { children: initializeData };
});
+
+ useEffect(() => {
+ async function initializeMermaid() {
+ try {
+ const { elements } = await parseMermaidToDrawnix(diagramDefinition, {
+ themeVariables: {
+ fontSize: '25px',
+ },
+ });
+ setValue(prev => ({ ...prev, children: elements }));
+ } catch (e) {
+ console.error('Failed to parse Mermaid diagram:', e);
+ }
+ }
+ initializeMermaid();
+ }, []);
+
return (
<>
<Drawnix
diff --git a/packages/drawnix/src/components/dialog/dialog.scss b/packages/drawnix/src/components/dialog/dialog.scss
new file mode 100644
index 0000000..d2ea42e
--- /dev/null
+++ b/packages/drawnix/src/components/dialog/dialog.scss
@@ -0,0 +1,12 @@
+.Dialog-overlay {
+ background: rgba(#121212, 0.2);
+ display: grid;
+ place-items: center;
+}
+
+.Dialog {
+ margin: 15px;
+ background-color: white;
+ padding: 15px;
+ border-radius: 4px;
+}
\ No newline at end of file
diff --git a/packages/drawnix/src/components/dialog/dialog.tsx b/packages/drawnix/src/components/dialog/dialog.tsx
new file mode 100644
index 0000000..05c0211
--- /dev/null
+++ b/packages/drawnix/src/components/dialog/dialog.tsx
@@ -0,0 +1,214 @@
+import * as React from 'react';
+import {
+ useFloating,
+ useClick,
+ useDismiss,
+ useRole,
+ useInteractions,
+ useMergeRefs,
+ FloatingPortal,
+ FloatingFocusManager,
+ FloatingOverlay,
+ useId,
+} from '@floating-ui/react';
+import './dialog.scss';
+
+interface DialogOptions {
+ initialOpen?: boolean;
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
+}
+
+export function useDialog({
+ initialOpen = false,
+ open: controlledOpen,
+ onOpenChange: setControlledOpen,
+}: DialogOptions = {}) {
+ const [uncontrolledOpen, setUncontrolledOpen] = React.useState(initialOpen);
+ const [labelId, setLabelId] = React.useState<string | undefined>();
+ const [descriptionId, setDescriptionId] = React.useState<
+ string | undefined
+ >();
+
+ const open = controlledOpen ?? uncontrolledOpen;
+ const setOpen = setControlledOpen ?? setUncontrolledOpen;
+
+ const data = useFloating({
+ open,
+ onOpenChange: setOpen,
+ });
+
+ const context = data.context;
+
+ const click = useClick(context, {
+ enabled: controlledOpen == null,
+ });
+ const dismiss = useDismiss(context, { outsidePressEvent: 'mousedown' });
+ const role = useRole(context);
+
+ const interactions = useInteractions([click, dismiss, role]);
+
+ return React.useMemo(
+ () => ({
+ open,
+ setOpen,
+ ...interactions,
+ ...data,
+ labelId,
+ descriptionId,
+ setLabelId,
+ setDescriptionId,
+ }),
+ [open, setOpen, interactions, data, labelId, descriptionId]
+ );
+}
+
+type ContextType =
+ | (ReturnType<typeof useDialog> & {
+ setLabelId: React.Dispatch<React.SetStateAction<string | undefined>>;
+ setDescriptionId: React.Dispatch<
+ React.SetStateAction<string | undefined>
+ >;
+ })
+ | null;
+
+const DialogContext = React.createContext<ContextType>(null);
+
+export const useDialogContext = () => {
+ const context = React.useContext(DialogContext);
+
+ if (context == null) {
+ throw new Error('Dialog components must be wrapped in <Dialog />');
+ }
+
+ return context;
+};
+
+export function Dialog({
+ children,
+ ...options
+}: {
+ children: React.ReactNode;
+} & DialogOptions) {
+ const dialog = useDialog(options);
+ return (
+ <DialogContext.Provider value={dialog}>{children}</DialogContext.Provider>
+ );
+}
+
+interface DialogTriggerProps {
+ children: React.ReactNode;
+ asChild?: boolean;
+}
+
+export const DialogTrigger = React.forwardRef<
+ HTMLElement,
+ React.HTMLProps<HTMLElement> & DialogTriggerProps
+>(function DialogTrigger({ children, asChild = false, ...props }, propRef) {
+ const context = useDialogContext();
+ const childrenRef = (children as any).ref;
+ const ref = useMergeRefs([context.refs.setReference, propRef, childrenRef]);
+
+ // `asChild` allows the user to pass any element as the anchor
+ if (asChild && React.isValidElement(children)) {
+ return React.cloneElement(
+ children,
+ context.getReferenceProps({
+ ref,
+ ...props,
+ ...children.props,
+ 'data-state': context.open ? 'open' : 'closed',
+ })
+ );
+ }
+
+ return (
+ <button
+ ref={ref}
+ // The user can style the trigger based on the state
+ data-state={context.open ? 'open' : 'closed'}
+ {...context.getReferenceProps(props)}
+ >
+ {children}
+ </button>
+ );
+});
+
+export const DialogContent = React.forwardRef<
+ HTMLDivElement,
+ React.HTMLProps<HTMLDivElement> & { container?: HTMLElement | null }
+>(function DialogContent(props, propRef) {
+ const { context: floatingContext, ...context } = useDialogContext();
+ const ref = useMergeRefs([context.refs.setFloating, propRef]);
+
+ if (!floatingContext.open) return null;
+
+ return (
+ <FloatingPortal root={props.container}>
+ <FloatingOverlay className="Dialog-overlay" lockScroll>
+ <FloatingFocusManager context={floatingContext}>
+ <div
+ ref={ref}
+ aria-labelledby={context.labelId}
+ aria-describedby={context.descriptionId}
+ {...context.getFloatingProps(props)}
+ >
+ {props.children}
+ </div>
+ </FloatingFocusManager>
+ </FloatingOverlay>
+ </FloatingPortal>
+ );
+});
+
+export const DialogHeading = React.forwardRef<
+ HTMLHeadingElement,
+ React.HTMLProps<HTMLHeadingElement>
+>(function DialogHeading({ children, ...props }, ref) {
+ const { setLabelId } = useDialogContext();
+ const id = useId();
+
+ // Only sets `aria-labelledby` on the Dialog root element
+ // if this component is mounted inside it.
+ React.useLayoutEffect(() => {
+ setLabelId(id);
+ return () => setLabelId(undefined);
+ }, [id, setLabelId]);
+
+ return (
+ <h2 {...props} ref={ref} id={id}>
+ {children}
+ </h2>
+ );
+});
+
+export const DialogDescription = React.forwardRef<
+ HTMLParagraphElement,
+ React.HTMLProps<HTMLParagraphElement>
+>(function DialogDescription({ children, ...props }, ref) {
+ const { setDescriptionId } = useDialogContext();
+ const id = useId();
+
+ // Only sets `aria-describedby` on the Dialog root element
+ // if this component is mounted inside it.
+ React.useLayoutEffect(() => {
+ setDescriptionId(id);
+ return () => setDescriptionId(undefined);
+ }, [id, setDescriptionId]);
+
+ return (
+ <p {...props} ref={ref} id={id}>
+ {children}
+ </p>
+ );
+});
+
+export const DialogClose = React.forwardRef<
+ HTMLButtonElement,
+ React.ButtonHTMLAttributes<HTMLButtonElement>
+>(function DialogClose(props, ref) {
+ const { setOpen } = useDialogContext();
+ return (
+ <button type="button" {...props} ref={ref} onClick={() => setOpen(false)} />
+ );
+});
diff --git a/packages/drawnix/src/components/icons.tsx b/packages/drawnix/src/components/icons.tsx
index 1f748aa..e072262 100644
--- a/packages/drawnix/src/components/icons.tsx
+++ b/packages/drawnix/src/components/icons.tsx
@@ -459,8 +459,19 @@ export const FeltTipPenIcon = createIcon(
export const ImageIcon = createIcon(
<svg viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
- <g id="image" stroke="none" fill='currentColor'>
+ <g id="image" stroke="none" fill="currentColor">
<path d="M10.496 7c-.824 0-1.572-.675-1.498-1.5 0-.825.674-1.5 1.498-1.5.823 0 1.497.675 1.497 1.5S11.319 7 10.496 7zM13.8 9.476V2.2H2.2v5.432l.1-.078C3.132 6.904 4.029 6.5 5 6.5c.823 0 1.552.27 2.342.778.226.145.449.304.735.518.06.045.546.413.69.52 1.634 1.21 2.833 1.6 4.798 1.207l.235-.047zm0 1.523V10.7c-5 1-6.3-3-8.8-3-1.5 0-2.8 1.6-2.8 1.6v4.6h11.6V11zM14 1c.6 0 1 .536 1 1.071v11.784c0 .642-.4 1.071-1 1.071H2c-.6 0-1-.429-1-1.07V2.07c0-.535.4-1.07 1-1.07h12z"></path>
</g>
</svg>
);
+
+export const ExtraToolsIcon = createIcon(
+ <svg stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
+ <g strokeWidth={1.5} fill='none'>
+ <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
+ <path d="M12 3l-4 7h8z"></path>
+ <path d="M17 17m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"></path>
+ <path d="M4 14m0 1a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1z"></path>
+ </g>
+ </svg>
+);
diff --git a/packages/drawnix/src/components/toolbar/creation-toolbar.tsx b/packages/drawnix/src/components/toolbar/creation-toolbar.tsx
index 560d368..a8ddf5a 100644
--- a/packages/drawnix/src/components/toolbar/creation-toolbar.tsx
+++ b/packages/drawnix/src/components/toolbar/creation-toolbar.tsx
@@ -11,6 +11,7 @@ import {
StraightArrowLineIcon,
FeltTipPenIcon,
ImageIcon,
+ ExtraToolsIcon,
} from '../icons';
import { useBoard } from '@drawnix/react-board';
import {
@@ -53,6 +54,16 @@ import {
insertImage,
loadHTMLImageElement,
} from '../../data/image';
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogHeading,
+ DialogTrigger,
+} from '../dialog/dialog';
+import MermaidToDrawnix from '../ttd-dialog/mermaid-to-drawnix';
+import { MermaidToDrawnixLibProps } from '../ttd-dialog/common';
export enum PopupKey {
'shape' = 'shape',
@@ -64,7 +75,7 @@ type AppToolButtonProps = {
name?: string;
icon: React.ReactNode;
pointer?: DrawnixPointerType;
- key?: PopupKey | 'image';
+ key?: PopupKey | 'image' | 'extra-tools';
};
const isBasicPointer = (pointer: string) => {
@@ -116,6 +127,11 @@ export const BUTTONS: AppToolButtonProps[] = [
title: 'Image',
key: 'image',
},
+ {
+ icon: ExtraToolsIcon,
+ title: '更多工具',
+ key: 'extra-tools',
+ },
];
// TODO provider by plait/draw
@@ -166,6 +182,14 @@ export const CreationToolbar = () => {
insertImage(board, imageFile);
};
+ const [dialogOpen, setDialogOpen] = useState(false);
+
+ const [mermaidToDrawnixLib, setMermaidToDrawnixLib] =
+ useState<MermaidToDrawnixLibProps>({
+ loaded: false,
+ api: import('@drawnix/mermaid-to-drawnix'),
+ });
+
return (
<Island
padding={1}
@@ -183,6 +207,7 @@ export const CreationToolbar = () => {
open={shapeOpen}
sideOffset={12}
onOpenChange={(open) => {
+ console.log('open', open);
setShapeOpen(open);
}}
>
@@ -260,6 +285,35 @@ export const CreationToolbar = () => {
</Popover>
);
}
+ if (button.key === 'extra-tools') {
+ return (
+ <Dialog
+ key={index}
+ open={dialogOpen}
+ onOpenChange={(open) => {
+ console.log('open', open);
+ setDialogOpen(open);
+ }}
+ >
+ <DialogTrigger asChild>
+ <ToolButton
+ type="radio"
+ icon={button.icon}
+ checked={isChecked(button)}
+ title={`${button.title}`}
+ aria-label={`${button.title}`}
+ onPointerUp={() => {
+ setDialogOpen(!dialogOpen);
+ console.log('dialogOpen', !dialogOpen);
+ }}
+ />
+ </DialogTrigger>
+ <DialogContent className="Dialog ttd-dialog" container={container}>
+ <MermaidToDrawnix mermaidToDrawnixLib={mermaidToDrawnixLib}></MermaidToDrawnix>
+ </DialogContent>
+ </Dialog>
+ );
+ }
return (
<ToolButton
key={index}
diff --git a/packages/drawnix/src/components/ttd-dialog/common.ts b/packages/drawnix/src/components/ttd-dialog/common.ts
new file mode 100644
index 0000000..841bd79
--- /dev/null
+++ b/packages/drawnix/src/components/ttd-dialog/common.ts
@@ -0,0 +1,118 @@
+import type { MermaidConfig } from '@drawnix/mermaid-to-drawnix/dist';
+import type { MermaidToDrawnixResult } from '@drawnix/mermaid-to-drawnix/dist/interfaces';
+import { PlaitBoard, PlaitElement } from '@plait/core';
+
+const resetPreview = ({
+ canvasRef,
+ setError,
+}: {
+ canvasRef: React.RefObject<HTMLDivElement | null>;
+ setError: (error: Error | null) => void;
+}) => {
+ const canvasNode = canvasRef.current;
+
+ if (!canvasNode) {
+ return;
+ }
+ const parent = canvasNode.parentElement;
+ if (!parent) {
+ return;
+ }
+ parent.style.background = '';
+ setError(null);
+ canvasNode.replaceChildren();
+};
+
+export interface MermaidToDrawnixLibProps {
+ loaded: boolean;
+ api: Promise<{
+ parseMermaidToDrawnix: (
+ definition: string,
+ config?: MermaidConfig
+ ) => Promise<MermaidToDrawnixResult>;
+ }>;
+}
+
+interface ConvertMermaidToDrawnixFormatProps {
+ canvasRef: React.RefObject<HTMLDivElement | null>;
+ mermaidToDrawnixLib: MermaidToDrawnixLibProps;
+ mermaidDefinition: string;
+ setError: (error: Error | null) => void;
+ data: React.MutableRefObject<{
+ elements: readonly PlaitElement[];
+ }>;
+}
+
+export const convertMermaidToDrawnix = async ({
+ canvasRef,
+ mermaidToDrawnixLib,
+ mermaidDefinition,
+ setError,
+ data,
+}: ConvertMermaidToDrawnixFormatProps) => {
+ const canvasNode = canvasRef.current;
+ const parent = canvasNode?.parentElement;
+
+ if (!canvasNode || !parent) {
+ return;
+ }
+
+ if (!mermaidDefinition) {
+ resetPreview({ canvasRef, setError });
+ return;
+ }
+
+ try {
+ const api = await mermaidToDrawnixLib.api;
+
+ let ret;
+ try {
+ ret = await api.parseMermaidToDrawnix(mermaidDefinition);
+ } catch (err: any) {
+ ret = await api.parseMermaidToDrawnix(
+ mermaidDefinition.replace(/"/g, "'")
+ );
+ }
+ const { elements } = ret;
+ setError(null);
+
+ data.current = {
+ elements,
+ };
+ } catch (err: any) {
+ setError(err);
+ }
+};
+
+export const saveMermaidDataToStorage = (mermaidDefinition: string) => {};
+
+export const insertToEditor = ({
+ board,
+ data,
+ text,
+ shouldSaveMermaidDataToStorage,
+}: {
+ board: PlaitBoard;
+ data: React.MutableRefObject<{
+ elements: readonly PlaitElement[];
+ }>;
+ text?: string;
+ shouldSaveMermaidDataToStorage?: boolean;
+}) => {
+ const { elements: newElements } = data.current;
+
+ if (!newElements.length) {
+ return;
+ }
+
+ // app.addElementsFromPasteOrLibrary({
+ // elements: newElements,
+ // files,
+ // position: 'center',
+ // fitToContent: true,
+ // });
+ // app.setOpenDialog(null);
+
+ if (shouldSaveMermaidDataToStorage && text) {
+ }
+};
diff --git a/packages/drawnix/src/components/ttd-dialog/mermaid-to-drawnix.scss b/packages/drawnix/src/components/ttd-dialog/mermaid-to-drawnix.scss
new file mode 100644
index 0000000..323c538
--- /dev/null
+++ b/packages/drawnix/src/components/ttd-dialog/mermaid-to-drawnix.scss
@@ -0,0 +1,10 @@
+.drawnix {
+ .dialog-mermaid {
+ &-title {
+ margin-block: 0.25rem;
+ font-size: 1.25rem;
+ font-weight: 700;
+ padding-inline: 2.5rem;
+ }
+ }
+}
diff --git a/packages/drawnix/src/components/ttd-dialog/mermaid-to-drawnix.tsx b/packages/drawnix/src/components/ttd-dialog/mermaid-to-drawnix.tsx
new file mode 100644
index 0000000..6986e8d
--- /dev/null
+++ b/packages/drawnix/src/components/ttd-dialog/mermaid-to-drawnix.tsx
@@ -0,0 +1,106 @@
+import { useState, useRef, useEffect, useDeferredValue } from 'react';
+import './mermaid-to-drawnix.scss';
+import './ttd-dialog.scss';
+import {
+ convertMermaidToDrawnix,
+ insertToEditor,
+ MermaidToDrawnixLibProps,
+} from './common';
+import { TTDDialogPanels } from './ttd-dialog-panels';
+import { TTDDialogPanel } from './ttd-dialog-panel';
+import { TTDDialogInput } from './ttd-dialog-input';
+import { TTDDialogOutput } from './ttd-dialog-output';
+import { TTDDialogSubmitShortcut } from './ttd-dialog-submit-shortcut';
+import { useDrawnix } from '../../hooks/use-drawnix';
+import { useBoard } from '@drawnix/react-board';
+import { PlaitElement } from '@plait/core';
+
+const MERMAID_EXAMPLE =
+ 'flowchart TD\n A[Christmas] -->|Get money| B(Go shopping)\n B --> C{Let me think}\n C -->|One| D[Laptop]\n C -->|Two| E[iPhone]\n C -->|Three| F[Car]';
+
+const MermaidToDrawnix = ({
+ mermaidToDrawnixLib,
+}: {
+ mermaidToDrawnixLib: MermaidToDrawnixLibProps;
+}) => {
+ const [text, setText] = useState(() => MERMAID_EXAMPLE);
+ const deferredText = useDeferredValue(text.trim());
+ const [error, setError] = useState<Error | null>(null);
+
+ const canvasRef = useRef<HTMLDivElement>(null);
+ const data = useRef<{
+ elements: readonly PlaitElement[];
+ }>({ elements: [] });
+
+ const app = useDrawnix();
+ const board = useBoard();
+
+ useEffect(() => {
+ convertMermaidToDrawnix({
+ canvasRef,
+ data,
+ mermaidToDrawnixLib,
+ setError,
+ mermaidDefinition: deferredText,
+ }).catch((err: any) => {
+ console.error(err);
+ });
+ }, [deferredText, mermaidToDrawnixLib]);
+
+ useEffect(
+ () => () => {
+ // debouncedSaveMermaidDefinition.flush();
+ },
+ []
+ );
+
+ const onInsertToEditor = () => {
+ insertToEditor({
+ board,
+ data,
+ text,
+ shouldSaveMermaidDataToStorage: true,
+ });
+ };
+
+ return (
+ <>
+ <div className="ttd-dialog-desc">
+ 目前仅支持
+ <a href="https://mermaid.js.org/syntax/flowchart.html">流程图</a>、
+ <a href="https://mermaid.js.org/syntax/sequenceDiagram.html">序列图</a>
+ 和<a href="https://mermaid.js.org/syntax/classDiagram.html">类图</a>
+ 。其他类型在 Drawnix 中将以图像呈现。
+ </div>
+ <TTDDialogPanels>
+ <TTDDialogPanel label={'Mermaid 语法'}>
+ <TTDDialogInput
+ input={text}
+ placeholder={'在此处编写 Mermaid 图表定义...'}
+ onChange={(event) => setText(event.target.value)}
+ onKeyboardSubmit={() => {
+ onInsertToEditor();
+ }}
+ />
+ </TTDDialogPanel>
+ <TTDDialogPanel
+ label={'预览'}
+ panelAction={{
+ action: () => {
+ onInsertToEditor();
+ },
+ label: '插入',
+ }}
+ renderSubmitShortcut={() => <TTDDialogSubmitShortcut />}
+ >
+ <TTDDialogOutput
+ canvasRef={canvasRef}
+ loaded={mermaidToDrawnixLib.loaded}
+ error={error}
+ />
+ </TTDDialogPanel>
+ </TTDDialogPanels>
+ </>
+ );
+};
+export default MermaidToDrawnix;
diff --git a/packages/drawnix/src/components/ttd-dialog/ttd-dialog-input.tsx b/packages/drawnix/src/components/ttd-dialog/ttd-dialog-input.tsx
new file mode 100644
index 0000000..e11d0dc
--- /dev/null
+++ b/packages/drawnix/src/components/ttd-dialog/ttd-dialog-input.tsx
@@ -0,0 +1,53 @@
+import type { ChangeEventHandler } from "react";
+import { useEffect, useRef } from "react";
+import { EVENT } from "../../constants";
+import { KEYS } from "../../keys";
+
+interface TTDDialogInputProps {
+ input: string;
+ placeholder: string;
+ onChange: ChangeEventHandler<HTMLTextAreaElement>;
+ onKeyboardSubmit?: () => void;
+}
+
+export const TTDDialogInput = ({
+ input,
+ placeholder,
+ onChange,
+ onKeyboardSubmit,
+}: TTDDialogInputProps) => {
+ const ref = useRef<HTMLTextAreaElement>(null);
+
+ const callbackRef = useRef(onKeyboardSubmit);
+ callbackRef.current = onKeyboardSubmit;
+
+ useEffect(() => {
+ if (!callbackRef.current) {
+ return;
+ }
+ const textarea = ref.current;
+ if (textarea) {
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event[KEYS.CTRL_OR_CMD] && event.key === KEYS.ENTER) {
+ event.preventDefault();
+ callbackRef.current?.();
+ }
+ };
+ textarea.addEventListener(EVENT.KEYDOWN, handleKeyDown);
+ return () => {
+ textarea.removeEventListener(EVENT.KEYDOWN, handleKeyDown);
+ };
+ }
+ }, []);
+
+ return (
+ <textarea
+ className="ttd-dialog-input"
+ onChange={onChange}
+ value={input}
+ placeholder={placeholder}
+ autoFocus
+ ref={ref}
+ />
+ );
+};
diff --git a/packages/drawnix/src/components/ttd-dialog/ttd-dialog-output.tsx b/packages/drawnix/src/components/ttd-dialog/ttd-dialog-output.tsx
new file mode 100644
index 0000000..81153dc
--- /dev/null
+++ b/packages/drawnix/src/components/ttd-dialog/ttd-dialog-output.tsx
@@ -0,0 +1,37 @@
+const ErrorComp = ({ error }: { error: string }) => {
+ return (
+ <div
+ data-testid="ttd-dialog-output-error"
+ className="ttd-dialog-output-error"
+ >
+ Error! <p>{error}</p>
+ </div>
+ );
+};
+
+interface TTDDialogOutputProps {
+ error: Error | null;
+ canvasRef: React.RefObject<HTMLDivElement>;
+ loaded: boolean;
+}
+
+export const TTDDialogOutput = ({
+ error,
+ canvasRef,
+ loaded,
+}: TTDDialogOutputProps) => {
+ return (
+ <div className="ttd-dialog-output-wrapper">
+ {error && <ErrorComp error={error.message} />}
+ {loaded ? (
+ <div
+ ref={canvasRef}
+ style={{ opacity: error ? '0.15' : 1 }}
+ className="ttd-dialog-output-canvas-container"
+ />
+ ) : (
+ <div className="ttd-dialog-output-loading">Loading...</div>
+ )}
+ </div>
+ );
+};
diff --git a/packages/drawnix/src/components/ttd-dialog/ttd-dialog-panel.tsx b/packages/drawnix/src/components/ttd-dialog/ttd-dialog-panel.tsx
new file mode 100644
index 0000000..ccc09dc
--- /dev/null
+++ b/packages/drawnix/src/components/ttd-dialog/ttd-dialog-panel.tsx
@@ -0,0 +1,61 @@
+import type { ReactNode } from "react";
+import classNames from "classnames";
+
+interface TTDDialogPanelProps {
+ label: string;
+ children: ReactNode;
+ panelAction?: {
+ label: string;
+ action: () => void;
+ icon?: ReactNode;
+ };
+ panelActionDisabled?: boolean;
+ onTextSubmitInProgress?: boolean;
+ renderTopRight?: () => ReactNode;
+ renderSubmitShortcut?: () => ReactNode;
+ renderBottomRight?: () => ReactNode;
+}
+
+export const TTDDialogPanel = ({
+ label,
+ children,
+ panelAction,
+ panelActionDisabled = false,
+ onTextSubmitInProgress,
+ renderTopRight,
+ renderSubmitShortcut,
+ renderBottomRight,
+}: TTDDialogPanelProps) => {
+ return (
+ <div className="ttd-dialog-panel">
+ <div className="ttd-dialog-panel__header">
+ <label>{label}</label>
+ {renderTopRight?.()}
+ </div>
+
+ {children}
+ <div
+ className={classNames("ttd-dialog-panel-button-container", {
+ invisible: !panelAction,
+ })}
+ style={{ display: "flex", alignItems: "center" }}
+ >
+ <button
+ className="ttd-dialog-panel-button"
+ onSelect={panelAction ? panelAction.action : () => {}}
+ disabled={panelActionDisabled || onTextSubmitInProgress}
+ >
+ <div className={classNames({ invisible: onTextSubmitInProgress })}>
+ {panelAction?.label}
+ {panelAction?.icon && <span>{panelAction.icon}</span>}
+ </div>
+ {/* {onTextSubmitInProgress && <Spinner />} */}
+ </button>
+ {!panelActionDisabled &&
+ !onTextSubmitInProgress &&
+ renderSubmitShortcut?.()}
+ {renderBottomRight?.()}
+ </div>
+ </div>
+ );
+};
diff --git a/packages/drawnix/src/components/ttd-dialog/ttd-dialog-panels.tsx b/packages/drawnix/src/components/ttd-dialog/ttd-dialog-panels.tsx
new file mode 100644
index 0000000..0e5e2b5
--- /dev/null
+++ b/packages/drawnix/src/components/ttd-dialog/ttd-dialog-panels.tsx
@@ -0,0 +1,5 @@
+import type { ReactNode } from "react";
+
+export const TTDDialogPanels = ({ children }: { children: ReactNode }) => {
+ return <div className="ttd-dialog-panels">{children}</div>;
+};
diff --git a/packages/drawnix/src/components/ttd-dialog/ttd-dialog-submit-shortcut.tsx b/packages/drawnix/src/components/ttd-dialog/ttd-dialog-submit-shortcut.tsx
new file mode 100644
index 0000000..c878416
--- /dev/null
+++ b/packages/drawnix/src/components/ttd-dialog/ttd-dialog-submit-shortcut.tsx
@@ -0,0 +1,14 @@
+import { getShortcutKey } from "../../utils/common";
+
+export const TTDDialogSubmitShortcut = () => {
+ return (
+ <div className="ttd-dialog-submit-shortcut">
+ <div className="ttd-dialog-submit-shortcut__key">
+ {getShortcutKey("CtrlOrCmd")}
+ </div>
+ <div className="ttd-dialog-submit-shortcut__key">
+ {getShortcutKey("Enter")}
+ </div>
+ </div>
+ );
+};
diff --git a/packages/drawnix/src/components/ttd-dialog/ttd-dialog.scss b/packages/drawnix/src/components/ttd-dialog/ttd-dialog.scss
new file mode 100644
index 0000000..1d5d865
--- /dev/null
+++ b/packages/drawnix/src/components/ttd-dialog/ttd-dialog.scss
@@ -0,0 +1,315 @@
+@import "../../styles/variables.module.scss";
+
+$verticalBreakpoint: 861px;
+
+.drawnix {
+ .Dialog.ttd-dialog {
+ padding: 1.25rem;
+
+ &.Dialog--fullscreen {
+ margin-top: 0;
+ }
+
+ .Island {
+ padding-inline: 0 !important;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ flex: 1 1 auto;
+ box-shadow: none;
+ }
+
+ .Modal__content {
+ height: auto;
+ max-height: 100%;
+
+ @media screen and (min-width: $verticalBreakpoint) {
+ max-height: 750px;
+ height: 100%;
+ }
+ }
+
+ .Dialog__content {
+ flex: 1 1 auto;
+ }
+ }
+
+ .ttd-dialog-desc {
+ font-size: 15px;
+ font-style: italic;
+ font-weight: 500;
+ margin-bottom: 1.5rem;
+ }
+
+ .ttd-dialog-tabs-root {
+ width: 100%;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ }
+
+ .ttd-dialog-tab-trigger {
+ color: var(--color-on-surface);
+ font-size: 0.875rem;
+ margin: 0;
+ padding: 0 1rem;
+ background-color: transparent;
+ border: 0;
+ height: 2.875rem;
+ font-weight: 600;
+ font-family: inherit;
+ letter-spacing: 0.4px;
+
+ &[data-state="active"] {
+ border-bottom: 2px solid var(--color-primary);
+ }
+ }
+
+ .ttd-dialog-triggers {
+ border-bottom: 1px solid var(--color-surface-high);
+ margin-bottom: 1.5rem;
+ padding-inline: 2.5rem;
+ }
+
+ .ttd-dialog-content {
+ padding-inline: 2.5rem;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+
+ &[hidden] {
+ display: none;
+ }
+ }
+
+ .ttd-dialog-input {
+ width: auto;
+ height: 10rem;
+ resize: none;
+ border-radius: var(--border-radius-lg);
+ border: 1px solid var(--dialog-border-color);
+ white-space: pre-wrap;
+ padding: 0.85rem;
+ box-sizing: border-box;
+ font-family: monospace;
+
+ @media screen and (min-width: $verticalBreakpoint) {
+ width: 100%;
+ height: 100%;
+ }
+ }
+
+ .ttd-dialog-output-wrapper {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 0.85rem;
+ box-sizing: border-box;
+ flex-grow: 1;
+ position: relative;
+
+ background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAMUlEQVQ4T2NkYGAQYcAP3uCTZhw1gGGYhAGBZIA/nYDCgBDAm9BGDWAAJyRCgLaBCAAgXwixzAS0pgAAAABJRU5ErkJggg==")
+ left center;
+ border-radius: var(--border-radius-lg);
+ border: 1px solid var(--dialog-border-color);
+
+ height: 400px;
+ width: auto;
+
+ @media screen and (min-width: $verticalBreakpoint) {
+ width: 100%;
+ // acts as min-height
+ height: 200px;
+ }
+
+ canvas {
+ max-width: 100%;
+ max-height: 100%;
+ }
+ }
+
+ .ttd-dialog-output-canvas-container {
+ display: flex;
+ width: 100%;
+ height: 100%;
+ align-items: center;
+ justify-content: center;
+ flex-grow: 1;
+ }
+
+ .ttd-dialog-output-error {
+ color: red;
+ font-weight: 700;
+ font-size: 30px;
+ word-break: break-word;
+ overflow: auto;
+ max-height: 100%;
+ height: 100%;
+ width: 100%;
+ text-align: center;
+ position: absolute;
+ z-index: 10;
+
+ p {
+ font-weight: 500;
+ font-family: Cascadia;
+ text-align: left;
+ white-space: pre-wrap;
+ font-size: 0.875rem;
+ padding: 0 10px;
+ }
+ }
+
+ .ttd-dialog-panels {
+ height: 100%;
+
+ @media screen and (min-width: $verticalBreakpoint) {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 4rem;
+ }
+ }
+
+ .ttd-dialog-panel {
+ display: flex;
+ flex-direction: column;
+ width: 100%;
+
+ &__header {
+ display: flex;
+ margin: 0px 4px 4px 4px;
+ align-items: center;
+ gap: 1rem;
+
+ label {
+ font-size: 14px;
+ font-style: normal;
+ font-weight: 600;
+ }
+ }
+
+ &:first-child {
+ .ttd-dialog-panel-button-container:not(.invisible) {
+ margin-bottom: 4rem;
+ }
+ }
+
+ @media screen and (min-width: $verticalBreakpoint) {
+ .ttd-dialog-panel-button-container:not(.invisible) {
+ margin-bottom: 0.5rem !important;
+ }
+ }
+
+ textarea {
+ height: 100%;
+ resize: none;
+ border-radius: var(--border-radius-lg);
+ border: 1px solid var(--dialog-border-color);
+ white-space: pre-wrap;
+ padding: 0.85rem;
+ box-sizing: border-box;
+ width: 100%;
+ font-family: monospace;
+
+ @media screen and (max-width: $verticalBreakpoint) {
+ width: auto;
+ height: 10rem;
+ }
+ }
+ }
+
+ .ttd-dialog-panel-button-container {
+ margin-top: 1rem;
+ margin-bottom: 0.5rem;
+
+ &.invisible {
+ .ttd-dialog-panel-button {
+ display: none;
+
+ @media screen and (min-width: $verticalBreakpoint) {
+ display: block;
+ visibility: hidden;
+ }
+ }
+ }
+ }
+
+ .ttd-dialog-panel-button {
+ &.drawnix-button {
+ font-family: inherit;
+ font-weight: 600;
+ height: 2.5rem;
+
+ font-size: 12px;
+ color: $oc-white;
+ background-color: var(--color-primary);
+ width: 100%;
+
+ &:hover {
+ background-color: var(--color-primary-darker);
+ }
+ &:active {
+ background-color: var(--color-primary-darkest);
+ }
+
+ &:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+
+ &:hover {
+ background-color: var(--color-primary);
+ }
+ }
+
+ @media screen and (min-width: $verticalBreakpoint) {
+ width: auto;
+ min-width: 7.5rem;
+ }
+
+ @at-root .drawnix.theme--dark#{&} {
+ color: var(--color-gray-100);
+ }
+ }
+
+ position: relative;
+
+ div {
+ display: contents;
+
+ &.invisible {
+ visibility: hidden;
+ }
+
+ &.Spinner {
+ display: flex !important;
+ position: absolute;
+ inset: 0;
+
+ --spinner-color: white;
+
+ @at-root .drawnix.theme--dark#{&} {
+ --spinner-color: var(--color-gray-100);
+ }
+ }
+
+ span {
+ padding-left: 0.5rem;
+ display: flex;
+ }
+ }
+ }
+
+ .ttd-dialog-submit-shortcut {
+ margin-inline-start: 0.5rem;
+ font-size: 0.625rem;
+ opacity: 0.6;
+ display: flex;
+ gap: 0.125rem;
+
+ &__key {
+ border: 1px solid gray;
+ padding: 2px 3px;
+ border-radius: 4px;
+ }
+ }
+}
diff --git a/packages/drawnix/src/plugins/freehand/utils.ts b/packages/drawnix/src/plugins/freehand/utils.ts
index 98266b5..ff44483 100644
--- a/packages/drawnix/src/plugins/freehand/utils.ts
+++ b/packages/drawnix/src/plugins/freehand/utils.ts
@@ -41,7 +41,7 @@ export const isHitFreehand = (
element: Freehand,
point: Point
) => {
- const antiPoint = rotateAntiPointsByElement(point, element) || point;
+ const antiPoint = rotateAntiPointsByElement(board, point, element) || point;
const points = element.points;
if (isClosedPoints(element.points)) {
return (
diff --git a/packages/drawnix/src/styles/theme.scss b/packages/drawnix/src/styles/theme.scss
index 7030f55..b14b31f 100644
--- a/packages/drawnix/src/styles/theme.scss
+++ b/packages/drawnix/src/styles/theme.scss
@@ -8,7 +8,7 @@
--island-border-color: #eeeeee;
--keybinding-color: var(--color-gray-40);
--shadow-island: 0 0 16px #00000014;
-
+ --dialog-border-color: var(--color-gray-20);
--button-hover-bg: var(--color-surface-high);
--button-active-border: var(--color-brand-active);
diff --git a/packages/drawnix/src/utils/common.ts b/packages/drawnix/src/utils/common.ts
index f75765d..ababfe9 100644
--- a/packages/drawnix/src/utils/common.ts
+++ b/packages/drawnix/src/utils/common.ts
@@ -1,4 +1,4 @@
-import { PlaitBoard, toImage, ToImageOptions } from '@plait/core';
+import { IS_APPLE, IS_MAC, PlaitBoard, toImage, ToImageOptions } from '@plait/core';
import type { ResolutionType } from './utility-types';
export const isPromiseLike = (
@@ -78,3 +78,16 @@ export const splitRows = <T>(shapes: T[], cols: number) => {
}
return result;
};
+
+export const getShortcutKey = (shortcut: string): string => {
+ shortcut = shortcut
+ .replace(/\bAlt\b/i, "Alt")
+ .replace(/\bShift\b/i, "Shift")
+ .replace(/\b(Enter|Return)\b/i, "Enter");
+ if (IS_APPLE || IS_MAC) {
+ return shortcut
+ .replace(/\bCtrlOrCmd\b/gi, "Cmd")
+ .replace(/\bAlt\b/i, "Option");
+ }
+ return shortcut.replace(/\bCtrlOrCmd\b/gi, "Ctrl");
+};
\ No newline at end of file