UNPKG

@gechiui/block-editor

Version:
133 lines (107 loc) 3.15 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useInputRules = useInputRules; var _element = require("@gechiui/element"); var _compose = require("@gechiui/compose"); var _richText = require("@gechiui/rich-text"); var _blocks = require("@gechiui/blocks"); var _data = require("@gechiui/data"); var _store = require("../../store"); /** * GeChiUI dependencies */ /** * Internal dependencies */ function useInputRules(props) { const { __unstableMarkLastChangeAsPersistent, __unstableMarkAutomaticChange } = (0, _data.useDispatch)(_store.store); const propsRef = (0, _element.useRef)(props); propsRef.current = props; return (0, _compose.useRefEffect)(element => { function inputRule() { const { value, onReplace } = propsRef.current; if (!onReplace) { return; } const { start, text } = value; const characterBefore = text.slice(start - 1, start); // The character right before the caret must be a plain space. if (characterBefore !== ' ') { return; } const trimmedTextBefore = text.slice(0, start).trim(); const prefixTransforms = (0, _blocks.getBlockTransforms)('from').filter(_ref => { let { type } = _ref; return type === 'prefix'; }); const transformation = (0, _blocks.findTransform)(prefixTransforms, _ref2 => { let { prefix } = _ref2; return trimmedTextBefore === prefix; }); if (!transformation) { return; } const content = (0, _richText.toHTMLString)({ value: (0, _richText.slice)(value, start, text.length) }); const block = transformation.transform(content); onReplace([block]); __unstableMarkAutomaticChange(); } function onInput(event) { const { inputType, type } = event; const { value, onChange, __unstableAllowPrefixTransformations, formatTypes } = propsRef.current; // Only run input rules when inserting text. if (inputType !== 'insertText' && type !== 'compositionend') { return; } if (__unstableAllowPrefixTransformations && inputRule) { inputRule(); } const transformed = formatTypes.reduce((accumlator, _ref3) => { let { __unstableInputRule } = _ref3; if (__unstableInputRule) { accumlator = __unstableInputRule(accumlator); } return accumlator; }, value); if (transformed !== value) { __unstableMarkLastChangeAsPersistent(); onChange({ ...transformed, activeFormats: value.activeFormats }); __unstableMarkAutomaticChange(); } } element.addEventListener('input', onInput); element.addEventListener('compositionend', onInput); return () => { element.removeEventListener('input', onInput); element.removeEventListener('compositionend', onInput); }; }, []); } //# sourceMappingURL=use-input-rules.js.map