pax_global_header00006660000000000000000000000064152566771250014532gustar00rootroot0000000000000052 comment=44956b6a1929d7bc99aca9a8ec01c790260fa45f prosemirror-history/000077500000000000000000000000001525667712500151605ustar00rootroot00000000000000prosemirror-history/.gitignore000066400000000000000000000000651525667712500171510ustar00rootroot00000000000000/node_modules .tern-port /dist /notes.txt /test/*.js prosemirror-history/.npmignore000066400000000000000000000000371525667712500171570ustar00rootroot00000000000000/node_modules .tern-port /test prosemirror-history/.npmrc000066400000000000000000000000231525667712500162730ustar00rootroot00000000000000package-lock=false prosemirror-history/.tern-project000066400000000000000000000001571525667712500176000ustar00rootroot00000000000000{ "libs": ["browser"], "plugins": { "node": {}, "complete_strings": {}, "es_modules": {} } } prosemirror-history/CHANGELOG.md000066400000000000000000000110601525667712500167670ustar00rootroot00000000000000## 1.5.1 (2026-09-29) ### Bug fixes Fix an issue that allowed remote changes to corrupt the undo history. ## 1.5.0 (2025-11-13) ### Bug fixes Don't call undo/redo commands in response to beforeinput events when the view isn't editable. Add isHistoryTransaction ### New features The new `isHistoryTransaction` predicate can be used to recognize transactions generated by the history system. ## 1.4.1 (2024-07-10) ### Bug fixes Fix an issue where mark steps could cause the history to treat otherwise adjacent changes as non-adjacent, and start superfluous new undo events. ## 1.4.0 (2024-03-21) ### New features Add `undoNoScroll`/`redoNoScroll` commands. ## 1.3.2 (2023-05-17) ### Bug fixes Include CommonJS type declarations in the package to please new TypeScript resolution settings. ## 1.3.1 (2023-04-26) ### Bug fixes Fix an issue where, if a composition moved the selection, it might get split across multiple undo events. ## 1.3.0 (2022-05-30) ### Bug fixes Fix an issue where the default behavior of history beforeInput events could still go through when the undo history is empty. ### New features Include TypeScript type declarations. ## 1.2.0 (2021-08-18) ### Bug fixes Fix a bug that caused the `beforeInput` handler to not actually invoke the history commands properly. ### New features The history plugin now listens for `beforeInput` events with `historyUndo` or `historyRedo` type, and applies the undo/redo commands when they occur. ## 1.1.3 (2019-12-10) ### Bug fixes Fixes a regression where appeneded transactions were combined into the previous history event even if that had been explicitly closed. ## 1.1.2 (2019-11-20) ### Bug fixes Rename ES module files to use a .js extension, since Webpack gets confused by .mjs ## 1.1.1 (2019-11-19) ### Bug fixes The file referred to in the package's `module` field now is compiled down to ES5. ## 1.1.0 (2019-11-08) ### Bug fixes Prevents appended transactions from starting a new event group, even if they were created a while after the previous transaction. ### New features Add a `module` field to package json file. ## 1.0.4 (2019-02-19) ### Bug fixes Fix a bug that corrupted selection data in the history when applying remote steps in some cases. ## 1.0.3 (2018-10-08) ### Bug fixes Appending a transaction to an undo transaction will no longer immediately clear the redo history. When handling appended transactions, the history will keep the last step in the original transaction, not the one from the appended transaction, for testing whether a subsequent transaction is adjacent to the previous one. ## 1.0.2 (2018-03-13) ### Bug fixes Fix a bug that could corrupt the history when rebasing changes because of collaborative editing. ## 1.0.1 (2018-03-05) ### Bug fixes Fix crash that could occur (in specific circumstance) when redoing. ## 0.24.0 (2017-09-25) ### New features It is no longer necessary to manually enable the `preserveItems` option to the history plugin when using collaborative editing. (This behavior is now automatically enabled when necessary.) ## 0.20.0 (2017-04-03) ### Bug fixes Appended transactions no longer generate undo history events. ## 0.19.0 (2017-03-16) ### New features A new function [`closeHistory`](https://prosemirror.net/docs/ref/version/0.19.0.html#history.closeHistory) can be used to force separation of history events at the start of a given transaction. ## 0.18.0 (2017-02-24) ### Bug fixes Fix a problem where simultaneous collaborative editing could break the undo history. ## 0.17.1 (2017-02-02) ### Bug fixes Fix issue where collaborative editing corner cases could corrupt the history. ## 0.12.1 (2016-11-01) ### Bug fixes Fix crash in undo or redo commands when the history is empty. ## 0.12.0 (2016-10-21) ### Breaking changes The [`history`](https://prosemirror.net/docs/ref/version/0.12.0.html#history.history) export is now a function that creates a history plugin, rather than a plugin instance. ### New features Add a [`newGroupDelay`](https://prosemirror.net/docs/ref/version/0.12.0.html#history.history^config.newGroupDelay) plugin option. This brings back the behavior where pausing between edits will automatically cause the history to put subsequent changes in a new undo event. ## 0.11.0 (2016-09-21) ### Breaking changes Moved into a separate module. Now acts as a plugin that can be omitted or replaced by a different implementation if desired. Merging subsequent changes into a single undo 'event' is now done by proximity in the document (the changes must touch) rather than in time. This will probably have to be further refined. prosemirror-history/CONTRIBUTING.md000066400000000000000000000073301525667712500174140ustar00rootroot00000000000000# How to contribute - [Getting help](#getting-help) - [Submitting bug reports](#submitting-bug-reports) - [Contributing code](#contributing-code) ## Getting help Community discussion, questions, and informal bug reporting is done on the [discuss.ProseMirror forum](http://discuss.prosemirror.net). ## Submitting bug reports Report bugs on the [issue tracker](https://code.haverbeke.berlin/prosemirror/prosemirror/issues). Before reporting a bug, please read these pointers. - The issue tracker is for *bugs*, not requests for help. Questions should be asked on the [forum](http://discuss.prosemirror.net). - Include information about the version of the code that exhibits the problem. For browser-related issues, include the browser and browser version on which the problem occurred. - Mention very precisely what went wrong. "X is broken" is not a good bug report. What did you expect to happen? What happened instead? Describe the exact steps a maintainer has to take to make the problem occur. A screencast can be useful, but is no substitute for a textual description. - A great way to make it easy to reproduce your problem, if it can not be trivially reproduced on the website demos, is to submit a script that triggers the issue. ## Contributing code Code generated by a language model is not welcome in this project. Please don't waste my time with it. If you want to make a change that involves a significant overhaul of the code or introduces a user-visible new feature, create an [issue](https://code.haverbeke.berlin/prosemirror/prosemirror/issues/) first with your proposal. - Make sure you have a [Codeberg](https://codeberg.org/user/sign_up) or [GitHub](https://github.com/signup/free) account. - Use that to create a [code.haverbeke.berlin account](https://code.haverbeke.berlin/user/login). - Fork the relevant repository. - Create a local checkout of the code. You can use the [main repository](https://code.haverbeke.berlin/prosemirror/prosemirror) to easily check out all core modules. - Make your changes, and commit them - If your changes are easy to test or likely to regress, add tests in the relevant `test/` directory. Either put them in an existing `test-*.js` file, if they fit there, or add a new file. - Make sure all tests pass. Run `npm run test` to verify tests pass (you will need Node.js v6+). - Submit a pull request. Don't put more than one feature/fix in a single pull request. By contributing code to ProseMirror you - Agree to license the contributed code under the project's [MIT license](https://code.haverbeke.berlin/prosemirror/prosemirror/blob/main/LICENSE). - Confirm that you have the right to contribute and license the code in question. (Either you hold all rights on the code, or the rights holder has explicitly granted the right to use it like this, through a compatible open source license or through a direct agreement with you.) ### Coding standards - ES6 syntax, targeting an ES5 runtime (i.e. don't use library elements added by ES6, don't use ES7/ES.next syntax). - 2 spaces per indentation level, no tabs. - No semicolons except when necessary. - Follow the surrounding code when it comes to spacing, brace placement, etc. - Brace-less single-statement bodies are encouraged whenever they don't impact readability. - [getdocs-ts](https://code.haverbeke.berlin/marijn/getdocs-ts)-style doc comments above items that are part of the public API. - When documenting non-public items, you can put the type after a single colon, so that getdocs doesn't pick it up and add it to the API reference. - ProseMirror does *not* follow JSHint or JSLint prescribed style. Patches that try to 'fix' code to pass one of these linters will not be accepted. prosemirror-history/LICENSE000066400000000000000000000021211525667712500161610ustar00rootroot00000000000000Copyright (C) 2015-2017 by Marijn Haverbeke and others Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. prosemirror-history/README.md000066400000000000000000000025611525667712500164430ustar00rootroot00000000000000# prosemirror-history [ [**WEBSITE**](https://prosemirror.net) | [**ISSUES**](https://code.haverbeke.berlin/prosemirror/prosemirror/issues) | [**FORUM**](https://discuss.prosemirror.net) | [**CHANGELOG**](https://code.haverbeke.berlin/prosemirror/prosemirror-history/src/branch/main/CHANGELOG.md) ] This is a [core module](https://prosemirror.net/docs/ref/#history) of [ProseMirror](https://prosemirror.net). ProseMirror is a well-behaved rich semantic content editor based on contentEditable, with support for collaborative editing and custom document schemas. This [module](https://prosemirror.net/docs/ref/#history) implements an undo/redo history plugin for ProseMirror. The [project page](https://prosemirror.net) has more information, a number of [examples](https://prosemirror.net/examples/) and the [documentation](https://prosemirror.net/docs/). This code is released under an [MIT license](https://code.haverbeke.berlin/prosemirror/prosemirror/src/branch/main/LICENSE). There's a [forum](http://discuss.prosemirror.net) for general discussion and support requests, and the [bug tracker](https://code.haverbeke.berlin/prosemirror/prosemirror/issues) is the place to report issues. We aim to be an inclusive, welcoming community. To make that explicit, we have a [code of conduct](http://contributor-covenant.org/version/1/1/0/) that applies to communication around the project. prosemirror-history/package.json000066400000000000000000000017401525667712500174500ustar00rootroot00000000000000{ "name": "prosemirror-history", "version": "1.5.1", "description": "Undo history for ProseMirror", "type": "module", "main": "dist/index.cjs", "module": "dist/index.js", "types": "dist/index.d.ts", "exports": { "import": "./dist/index.js", "require": "./dist/index.cjs" }, "sideEffects": false, "license": "MIT", "maintainers": [ { "name": "Marijn Haverbeke", "email": "marijn@haverbeke.berlin", "web": "http://marijnhaverbeke.nl" } ], "repository": { "type": "git", "url": "git+https://code.haverbeke.berlin/prosemirror/prosemirror-history.git" }, "dependencies": { "prosemirror-state": "^1.2.2", "prosemirror-transform": "^1.0.0", "prosemirror-view": "^1.31.0", "rope-sequence": "^1.3.0" }, "devDependencies": { "@prosemirror/buildhelper": "^0.1.5", "prosemirror-test-builder": "^1.0.0" }, "scripts": { "test": "pm-runtests", "prepare": "pm-buildhelper src/history.ts" } } prosemirror-history/src/000077500000000000000000000000001525667712500157475ustar00rootroot00000000000000prosemirror-history/src/README.md000066400000000000000000000006411525667712500172270ustar00rootroot00000000000000An implementation of an undo/redo history for ProseMirror. This history is _selective_, meaning it does not just roll back to a previous state but can undo some changes while keeping other, later changes intact. (This is necessary for collaborative editing, and comes up in other situations as well.) @history @undo @redo @undoNoScroll @redoNoScroll @undoDepth @redoDepth @closeHistory @isHistoryTransaction prosemirror-history/src/history.ts000066400000000000000000000427751525667712500200370ustar00rootroot00000000000000import RopeSequence from "rope-sequence" import {Mapping, Step, StepMap, Transform} from "prosemirror-transform" import {Plugin, Command, PluginKey, EditorState, Transaction, SelectionBookmark} from "prosemirror-state" // ProseMirror's history isn't simply a way to roll back to a previous // state, because ProseMirror supports applying changes without adding // them to the history (for example during collaboration). // // To this end, each 'Branch' (one for the undo history and one for // the redo history) keeps an array of 'Items', which can optionally // hold a step (an actual undoable change), and always hold a position // map (which is needed to move changes below them to apply to the // current document). // // An item that has both a step and a selection bookmark is the start // of an 'event' — a group of changes that will be undone or redone at // once. (It stores only the bookmark, since that way we don't have to // provide a document until the selection is actually applied, which // is useful when compressing.) // Used to schedule history compression const max_empty_items = 500 class Branch { constructor(readonly items: RopeSequence, readonly eventCount: number) {} // Pop the latest event off the branch's history and apply it // to a document transform. popEvent(state: EditorState, preserveItems: boolean) { if (this.eventCount == 0) return null let end = this.items.length for (;; end--) { let next = this.items.get(end - 1) if (next.selection) { --end; break } } let remap: Mapping | undefined, mapFrom: number | undefined if (preserveItems) { remap = this.remapping(end, this.items.length) mapFrom = remap.maps.length } let transform = state.tr let selection: SelectionBookmark | undefined, remaining: Branch | undefined let addAfter: Item[] = [], addBefore: Item[] = [] this.items.forEach((item, i) => { if (!item.step) { if (!remap) { remap = this.remapping(end, i + 1) mapFrom = remap.maps.length } mapFrom!-- addBefore.push(item) return } if (remap) { addBefore.push(new Item(item.map)) let step = item.step.map(remap.slice(mapFrom)), map if (step && transform.maybeStep(step).doc) { map = transform.mapping.maps[transform.mapping.maps.length - 1] addAfter.push(new Item(map, undefined, undefined, addAfter.length + addBefore.length)) } mapFrom!-- if (map) remap.appendMap(map, mapFrom) } else { transform.maybeStep(item.step) } if (item.selection) { selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection remaining = new Branch(this.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this.eventCount - 1) return false } }, this.items.length, 0) return {remaining: remaining!, transform, selection: selection!} } // Create a new branch with the given transform added. addTransform(transform: Transform, selection: SelectionBookmark | undefined, histOptions: Required, preserveItems: boolean) { let newItems = [], eventCount = this.eventCount let oldItems = this.items, lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null for (let i = 0; i < transform.steps.length; i++) { let step = transform.steps[i].invert(transform.docs[i]) let item = new Item(transform.mapping.maps[i], step, selection), merged if (merged = lastItem && lastItem.merge(item)) { item = merged if (i) newItems.pop() else oldItems = oldItems.slice(0, oldItems.length - 1) } newItems.push(item) if (selection) { eventCount++ selection = undefined } if (!preserveItems) lastItem = item } let overflow = eventCount - histOptions.depth if (overflow > DEPTH_OVERFLOW) { oldItems = cutOffEvents(oldItems, overflow) eventCount -= overflow } return new Branch(oldItems.append(newItems), eventCount) } remapping(from: number, to: number): Mapping { let maps = new Mapping this.items.forEach((item, i) => { let mirrorPos = item.mirrorOffset != null && i - item.mirrorOffset >= from ? maps.maps.length - item.mirrorOffset : undefined maps.appendMap(item.map, mirrorPos) }, from, to) return maps } addMaps(array: readonly StepMap[]) { if (this.eventCount == 0) return this return new Branch(this.items.append(array.map(map => new Item(map))), this.eventCount) } // When the collab module receives remote changes, the history has // to know about those, so that it can adjust the steps that were // rebased on top of the remote changes, and include the position // maps for the remote changes in its array of items. rebased(rebasedTransform: Transform, rebasedCount: number) { if (!this.eventCount) return this rebasedCount = Math.min(this.items.length, rebasedCount) let rebasedItems: Item[] = [], start = this.items.length - rebasedCount let mapping = rebasedTransform.mapping let newUntil = rebasedTransform.steps.length let eventCount = this.eventCount this.items.forEach(item => { if (item.selection) eventCount-- }, start) let iRebased = rebasedCount this.items.forEach(item => { let pos = mapping.getMirror(--iRebased) if (pos == null) return newUntil = Math.min(newUntil, pos) let map = mapping.maps[pos] if (item.step) { let step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]) let selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos)) if (selection) eventCount++ rebasedItems.push(new Item(map, step, selection)) } else { rebasedItems.push(new Item(map)) } }, start) let newMaps = [] for (let i = rebasedCount; i < newUntil; i++) newMaps.push(new Item(mapping.maps[i])) let items = this.items.slice(0, start).append(newMaps).append(rebasedItems) let branch = new Branch(items, eventCount) if (branch.emptyItemCount() > max_empty_items) branch = branch.compress(this.items.length - rebasedItems.length) return branch } emptyItemCount() { let count = 0 this.items.forEach(item => { if (!item.step) count++ }) return count } // Compressing a branch means rewriting it to push the air (map-only // items) out. During collaboration, these naturally accumulate // because each remote change adds one. The `upto` argument is used // to ensure that only the items below a given level are compressed, // because `rebased` relies on a clean, untouched set of items in // order to associate old items with rebased steps. compress(upto = this.items.length) { let remap = this.remapping(0, upto), mapFrom = remap.maps.length let items: Item[] = [], events = 0 this.items.forEach((item, i) => { if (i >= upto) { items.push(item) if (item.selection) events++ } else if (item.step) { let step = item.step.map(remap.slice(mapFrom)), map = step && step.getMap() mapFrom-- if (map) remap.appendMap(map, mapFrom) if (step) { let selection = item.selection && item.selection.map(remap.slice(mapFrom)) if (selection) events++ let newItem = new Item(map!.invert(), step, selection), merged, last = items.length - 1 if (merged = items.length && items[last].merge(newItem)) items[last] = merged else items.push(newItem) } } else if (item.map) { mapFrom-- } }, this.items.length, 0) return new Branch(RopeSequence.from(items.reverse()), events) } static empty = new Branch(RopeSequence.empty, 0) } function cutOffEvents(items: RopeSequence, n: number) { let cutPoint: number | undefined items.forEach((item, i) => { if (item.selection && (n-- == 0)) { cutPoint = i return false } }) return items.slice(cutPoint!) } class Item { constructor( // The (forward) step map for this item. readonly map: StepMap, // The inverted step readonly step?: Step, // If this is non-null, this item is the start of a group, and // this selection is the starting selection for the group (the one // that was active before the first step was applied) readonly selection?: SelectionBookmark, // If this item is the inverse of a previous mapping on the stack, // this points at the inverse's offset readonly mirrorOffset?: number ) {} merge(other: Item) { if (this.step && other.step && !other.selection) { let step = other.step.merge(this.step) if (step) return new Item(step.getMap().invert(), step, this.selection) } } } // The value of the state field that tracks undo/redo history for that // state. Will be stored in the plugin state when the history plugin // is active. class HistoryState { constructor( readonly done: Branch, readonly undone: Branch, readonly prevRanges: readonly number[] | null, readonly prevTime: number, readonly prevComposition: number ) {} } const DEPTH_OVERFLOW = 20 // Record a transformation in undo history. function applyTransaction(history: HistoryState, state: EditorState, tr: Transaction, options: Required) { let historyTr = tr.getMeta(historyKey), rebased if (historyTr) return historyTr.historyState if (tr.getMeta(closeHistoryKey)) history = new HistoryState(history.done, history.undone, null, 0, -1) let appended = tr.getMeta("appendedTransaction") if (tr.steps.length == 0) { return history } else if (appended && appended.getMeta(historyKey)) { if (appended.getMeta(historyKey).redo) return new HistoryState(history.done.addTransform(tr, undefined, options, mustPreserveItems(state)), history.undone, rangesFor(tr.mapping.maps), history.prevTime, history.prevComposition) else return new HistoryState(history.done, history.undone.addTransform(tr, undefined, options, mustPreserveItems(state)), null, history.prevTime, history.prevComposition) } else if (tr.getMeta("addToHistory") !== false && !(appended && appended.getMeta("addToHistory") === false)) { // Group transforms that occur in quick succession into one event. let composition = tr.getMeta("composition") let newGroup = history.prevTime == 0 || (!appended && history.prevComposition != composition && (history.prevTime < (tr.time || 0) - options.newGroupDelay || !isAdjacentTo(tr, history.prevRanges!))) let prevRanges = appended ? mapRanges(history.prevRanges!, tr.mapping) : rangesFor(tr.mapping.maps) return new HistoryState(history.done.addTransform(tr, newGroup ? state.selection.getBookmark() : undefined, options, mustPreserveItems(state)), Branch.empty, prevRanges, tr.time, composition == null ? history.prevComposition : composition) } else if (rebased = tr.getMeta("rebased")) { // Used by the collab module to tell the history that some of its // content has been rebased. return new HistoryState(history.done.rebased(tr, rebased), history.undone.rebased(tr, rebased), mapRanges(history.prevRanges!, tr.mapping), history.prevTime, history.prevComposition) } else { return new HistoryState(history.done.addMaps(tr.mapping.maps), history.undone.addMaps(tr.mapping.maps), mapRanges(history.prevRanges!, tr.mapping), history.prevTime, history.prevComposition) } } function isAdjacentTo(transform: Transform, prevRanges: readonly number[]) { if (!prevRanges) return false if (!transform.docChanged) return true let adjacent = false transform.mapping.maps[0].forEach((start, end) => { for (let i = 0; i < prevRanges.length; i += 2) if (start <= prevRanges[i + 1] && end >= prevRanges[i]) adjacent = true }) return adjacent } function rangesFor(maps: readonly StepMap[]) { let result: number[] = [] for (let i = maps.length - 1; i >= 0 && result.length == 0; i--) maps[i].forEach((_from, _to, from, to) => result.push(from, to)) return result } function mapRanges(ranges: readonly number[], mapping: Mapping) { if (!ranges) return null let result = [] for (let i = 0; i < ranges.length; i += 2) { let from = mapping.map(ranges[i], 1), to = mapping.map(ranges[i + 1], -1) if (from <= to) result.push(from, to) } return result } // Apply the latest event from one branch to the document and shift the event // onto the other branch. function histTransaction(history: HistoryState, state: EditorState, redo: boolean): Transaction | null { let preserveItems = mustPreserveItems(state) let histOptions = (historyKey.get(state)!.spec as any).config as Required let pop = (redo ? history.undone : history.done).popEvent(state, preserveItems) if (!pop) return null let selection = pop.selection!.resolve(pop.transform.doc) let added = (redo ? history.done : history.undone).addTransform(pop.transform, state.selection.getBookmark(), histOptions, preserveItems) let newHist = new HistoryState(redo ? added : pop.remaining, redo ? pop.remaining : added, null, 0, -1) return pop.transform.setSelection(selection).setMeta(historyKey, {redo, historyState: newHist}) } let cachedPreserveItems = false, cachedPreserveItemsPlugins: readonly Plugin[] | null = null // Check whether any plugin in the given state has a // `historyPreserveItems` property in its spec, in which case we must // preserve steps exactly as they came in, so that they can be // rebased. function mustPreserveItems(state: EditorState) { let plugins = state.plugins if (cachedPreserveItemsPlugins != plugins) { cachedPreserveItems = false cachedPreserveItemsPlugins = plugins for (let i = 0; i < plugins.length; i++) if ((plugins[i].spec as any).historyPreserveItems) { cachedPreserveItems = true break } } return cachedPreserveItems } /// Set a flag on the given transaction that will prevent further steps /// from being appended to an existing history event (so that they /// require a separate undo command to undo). export function closeHistory(tr: Transaction) { return tr.setMeta(closeHistoryKey, true) } const historyKey = new PluginKey("history") const closeHistoryKey = new PluginKey("closeHistory") interface HistoryOptions { /// The amount of history events that are collected before the /// oldest events are discarded. Defaults to 100. depth?: number /// The delay between changes after which a new group should be /// started. Defaults to 500 (milliseconds). Note that when changes /// aren't adjacent, a new group is always started. newGroupDelay?: number } /// Returns a plugin that enables the undo history for an editor. The /// plugin will track undo and redo stacks, which can be used with the /// [`undo`](#history.undo) and [`redo`](#history.redo) commands. /// /// You can set an `"addToHistory"` [metadata /// property](#state.Transaction.setMeta) of `false` on a transaction /// to prevent it from being rolled back by undo. export function history(config: HistoryOptions = {}): Plugin { config = {depth: config.depth || 100, newGroupDelay: config.newGroupDelay || 500} return new Plugin({ key: historyKey, state: { init() { return new HistoryState(Branch.empty, Branch.empty, null, 0, -1) }, apply(tr, hist, state) { return applyTransaction(hist, state, tr, config as Required) } }, config, props: { handleDOMEvents: { beforeinput(view, e: Event) { let inputType = (e as InputEvent).inputType let command = inputType == "historyUndo" ? undo : inputType == "historyRedo" ? redo : null if (!command || !view.editable) return false e.preventDefault() return command(view.state, view.dispatch) } } } }) } function buildCommand(redo: boolean, scroll: boolean): Command { return (state, dispatch) => { let hist = historyKey.getState(state) if (!hist || (redo ? hist.undone : hist.done).eventCount == 0) return false if (dispatch) { let tr = histTransaction(hist, state, redo) if (tr) dispatch(scroll ? tr.scrollIntoView() : tr) } return true } } /// A command function that undoes the last change, if any. export const undo = buildCommand(false, true) /// A command function that redoes the last undone change, if any. export const redo = buildCommand(true, true) /// A command function that undoes the last change. Don't scroll the /// selection into view. export const undoNoScroll = buildCommand(false, false) /// A command function that redoes the last undone change. Don't /// scroll the selection into view. export const redoNoScroll = buildCommand(true, false) /// The amount of undoable events available in a given state. export function undoDepth(state: EditorState) { let hist = historyKey.getState(state) return hist ? hist.done.eventCount : 0 } /// The amount of redoable events available in a given editor state. export function redoDepth(state: EditorState) { let hist = historyKey.getState(state) return hist ? hist.undone.eventCount : 0 } /// Returns true if the given transaction was generated by the history /// plugin. export function isHistoryTransaction(tr: Transaction) { return tr.getMeta(historyKey) != null } prosemirror-history/test/000077500000000000000000000000001525667712500161375ustar00rootroot00000000000000prosemirror-history/test/test-history.ts000066400000000000000000000354761525667712500212040ustar00rootroot00000000000000import {eq, schema, doc, p} from "prosemirror-test-builder" import {Slice, Fragment, Node} from "prosemirror-model" import {EditorState, Plugin, TextSelection, Command} from "prosemirror-state" import {ReplaceStep} from "prosemirror-transform" import ist from "ist" import {history, closeHistory, undo, redo, undoDepth, redoDepth} from "prosemirror-history" let plugin = history() function mkState(doc?: Node, config?: any) { let plugins = [config ? history(config) : plugin] if (config && config.preserveItems) plugins.push(new Plugin({historyPreserveItems: true} as any)) return EditorState.create({schema, plugins: plugins.concat(config && config.plugins || []), doc}) } function type(state: EditorState, text: string) { return state.apply(state.tr.insertText(text)) } function command(state: EditorState, command: Command) { command(state, tr => state = state.apply(tr)) return state } function compress(state: EditorState) { // NOTE: This is mutating stuff that shouldn't be mutated. Not safe // to do outside of these tests. plugin.getState(state).done = plugin.getState(state).done.compress() } describe("history", () => { it("enables undo", () => { let state = mkState() state = type(state, "a") state = type(state, "b") ist(state.doc, doc(p("ab")), eq) state = command(state, undo) ist(state.doc, doc(p()), eq) }) it("enables redo", () => { let state = mkState() state = type(state, "a") state = type(state, "b") state = command(state, undo) ist(state.doc, doc(p()), eq) state = command(state, redo) ist(state.doc, doc(p("ab")), eq) }) it("tracks multiple levels of history", () => { let state = mkState() state = type(state, "a") state = type(state, "b") state = state.apply(state.tr.insertText("c", 1)) ist(state.doc, doc(p("cab")), eq) state = command(state, undo) ist(state.doc, doc(p("ab")), eq) state = command(state, undo) ist(state.doc, doc(p()), eq) state = command(state, redo) ist(state.doc, doc(p("ab")), eq) state = command(state, redo) ist(state.doc, doc(p("cab")), eq) state = command(state, undo) ist(state.doc, doc(p("ab")), eq) }) it("starts a new event when newGroupDelay elapses", () => { let state = mkState(undefined, {newGroupDelay: 1000}) state = state.apply(state.tr.insertText("a").setTime(1000)) state = state.apply(state.tr.insertText("b").setTime(1600)) ist(undoDepth(state), 1) state = state.apply(state.tr.insertText("c").setTime(2700)) ist(undoDepth(state), 2) state = command(state, undo) state = state.apply(state.tr.insertText("d").setTime(2800)) ist(undoDepth(state), 2) }) it("starts a new event for non-adjacent changes", () => { let state = mkState(doc(p("abc")), {newGroupDelay: 1000}) state = state.apply(state.tr.insertText("x", 1)) state = state.apply(state.tr.insertText("y", 5)) ist(undoDepth(state), 2) }) it("doesn't get confused by non-replacement steps when checking adjacency", () => { let state = mkState(doc(p()), {newGroupDelay: 1000}) state = state.apply(state.tr.insertText("x", 1).addMark(1, 2, schema.marks.em.create())) state = state.apply(state.tr.insertText("y", 2).addMark(2, 3, schema.marks.em.create())) ist(undoDepth(state), 1) }) it("allows changes that aren't part of the history", () => { let state = mkState() state = type(state, "hello") state = state.apply(state.tr.insertText("oops", 1).setMeta("addToHistory", false)) state = state.apply(state.tr.insertText("!", 10).setMeta("addToHistory", false)) state = command(state, undo) ist(state.doc, doc(p("oops!")), eq) }) it("doesn't get confused by an undo not adding any redo item", () => { let state = mkState() state = state.apply(state.tr.insertText("foo")) state = state.apply(state.tr.replaceWith(1, 4, schema.text("bar")).setMeta("addToHistory", false)) state = command(state, undo) state = command(state, redo) ist(state.doc, doc(p("bar")), eq) }) function unsyncedComplex(state: EditorState, doCompress: boolean) { state = type(state, "hello") state = state.apply(closeHistory(state.tr)) state = type(state, "!") state = state.apply(state.tr.insertText("....", 1).setMeta("addToHistory", false)) state = state.apply(state.tr.split(3)) ist(state.doc, doc(p(".."), p("..hello!")), eq) state = state.apply(state.tr.split(2).setMeta("addToHistory", false)) if (doCompress) compress(state) state = command(state, undo) state = command(state, undo) ist(state.doc, doc(p("."), p("...hello")), eq) state = command(state, undo) ist(state.doc, doc(p("."), p("...")), eq) } it("can handle complex editing sequences", () => { unsyncedComplex(mkState(), false) }) it("can handle complex editing sequences with compression", () => { unsyncedComplex(mkState(), true) }) it("supports overlapping edits", () => { let state = mkState() state = type(state, "hello") state = state.apply(closeHistory(state.tr)) state = state.apply(state.tr.delete(1, 6)) ist(state.doc, doc(p()), eq) state = command(state, undo) ist(state.doc, doc(p("hello")), eq) state = command(state, undo) ist(state.doc, doc(p()), eq) }) it("supports overlapping edits that aren't collapsed", () => { let state = mkState() state = state.apply(state.tr.insertText("h", 1).setMeta("addToHistory", false)) state = type(state, "ello") state = state.apply(closeHistory(state.tr)) state = state.apply(state.tr.delete(1, 6)) ist(state.doc, doc(p()), eq) state = command(state, undo) ist(state.doc, doc(p("hello")), eq) state = command(state, undo) ist(state.doc, doc(p("h")), eq) }) it("supports overlapping unsynced deletes", () => { let state = mkState() state = type(state, "hi") state = state.apply(closeHistory(state.tr)) state = type(state, "hello") state = state.apply(state.tr.delete(1, 8).setMeta("addToHistory", false)) ist(state.doc, doc(p()), eq) state = command(state, undo) ist(state.doc, doc(p()), eq) }) it("can go back and forth through history multiple times", () => { let state = mkState() state = type(state, "one") state = type(state, " two") state = state.apply(closeHistory(state.tr)) state = type(state, " three") state = state.apply(state.tr.insertText("zero ", 1)) state = state.apply(closeHistory(state.tr)) state = state.apply(state.tr.split(1)) state = state.apply(state.tr.setSelection(TextSelection.create(state.doc, 1))) state = type(state, "top") for (let i = 0; i < 6; i++) { let re = i % 2 for (let j = 0; j < 4; j++) state = command(state, re ? redo : undo) ist(state.doc, re ? doc(p("top"), p("zero one two three")) : doc(p()), eq) } }) it("supports non-tracked changes next to tracked changes", () => { let state = mkState() state = type(state, "o") state = state.apply(state.tr.split(1)) state = state.apply(state.tr.insertText("zzz", 4).setMeta("addToHistory", false)) state = command(state, undo) ist(state.doc, doc(p("zzz")), eq) }) it("can go back and forth through history when preserving items", () => { let state = mkState() state = type(state, "one") state = type(state, " two") state = state.apply(closeHistory(state.tr)) state = state.apply(state.tr.insertText("xxx", state.selection.head).setMeta("addToHistory", false)) state = type(state, " three") state = state.apply(state.tr.insertText("zero ", 1)) state = state.apply(closeHistory(state.tr)) state = state.apply(state.tr.split(1)) state = state.apply(state.tr.setSelection(TextSelection.create(state.doc, 1))) state = type(state, "top") state = state.apply(state.tr.insertText("yyy", 1).setMeta("addToHistory", false)) for (let i = 0; i < 3; i++) { if (i == 2) compress(state) for (let j = 0; j < 4; j++) state = command(state, undo) ist(state.doc, doc(p("yyyxxx")), eq) for (let j = 0; j < 4; j++) state = command(state, redo) ist(state.doc, doc(p("yyytop"), p("zero one twoxxx three")), eq) } }) it("restores selection on undo", () => { let state = mkState() state = type(state, "hi") state = state.apply(closeHistory(state.tr)) state = state.apply(state.tr.setSelection(TextSelection.create(state.doc, 1, 3))) let selection = state.selection state = state.apply(state.tr.replaceWith(selection.from, selection.to, schema.text("hello"))) let selection2 = state.selection state = command(state, undo) ist(state.selection.eq(selection)) state = command(state, redo) ist(state.selection.eq(selection2)) }) it("rebases selection on undo", () => { let state = mkState() state = type(state, "hi") state = state.apply(closeHistory(state.tr)) state = state.apply(state.tr.setSelection(TextSelection.create(state.doc, 1, 3))) state = state.apply(state.tr.insert(1, schema.text("hello"))) state = state.apply(state.tr.insert(1, schema.text("---")).setMeta("addToHistory", false)) state = command(state, undo) ist(state.selection.head, 6) }) it("handles change overwriting in item-preserving mode", () => { let state = mkState(undefined, {preserveItems: true}) state = type(state, "a") state = type(state, "b") state = state.apply(closeHistory(state.tr)) state = state.apply(state.tr.setSelection(TextSelection.create(state.doc, 1, 3))) state = type(state, "c") state = command(state, undo) state = command(state, undo) ist(state.doc, doc(p()), eq) }) it("supports querying for the undo and redo depth", () => { let state = mkState() state = type(state, "a") ist(undoDepth(state), 1) ist(redoDepth(state), 0) state = state.apply(state.tr.insertText("b", 1).setMeta("addToHistory", false)) ist(undoDepth(state), 1) ist(redoDepth(state), 0) state = command(state, undo) ist(undoDepth(state), 0) ist(redoDepth(state), 1) state = command(state, redo) ist(undoDepth(state), 1) ist(redoDepth(state), 0) }) it("all functions gracefully handle EditorStates without history", () => { let state = EditorState.create({schema}) ist(undoDepth(state), 0) ist(redoDepth(state), 0) ist(undo(state), false) ist(redo(state), false) }) it("truncates history", () => { let state = mkState(undefined, {depth: 2}) for (let i = 1; i < 40; ++i) { state = type(state, "a") state = state.apply(closeHistory(state.tr)) ist(undoDepth(state), (i - 2) % 21 + 2) } }) it("supports transactions with multiple steps", () => { let state = mkState() state = state.apply(state.tr.insertText("a").insertText("b")) state = state.apply(state.tr.insertText("c", 1)) ist(state.doc, doc(p("cab")), eq) state = command(state, undo) ist(state.doc, doc(p("ab")), eq) state = command(state, undo) ist(state.doc, doc(p()), eq) state = command(state, redo) ist(state.doc, doc(p("ab")), eq) state = command(state, redo) ist(state.doc, doc(p("cab")), eq) state = command(state, undo) ist(state.doc, doc(p("ab")), eq) }) it("combines appended transactions in the event started by the base transaction", () => { let state = mkState(doc(p("x")), {plugins: [new Plugin({ appendTransaction: (_trs, _old, state) => { if (state.doc.content.size == 4) return state.tr.insert(1, schema.text("A")) } })]}) state = state.apply(state.tr.insert(2, schema.text("I"))) ist(state.doc, doc(p("AxI")), eq) ist(undoDepth(state), 1) state = command(state, undo) ist(state.doc, doc(p("x")), eq) }) it("includes transactions appended to undo in the redo history", () => { let state = mkState(doc(p("x")), {plugins: [new Plugin({ appendTransaction: (trs, _old, state) => { let add = trs[0].getMeta("add") if (add) return state.tr.insert(1, schema.text(add)) } })]}) state = state.apply(state.tr.insert(2, schema.text("I")).setMeta("add", "A")) ist(state.doc, doc(p("AxI")), eq) undo(state, tr => state = state.apply(tr.setMeta("add", "B"))) ist(state.doc, doc(p("Bx")), eq) redo(state, tr => state = state.apply(tr.setMeta("add", "C"))) ist(state.doc, doc(p("CAxI")), eq) state = command(state, undo) ist(state.doc, doc(p("Bx")), eq) }) it("doesn't close the history on appended transactions", () => { let state = mkState(doc(p("x")), {plugins: [new Plugin({ appendTransaction: (trs, _old, state) => { let add = trs[0].getMeta("add") if (add) return state.tr.insert(1, schema.text(add)) } })]}) state = state.apply(state.tr.insert(2, schema.text("R")).setMeta("add", "A")) state = state.apply(state.tr.insert(3, schema.text("M"))) state = command(state, undo) ist(state.doc, doc(p("x")), eq) }) it("supports rebasing", () => { // This test simulates a collab editing session where the local editor // receives a step (`right`) that's on top of the parent step (`base`) of // the last local step (`left`). // Shared base step let state = mkState() state = type(state, "base") state = state.apply(closeHistory(state.tr)) const baseDoc = state.doc // Local unconfirmed step // // - left // / // base - // \ // - right let rightStep = new ReplaceStep(5, 5, new Slice(Fragment.from(schema.text(" right")), 0, 0)) state = state.apply(state.tr.step(rightStep)) ist(state.doc, doc(p("base right")), eq) ist(undoDepth(state), 2) let leftStep = new ReplaceStep(1, 1, new Slice(Fragment.from(schema.text("left ")), 0, 0)) // Receive remote step and rebase local unconfirmed step // // base --> left --> right' const tr = state.tr tr.step(rightStep.invert(baseDoc)) tr.step(leftStep) tr.step(rightStep.map(tr.mapping.slice(1))!) tr.mapping.setMirror(0, tr.steps.length - 1) tr.setMeta("addToHistory", false) tr.setMeta("rebased", 1) state = state.apply(tr) ist(state.doc, doc(p("left base right")), eq) ist(undoDepth(state), 2) // Undo local unconfirmed step // // base --> left state = command(state, undo) ist(state.doc, doc(p("left base")), eq) // Redo local unconfirmed step // // base --> left --> right' state = command(state, redo) ist(state.doc, doc(p("left base right")), eq) }) it("properly maps selection when rebasing", () => { let state = mkState(doc(p("123456789ABCD"))) state = state.apply(state.tr.setSelection(TextSelection.create(state.doc, 6, 13))) state = state.apply(state.tr.delete(6, 13)) let rebase = state.tr.insert(6, schema.text("6789ABC")).insert(14, schema.text("E")).delete(6, 13) .setMeta("rebased", 1).setMeta("addToHistory", false) rebase.mapping.setMirror(0, 2) state = state.apply(rebase) state = command(state, undo) }) })