UNPKG

@remirror/core

Version:

Where your quest to create a world class editing experience begins.

1,380 lines (1,365 loc) 154 kB
var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __defNormalProp = (obj, key2, value) => key2 in obj ? __defProp(obj, key2, { enumerable: true, configurable: true, writable: true, value }) : obj[key2] = value; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key2 of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key2) && key2 !== except) __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable }); } return to; }; var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __decorateClass = (decorators, target, key2, kind) => { var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key2) : target; for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key2, result) : decorator(result)) || result; if (kind && result) __defProp(target, key2, result); return result; }; var __publicField = (obj, key2, value) => { __defNormalProp(obj, typeof key2 !== "symbol" ? key2 + "" : key2, value); return value; }; var __accessCheck = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet = (obj, member, getter) => { __accessCheck(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet = (obj, member, value, setter) => { __accessCheck(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; // packages/remirror__core/src/index.ts var src_exports = {}; __export(src_exports, { AttributesExtension: () => AttributesExtension, CommandsExtension: () => CommandsExtension, DEFAULT_SHORTCUTS: () => DEFAULT_SHORTCUTS, DecorationsExtension: () => DecorationsExtension, DelayedCommand: () => DelayedCommand, DocChangedExtension: () => DocChangedExtension, Framework: () => Framework, GOOGLE_DOC_SHORTCUTS: () => GOOGLE_DOC_SHORTCUTS, HelpersExtension: () => HelpersExtension, InputRulesExtension: () => InputRulesExtension, KeymapExtension: () => KeymapExtension, MarkExtension: () => MarkExtension, MetaExtension: () => MetaExtension, NodeExtension: () => NodeExtension, NodeViewsExtension: () => NodeViewsExtension, PasteRulesExtension: () => PasteRulesExtension, PlainExtension: () => PlainExtension, PluginsExtension: () => PluginsExtension, RemirrorManager: () => RemirrorManager, SchemaExtension: () => SchemaExtension, SuggestExtension: () => SuggestExtension, TagsExtension: () => TagsExtension, UploadExtension: () => UploadExtension, builtinPreset: () => builtinPreset, command: () => command, delayedCommand: () => delayedCommand, extension: () => extension, extensionDecorator: () => extensionDecorator, findUploadPlaceholderPayload: () => findUploadPlaceholderPayload, findUploadPlaceholderPos: () => findUploadPlaceholderPos, hasUploadingFile: () => hasUploadingFile, helper: () => helper, insertText: () => insertText, isDelayedValue: () => isDelayedValue, isExtension: () => isExtension, isExtensionConstructor: () => isExtensionConstructor, isExtensionTag: () => isExtensionTag, isMarkExtension: () => isMarkExtension, isNodeExtension: () => isNodeExtension, isPlainExtension: () => isPlainExtension, isRemirrorManager: () => isRemirrorManager, keyBinding: () => keyBinding, keyboardShortcuts: () => keyboardShortcuts, mutateDefaultExtensionOptions: () => mutateDefaultExtensionOptions, setUploadPlaceholderAction: () => setUploadPlaceholderAction, toggleMark: () => toggleMark, uploadFile: () => uploadFile }); module.exports = __toCommonJS(src_exports); // packages/remirror__core/src/builtins/attributes-extension.ts var import_core_helpers5 = require("@remirror/core-helpers"); // packages/remirror__core/src/extension/extension.ts var import_core_constants3 = require("@remirror/core-constants"); var import_core_helpers3 = require("@remirror/core-helpers"); var import_core_utils2 = require("@remirror/core-utils"); // packages/remirror__core/src/extension/base-class.ts var import_core_constants2 = require("@remirror/core-constants"); var import_core_helpers2 = require("@remirror/core-helpers"); var import_core_utils = require("@remirror/core-utils"); // packages/remirror__core/src/helpers.ts var import_core_constants = require("@remirror/core-constants"); var import_core_helpers = require("@remirror/core-helpers"); function defaultEquals(valueA, valueB) { return valueA === valueB; } function getChangedOptions(props) { const { previousOptions, update, equals = defaultEquals } = props; const next = (0, import_core_helpers.freeze)({ ...previousOptions, ...update }); const changes = (0, import_core_helpers.object)(); const optionKeys = (0, import_core_helpers.keys)(previousOptions); for (const key2 of optionKeys) { const previousValue = previousOptions[key2]; const value = next[key2]; if (equals(previousValue, value)) { changes[key2] = { changed: false }; continue; } changes[key2] = { changed: true, previousValue, value }; } const pickChanged = (keys3) => { const picked = (0, import_core_helpers.object)(); for (const key2 of keys3) { const item = changes[key2]; if (item == null ? void 0 : item.changed) { picked[key2] = item.value; } } return picked; }; return { changes: (0, import_core_helpers.freeze)(changes), options: next, pickChanged }; } var codeLabelMap = { [import_core_constants.ErrorConstant.DUPLICATE_HELPER_NAMES]: "helper method", [import_core_constants.ErrorConstant.DUPLICATE_COMMAND_NAMES]: "command method" }; function throwIfNameNotUnique(props) { const { name, set, code } = props; const label = codeLabelMap[code]; (0, import_core_helpers.invariant)(!set.has(name), { code, message: `There is a naming conflict for the name: ${name} used in this '${label}'. Please rename or remove from the editor to avoid runtime errors.` }); set.add(name); } // packages/remirror__core/src/extension/base-class.ts var IGNORE = "__IGNORE__"; var GENERAL_OPTIONS = "__ALL__"; var BaseClass = class { constructor(defaultOptions2, ...[options]) { __publicField(this, "~O", {}); __publicField(this, "_initialOptions"); __publicField(this, "_dynamicKeys"); __publicField(this, "_options"); __publicField(this, "_mappedHandlers"); __publicField(this, "onAddCustomHandler"); this._mappedHandlers = (0, import_core_helpers2.object)(); this.populateMappedHandlers(); this._options = this._initialOptions = (0, import_core_helpers2.deepMerge)(defaultOptions2, this.constructor.defaultOptions, options != null ? options : (0, import_core_helpers2.object)(), this.createDefaultHandlerOptions()); this._dynamicKeys = this.getDynamicKeys(); this.init(); } get options() { return this._options; } get dynamicKeys() { return this._dynamicKeys; } get initialOptions() { return this._initialOptions; } init() { } getDynamicKeys() { const dynamicKeys = []; const { customHandlerKeys, handlerKeys, staticKeys } = this.constructor; for (const key2 of (0, import_core_helpers2.keys)(this._options)) { if (staticKeys.includes(key2) || handlerKeys.includes(key2) || customHandlerKeys.includes(key2)) { continue; } dynamicKeys.push(key2); } return dynamicKeys; } ensureAllKeysAreDynamic(update) { if (import_core_utils.environment.isProduction) { return; } const invalid = []; for (const key2 of (0, import_core_helpers2.keys)(update)) { if (this._dynamicKeys.includes(key2)) { continue; } invalid.push(key2); } (0, import_core_helpers2.invariant)((0, import_core_helpers2.isEmptyArray)(invalid), { code: import_core_constants2.ErrorConstant.INVALID_SET_EXTENSION_OPTIONS, message: `Invalid properties passed into the 'setOptions()' method: ${JSON.stringify(invalid)}.` }); } setOptions(update) { var _a; const previousOptions = this.getDynamicOptions(); this.ensureAllKeysAreDynamic(update); const { changes, options, pickChanged } = getChangedOptions({ previousOptions, update }); this.updateDynamicOptions(options); (_a = this.onSetOptions) == null ? void 0 : _a.call(this, { reason: "set", changes, options, pickChanged, initialOptions: this._initialOptions }); } resetOptions() { var _a; const previousOptions = this.getDynamicOptions(); const { changes, options, pickChanged } = getChangedOptions({ previousOptions, update: this._initialOptions }); this.updateDynamicOptions(options); (_a = this.onSetOptions) == null ? void 0 : _a.call(this, { reason: "reset", options, changes, pickChanged, initialOptions: this._initialOptions }); } getDynamicOptions() { return (0, import_core_helpers2.omit)(this._options, [ ...this.constructor.customHandlerKeys, ...this.constructor.handlerKeys ]); } updateDynamicOptions(options) { this._options = { ...this._options, ...options }; } populateMappedHandlers() { for (const key2 of this.constructor.handlerKeys) { this._mappedHandlers[key2] = []; } } createDefaultHandlerOptions() { const methods = (0, import_core_helpers2.object)(); for (const key2 of this.constructor.handlerKeys) { methods[key2] = (...args) => { var _a; const { handlerKeyOptions } = this.constructor; const reducer = (_a = handlerKeyOptions[key2]) == null ? void 0 : _a.reducer; let returnValue = reducer == null ? void 0 : reducer.getDefault(...args); for (const [, handler] of this._mappedHandlers[key2]) { const value = handler(...args); returnValue = reducer ? reducer.accumulator(returnValue, value, ...args) : value; if (shouldReturnEarly(handlerKeyOptions, returnValue, key2)) { return returnValue; } } return returnValue; }; } return methods; } addHandler(key2, method, priority = import_core_constants2.ExtensionPriority.Default) { this._mappedHandlers[key2].push([priority, method]); this.sortHandlers(key2); return () => this._mappedHandlers[key2] = this._mappedHandlers[key2].filter(([, handler]) => handler !== method); } hasHandlers(key2) { var _a; return ((_a = this._mappedHandlers[key2]) != null ? _a : []).length > 0; } sortHandlers(key2) { this._mappedHandlers[key2] = (0, import_core_helpers2.sort)(this._mappedHandlers[key2], ([a], [z]) => z - a); } addCustomHandler(key2, value) { var _a, _b; return (_b = (_a = this.onAddCustomHandler) == null ? void 0 : _a.call(this, { [key2]: value })) != null ? _b : import_core_helpers2.noop; } }; __publicField(BaseClass, "defaultOptions", {}); __publicField(BaseClass, "staticKeys", []); __publicField(BaseClass, "handlerKeys", []); __publicField(BaseClass, "handlerKeyOptions", {}); __publicField(BaseClass, "customHandlerKeys", []); function shouldReturnEarly(handlerKeyOptions, returnValue, handlerKey) { const { [GENERAL_OPTIONS]: generalOptions } = handlerKeyOptions; const handlerOptions = handlerKeyOptions[handlerKey]; if (!generalOptions && !handlerOptions) { return false; } if (handlerOptions && handlerOptions.earlyReturnValue !== IGNORE && ((0, import_core_helpers2.isFunction)(handlerOptions.earlyReturnValue) ? handlerOptions.earlyReturnValue(returnValue) === true : returnValue === handlerOptions.earlyReturnValue)) { return true; } if (generalOptions && generalOptions.earlyReturnValue !== IGNORE && ((0, import_core_helpers2.isFunction)(generalOptions.earlyReturnValue) ? generalOptions.earlyReturnValue(returnValue) === true : returnValue === generalOptions.earlyReturnValue)) { return true; } return false; } // packages/remirror__core/src/extension/extension.ts var Extension = class extends BaseClass { constructor(...args) { super(defaultOptions, ...args); __publicField(this, "priorityOverride"); __publicField(this, "_extensions"); __publicField(this, "extensionMap"); __publicField(this, "_store"); __publicField(this, "~E", {}); this._extensions = (0, import_core_helpers3.uniqueBy)(this.createExtensions(), (extension2) => extension2.constructor); this.extensionMap = /* @__PURE__ */ new Map(); for (const extension2 of this._extensions) { this.extensionMap.set(extension2.constructor, extension2); } } get priority() { var _a, _b; return (_b = (_a = this.priorityOverride) != null ? _a : this.options.priority) != null ? _b : this.constructor.defaultPriority; } get constructorName() { return `${(0, import_core_helpers3.pascalCase)(this.name)}Extension`; } get store() { (0, import_core_helpers3.invariant)(this._store, { code: import_core_constants3.ErrorConstant.MANAGER_PHASE_ERROR, message: `An error occurred while attempting to access the 'extension.store' when the Manager has not yet set created the lifecycle methods.` }); return (0, import_core_helpers3.freeze)(this._store, { requireKeys: true }); } get extensions() { return this._extensions; } replaceChildExtension(constructor, extension2) { if (!this.extensionMap.has(constructor)) { return; } this.extensionMap.set(constructor, extension2); this._extensions = this.extensions.map((currentExtension) => extension2.constructor === constructor ? extension2 : currentExtension); } createExtensions() { return []; } getExtension(Constructor) { const extension2 = this.extensionMap.get(Constructor); (0, import_core_helpers3.invariant)(extension2, { code: import_core_constants3.ErrorConstant.INVALID_GET_EXTENSION, message: `'${Constructor.name}' does not exist within the preset: '${this.name}'` }); return extension2; } isOfType(Constructor) { return this.constructor === Constructor; } setStore(store) { if (this._store) { return; } this._store = store; } clone(...args) { return new this.constructor(...args); } setPriority(priority) { this.priorityOverride = priority; } }; __publicField(Extension, "defaultPriority", import_core_constants3.ExtensionPriority.Default); var PlainExtension = class extends Extension { static get [import_core_constants3.__INTERNAL_REMIRROR_IDENTIFIER_KEY__]() { return import_core_constants3.RemirrorIdentifier.PlainExtensionConstructor; } get [import_core_constants3.__INTERNAL_REMIRROR_IDENTIFIER_KEY__]() { return import_core_constants3.RemirrorIdentifier.PlainExtension; } }; var MarkExtension = class extends Extension { static get [import_core_constants3.__INTERNAL_REMIRROR_IDENTIFIER_KEY__]() { return import_core_constants3.RemirrorIdentifier.MarkExtensionConstructor; } get [import_core_constants3.__INTERNAL_REMIRROR_IDENTIFIER_KEY__]() { return import_core_constants3.RemirrorIdentifier.MarkExtension; } get type() { return (0, import_core_helpers3.assertGet)(this.store.schema.marks, this.name); } constructor(...args) { super(...args); } }; __publicField(MarkExtension, "disableExtraAttributes", false); var NodeExtension = class extends Extension { static get [import_core_constants3.__INTERNAL_REMIRROR_IDENTIFIER_KEY__]() { return import_core_constants3.RemirrorIdentifier.NodeExtensionConstructor; } get [import_core_constants3.__INTERNAL_REMIRROR_IDENTIFIER_KEY__]() { return import_core_constants3.RemirrorIdentifier.NodeExtension; } get type() { return (0, import_core_helpers3.assertGet)(this.store.schema.nodes, this.name); } constructor(...args) { super(...args); } }; __publicField(NodeExtension, "disableExtraAttributes", false); var defaultOptions = { priority: void 0, extraAttributes: {}, disableExtraAttributes: false, exclude: {} }; function mutateDefaultExtensionOptions(mutatorMethod) { mutatorMethod(defaultOptions); } function isExtension(value) { return (0, import_core_utils2.isRemirrorType)(value) && (0, import_core_utils2.isIdentifierOfType)(value, [ import_core_constants3.RemirrorIdentifier.PlainExtension, import_core_constants3.RemirrorIdentifier.MarkExtension, import_core_constants3.RemirrorIdentifier.NodeExtension ]); } function isExtensionConstructor(value) { return (0, import_core_utils2.isRemirrorType)(value) && (0, import_core_utils2.isIdentifierOfType)(value, [ import_core_constants3.RemirrorIdentifier.PlainExtensionConstructor, import_core_constants3.RemirrorIdentifier.MarkExtensionConstructor, import_core_constants3.RemirrorIdentifier.NodeExtensionConstructor ]); } function isPlainExtension(value) { return (0, import_core_utils2.isRemirrorType)(value) && (0, import_core_utils2.isIdentifierOfType)(value, import_core_constants3.RemirrorIdentifier.PlainExtension); } function isNodeExtension(value) { return (0, import_core_utils2.isRemirrorType)(value) && (0, import_core_utils2.isIdentifierOfType)(value, import_core_constants3.RemirrorIdentifier.NodeExtension); } function isMarkExtension(value) { return (0, import_core_utils2.isRemirrorType)(value) && (0, import_core_utils2.isIdentifierOfType)(value, import_core_constants3.RemirrorIdentifier.MarkExtension); } // packages/remirror__core/src/extension/extension-decorator.ts var import_core_helpers4 = require("@remirror/core-helpers"); function extension(options) { return (ReadonlyConstructor) => { const { defaultOptions: defaultOptions2, customHandlerKeys, handlerKeys, staticKeys, defaultPriority, handlerKeyOptions, ...rest } = options; const Constructor = (0, import_core_helpers4.Cast)(ReadonlyConstructor); if (defaultOptions2) { Constructor.defaultOptions = defaultOptions2; } if (defaultPriority) { Constructor.defaultPriority = defaultPriority; } if (handlerKeyOptions) { Constructor.handlerKeyOptions = handlerKeyOptions; } Constructor.staticKeys = staticKeys != null ? staticKeys : []; Constructor.handlerKeys = handlerKeys != null ? handlerKeys : []; Constructor.customHandlerKeys = customHandlerKeys != null ? customHandlerKeys : []; for (const [key2, value] of Object.entries(rest)) { if (Constructor[key2]) { continue; } Constructor[key2] = value; } return (0, import_core_helpers4.Cast)(Constructor); }; } var extensionDecorator = extension; // packages/remirror__core/src/builtins/attributes-extension.ts var AttributesExtension = class extends PlainExtension { constructor() { super(...arguments); __publicField(this, "attributeList", []); __publicField(this, "attributeObject", (0, import_core_helpers5.object)()); __publicField(this, "updateAttributes", (triggerUpdate = true) => { this.transformAttributes(); if (triggerUpdate) { this.store.commands.forceUpdate("attributes"); } }); } get name() { return "attributes"; } onCreate() { this.transformAttributes(); this.store.setExtensionStore("updateAttributes", this.updateAttributes); } transformAttributes() { var _a, _b, _c, _d; this.attributeObject = (0, import_core_helpers5.object)(); if ((_a = this.store.managerSettings.exclude) == null ? void 0 : _a.attributes) { this.store.setStoreKey("attributes", this.attributeObject); return; } this.attributeList = []; for (const extension2 of this.store.extensions) { if ((_b = extension2.options.exclude) == null ? void 0 : _b.attributes) { continue; } const createdAttributes = (_c = extension2.createAttributes) == null ? void 0 : _c.call(extension2); const attributes = { ...createdAttributes, class: (0, import_core_helpers5.cx)(...(_d = extension2.classNames) != null ? _d : [], createdAttributes == null ? void 0 : createdAttributes.class) }; this.attributeList.unshift(attributes); } for (const attributes of this.attributeList) { this.attributeObject = { ...this.attributeObject, ...attributes, class: (0, import_core_helpers5.cx)(this.attributeObject.class, attributes.class) }; } this.store.setStoreKey("attributes", this.attributeObject); } }; // packages/remirror__core/src/builtins/builtin-decorators.ts function helper(options = {}) { return (target, propertyKey, _descriptor) => { var _a; ((_a = target.decoratedHelpers) != null ? _a : target.decoratedHelpers = {})[propertyKey] = options; }; } function command(options = {}) { return (target, propertyKey, _descriptor) => { var _a; ((_a = target.decoratedCommands) != null ? _a : target.decoratedCommands = {})[propertyKey] = options; }; } function keyBinding(options) { return (target, propertyKey, _descriptor) => { var _a; ((_a = target.decoratedKeybindings) != null ? _a : target.decoratedKeybindings = {})[propertyKey] = options; }; } // packages/remirror__core/src/builtins/builtin-preset.ts var import_core_helpers18 = require("@remirror/core-helpers"); // packages/remirror__core/src/builtins/commands-extension.ts var import_core_constants5 = require("@remirror/core-constants"); var import_core_helpers7 = require("@remirror/core-helpers"); var import_core_utils4 = require("@remirror/core-utils"); var import_messages = require("@remirror/messages"); var import_model = require("@remirror/pm/model"); var import_state = require("@remirror/pm/state"); // packages/remirror__core/src/commands.ts var import_core_constants4 = require("@remirror/core-constants"); var import_core_helpers6 = require("@remirror/core-helpers"); var import_core_utils3 = require("@remirror/core-utils"); var import_commands = require("@remirror/pm/commands"); function isDelayedValue(value) { return (0, import_core_helpers6.isFunction)(value) || (0, import_core_helpers6.isPromise)(value); } function delayedCommand({ immediate, promise, onDone, onFail }) { return (props) => { const { view } = props; if ((immediate == null ? void 0 : immediate(props)) === false) { return false; } if (!view) { return true; } const deferred = (0, import_core_helpers6.isFunction)(promise) ? promise() : promise; deferred.then((value) => { onDone({ state: view.state, tr: view.state.tr, dispatch: view.dispatch, view, value }); }).catch(() => { onFail == null ? void 0 : onFail({ state: view.state, tr: view.state.tr, dispatch: view.dispatch, view }); }); return true; }; } var DelayedCommand = class { constructor(promiseCreator) { this.promiseCreator = promiseCreator; __publicField(this, "failureHandlers", []); __publicField(this, "successHandlers", []); __publicField(this, "validateHandlers", []); __publicField(this, "generateCommand", () => { return (props) => { let isValid = true; const { view, tr, dispatch } = props; if (!view) { return false; } for (const handler of this.validateHandlers) { if (!handler({ ...props, dispatch: () => { } })) { isValid = false; break; } } if (!dispatch || !isValid) { return isValid; } const deferred = this.promiseCreator(props); deferred.then((value) => { this.runHandlers(this.successHandlers, { value, state: view.state, tr: view.state.tr, dispatch: view.dispatch, view }); }).catch((error) => { this.runHandlers(this.failureHandlers, { error, state: view.state, tr: view.state.tr, dispatch: view.dispatch, view }); }); dispatch(tr); return true; }; }); } validate(handler, method = "push") { this.validateHandlers[method](handler); return this; } success(handler, method = "push") { this.successHandlers[method](handler); return this; } failure(handler, method = "push") { this.failureHandlers[method](handler); return this; } runHandlers(handlers, param) { var _a; for (const handler of handlers) { if (!handler({ ...param, dispatch: () => { } })) { break; } } (_a = param.dispatch) == null ? void 0 : _a.call(param, param.tr); } }; function toggleMark(props) { const { type, attrs, range, selection } = props; return (props2) => { var _a; const { dispatch, tr, state } = props2; const markType = (0, import_core_helpers6.isString)(type) ? state.schema.marks[type] : type; (0, import_core_helpers6.invariant)(markType, { code: import_core_constants4.ErrorConstant.SCHEMA, message: `Mark type: ${type} does not exist on the current schema.` }); if (range || selection) { const { from, to } = (0, import_core_utils3.getTextSelection)((_a = selection != null ? selection : range) != null ? _a : tr.selection, tr.doc); (0, import_core_utils3.isMarkActive)({ trState: tr, type, ...range }) ? dispatch == null ? void 0 : dispatch(tr.removeMark(from, to, markType)) : dispatch == null ? void 0 : dispatch(tr.addMark(from, to, markType.create(attrs))); return true; } return (0, import_core_utils3.convertCommand)((0, import_commands.toggleMark)(markType, attrs))(props2); }; } function markApplies(type, doc, ranges) { for (const { $from, $to } of ranges) { let markIsAllowed = $from.depth === 0 ? doc.type.allowsMarkType(type) : false; doc.nodesBetween($from.pos, $to.pos, (node) => { if (markIsAllowed) { return false; } markIsAllowed = node.inlineContent && node.type.allowsMarkType(type); return; }); if (markIsAllowed) { return true; } } return false; } function applyMark(type, attrs, selectionPoint) { return ({ tr, dispatch, state }) => { const selection = (0, import_core_utils3.getTextSelection)(selectionPoint != null ? selectionPoint : tr.selection, tr.doc); const $cursor = (0, import_core_utils3.getCursor)(selection); const markType = (0, import_core_helpers6.isString)(type) ? state.schema.marks[type] : type; (0, import_core_helpers6.invariant)(markType, { code: import_core_constants4.ErrorConstant.SCHEMA, message: `Mark type: ${type} does not exist on the current schema.` }); if (selection.empty && !$cursor || !markApplies(markType, tr.doc, selection.ranges)) { return false; } if (!dispatch) { return true; } if ($cursor) { tr.removeStoredMark(markType); if (attrs) { tr.addStoredMark(markType.create(attrs)); } dispatch(tr); return true; } let containsMark = false; for (const { $from, $to } of selection.ranges) { if (containsMark) { break; } containsMark = tr.doc.rangeHasMark($from.pos, $to.pos, markType); } for (const { $from, $to } of selection.ranges) { if (containsMark) { tr.removeMark($from.pos, $to.pos, markType); } if (attrs) { tr.addMark($from.pos, $to.pos, markType.create(attrs)); } } dispatch(tr); return true; }; } function insertText(text, options = {}) { return ({ tr, dispatch, state }) => { const schema = state.schema; const selection = tr.selection; const { from = selection.from, to = from != null ? from : selection.to, marks = {} } = options; if (!dispatch) { return true; } tr.insertText(text, from, to); const end = (0, import_core_helpers6.assertGet)(tr.steps, tr.steps.length - 1).getMap().map(to); for (const [markName, attributes] of (0, import_core_helpers6.entries)(marks)) { tr.addMark(from, end, (0, import_core_helpers6.assertGet)(schema.marks, markName).create(attributes)); } dispatch(tr); return true; }; } // packages/remirror__core/src/builtins/commands-extension.ts var CommandsExtension = class extends PlainExtension { constructor() { super(...arguments); __publicField(this, "_transaction"); __publicField(this, "decorated", /* @__PURE__ */ new Map()); __publicField(this, "forceUpdateTransaction", (tr, ...keys3) => { const { forcedUpdates } = this.getCommandMeta(tr); this.setCommandMeta(tr, { forcedUpdates: (0, import_core_helpers7.uniqueArray)([...forcedUpdates, ...keys3]) }); return tr; }); } get name() { return "commands"; } get transaction() { const state = this.store.getState(); if (!this._transaction) { this._transaction = state.tr; } const isValid = this._transaction.before.eq(state.doc); const hasSteps = !(0, import_core_helpers7.isEmptyArray)(this._transaction.steps); if (!isValid) { const tr = state.tr; if (hasSteps) { for (const step of this._transaction.steps) { tr.step(step); } } this._transaction = tr; } return this._transaction; } onCreate() { this.store.setStoreKey("getForcedUpdates", this.getForcedUpdates.bind(this)); } onView(view) { var _a, _b, _c; const { extensions, helpers } = this.store; const commands = (0, import_core_helpers7.object)(); const names = /* @__PURE__ */ new Set(); let allDecoratedCommands = (0, import_core_helpers7.object)(); const chain = (tr) => { var _a2; const customChain = (0, import_core_helpers7.object)(); const getTr = () => tr != null ? tr : this.transaction; let commandChain = []; const getChain = () => commandChain; for (const [name, command2] of Object.entries(commands)) { if ((_a2 = allDecoratedCommands[name]) == null ? void 0 : _a2.disableChaining) { continue; } customChain[name] = this.chainedFactory({ chain: customChain, command: command2.original, getTr, getChain }); } const dispatch = (transaction) => { (0, import_core_helpers7.invariant)(transaction === getTr(), { message: "Chaining currently only supports `CommandFunction` methods which do not use the `state.tr` property. Instead you should use the provided `tr` property." }); }; customChain.run = (options = {}) => { const commands2 = commandChain; commandChain = []; for (const cmd of commands2) { if (!cmd(dispatch) && options.exitEarly) { return; } } view.dispatch(getTr()); }; customChain.tr = () => { const commands2 = commandChain; commandChain = []; for (const cmd of commands2) { cmd(dispatch); } return getTr(); }; customChain.enabled = () => { for (const cmd of commandChain) { if (!cmd()) { return false; } } return true; }; return customChain; }; for (const extension2 of extensions) { const extensionCommands = (_b = (_a = extension2.createCommands) == null ? void 0 : _a.call(extension2)) != null ? _b : {}; const decoratedCommands = (_c = extension2.decoratedCommands) != null ? _c : {}; const active = {}; allDecoratedCommands = { ...allDecoratedCommands, decoratedCommands }; for (const [commandName, options] of Object.entries(decoratedCommands)) { const shortcut = (0, import_core_helpers7.isString)(options.shortcut) && options.shortcut.startsWith("_|") ? { shortcut: helpers.getNamedShortcut(options.shortcut, extension2.options) } : void 0; this.updateDecorated(commandName, { ...options, name: extension2.name, ...shortcut }); extensionCommands[commandName] = extension2[commandName].bind(extension2); if (options.active) { active[commandName] = () => { var _a2, _b2; return (_b2 = (_a2 = options.active) == null ? void 0 : _a2.call(options, extension2.options, this.store)) != null ? _b2 : false; }; } } if ((0, import_core_helpers7.isEmptyObject)(extensionCommands)) { continue; } this.addCommands({ active, names, commands, extensionCommands }); } const chainProperty = chain(); for (const [key2, command2] of Object.entries(chainProperty)) { chain[key2] = command2; } this.store.setStoreKey("commands", commands); this.store.setStoreKey("chain", chain); this.store.setExtensionStore("commands", commands); this.store.setExtensionStore("chain", chain); } onStateUpdate({ state }) { this._transaction = state.tr; } createPlugin() { return {}; } customDispatch(command2) { return command2; } insertText(text, options = {}) { if ((0, import_core_helpers7.isString)(text)) { return insertText(text, options); } return this.store.createPlaceholderCommand({ promise: text, placeholder: { type: "inline" }, onSuccess: (value, range, props) => { return this.insertText(value, { ...options, ...range })(props); } }).generateCommand(); } selectText(selection, options = {}) { return ({ tr, dispatch }) => { const textSelection = (0, import_core_utils4.getTextSelection)(selection, tr.doc); const selectionUnchanged = tr.selection.anchor === textSelection.anchor && tr.selection.head === textSelection.head; if (selectionUnchanged && !options.forceUpdate) { return false; } dispatch == null ? void 0 : dispatch(tr.setSelection(textSelection)); return true; }; } selectMark(type) { return (props) => { const { tr } = props; const range = (0, import_core_utils4.getMarkRange)(tr.selection.$from, type); if (!range) { return false; } return this.store.commands.selectText.original({ from: range.from, to: range.to })(props); }; } delete(range) { return ({ tr, dispatch }) => { const { from, to } = range != null ? range : tr.selection; dispatch == null ? void 0 : dispatch(tr.delete(from, to)); return true; }; } emptyUpdate(action) { return ({ tr, dispatch }) => { if (dispatch) { action == null ? void 0 : action(); dispatch(tr); } return true; }; } forceUpdate(...keys3) { return ({ tr, dispatch }) => { dispatch == null ? void 0 : dispatch(this.forceUpdateTransaction(tr, ...keys3)); return true; }; } updateNodeAttributes(pos, attrs) { return ({ tr, dispatch }) => { dispatch == null ? void 0 : dispatch(tr.setNodeMarkup(pos, void 0, attrs)); return true; }; } setContent(content, selection) { return (props) => { const { tr, dispatch } = props; const state = this.store.manager.createState({ content, selection }); if (!state) { return false; } dispatch == null ? void 0 : dispatch(tr.replaceRangeWith(0, tr.doc.nodeSize - 2, state.doc)); return true; }; } resetContent() { return (props) => { const { tr, dispatch } = props; const doc = this.store.manager.createEmptyDoc(); if (doc) { return this.setContent(doc)(props); } dispatch == null ? void 0 : dispatch(tr.delete(0, tr.doc.nodeSize)); return true; }; } emptySelection() { return ({ tr, dispatch }) => { if (tr.selection.empty) { return false; } dispatch == null ? void 0 : dispatch(tr.setSelection(import_state.TextSelection.near(tr.selection.$anchor))); return true; }; } insertNewLine() { return ({ dispatch, tr }) => { if (!(0, import_core_utils4.isTextSelection)(tr.selection)) { return false; } dispatch == null ? void 0 : dispatch(tr.insertText("\n")); return true; }; } insertNode(node, options = {}) { return ({ dispatch, tr, state }) => { var _a, _b; const { attrs, range, selection, replaceEmptyParentBlock = false } = options; const { from, to, $from } = (0, import_core_utils4.getTextSelection)((_a = selection != null ? selection : range) != null ? _a : tr.selection, tr.doc); if ((0, import_core_utils4.isProsemirrorNode)(node) || (0, import_core_utils4.isProsemirrorFragment)(node)) { const pos = $from.before($from.depth); dispatch == null ? void 0 : dispatch(replaceEmptyParentBlock && from === to && (0, import_core_utils4.isEmptyBlockNode)($from.parent) ? tr.replaceWith(pos, pos + $from.parent.nodeSize, node) : tr.replaceWith(from, to, node)); return true; } const nodeType = (0, import_core_helpers7.isString)(node) ? state.schema.nodes[node] : node; (0, import_core_helpers7.invariant)(nodeType, { code: import_core_constants5.ErrorConstant.SCHEMA, message: `The requested node type ${node} does not exist in the schema.` }); const marks = (_b = options.marks) == null ? void 0 : _b.map((mark) => { if (mark instanceof import_model.Mark) { return mark; } const markType = (0, import_core_helpers7.isString)(mark) ? state.schema.marks[mark] : mark; (0, import_core_helpers7.invariant)(markType, { code: import_core_constants5.ErrorConstant.SCHEMA, message: `The requested mark type ${mark} does not exist in the schema.` }); return markType.create(); }); const content = nodeType.createAndFill(attrs, (0, import_core_helpers7.isString)(options.content) ? state.schema.text(options.content) : options.content, marks); if (!content) { return false; } const isReplacement = from !== to; dispatch == null ? void 0 : dispatch(isReplacement ? tr.replaceRangeWith(from, to, content) : tr.insert(from, content)); return true; }; } focus(position) { return (props) => { const { dispatch, tr } = props; const { view } = this.store; if (position === false) { return false; } if (view.hasFocus() && (position === void 0 || position === true)) { return false; } if (position === void 0 || position === true) { const { from = 0, to = from } = tr.selection; position = { from, to }; } if (dispatch) { this.delayedFocus(); } return this.selectText(position)(props); }; } blur(position) { return (props) => { const { view } = this.store; if (!view.hasFocus()) { return false; } requestAnimationFrame(() => { view.dom.blur(); }); return position ? this.selectText(position)(props) : true; }; } setBlockNodeType(nodeType, attrs, selection, preserveAttrs = true) { return (0, import_core_utils4.setBlockType)(nodeType, attrs, selection, preserveAttrs); } toggleWrappingNode(nodeType, attrs, selection) { return (0, import_core_utils4.toggleWrap)(nodeType, attrs, selection); } toggleBlockNodeItem(toggleProps) { return (0, import_core_utils4.toggleBlockItem)(toggleProps); } wrapInNode(nodeType, attrs, range) { return (0, import_core_utils4.wrapIn)(nodeType, attrs, range); } applyMark(markType, attrs, selection) { return applyMark(markType, attrs, selection); } toggleMark(props) { return toggleMark(props); } removeMark(props) { return (0, import_core_utils4.removeMark)(props); } setMeta(name, value) { return ({ tr }) => { tr.setMeta(name, value); return true; }; } selectAll() { return this.selectText("all"); } copy() { return (props) => { if (props.tr.selection.empty) { return false; } if (props.dispatch) { document.execCommand("copy"); } return true; }; } paste() { return this.store.createPlaceholderCommand({ promise: () => navigator.clipboard.readText(), placeholder: { type: "inline" }, onSuccess: (value, selection, props) => { return this.insertNode((0, import_core_utils4.htmlToProsemirrorNode)({ content: value, schema: props.state.schema }), { selection })(props); } }).generateCommand(); } cut() { return (props) => { if (props.tr.selection.empty) { return false; } if (props.dispatch) { document.execCommand("cut"); } return true; }; } replaceText(props) { return (0, import_core_utils4.replaceText)(props); } getAllCommandOptions() { const uiCommands = {}; for (const [name, options] of this.decorated) { if ((0, import_core_helpers7.isEmptyObject)(options)) { continue; } uiCommands[name] = options; } return uiCommands; } getCommandOptions(name) { return this.decorated.get(name); } getCommandProp() { return { tr: this.transaction, dispatch: this.store.view.dispatch, state: this.store.view.state, view: this.store.view }; } updateDecorated(name, options) { var _a; if (!options) { this.decorated.delete(name); return; } const decoratorOptions = (_a = this.decorated.get(name)) != null ? _a : { name: "" }; this.decorated.set(name, { ...decoratorOptions, ...options }); } handleIosFocus() { if (!import_core_utils4.environment.isIos) { return; } this.store.view.dom.focus(); } delayedFocus() { this.handleIosFocus(); requestAnimationFrame(() => { this.store.view.focus(); this.store.view.dispatch(this.transaction.scrollIntoView()); }); } getForcedUpdates(tr) { return this.getCommandMeta(tr).forcedUpdates; } getCommandMeta(tr) { var _a; const meta = (_a = tr.getMeta(this.pluginKey)) != null ? _a : {}; return { ...DEFAULT_COMMAND_META, ...meta }; } setCommandMeta(tr, update) { const meta = this.getCommandMeta(tr); tr.setMeta(this.pluginKey, { ...meta, ...update }); } addCommands(props) { const { extensionCommands, commands, names, active } = props; for (const [name, command2] of (0, import_core_helpers7.entries)(extensionCommands)) { throwIfNameNotUnique({ name, set: names, code: import_core_constants5.ErrorConstant.DUPLICATE_COMMAND_NAMES }); (0, import_core_helpers7.invariant)(!forbiddenNames.has(name), { code: import_core_constants5.ErrorConstant.DUPLICATE_COMMAND_NAMES, message: "The command name you chose is forbidden." }); commands[name] = this.createUnchainedCommand(command2, active[name]); } } unchainedFactory(props) { return (...args) => { const { shouldDispatch = true, command: command2 } = props; const { view } = this.store; const { state } = view; let dispatch; if (shouldDispatch) { dispatch = view.dispatch; } return command2(...args)({ state, dispatch, view, tr: state.tr }); }; } createUnchainedCommand(command2, active) { const unchainedCommand = this.unchainedFactory({ command: command2 }); unchainedCommand.enabled = this.unchainedFactory({ command: command2, shouldDispatch: false }); unchainedCommand.isEnabled = unchainedCommand.enabled; unchainedCommand.original = command2; unchainedCommand.active = active; return unchainedCommand; } chainedFactory(props) { return (...args) => { const { chain: chained, command: command2, getTr, getChain } = props; const lazyChain = getChain(); const { view } = this.store; const { state } = view; lazyChain.push((dispatch) => { return command2(...args)({ state, dispatch, view, tr: getTr() }); }); return chained; }; } }; __decorateClass([ command() ], CommandsExtension.prototype, "customDispatch", 1); __decorateClass([ command() ], CommandsExtension.prototype, "insertText", 1); __decorateClass([ command() ], CommandsExtension.prototype, "selectText", 1); __decorateClass([ command() ], CommandsExtension.prototype, "selectMark", 1); __decorateClass([ command() ], CommandsExtension.prototype, "delete", 1); __decorateClass([ command() ], CommandsExtension.prototype, "emptyUpdate", 1); __decorateClass([ command() ], CommandsExtension.prototype, "forceUpdate", 1); __decorateClass([ command() ], CommandsExtension.prototype, "updateNodeAttributes", 1); __decorateClass([ command() ], CommandsExtension.prototype, "setContent", 1); __decorateClass([ command() ], CommandsExtension.prototype, "resetContent", 1); __decorateClass([ command() ], CommandsExtension.prototype, "emptySelection", 1); __decorateClass([ command() ], CommandsExtension.prototype, "insertNewLine", 1); __decorateClass([ command() ], CommandsExtension.prototype, "insertNode", 1); __decorateClass([ command() ], CommandsExtension.prototype, "focus", 1); __decorateClass([ command() ], CommandsExtension.prototype, "blur", 1); __decorateClass([ command() ], CommandsExtension.prototype, "setBlockNodeType", 1); __decorateClass([ command() ], CommandsExtension.prototype, "toggleWrappingNode", 1); __decorateClass([ command() ], CommandsExtension.prototype, "toggleBlockNodeItem", 1); __decorateClass([ command() ], CommandsExtension.prototype, "wrapInNode", 1); __decorateClass([ command() ], CommandsExtension.prototype, "applyMark", 1); __decorateClass([ command() ], CommandsExtension.prototype, "toggleMark", 1); __decorateClass([ command() ], CommandsExtension.prototype, "removeMark", 1); __decorateClass([ command() ], CommandsExtension.prototype, "setMeta", 1); __decorateClass([ command({ description: ({ t }) => t(import_messages.CoreMessages.SELECT_ALL_DESCRIPTION), label: ({ t }) => t(import_messages.CoreMessages.SELECT_ALL_LABEL), shortcut: import_core_constants5.NamedShortcut.SelectAll }) ], CommandsExtension.prototype, "selectAll", 1); __decorateClass([ command({ description: ({ t }) => t(import_messages.CoreMessages.COPY_DESCRIPTION), label: ({ t }) => t(import_messages.CoreMessages.COPY_LABEL), shortcut: import_core_constants5.NamedShortcut.Copy, icon: "fileCopyLine" }) ], CommandsExtension.prototype, "copy", 1); __decorateClass([ command({ description: ({ t }) => t(import_messages.CoreMessages.PASTE_DESCRIPTION), label: ({ t }) => t(import_messages.CoreMessages.PASTE_LABEL), shortcut: import_core_constants5.NamedShortcut.Paste, icon: "clipboardLine" }) ], CommandsExtension.prototype, "paste", 1); __decorateClass([ command({ description: ({ t }) => t(import_messages.CoreMessages.CUT_DESCRIPTION), label: ({ t }) => t(import_messages.CoreMessages.CUT_LABEL), shortcut: import_core_constants5.NamedShortcut.Cut, icon: "scissorsFill" }) ], CommandsExtension.prototype, "cut", 1); __decorateClass([ command() ], CommandsExtension.prototype, "replaceText", 1); __decorateClass([ helper() ], CommandsExtension.prototype, "getAllCommandOptions", 1); __decorateClass([ helper() ], CommandsExtension.prototype, "getCommandOptions", 1); __decorateClass([ helper() ], CommandsExtension.prototype, "getCommandProp", 1); CommandsExtension = __decorateClass([ extension({ defaultPriority: import_core_constants5.ExtensionPriority.Highest, defaultOptions: { trackerClassName: "remirror-tracker-position", trackerNodeName: "span" }, staticKeys: ["trackerClassName", "trackerNodeName"] }) ], CommandsExtension); var DEFAULT_COMMAND_META = { forcedUpdates: [] }; var forbiddenNames = /* @__PURE__ */ new Set(["run", "chain", "original", "raw", "enabled", "tr"]); // packages/remirror__core/src/builtins/decorations-extension.ts var import_core_constants6 = require("@remirror/core-constants"); var import_core_helpers8 = require("@remirror/core-helpers"); var import_core_utils5 = require("@remirror/core-utils"); var import_view = require("@remirror/pm/view"); var DecorationsExtension = class extends PlainExtension { constructor() { super(...arguments); __publicField(this, "placeholders", import_view.DecorationSet.empty); __publicField(this, "placeholderWidgets", /* @__PURE__ */ new Map()); __publicField(this, "createPlaceholderCommand", (props) => { const id = (0, import_core_helpers8.uniqueId)(); const { promise, placeholder, onFailure, onSuccess } = props; return new DelayedCommand(promise).validate((props2) => { return this.addPlaceholder(id, placeholder)(props2); }).success((props2) => { var _a; const { state, tr, dispatch, view, value } = props2; const range = this.store.helpers.find