UNPKG

@wordpress/editor

Version:
104 lines (103 loc) 3.34 kB
// packages/editor/src/components/post-text-editor/index.js import Textarea from "react-autosize-textarea"; import { useLayoutEffect, useRef } from "@wordpress/element"; import { __ } from "@wordpress/i18n"; import { store as coreStore } from "@wordpress/core-data"; import { useDispatch, useSelect } from "@wordpress/data"; import { useInstanceId } from "@wordpress/compose"; import { VisuallyHidden } from "@wordpress/ui"; import { store as editorStore } from "../../store/index.mjs"; import { adjustPosition, getDiff } from "./utils.mjs"; import { Fragment, jsx, jsxs } from "react/jsx-runtime"; function PostTextEditor() { const instanceId = useInstanceId(PostTextEditor); const textareaRef = useRef(); const previousValueRef = useRef(); const selectionRef = useRef(); const { value, type, id } = useSelect((select) => { const { getCurrentPostType, getCurrentPostId, getEditedPostContent } = select(editorStore); return { value: getEditedPostContent(), type: getCurrentPostType(), id: getCurrentPostId() }; }, []); const { editEntityRecord } = useDispatch(coreStore); useLayoutEffect(() => { const textarea = textareaRef.current; const previousValue = previousValueRef.current; previousValueRef.current = value; if (!textarea || previousValue === void 0 || previousValue === value || !selectionRef.current) { return; } const { selectionStart, selectionEnd, selectionDirection } = selectionRef.current; const changes = getDiff(previousValue, value); const adjustedSelectionStart = adjustPosition( selectionStart, changes, previousValue, value ); const adjustedSelectionEnd = adjustPosition( selectionEnd, changes, previousValue, value ); textarea.setSelectionRange( adjustedSelectionStart, adjustedSelectionEnd, selectionDirection ); selectionRef.current = { selectionStart: adjustedSelectionStart, selectionEnd: adjustedSelectionEnd, selectionDirection }; }, [value]); const updateSelection = (event) => { const { selectionStart, selectionEnd, selectionDirection } = event.target; selectionRef.current = { selectionStart, selectionEnd, selectionDirection }; }; return /* @__PURE__ */ jsxs(Fragment, { children: [ /* @__PURE__ */ jsx( VisuallyHidden, { render: /* @__PURE__ */ jsx("label", { htmlFor: `post-content-${instanceId}` }), children: __("Type text or HTML") } ), /* @__PURE__ */ jsx( Textarea, { autoComplete: "off", dir: "auto", ref: textareaRef, value, onChange: (event) => { updateSelection(event); previousValueRef.current = event.target.value; editEntityRecord("postType", type, id, { content: event.target.value, blocks: void 0, selection: void 0 }); }, onFocus: updateSelection, onMouseUp: updateSelection, onKeyUp: updateSelection, className: "editor-post-text-editor", id: `post-content-${instanceId}`, placeholder: __("Start writing with text or HTML") } ) ] }); } export { PostTextEditor as default }; //# sourceMappingURL=index.mjs.map