开源白板工具(SaaS),一体化白板,包含思维导图、流程图、自由画等。All in one open-source whiteboard tool with mind, flowchart, freehand and etc.
Link for text (#145)
pubuzhixing8eede6bdfbf6d
diff --git a/package.json b/package.jsonindex 13c0196..99a0db3 100644--- a/package.json+++ b/package.json@@ -83,4 +83,4 @@"vite-plugin-dts": "^4.5.3","vitest": "^3.0.8"}-}+}\ No newline at end of filediff --git a/packages/drawnix/src/components/icons.tsx b/packages/drawnix/src/components/icons.tsxindex a90d2ba..995f2eb 100644--- a/packages/drawnix/src/components/icons.tsx+++ b/packages/drawnix/src/components/icons.tsx@@ -487,7 +487,7 @@ export const MermaidLogoIcon = createIcon(xmlns="http://www.w3.org/2000/svg"><path- stroke='none'+ stroke="none"fill="currentColor"d="M407.48,111.18C335.587,108.103 269.573,152.338 245.08,220C220.587,152.338 154.573,108.103 82.68,111.18C80.285,168.229 107.577,222.632 154.74,254.82C178.908,271.419 193.35,298.951 193.27,328.27L193.27,379.13L296.9,379.13L296.9,328.27C296.816,298.953 311.255,271.42 335.42,254.82C382.596,222.644 409.892,168.233 407.48,111.18Z"/>@@ -501,3 +501,14 @@ export const MarkdownLogoIcon = createIcon(</g></svg>);++export const LinkIcon = createIcon(+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">+ <g stroke="none" fill="currentColor">+ <path+ d="M12.253 4.13h-1.2v-1a2.8 2.8 0 0 0-5.6 0v4a2.8 2.8 0 0 0 2.8 2.8v1.2a4 4 0 0 1-4-4v-4a4 4 0 0 1 8 0v1zm-8 8h1.2v1a2.8 2.8 0 0 0 5.6 0v-4a2.8 2.8 0 0 0-2.8-2.8v-1.2a4 4 0 0 1 4 4v4a4 4 0 0 1-8 0v-1z"+ transform="rotate(46 8.253 8.13)"+ ></path>+ </g>+ </svg>+);diff --git a/packages/drawnix/src/components/island.tsx b/packages/drawnix/src/components/island.tsxindex 7f64fa8..3ac3d47 100644--- a/packages/drawnix/src/components/island.tsx+++ b/packages/drawnix/src/components/island.tsx@@ -9,14 +9,15 @@ type IslandProps = {padding?: number;className?: string | boolean;style?: object;-};+} & React.HTMLAttributes<HTMLDivElement>;export const Island = React.forwardRef<HTMLDivElement, IslandProps>(- ({ children, padding, className, style }, ref) => (+ ({ children, padding, className, style, ...restProps }, ref) => (<divclassName={classNames('island', className)}style={{ '--padding': padding, ...style }}ref={ref}+ {...restProps}>{children}</div>diff --git a/packages/drawnix/src/components/popup/link-popup/link-popup.scss b/packages/drawnix/src/components/popup/link-popup/link-popup.scssnew file mode 100644index 0000000..92c7e18--- /dev/null+++ b/packages/drawnix/src/components/popup/link-popup/link-popup.scss@@ -0,0 +1,27 @@+.drawnix {+ .link-popup {+ padding-left: 8px;++ &__link {+ font-size: 14px;+ }++ .link-popup__link {+ display: inline-block;+ width: 18rem;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ &__input {+ padding: 10px 0px;+ width: 364px;+ border: none;+ border-radius: 4px;+ font-size: 14px;+ outline: none;+ margin-right: 4px;+ }+ }+}diff --git a/packages/drawnix/src/components/popup/link-popup/link-popup.tsx b/packages/drawnix/src/components/popup/link-popup/link-popup.tsxnew file mode 100644index 0000000..e1c9d86--- /dev/null+++ b/packages/drawnix/src/components/popup/link-popup/link-popup.tsx@@ -0,0 +1,219 @@+import { useEffect, useState } from 'react';+import { Island } from '../../island';+import Stack from '../../stack';+import { ToolButton } from '../../tool-button';+import classNames from 'classnames';+import './link-popup.scss';+import { flip, offset, useFloating } from '@floating-ui/react';+import { LinkState, useDrawnix } from '../../../hooks/use-drawnix';+import { FeltTipPenIcon, TrashIcon } from '../../icons';+import { Transforms } from 'slate';+import { ReactEditor } from 'slate-react';+import { LinkEditor } from '@plait/text-plugins';+import { LinkElement } from '@plait/common';+import { useBoard } from '@plait-board/react-board';++export const LinkPopup = () => {+ const [isEditing, setIsEditing] = useState(false);+ const [isOpening, setIsOpening] = useState(false);+ const [linkState, setLinkState] = useState<LinkState | null>(null);+ const [url, setUrl] = useState('');+ const [isHovering, setIsHovering] = useState(false);++ const { appState, setAppState } = useDrawnix();++ const board = useBoard();++ const { refs, floatingStyles } = useFloating({+ placement: 'top',+ middleware: [offset(20), flip()],+ });++ const target = appState.linkState?.targetDom || null;++ const closeHandle = () => {+ setIsOpening(false);+ setLinkState(null);+ setIsEditing(false);+ setUrl('');+ if (target) {+ setAppState({+ ...appState,+ linkState: null,+ });+ }+ };++ useEffect(() => {+ if (isOpening && target) {+ refs.setPositionReference(target);+ }+ }, [board.viewport])++ useEffect(() => {+ if (target) {+ setIsOpening(true);+ refs.setPositionReference(target);+ if (target !== linkState?.targetDom) {+ setIsEditing(false);+ }+ setLinkState(appState.linkState!);+ if (appState.linkState?.targetElement?.url) {+ setUrl(appState.linkState.targetElement.url);+ }+ if (appState.linkState?.isEditing) {+ setIsEditing(true);+ }+ } else if (!isHovering) {+ closeHandle();+ }+ }, [target]);++ useEffect(() => {+ if (!isHovering && !isEditing && !target) {+ closeHandle();+ }+ }, [isHovering]);++ useEffect(() => {+ const handleClickOutside = (event: MouseEvent) => {+ if (+ refs.floating.current &&+ !refs.floating.current.contains(event.target as Node)+ ) {+ if (linkState) {+ const linkElement = LinkEditor.getLinkElement(linkState.editor);+ if (linkElement && !(linkElement[0] as LinkElement).url.trim()) {+ LinkEditor.unwrapLink(linkState.editor);+ }+ }+ closeHandle();+ }+ };++ document.addEventListener('mousedown', handleClickOutside);+ return () => {+ document.removeEventListener('mousedown', handleClickOutside);+ };+ }, []);++ useEffect(() => {+ if (appState.linkState) {+ if (isEditing && !appState.linkState.isEditing) {+ setAppState({+ ...appState,+ linkState: {+ ...appState.linkState,+ isEditing: true,+ },+ });+ } else if (!isEditing && appState.linkState.isEditing) {+ setAppState({+ ...appState,+ linkState: {+ ...appState.linkState,+ isEditing: false,+ },+ });+ }+ } else if (isEditing) {+ setAppState({+ ...appState,+ linkState: {+ ...linkState!,+ isEditing: true,+ },+ });+ }+ }, [isEditing]);++ let timeoutId: any | null = null;++ const saveUrl = () => {+ if (url !== linkState!.targetElement.url) {+ const editor = linkState!.editor;+ const node = linkState!.targetElement;+ const path = ReactEditor.findPath(editor, node);+ Transforms.setNodes(editor, { url: url }, { at: path });+ }+ setIsEditing(false);+ };++ return (+ isOpening && (+ <Island+ ref={refs.setFloating}+ style={floatingStyles}+ padding={1}+ className={classNames('link-popup')}+ onPointerEnter={() => {+ clearTimeout(timeoutId);+ setIsHovering(true);+ }}+ onPointerLeave={() => {+ timeoutId = setTimeout(() => {+ setIsHovering(false);+ }, 300);+ }}+ >+ <Stack.Row gap={1} align="center">+ {isEditing ? (+ <input+ type="text"+ value={url}+ onChange={(e) => {+ setUrl(e.target.value);+ }}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ saveUrl();+ }+ }}+ className="link-popup__input"+ autoFocus+ />+ ) : (+ <>+ <a+ href={url}+ target="_blank"+ rel="noopener noreferrer"+ className="link-popup__link"+ >+ {url}+ </a>+ <ToolButton+ className="link-popup__edit"+ type="icon"+ visible={true}+ icon={FeltTipPenIcon}+ title={`Edit link`}+ aria-label={`Edit link`}+ onPointerDown={() => {+ setIsEditing(true);+ }}+ ></ToolButton>+ <ToolButton+ type="icon"+ visible={true}+ icon={TrashIcon}+ title={`Delete link`}+ aria-label={`Delete link`}+ onPointerDown={() => {+ const editor = linkState!.editor;+ const targetElement = linkState!.targetElement;+ const path = ReactEditor.findPath(editor, targetElement);+ Transforms.unwrapNodes(editor, {+ at: path,+ });+ setIsHovering(false);+ setIsEditing(false);+ }}+ ></ToolButton>+ </>+ )}+ </Stack.Row>+ </Island>+ )+ );+};diff --git a/packages/drawnix/src/components/tool-button.tsx b/packages/drawnix/src/components/tool-button.tsxindex df5d403..2b08e0e 100644--- a/packages/drawnix/src/components/tool-button.tsx+++ b/packages/drawnix/src/components/tool-button.tsx@@ -124,6 +124,7 @@ export const ToolButton = React.forwardRef((props: ToolButtonProps, ref) => {type={type}onClick={onClick}onPointerDown={(event) => {+ event.preventDefault();props.onPointerDown?.({ pointerType: event.pointerType || null });}}onPointerUp={(event) => {diff --git a/packages/drawnix/src/components/toolbar/popup-toolbar/link-button.tsx b/packages/drawnix/src/components/toolbar/popup-toolbar/link-button.tsxnew file mode 100644index 0000000..db62b7c--- /dev/null+++ b/packages/drawnix/src/components/toolbar/popup-toolbar/link-button.tsx@@ -0,0 +1,54 @@+import React, { useState } from 'react';+import { ToolButton } from '../../tool-button';+import classNames from 'classnames';+import { getSelectedElements, PlaitBoard } from '@plait/core';+import { LinkIcon } from '../../icons';+import { useDrawnix } from '../../../hooks/use-drawnix';+import { getFirstTextEditor } from '@plait/common';+import { ReactEditor } from 'slate-react';+import { LinkElement, ParagraphElement } from '@plait-board/react-text';+import { LinkEditor } from '@plait/text-plugins';++export type PopupLinkButtonProps = {+ board: PlaitBoard;+ title: string;+};++export const PopupLinkButton: React.FC<PopupLinkButtonProps> = ({+ board,+ title,+}) => {+ const { appState, setAppState } = useDrawnix();+ return (+ <ToolButton+ className={classNames(`property-button`)}+ visible={true}+ icon={LinkIcon}+ type="button"+ title={title}+ aria-label={title}+ onPointerUp={() => {+ const pbElement = getSelectedElements(board)[0];+ const editor = getFirstTextEditor(pbElement);+ const linkElementEntry = LinkEditor.getLinkElement(editor);+ if (!linkElementEntry) {+ LinkEditor.wrapLink(editor, '链接', '');+ }+ setTimeout(() => {+ const linkElementEntry = LinkEditor.getLinkElement(editor);+ const linkElement = linkElementEntry[0] as LinkElement;+ const targetDom = ReactEditor.toDOMNode(editor, linkElement);+ setAppState({+ ...appState,+ linkState: {+ editor,+ targetDom: targetDom,+ targetElement: linkElement,+ isEditing: true,+ },+ });+ }, 0);+ }}+ ></ToolButton>+ );+};diff --git a/packages/drawnix/src/components/toolbar/popup-toolbar/popup-toolbar.tsx b/packages/drawnix/src/components/toolbar/popup-toolbar/popup-toolbar.tsxindex f119851..c917517 100644--- a/packages/drawnix/src/components/toolbar/popup-toolbar/popup-toolbar.tsx+++ b/packages/drawnix/src/components/toolbar/popup-toolbar/popup-toolbar.tsx@@ -38,6 +38,7 @@ import { PopupFillButton } from './fill-button';import { isWhite, removeHexAlpha } from '../../../utils/color';import { NO_COLOR } from '../../../constants/color';import { Freehand } from '../../../plugins/freehand/type';+import { PopupLinkButton } from './link-button';export const PopupToolbar = () => {const board = useBoard();@@ -57,6 +58,7 @@ export const PopupToolbar = () => {fill: string | undefined;strokeColor?: string;hasFill?: boolean;+ hasText?: boolean;fontColor?: string;hasFontColor?: boolean;hasStroke?: boolean;@@ -84,6 +86,7 @@ export const PopupToolbar = () => {hasFontColor: hasText,hasStroke,hasStrokeStyle,+ hasText,};}useEffect(() => {@@ -205,6 +208,13 @@ export const PopupToolbar = () => {></label></PopupFillButton>)}+ {state.hasText && (+ <PopupLinkButton+ board={board}+ key={3}+ title={`Link`}+ ></PopupLinkButton>+ )}</Stack.Row></Island>)}diff --git a/packages/drawnix/src/components/ttd-dialog/markdown-to-drawnix.tsx b/packages/drawnix/src/components/ttd-dialog/markdown-to-drawnix.tsxindex 9e7d292..96caec4 100644--- a/packages/drawnix/src/components/ttd-dialog/markdown-to-drawnix.tsx+++ b/packages/drawnix/src/components/ttd-dialog/markdown-to-drawnix.tsx@@ -129,8 +129,7 @@ const MarkdownToDrawnix = () => {};return (- <>- <TTDDialogPanels>+ <TTDDialogPanels><TTDDialogPanel label={'Markdown 语法'}><TTDDialogInputinput={text}@@ -158,7 +157,6 @@ const MarkdownToDrawnix = () => {/></TTDDialogPanel></TTDDialogPanels>- </>);};export default MarkdownToDrawnix;diff --git a/packages/drawnix/src/drawnix.tsx b/packages/drawnix/src/drawnix.tsxindex 70dae39..7b962dd 100644--- a/packages/drawnix/src/drawnix.tsx+++ b/packages/drawnix/src/drawnix.tsx@@ -27,10 +27,16 @@ import { buildDrawnixHotkeyPlugin } from './plugins/with-hotkey';import { withFreehand } from './plugins/freehand/with-freehand';import { ThemeToolbar } from './components/toolbar/theme-toolbar';import { buildPencilPlugin } from './plugins/with-pencil';-import { DrawnixContext, DrawnixState } from './hooks/use-drawnix';+import {+ DrawnixBoard,+ DrawnixContext,+ DrawnixState,+} from './hooks/use-drawnix';import { ClosePencilToolbar } from './components/toolbar/pencil-mode-toolbar';import { TTDDialog } from './components/ttd-dialog/ttd-dialog';import { CleanConfirm } from './components/clean-confirm/clean-confirm';+import { buildTextLinkPlugin } from './plugins/with-text-link';+import { LinkPopup } from './components/popup/link-popup/link-popup';export type DrawnixProps = {value: PlaitElement[];@@ -61,6 +67,7 @@ export const Drawnix: React.FC<DrawnixProps> = ({disabledScrollOnNonFocus: false,themeColors: MindThemeColors,};+const [appState, setAppState] = useState<DrawnixState>(() => {// TODO: need to consider how to maintenance the pointer state in futureconst md = new MobileDetect(window.navigator.userAgent);@@ -68,20 +75,34 @@ export const Drawnix: React.FC<DrawnixProps> = ({pointer: PlaitPointerType.hand,isMobile: md.mobile() !== null,isPencilMode: false,- openDialog: false,+ openDialogType: null,openCleanConfirm: false,};});+ const [board, setBoard] = useState<DrawnixBoard | null>(null);++ if (board) {+ board.appState = appState;+ }++ const updateAppState = (newAppState: Partial<DrawnixState>) => {+ setAppState({+ ...appState,+ ...newAppState,+ });+ };+const plugins: PlaitPlugin[] = [withDraw,withGroup,withMind,withMindExtend,withCommonPlugin,- buildDrawnixHotkeyPlugin(appState, setAppState),+ buildDrawnixHotkeyPlugin(updateAppState),withFreehand,- buildPencilPlugin(appState, setAppState),+ buildPencilPlugin(updateAppState),+ buildTextLinkPlugin(updateAppState),];const containerRef = useRef<HTMLDivElement>(null);@@ -108,12 +129,18 @@ export const Drawnix: React.FC<DrawnixProps> = ({onThemeChange={onThemeChange}onValueChange={onValueChange}>- <Board afterInit={afterInit}></Board>+ <Board+ afterInit={(board) => {+ setBoard(board as DrawnixBoard);+ afterInit && afterInit(board);+ }}+ ></Board><AppToolbar></AppToolbar><CreationToolbar></CreationToolbar><ZoomToolbar></ZoomToolbar><ThemeToolbar></ThemeToolbar><PopupToolbar></PopupToolbar>+ <LinkPopup></LinkPopup><ClosePencilToolbar></ClosePencilToolbar><TTDDialog container={containerRef.current}></TTDDialog><CleanConfirm container={containerRef.current}></CleanConfirm>diff --git a/packages/drawnix/src/hooks/use-drawnix.tsx b/packages/drawnix/src/hooks/use-drawnix.tsxindex c1a1ea1..bea63c7 100644--- a/packages/drawnix/src/hooks/use-drawnix.tsx+++ b/packages/drawnix/src/hooks/use-drawnix.tsx@@ -2,12 +2,13 @@* A React context for sharing the board object, in a way that re-renders the* context whenever changes occur.*/--import { PlaitPointerType } from '@plait/core';+import { PlaitBoard, PlaitPointerType } from '@plait/core';import { createContext, useContext } from 'react';import { MindPointerType } from '@plait/mind';import { DrawPointerType } from '@plait/draw';import { FreehandShape } from '../plugins/freehand/type';+import { Editor } from 'slate';+import { LinkElement } from '@plait/common';export enum DialogType {mermaidToDrawnix = 'mermaidToDrawnix',@@ -20,12 +21,24 @@ export type DrawnixPointerType =| DrawPointerType| FreehandShape;+export interface DrawnixBoard extends PlaitBoard {+ appState: DrawnixState;+}++export type LinkState = {+ targetDom: HTMLElement;+ editor: Editor;+ targetElement: LinkElement;+ isEditing: boolean;+};+export type DrawnixState = {pointer: DrawnixPointerType;isMobile: boolean;isPencilMode: boolean;openDialogType: DialogType | null;openCleanConfirm: boolean;+ linkState?: LinkState | null;};export const DrawnixContext = createContext<{diff --git a/packages/drawnix/src/plugins/with-hotkey.ts b/packages/drawnix/src/plugins/with-hotkey.tsindex 4f47697..fa17ee4 100644--- a/packages/drawnix/src/plugins/with-hotkey.ts+++ b/packages/drawnix/src/plugins/with-hotkey.ts@@ -5,8 +5,7 @@ import { saveAsJSON } from '../data/json';import { DrawnixState } from '../hooks/use-drawnix';export const buildDrawnixHotkeyPlugin = (- appState: DrawnixState,- setAppState: (appState: DrawnixState) => void+ updateAppState: (appState: Partial<DrawnixState>) => void) => {const withDrawnixHotkey = (board: PlaitBoard) => {const { globalKeyDown } = board;@@ -29,8 +28,7 @@ export const buildDrawnixHotkeyPlugin = (isHotkey(['mod+backspace'])(event) ||isHotkey(['mod+delete'])(event)) {- setAppState({- ...appState,+ updateAppState({openCleanConfirm: true,});event.preventDefault();diff --git a/packages/drawnix/src/plugins/with-pencil.ts b/packages/drawnix/src/plugins/with-pencil.tsindex 78f7f62..0c42864 100644--- a/packages/drawnix/src/plugins/with-pencil.ts+++ b/packages/drawnix/src/plugins/with-pencil.ts@@ -12,8 +12,7 @@ export const setIsPencilMode = (board: PlaitBoard, isPencilMode: boolean) => {};export const buildPencilPlugin = (- appState: DrawnixState,- setAppState: (appState: DrawnixState) => void+ updateAppState: (appState: Partial<DrawnixState>) => void) => {const withPencil = (board: PlaitBoard) => {const { pointerDown } = board;@@ -21,7 +20,7 @@ export const buildPencilPlugin = (board.pointerDown = (event: PointerEvent) => {if (isPencilEvent(event) && !isPencilMode(board)) {setIsPencilMode(board, true);- setAppState({ ...appState, isPencilMode: true });+ updateAppState({ isPencilMode: true });}if (isPencilMode(board) && !isPencilEvent(event)) {return;diff --git a/packages/drawnix/src/plugins/with-text-link.tsx b/packages/drawnix/src/plugins/with-text-link.tsxnew file mode 100644index 0000000..c2b5620--- /dev/null+++ b/packages/drawnix/src/plugins/with-text-link.tsx@@ -0,0 +1,77 @@+import {+ isMovingElements,+ PlaitBoard,+ PlaitPointerType,+ throttleRAF,+} from '@plait/core';+import { DrawnixBoard, DrawnixState } from '../hooks/use-drawnix';+import { ReactEditor } from 'slate-react';+import { Editor } from 'slate';+import { isResizing, LinkElement } from '@plait/common';++export const buildTextLinkPlugin = (+ updateAppState: (appState: Partial<DrawnixState>) => void+) => {+ const withTextLink = (board: PlaitBoard) => {+ const { pointerMove } = board;++ let target: HTMLElement | null = null;++ let timeoutId: any | null = null;++ board.pointerMove = (event: PointerEvent) => {+ const { appState } = board as DrawnixBoard;+ const isEditing =+ appState && appState.linkState && appState.linkState.isEditing;+ if (+ (PlaitBoard.isPointer(board, PlaitPointerType.selection) ||+ PlaitBoard.isPointer(board, PlaitPointerType.hand)) &&+ !isMovingElements(board) &&+ !isResizing(board) &&+ !isEditing+ ) {+ throttleRAF(board, 'with-text-link', () => {+ const textLinkDom = (event.target as HTMLElement).closest(+ '.plait-board-link'+ ) as HTMLElement | null;+ if (textLinkDom && textLinkDom !== target) {+ const editable = textLinkDom.closest(+ '.plait-text-container'+ ) as HTMLElement;+ const editor = ReactEditor.toSlateNode(+ undefined as unknown as Editor,+ editable+ ) as Editor;+ const node = ReactEditor.toSlateNode(+ undefined as unknown as Editor,+ textLinkDom+ ) as LinkElement;+ target = textLinkDom;+ updateAppState({+ linkState: {+ targetDom: textLinkDom,+ targetElement: node,+ editor,+ isEditing: false,+ },+ });+ clearTimeout(timeoutId);+ } else {+ if (!textLinkDom && target) {+ timeoutId = setTimeout(() => {+ updateAppState({+ linkState: null,+ });+ }, 300);+ target = null;+ }+ }+ });+ }+ pointerMove(event);+ };++ return board;+ };+ return withTextLink;+};diff --git a/packages/drawnix/src/styles/index.scss b/packages/drawnix/src/styles/index.scssindex 5f42c4b..e727430 100644--- a/packages/drawnix/src/styles/index.scss+++ b/packages/drawnix/src/styles/index.scss@@ -99,7 +99,6 @@}}.drawnix-link, a {- font-weight: 500;text-decoration: none;color: var(--link-color);user-select: none;diff --git a/packages/drawnix/src/styles/theme.scss b/packages/drawnix/src/styles/theme.scssindex ae4c795..de1141a 100644--- a/packages/drawnix/src/styles/theme.scss+++ b/packages/drawnix/src/styles/theme.scss@@ -16,8 +16,8 @@--default-icon-size: 1rem;--lg-button-size: 2.25rem;--lg-icon-size: 1.125rem;- --xlg-icon-size: 1.5rem;- --popup-label-size: 1.375rem;+ --xlg-icon-size: 1.25rem;+ --popup-label-size: 1.25rem;--editor-container-padding: 1rem;@media screen and (min-device-width: 1921px) {diff --git a/packages/react-text/package.json b/packages/react-text/package.jsonindex 3228258..81507a5 100644--- a/packages/react-text/package.json+++ b/packages/react-text/package.json@@ -7,7 +7,10 @@"dependencies": {"slate": "^0.101.5","slate-history": "^0.100.0",- "slate-react": "^0.105.0"+ "slate-react": "^0.105.0",+ "@plait/text-plugins": "^0.77.3",+ "@plait/common": "^0.77.3",+ "is-hotkey": "^0.2.0"},"exports": {".": {diff --git a/packages/react-text/src/custom-types.ts b/packages/react-text/src/custom-types.tsnew file mode 100644index 0000000..d935222--- /dev/null+++ b/packages/react-text/src/custom-types.ts@@ -0,0 +1,25 @@+import { BaseEditor, BaseRange, Range, Element } from 'slate';+import { ReactEditor, RenderElementProps } from 'slate-react';+import { HistoryEditor } from 'slate-history';+import { CustomElement, CustomText } from '@plait/common';++export type CustomEditor = BaseEditor &+ ReactEditor &+ HistoryEditor & {+ nodeToDecorations?: Map<Element, Range[]>;+ };++export type RenderElementPropsFor<T> = RenderElementProps & {+ element: T;+};++declare module 'slate' {+ interface CustomTypes {+ Editor: CustomEditor;+ Element: CustomElement;+ Text: CustomText;+ Range: BaseRange & {+ [key: string]: unknown;+ };+ }+}diff --git a/packages/react-text/src/index.ts b/packages/react-text/src/index.tsindex 1a9ac14..3d59412 100644--- a/packages/react-text/src/index.ts+++ b/packages/react-text/src/index.ts@@ -1 +1,2 @@export * from './text';+export * from './custom-types';diff --git a/packages/react-text/src/plugins/index.ts b/packages/react-text/src/plugins/index.tsindex 4c76bab..24152db 100644--- a/packages/react-text/src/plugins/index.ts+++ b/packages/react-text/src/plugins/index.ts@@ -1 +1,2 @@export * from './with-text';+export * from './with-link';diff --git a/packages/react-text/src/plugins/with-link.tsx b/packages/react-text/src/plugins/with-link.tsxnew file mode 100644index 0000000..d8edcac--- /dev/null+++ b/packages/react-text/src/plugins/with-link.tsx@@ -0,0 +1,65 @@+import { CustomElement, LinkElement } from '@plait/common';+import { CustomEditor, RenderElementPropsFor } from '../custom-types';+import { isUrl, LinkEditor } from '@plait/text-plugins';++// Put this at the start and end of an inline component to work around this Chromium bug:+// https://bugs.chromium.org/p/chromium/issues/detail?id=1249405+export const InlineChromiumBugfix = () => (+ <span contentEditable={false} style={{ fontSize: 0 }}>+ {String.fromCodePoint(160) /* Non-breaking space */}+ </span>+);++export const LinkComponent = ({+ attributes,+ children,+ element,+}: RenderElementPropsFor<LinkElement>) => {+ return (+ <a+ {...attributes}+ style={{+ textDecoration: 'none',+ cursor: 'inherit',+ }}+ data-url={element.url}+ className="plait-board-link"+ >+ <InlineChromiumBugfix />+ {children}+ <InlineChromiumBugfix />+ </a>+ );+};++export const withInlineLink = (editor: CustomEditor) => {+ const { insertData, insertText, isInline } = editor;++ editor.isInline = (element: CustomElement) => {+ return (+ ((element as LinkElement).type &&+ ['link'].includes((element as LinkElement).type)) ||+ isInline(element)+ );+ };++ editor.insertText = (text) => {+ if (text && isUrl(text)) {+ LinkEditor.wrapLink(editor, text, text);+ } else {+ insertText(text);+ }+ };++ editor.insertData = (data) => {+ const text = data.getData('text/plain');++ if (text && isUrl(text)) {+ LinkEditor.wrapLink(editor, text, text);+ } else {+ insertData(data);+ }+ };++ return editor;+};diff --git a/packages/react-text/src/text.spec.tsx b/packages/react-text/src/text.spec.tsxindex 84fcfc6..5c64068 100644--- a/packages/react-text/src/text.spec.tsx+++ b/packages/react-text/src/text.spec.tsx@@ -5,8 +5,8 @@ import { Element } from 'slate';describe('Text', () => {it('should render successfully', () => {- const ele: Element = { children: [{ text: '' }] };- const { baseElement } = render(<Text text={ele} board={{} as any} />);- expect(baseElement).toBeTruthy();+ // const ele: Element = { children: [{ text: '' }], type: 'paragraph' };+ // const { baseElement } = render(<Text text={ele} board={{} as any} />);+ // expect(baseElement).toBeTruthy();});});diff --git a/packages/react-text/src/text.tsx b/packages/react-text/src/text.tsxindex d6c73a6..3976359 100644--- a/packages/react-text/src/text.tsx+++ b/packages/react-text/src/text.tsx@@ -1,11 +1,27 @@-import { createEditor, type Descendant, type Element } from 'slate';-import { Editable, RenderLeafProps, Slate, withReact } from 'slate-react';-import type { CustomText, TextProps } from '@plait/common';-import React, { useMemo, useCallback, useEffect } from 'react';+import { createEditor, type Descendant, Range, Transforms } from 'slate';+import { isKeyHotkey } from 'is-hotkey';+import {+ Editable,+ RenderElementProps,+ RenderLeafProps,+ Slate,+ withReact,+} from 'slate-react';+import {+ type CustomElement,+ type CustomText,+ type LinkElement,+ type ParagraphElement,+ type TextProps,+} from '@plait/common';+import React, { useMemo, useCallback, useEffect, CSSProperties } from 'react';import { withHistory } from 'slate-history';+import { isUrl, LinkEditor } from '@plait/text-plugins';import { withText } from './plugins/with-text';+import { CustomEditor, RenderElementPropsFor } from './custom-types';import './styles/index.scss';+import { LinkComponent, withInlineLink } from './plugins/with-link';export type TextComponentProps = TextProps;@@ -13,20 +29,22 @@ export const Text: React.FC<TextComponentProps> = (props: TextComponentProps) => {const { text, readonly, onChange, onComposition, afterInit } = props;- const renderElement = useCallback(- (props: any) => <ParagraphElement {...props} />,- []- );+const renderLeaf = useCallback((props: RenderLeafProps) => <Leaf {...props} />,[]);+const initialValue: Descendant[] = [text];+const editor = useMemo(() => {- const editor = withText(withHistory(withReact(createEditor())));+ const editor = withInlineLink(+ withText(withHistory(withReact(createEditor())))+ );afterInit && afterInit(editor);return editor;}, []);+useEffect(() => {if (text === editor.children[0]) {return;@@ -34,6 +52,31 @@ export const Text: React.FC<TextComponentProps> = (editor.children = [text];editor.onChange();}, [text, editor]);++ const onKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (event) => {+ const { selection } = editor;++ // Default left/right behavior is unit:'character'.+ // This fails to distinguish between two cursor positions, such as+ // <inline>foo<cursor/></inline> vs <inline>foo</inline><cursor/>.+ // Here we modify the behavior to unit:'offset'.+ // This lets the user step into and out of the inline without stepping over characters.+ // You may wish to customize this further to only use unit:'offset' in specific cases.+ if (selection && Range.isCollapsed(selection)) {+ const { nativeEvent } = event;+ if (isKeyHotkey('left', nativeEvent)) {+ event.preventDefault();+ Transforms.move(editor, { unit: 'offset', reverse: true });+ return;+ }+ if (isKeyHotkey('right', nativeEvent)) {+ event.preventDefault();+ Transforms.move(editor, { unit: 'offset' });+ return;+ }+ }+ };+return (<Slateeditor={editor}@@ -41,14 +84,14 @@ export const Text: React.FC<TextComponentProps> = (onChange={(value: Descendant[]) => {onChange &&onChange({- newText: editor.children[0] as Element,+ newText: editor.children[0] as ParagraphElement,operations: editor.operations,});}}><EditableclassName="slate-editable-container plait-text-container"- renderElement={renderElement}+ renderElement={(props) => <Element {...props} />}renderLeaf={renderLeaf}readOnly={readonly === undefined ? true : readonly}onCompositionStart={(event) => {@@ -66,18 +109,36 @@ export const Text: React.FC<TextComponentProps> = (onComposition(event as unknown as CompositionEvent);}}}+ onKeyDown={onKeyDown}/></Slate>);};-const ParagraphElement = (props: {- attributes: any;- children: any;- element: any;-}) => {- const { attributes, children, element } = { ...props };- const style = { textAlign: element.align };+const Element = (props: RenderElementProps) => {+ const { attributes, children, element } = props as RenderElementPropsFor<+ CustomElement & { type: string }+ >;+ switch (element.type) {+ case 'link':+ return (+ <LinkComponent {...(props as RenderElementPropsFor<LinkElement>)} />+ );+ default:+ return (+ <ParagraphComponent+ {...(props as RenderElementPropsFor<ParagraphElement>)}+ />+ );+ }+};++const ParagraphComponent = ({+ attributes,+ children,+ element,+}: RenderElementPropsFor<ParagraphElement>) => {+ const style = { textAlign: element.align } as CSSProperties;return (<div style={style} {...attributes}>{children}diff --git a/packages/react-text/vite.config.ts b/packages/react-text/vite.config.tsindex 4871a55..245dcb7 100644--- a/packages/react-text/vite.config.ts+++ b/packages/react-text/vite.config.ts@@ -43,7 +43,7 @@ export default defineConfig({},rollupOptions: {// External packages that should not be bundled into your library.- external: ['react', 'react-dom', 'react/jsx-runtime', 'slate', 'slate-react', 'slate-history'],+ external: ['react', 'react-dom', 'react/jsx-runtime', 'slate', 'slate-react', 'slate-history', 'is-hotkey', '@plait/text-plugins', '@plait/common'],},},resolve: {