pax_global_header00006660000000000000000000000064143522746610014524gustar00rootroot0000000000000052 comment=c3bef001f7c563814f871351db3698c85433aa25 state-6.2.0/000077500000000000000000000000001435227466100126515ustar00rootroot00000000000000state-6.2.0/.github/000077500000000000000000000000001435227466100142115ustar00rootroot00000000000000state-6.2.0/.github/workflows/000077500000000000000000000000001435227466100162465ustar00rootroot00000000000000state-6.2.0/.github/workflows/dispatch.yml000066400000000000000000000006371435227466100205760ustar00rootroot00000000000000name: Trigger CI on: push jobs: build: name: Dispatch to main repo runs-on: ubuntu-latest steps: - name: Emit repository_dispatch uses: mvasigh/dispatch-action@main with: # You should create a personal access token and store it in your repository token: ${{ secrets.DISPATCH_AUTH }} repo: dev owner: codemirror event_type: push state-6.2.0/.gitignore000066400000000000000000000001271435227466100146410ustar00rootroot00000000000000/node_modules package-lock.json /dist /test/*.js /test/*.d.ts /test/*.d.ts.map .tern-* state-6.2.0/.npmignore000066400000000000000000000001001435227466100146370ustar00rootroot00000000000000/src /test /node_modules .tern-* rollup.config.js tsconfig.json state-6.2.0/CHANGELOG.md000066400000000000000000000135431435227466100144700ustar00rootroot00000000000000## 6.2.0 (2022-12-26) ### New features `EditorSelection.range` now accepts an optional 4th argument to specify the bidi level of the range's head position. ## 6.1.4 (2022-11-15) ### Bug fixes Fix a bug that caused the `openStart` value passed to span iterators to be incorrect around widgets in some circumstances. ## 6.1.3 (2022-11-10) ### Bug fixes Avoid unnecessary calls to computed facet getters when a state is reconfigured but no dependencies of the computed facet change. Fix an infinite loop in `RangeSet.eq` when the `to` parameter isn't given. ## 6.1.2 (2022-09-21) ### Bug fixes Fix an issue where, when multiple transaction extenders took effect, only the highest-precedence one was actually included in the transaction. ## 6.1.1 (2022-08-03) ### Bug fixes Fix a bug in range set span iteration that would cause decorations to be inappropriately split in some situations. ## 6.1.0 (2022-06-30) ### Bug fixes Refine change mapping to preserve insertions made by concurrent changes. ### New features The `enables` option to `Facet.define` may now take a function, which will be called with the facet value to create the extensions. ## 6.0.1 (2022-06-17) ### Bug fixes Fix a problem that caused effects' `map` methods to be called with an incorrect change set when filtering changes. ## 6.0.0 (2022-06-08) ### Breaking changes Update dependencies to 6.0.0 ## 0.20.1 (2022-06-02) ### New features `EditorView.phrase` now accepts additional arguments, which it will interpolate into the phrase in the place of `$` markers. ## 0.20.0 (2022-04-20) ### Breaking changes The deprecated precedence names `fallback`, `extend`, and `override` were removed from the library. ### Bug fixes Fix a bug where, if an extension value occurs multiple times, its lowest, rather than highest precedence is used. Fix an issue where facets with computed inputs would unneccesarily have their outputs recreated on state reconfiguration. Fix a bug in the order in which new values for state fields and facets were computed, which could cause dynamic facets to hold the wrong value in some situations. ### New features The exports from @codemirror/rangeset now live in this package. The exports from @codemirror/text now live in this package. ## 0.19.9 (2022-02-16) ### Bug fixes Mapping a non-empty selection range now always puts any newly inserted text on the sides of the range outside of the mapped version. ## 0.19.8 (2022-02-15) ### Bug fixes Fix a bug where facet values with computed inputs could incorrectly retain their old value on reconfiguration. ## 0.19.7 (2022-02-11) ### Bug fixes Avoid recomputing facets on state reconfiguration if that facet's inputs stayed precisely the same. Selection ranges created with `EditorSelection.range` will now have an assoc pointing at their anchor, when non-empty. ## 0.19.6 (2021-11-19) ### Bug fixes Fix a bug that caused facet compare functions to be called with an invalid value in some situations. Fix a bug that caused dynamic facet values to be incorrectly kept unchanged when reconfiguration changed one of their dependencies. ## 0.19.5 (2021-11-10) ### Bug fixes Fix a bug that would cause dynamic facet values influenced by a state reconfiguration to not properly recompute. ## 0.19.4 (2021-11-05) ### Bug fixes When reconfiguring a state, effects from the reconfiguring transaction can now be seen by newly added state fields. ## 0.19.3 (2021-11-03) ### New features The precedence levels (under `Prec`) now have more generic names, because their 'meaningful' names were entirely inappropriate in many situations. ## 0.19.2 (2021-09-13) ### New features The editor state now has a `readOnly` property with a matching facet to control its value. ## 0.19.1 (2021-08-15) ### Bug fixes Fix a bug where `wordAt` never returned a useful result. ## 0.19.0 (2021-08-11) ### Breaking changes User event strings now work differently—the events emitted by the core packages follow a different system, and hierarchical event tags can be created by separating the words with dots. ### New features `languageDataAt` now takes an optional `side` argument to specificy which side of the position you're interested in. It is now possible to add a user event annotation with a direct `userEvent` property on a transaction spec. Transactions now have an `isUserEvent` method that can be used to check if it is (a subtype of) some user event type. ## 0.18.7 (2021-05-04) ### Bug fixes Fix an issue where state fields might be initialized with a state that they aren't actually part of during reconfiguration. ## 0.18.6 (2021-04-12) ### New features The new `EditorState.wordAt` method finds the word at a given position. ## 0.18.5 (2021-04-08) ### Bug fixes Fix an issue in the compiled output that would break the code when minified with terser. ## 0.18.4 (2021-04-06) ### New features The new `Transaction.remote` annotation can be used to mark and recognize transactions created by other actors. ## 0.18.3 (2021-03-23) ### New features The `ChangeDesc` class now has `toJSON` and `fromJSON` methods. ## 0.18.2 (2021-03-14) ### Bug fixes Fix unintended ES2020 output (the package contains ES6 code again). ## 0.18.1 (2021-03-10) ### New features The new `Compartment.get` method can be used to get the content of a compartment in a given state. ## 0.18.0 (2021-03-03) ### Breaking changes `tagExtension` and the `reconfigure` transaction spec property have been replaced with the concept of configuration compartments and reconfiguration effects (see `Compartment`, `StateEffect.reconfigure`, and `StateEffect.appendConfig`). ## 0.17.2 (2021-02-19) ### New features `EditorSelection.map` and `SelectionRange.map` now take an optional second argument to indicate which direction to map to. ## 0.17.1 (2021-01-06) ### New features The package now also exports a CommonJS module. ## 0.17.0 (2020-12-29) ### Breaking changes First numbered release. state-6.2.0/LICENSE000066400000000000000000000021301435227466100136520ustar00rootroot00000000000000MIT License Copyright (C) 2018-2021 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. state-6.2.0/README.md000066400000000000000000000017741435227466100141410ustar00rootroot00000000000000# @codemirror/state [![NPM version](https://img.shields.io/npm/v/@codemirror/state.svg)](https://www.npmjs.org/package/@codemirror/state) [ [**WEBSITE**](https://codemirror.net/) | [**DOCS**](https://codemirror.net/docs/ref/#state) | [**ISSUES**](https://github.com/codemirror/dev/issues) | [**FORUM**](https://discuss.codemirror.net/c/next/) | [**CHANGELOG**](https://github.com/codemirror/state/blob/main/CHANGELOG.md) ] This package implements the editor state data structures for the [CodeMirror](https://codemirror.net/) code editor. The [project page](https://codemirror.net/) has more information, a number of [examples](https://codemirror.net/examples/) and the [documentation](https://codemirror.net/docs/). This code is released under an [MIT license](https://github.com/codemirror/state/tree/main/LICENSE). 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. state-6.2.0/package.json000066400000000000000000000014371435227466100151440ustar00rootroot00000000000000{ "name": "@codemirror/state", "version": "6.2.0", "description": "Editor state data structures for the CodeMirror code editor", "scripts": { "test": "cm-runtests", "prepare": "cm-buildhelper src/index.ts" }, "keywords": [ "editor", "code" ], "author": { "name": "Marijn Haverbeke", "email": "marijnh@gmail.com", "url": "http://marijnhaverbeke.nl" }, "type": "module", "main": "dist/index.cjs", "exports": { "import": "./dist/index.js", "require": "./dist/index.cjs" }, "types": "dist/index.d.ts", "module": "dist/index.js", "sideEffects": false, "license": "MIT", "devDependencies": { "@codemirror/buildhelper": "^0.1.5" }, "repository": { "type": "git", "url": "https://github.com/codemirror/state.git" } } state-6.2.0/src/000077500000000000000000000000001435227466100134405ustar00rootroot00000000000000state-6.2.0/src/README.md000066400000000000000000000050741435227466100147250ustar00rootroot00000000000000In its most basic form, an editor's state is made up of a current document and a selection. Because there are a lot of extra pieces that an editor might need to keep in its state (such as an [undo history](#commands.history) or [syntax tree](#language.syntaxTree)), it is possible for extensions to add additional [fields](#state.StateField) to the state object. @EditorStateConfig @EditorState @SelectionRange @EditorSelection @CharCategory ### Text The `Text` type stores documents in an immutable tree-shaped representation that allows: - Efficient indexing both by code unit offset and by line number. - Structure-sharing immutable updates. - Access to and iteration over parts of the document without copying or concatenating big strings. Line numbers start at 1. Character positions are counted from zero, and count each line break and UTF-16 code unit as one unit. @Text @Line @TextIterator #### Column Utilities @countColumn @findColumn #### Code Points and Characters If you support environments that don't yet have `String.fromCodePoint` and `codePointAt`, this package provides portable replacements for them. @codePointAt @fromCodePoint @codePointSize @findClusterBreak ### Changes and Transactions CodeMirror treats changes to the document as [objects](#state.ChangeSet), which are usually part of a [transaction](#state.Transaction). This is how you'd make a change to a document (replacing “world” with “editor”) and create a new state with the updated document: ```javascript let state = EditorState.create({doc: "hello world"}) let transaction = state.update({changes: {from: 6, to: 11, insert: "editor"}}) console.log(transaction.state.doc.toString()) // "hello editor" ``` @TransactionSpec @ChangeSpec @Transaction @ChangeDesc @MapMode @ChangeSet @Annotation @AnnotationType @StateEffect @StateEffectType ### Extending Editor State The following are some types and mechanisms used when writing extensions for the editor state. @StateCommand @Extension @StateField @Facet @Prec @Compartment ### Range Sets Range sets provide a data structure that can hold a collection of tagged, possibly overlapping [ranges](#state.Range) in such a way that they can efficiently be [mapped](#state.RangeSet.map) though document changes. They are used for storing things like [decorations](#view.Decoration) or [gutter markers](#view.GutterMarker). @RangeValue @Range @RangeSet @RangeCursor @RangeSetBuilder @RangeComparator @SpanIterator ### Utilities @combineConfig state-6.2.0/src/change.ts000066400000000000000000000537401435227466100152460ustar00rootroot00000000000000import {Text} from "./text" export const DefaultSplit = /\r\n?|\n/ /// Distinguishes different ways in which positions can be mapped. export enum MapMode { /// Map a position to a valid new position, even when its context /// was deleted. Simple, /// Return null if deletion happens across the position. TrackDel, /// Return null if the character _before_ the position is deleted. TrackBefore, /// Return null if the character _after_ the position is deleted. TrackAfter } /// A change description is a variant of [change set](#state.ChangeSet) /// that doesn't store the inserted text. As such, it can't be /// applied, but is cheaper to store and manipulate. export class ChangeDesc { // Sections are encoded as pairs of integers. The first is the // length in the current document, and the second is -1 for // unaffected sections, and the length of the replacement content // otherwise. So an insertion would be (0, n>0), a deletion (n>0, // 0), and a replacement two positive numbers. /// @internal protected constructor( /// @internal readonly sections: readonly number[] ) {} /// The length of the document before the change. get length() { let result = 0 for (let i = 0; i < this.sections.length; i += 2) result += this.sections[i] return result } /// The length of the document after the change. get newLength() { let result = 0 for (let i = 0; i < this.sections.length; i += 2) { let ins = this.sections[i + 1] result += ins < 0 ? this.sections[i] : ins } return result } /// False when there are actual changes in this set. get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0 } /// Iterate over the unchanged parts left by these changes. `posA` /// provides the position of the range in the old document, `posB` /// the new position in the changed document. iterGaps(f: (posA: number, posB: number, length: number) => void) { for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) { let len = this.sections[i++], ins = this.sections[i++] if (ins < 0) { f(posA, posB, len) posB += len } else { posB += ins } posA += len } } /// Iterate over the ranges changed by these changes. (See /// [`ChangeSet.iterChanges`](#state.ChangeSet.iterChanges) for a /// variant that also provides you with the inserted text.) /// `fromA`/`toA` provides the extent of the change in the starting /// document, `fromB`/`toB` the extent of the replacement in the /// changed document. /// /// When `individual` is true, adjacent changes (which are kept /// separate for [position mapping](#state.ChangeDesc.mapPos)) are /// reported separately. iterChangedRanges(f: (fromA: number, toA: number, fromB: number, toB: number) => void, individual = false) { iterChanges(this, f, individual) } /// Get a description of the inverted form of these changes. get invertedDesc() { let sections = [] for (let i = 0; i < this.sections.length;) { let len = this.sections[i++], ins = this.sections[i++] if (ins < 0) sections.push(len, ins) else sections.push(ins, len) } return new ChangeDesc(sections) } /// Compute the combined effect of applying another set of changes /// after this one. The length of the document after this set should /// match the length before `other`. composeDesc(other: ChangeDesc) { return this.empty ? other : other.empty ? this : composeSets(this, other) } /// Map this description, which should start with the same document /// as `other`, over another set of changes, so that it can be /// applied after it. When `before` is true, map as if the changes /// in `other` happened before the ones in `this`. mapDesc(other: ChangeDesc, before = false): ChangeDesc { return other.empty ? this : mapSet(this, other, before) } /// Map a given position through these changes, to produce a /// position pointing into the new document. /// /// `assoc` indicates which side the position should be associated /// with. When it is negative or zero, the mapping will try to keep /// the position close to the character before it (if any), and will /// move it before insertions at that point or replacements across /// that point. When it is positive, the position is associated with /// the character after it, and will be moved forward for insertions /// at or replacements across the position. Defaults to -1. /// /// `mode` determines whether deletions should be /// [reported](#state.MapMode). It defaults to /// [`MapMode.Simple`](#state.MapMode.Simple) (don't report /// deletions). mapPos(pos: number, assoc?: number): number mapPos(pos: number, assoc: number, mode: MapMode): number | null mapPos(pos: number, assoc = -1, mode: MapMode = MapMode.Simple) { let posA = 0, posB = 0 for (let i = 0; i < this.sections.length;) { let len = this.sections[i++], ins = this.sections[i++], endA = posA + len if (ins < 0) { if (endA > pos) return posB + (pos - posA) posB += len } else { if (mode != MapMode.Simple && endA >= pos && (mode == MapMode.TrackDel && posA < pos && endA > pos || mode == MapMode.TrackBefore && posA < pos || mode == MapMode.TrackAfter && endA > pos)) return null if (endA > pos || endA == pos && assoc < 0 && !len) return pos == posA || assoc < 0 ? posB : posB + ins posB += ins } posA = endA } if (pos > posA) throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`) return posB } /// Check whether these changes touch a given range. When one of the /// changes entirely covers the range, the string `"cover"` is /// returned. touchesRange(from: number, to = from): boolean | "cover" { for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) { let len = this.sections[i++], ins = this.sections[i++], end = pos + len if (ins >= 0 && pos <= to && end >= from) return pos < from && end > to ? "cover" : true pos = end } return false } /// @internal toString() { let result = "" for (let i = 0; i < this.sections.length;) { let len = this.sections[i++], ins = this.sections[i++] result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : "") } return result } /// Serialize this change desc to a JSON-representable value. toJSON() { return this.sections } /// Create a change desc from its JSON representation (as produced /// by [`toJSON`](#state.ChangeDesc.toJSON). static fromJSON(json: any) { if (!Array.isArray(json) || json.length % 2 || json.some(a => typeof a != "number")) throw new RangeError("Invalid JSON representation of ChangeDesc") return new ChangeDesc(json as number[]) } /// @internal static create(sections: readonly number[]) { return new ChangeDesc(sections) } } /// This type is used as argument to /// [`EditorState.changes`](#state.EditorState.changes) and in the /// [`changes` field](#state.TransactionSpec.changes) of transaction /// specs to succinctly describe document changes. It may either be a /// plain object describing a change (a deletion, insertion, or /// replacement, depending on which fields are present), a [change /// set](#state.ChangeSet), or an array of change specs. export type ChangeSpec = {from: number, to?: number, insert?: string | Text} | ChangeSet | readonly ChangeSpec[] /// A change set represents a group of modifications to a document. It /// stores the document length, and can only be applied to documents /// with exactly that length. export class ChangeSet extends ChangeDesc { private constructor( sections: readonly number[], /// @internal readonly inserted: readonly Text[] ) { super(sections) } /// Apply the changes to a document, returning the modified /// document. apply(doc: Text) { if (this.length != doc.length) throw new RangeError("Applying change set to a document with the wrong length") iterChanges(this, (fromA, toA, fromB, _toB, text) => doc = doc.replace(fromB, fromB + (toA - fromA), text), false) return doc } mapDesc(other: ChangeDesc, before = false): ChangeDesc { return mapSet(this, other, before, true) } /// Given the document as it existed _before_ the changes, return a /// change set that represents the inverse of this set, which could /// be used to go from the document created by the changes back to /// the document as it existed before the changes. invert(doc: Text) { let sections = this.sections.slice(), inserted = [] for (let i = 0, pos = 0; i < sections.length; i += 2) { let len = sections[i], ins = sections[i + 1] if (ins >= 0) { sections[i] = ins; sections[i + 1] = len let index = i >> 1 while (inserted.length < index) inserted.push(Text.empty) inserted.push(len ? doc.slice(pos, pos + len) : Text.empty) } pos += len } return new ChangeSet(sections, inserted) } /// Combine two subsequent change sets into a single set. `other` /// must start in the document produced by `this`. If `this` goes /// `docA` → `docB` and `other` represents `docB` → `docC`, the /// returned value will represent the change `docA` → `docC`. compose(other: ChangeSet) { return this.empty ? other : other.empty ? this : composeSets(this, other, true) } /// Given another change set starting in the same document, maps this /// change set over the other, producing a new change set that can be /// applied to the document produced by applying `other`. When /// `before` is `true`, order changes as if `this` comes before /// `other`, otherwise (the default) treat `other` as coming first. /// /// Given two changes `A` and `B`, `A.compose(B.map(A))` and /// `B.compose(A.map(B, true))` will produce the same document. This /// provides a basic form of [operational /// transformation](https://en.wikipedia.org/wiki/Operational_transformation), /// and can be used for collaborative editing. map(other: ChangeDesc, before = false): ChangeSet { return other.empty ? this : mapSet(this, other, before, true) } /// Iterate over the changed ranges in the document, calling `f` for /// each, with the range in the original document (`fromA`-`toA`) /// and the range that replaces it in the new document /// (`fromB`-`toB`). /// /// When `individual` is true, adjacent changes are reported /// separately. iterChanges(f: (fromA: number, toA: number, fromB: number, toB: number, inserted: Text) => void, individual = false) { iterChanges(this, f, individual) } /// Get a [change description](#state.ChangeDesc) for this change /// set. get desc() { return ChangeDesc.create(this.sections) } /// @internal filter(ranges: readonly number[]) { let resultSections: number[] = [], resultInserted: Text[] = [], filteredSections: number[] = [] let iter = new SectionIter(this) done: for (let i = 0, pos = 0;;) { let next = i == ranges.length ? 1e9 : ranges[i++] while (pos < next || pos == next && iter.len == 0) { if (iter.done) break done let len = Math.min(iter.len, next - pos) addSection(filteredSections, len, -1) let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0 addSection(resultSections, len, ins) if (ins > 0) addInsert(resultInserted, resultSections, iter.text) iter.forward(len) pos += len } let end = ranges[i++] while (pos < end) { if (iter.done) break done let len = Math.min(iter.len, end - pos) addSection(resultSections, len, -1) addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0) iter.forward(len) pos += len } } return {changes: new ChangeSet(resultSections, resultInserted), filtered: ChangeDesc.create(filteredSections)} } /// Serialize this change set to a JSON-representable value. toJSON(): any { let parts: (number | [number, ...string[]])[] = [] for (let i = 0; i < this.sections.length; i += 2) { let len = this.sections[i], ins = this.sections[i + 1] if (ins < 0) parts.push(len) else if (ins == 0) parts.push([len]) else parts.push(([len] as [number, ...string[]]).concat(this.inserted[i >> 1].toJSON()) as any) } return parts } /// Create a change set for the given changes, for a document of the /// given length, using `lineSep` as line separator. static of(changes: ChangeSpec, length: number, lineSep?: string): ChangeSet { let sections: number[] = [], inserted: Text[] = [], pos = 0 let total: ChangeSet | null = null function flush(force = false) { if (!force && !sections.length) return if (pos < length) addSection(sections, length - pos, -1) let set = new ChangeSet(sections, inserted) total = total ? total.compose(set.map(total)) : set sections = []; inserted = []; pos = 0 } function process(spec: ChangeSpec) { if (Array.isArray(spec)) { for (let sub of spec) process(sub) } else if (spec instanceof ChangeSet) { if (spec.length != length) throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`) flush() total = total ? total.compose(spec.map(total)) : spec } else { let {from, to = from, insert} = spec as {from: number, to?: number, insert?: string | Text} if (from > to || from < 0 || to > length) throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`) let insText = !insert ? Text.empty : typeof insert == "string" ? Text.of(insert.split(lineSep || DefaultSplit)) : insert let insLen = insText.length if (from == to && insLen == 0) return if (from < pos) flush() if (from > pos) addSection(sections, from - pos, -1) addSection(sections, to - from, insLen) addInsert(inserted, sections, insText) pos = to } } process(changes) flush(!total) return total! } /// Create an empty changeset of the given length. static empty(length: number) { return new ChangeSet(length ? [length, -1] : [], []) } /// Create a changeset from its JSON representation (as produced by /// [`toJSON`](#state.ChangeSet.toJSON). static fromJSON(json: any) { if (!Array.isArray(json)) throw new RangeError("Invalid JSON representation of ChangeSet") let sections = [], inserted = [] for (let i = 0; i < json.length; i++) { let part = json[i] if (typeof part == "number") { sections.push(part, -1) } else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i) => i && typeof e != "string")) { throw new RangeError("Invalid JSON representation of ChangeSet") } else if (part.length == 1) { sections.push(part[0], 0) } else { while (inserted.length < i) inserted.push(Text.empty) inserted[i] = Text.of(part.slice(1)) sections.push(part[0], inserted[i].length) } } return new ChangeSet(sections, inserted) } /// @internal static createSet(sections: readonly number[], inserted: readonly Text[]) { return new ChangeSet(sections, inserted) } } function addSection(sections: number[], len: number, ins: number, forceJoin = false) { if (len == 0 && ins <= 0) return let last = sections.length - 2 if (last >= 0 && ins <= 0 && ins == sections[last + 1]) sections[last] += len else if (len == 0 && sections[last] == 0) sections[last + 1] += ins else if (forceJoin) { sections[last] += len; sections[last + 1] += ins } else sections.push(len, ins) } function addInsert(values: Text[], sections: readonly number[], value: Text) { if (value.length == 0) return let index = (sections.length - 2) >> 1 if (index < values.length) { values[values.length - 1] = values[values.length - 1].append(value) } else { while (values.length < index) values.push(Text.empty) values.push(value) } } function iterChanges(desc: ChangeDesc, f: (fromA: number, toA: number, fromB: number, toB: number, text: Text) => void, individual: boolean) { let inserted = (desc as ChangeSet).inserted for (let posA = 0, posB = 0, i = 0; i < desc.sections.length;) { let len = desc.sections[i++], ins = desc.sections[i++] if (ins < 0) { posA += len; posB += len } else { let endA = posA, endB = posB, text = Text.empty for (;;) { endA += len; endB += ins if (ins && inserted) text = text.append(inserted[(i - 2) >> 1]) if (individual || i == desc.sections.length || desc.sections[i + 1] < 0) break len = desc.sections[i++]; ins = desc.sections[i++] } f(posA, endA, posB, endB, text) posA = endA; posB = endB } } } function mapSet(setA: ChangeSet, setB: ChangeDesc, before: boolean, mkSet: true): ChangeSet function mapSet(setA: ChangeDesc, setB: ChangeDesc, before: boolean): ChangeDesc function mapSet(setA: ChangeDesc, setB: ChangeDesc, before: boolean, mkSet = false): ChangeSet | ChangeDesc { // Produce a copy of setA that applies to the document after setB // has been applied (assuming both start at the same document). let sections: number[] = [], insert: Text[] | null = mkSet ? [] : null let a = new SectionIter(setA), b = new SectionIter(setB) // Iterate over both sets in parallel. inserted tracks, for changes // in A that have to be processed piece-by-piece, whether their // content has been inserted already, and refers to the section // index. for (let inserted = -1;;) { if (a.ins == -1 && b.ins == -1) { // Move across ranges skipped by both sets. let len = Math.min(a.len, b.len) addSection(sections, len, -1) a.forward(len) b.forward(len) } else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) { // If there's a change in B that comes before the next change in // A (ordered by start pos, then len, then before flag), skip // that (and process any changes in A it covers). let len = b.len addSection(sections, b.ins, -1) while (len) { let piece = Math.min(a.len, len) if (a.ins >= 0 && inserted < a.i && a.len <= piece) { addSection(sections, 0, a.ins) if (insert) addInsert(insert, sections, a.text) inserted = a.i } a.forward(piece) len -= piece } b.next() } else if (a.ins >= 0) { // Process the part of a change in A up to the start of the next // non-deletion change in B (if overlapping). let len = 0, left = a.len while (left) { if (b.ins == -1) { let piece = Math.min(left, b.len) len += piece left -= piece b.forward(piece) } else if (b.ins == 0 && b.len < left) { left -= b.len b.next() } else { break } } addSection(sections, len, inserted < a.i ? a.ins : 0) if (insert && inserted < a.i) addInsert(insert, sections, a.text) inserted = a.i a.forward(a.len - left) } else if (a.done && b.done) { return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections) } else { throw new Error("Mismatched change set lengths") } } } function composeSets(setA: ChangeSet, setB: ChangeSet, mkSet: true): ChangeSet function composeSets(setA: ChangeDesc, setB: ChangeDesc): ChangeDesc function composeSets(setA: ChangeDesc, setB: ChangeDesc, mkSet = false): ChangeDesc { let sections: number[] = [] let insert: Text[] | null = mkSet ? [] : null let a = new SectionIter(setA), b = new SectionIter(setB) for (let open = false;;) { if (a.done && b.done) { return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections) } else if (a.ins == 0) { // Deletion in A addSection(sections, a.len, 0, open) a.next() } else if (b.len == 0 && !b.done) { // Insertion in B addSection(sections, 0, b.ins, open) if (insert) addInsert(insert, sections, b.text) b.next() } else if (a.done || b.done) { throw new Error("Mismatched change set lengths") } else { let len = Math.min(a.len2, b.len), sectionLen = sections.length if (a.ins == -1) { let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins addSection(sections, len, insB, open) if (insert && insB) addInsert(insert, sections, b.text) } else if (b.ins == -1) { addSection(sections, a.off ? 0 : a.len, len, open) if (insert) addInsert(insert, sections, a.textBit(len)) } else { addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open) if (insert && !b.off) addInsert(insert, sections, b.text) } open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen) a.forward2(len) b.forward(len) } } } class SectionIter { i = 0 len!: number off!: number ins!: number constructor(readonly set: ChangeDesc) { this.next() } next() { let {sections} = this.set if (this.i < sections.length) { this.len = sections[this.i++] this.ins = sections[this.i++] } else { this.len = 0; this.ins = -2 } this.off = 0 } get done() { return this.ins == -2 } get len2() { return this.ins < 0 ? this.len : this.ins } get text() { let {inserted} = this.set as ChangeSet, index = (this.i - 2) >> 1 return index >= inserted.length ? Text.empty : inserted[index] } textBit(len?: number) { let {inserted} = this.set as ChangeSet, index = (this.i - 2) >> 1 return index >= inserted.length && !len ? Text.empty : inserted[index].slice(this.off, len == null ? undefined : this.off + len) } forward(len: number) { if (len == this.len) this.next() else { this.len -= len; this.off += len } } forward2(len: number) { if (this.ins == -1) this.forward(len) else if (len == this.ins) this.next() else { this.ins -= len; this.off += len } } } state-6.2.0/src/char.ts000066400000000000000000000115201435227466100147240ustar00rootroot00000000000000// Compressed representation of the Grapheme_Cluster_Break=Extend // information from // http://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakProperty.txt. // Each pair of elements represents a range, as an offet from the // previous range and a length. Numbers are in base-36, with the empty // string being a shorthand for 1. let extend = "lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(s => s ? parseInt(s, 36) : 1) // Convert offsets into absolute values for (let i = 1; i < extend.length; i++) extend[i] += extend[i - 1] function isExtendingChar(code: number) { for (let i = 1; i < extend.length; i += 2) if (extend[i] > code) return extend[i - 1] <= code return false } function isRegionalIndicator(code: number) { return code >= 0x1F1E6 && code <= 0x1F1FF } const ZWJ = 0x200d /// Returns a next grapheme cluster break _after_ (not equal to) /// `pos`, if `forward` is true, or before otherwise. Returns `pos` /// itself if no further cluster break is available in the string. /// Moves across surrogate pairs, extending characters (when /// `includeExtending` is true), characters joined with zero-width /// joiners, and flag emoji. export function findClusterBreak(str: string, pos: number, forward = true, includeExtending = true) { return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending) } function nextClusterBreak(str: string, pos: number, includeExtending: boolean) { if (pos == str.length) return pos // If pos is in the middle of a surrogate pair, move to its start if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1))) pos-- let prev = codePointAt(str, pos) pos += codePointSize(prev) while (pos < str.length) { let next = codePointAt(str, pos) if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) { pos += codePointSize(next) prev = next } else if (isRegionalIndicator(next)) { let countBefore = 0, i = pos - 2 while (i >= 0 && isRegionalIndicator(codePointAt(str, i))) { countBefore++; i -= 2 } if (countBefore % 2 == 0) break else pos += 2 } else { break } } return pos } function prevClusterBreak(str: string, pos: number, includeExtending: boolean) { while (pos > 0) { let found = nextClusterBreak(str, pos - 2, includeExtending) if (found < pos) return found pos-- } return 0 } function surrogateLow(ch: number) { return ch >= 0xDC00 && ch < 0xE000 } function surrogateHigh(ch: number) { return ch >= 0xD800 && ch < 0xDC00 } /// Find the code point at the given position in a string (like the /// [`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt) /// string method). export function codePointAt(str: string, pos: number) { let code0 = str.charCodeAt(pos) if (!surrogateHigh(code0) || pos + 1 == str.length) return code0 let code1 = str.charCodeAt(pos + 1) if (!surrogateLow(code1)) return code0 return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000 } /// Given a Unicode codepoint, return the JavaScript string that /// respresents it (like /// [`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)). export function fromCodePoint(code: number) { if (code <= 0xffff) return String.fromCharCode(code) code -= 0x10000 return String.fromCharCode((code >> 10) + 0xd800, (code & 1023) + 0xdc00) } /// The amount of positions a character takes up a JavaScript string. export function codePointSize(code: number): 1 | 2 { return code < 0x10000 ? 1 : 2 } state-6.2.0/src/charcategory.ts000066400000000000000000000022101435227466100164560ustar00rootroot00000000000000/// The categories produced by a [character /// categorizer](#state.EditorState.charCategorizer). These are used /// do things like selecting by word. export enum CharCategory { /// Word characters. Word, /// Whitespace. Space, /// Anything else. Other } const nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/ let wordChar: RegExp | null try { wordChar = new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u") } catch (_) {} function hasWordChar(str: string): boolean { if (wordChar) return wordChar.test(str) for (let i = 0; i < str.length; i++) { let ch = str[i] if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))) return true } return false } export function makeCategorizer(wordChars: string) { return (char: string) => { if (!/\S/.test(char)) return CharCategory.Space if (hasWordChar(char)) return CharCategory.Word for (let i = 0; i < wordChars.length; i++) if (char.indexOf(wordChars[i]) > -1) return CharCategory.Word return CharCategory.Other } } state-6.2.0/src/column.ts000066400000000000000000000021171435227466100153060ustar00rootroot00000000000000import {findClusterBreak} from "./char" /// Count the column position at the given offset into the string, /// taking extending characters and tab size into account. export function countColumn(string: string, tabSize: number, to = string.length): number { let n = 0 for (let i = 0; i < to;) { if (string.charCodeAt(i) == 9) { n += tabSize - (n % tabSize) i++ } else { n++ i = findClusterBreak(string, i) } } return n } /// Find the offset that corresponds to the given column position in a /// string, taking extending characters and tab size into account. By /// default, the string length is returned when it is too short to /// reach the column. Pass `strict` true to make it return -1 in that /// situation. export function findColumn(string: string, col: number, tabSize: number, strict?: boolean): number { for (let i = 0, n = 0;;) { if (n >= col) return i if (i == string.length) break n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1 i = findClusterBreak(string, i) } return strict === true ? -1 : string.length } state-6.2.0/src/config.ts000066400000000000000000000023711435227466100152600ustar00rootroot00000000000000/// Utility function for combining behaviors to fill in a config /// object from an array of provided configs. `defaults` should hold /// default values for all optional fields in `Config`. /// /// The function will, by default, error /// when a field gets two values that aren't `===`-equal, but you can /// provide combine functions per field to do something else. export function combineConfig( configs: readonly Partial[], defaults: Partial, // Should hold only the optional properties of Config, but I haven't managed to express that combine: {[P in keyof Config]?: (first: Config[P], second: Config[P]) => Config[P]} = {} ): Config { let result: any = {} for (let config of configs) for (let key of Object.keys(config) as (keyof Config)[]) { let value = config[key], current = result[key] if (current === undefined) result[key] = value else if (current === value || value === undefined) {} // No conflict else if (Object.hasOwnProperty.call(combine, key)) result[key] = combine[key]!(current as any, value as any) else throw new Error("Config merge conflict for field " + (key as string)) } for (let key in defaults) if (result[key] === undefined) result[key] = defaults[key] return result } state-6.2.0/src/extension.ts000066400000000000000000000024421435227466100160260ustar00rootroot00000000000000import {EditorState} from "./state" import {Transaction, TransactionSpec} from "./transaction" import {Facet} from "./facet" export const languageData = Facet.define<(state: EditorState, pos: number, side: -1 | 0 | 1) => readonly {[name: string]: any}[]>() /// Subtype of [`Command`](#view.Command) that doesn't require access /// to the actual editor view. Mostly useful to define commands that /// can be run and tested outside of a browser environment. export type StateCommand = (target: {state: EditorState, dispatch: (transaction: Transaction) => void}) => boolean export const allowMultipleSelections = Facet.define({ combine: values => values.some(v => v), static: true }) export const lineSeparator = Facet.define({ combine: values => values.length ? values[0] : undefined, static: true }) export const changeFilter = Facet.define<(tr: Transaction) => boolean | readonly number[]>() export const transactionFilter = Facet.define<(tr: Transaction) => TransactionSpec | readonly TransactionSpec[]>() export const transactionExtender = Facet.define<(tr: Transaction) => Pick | null>() export const readOnly = Facet.define({ combine: values => values.length ? values[0] : false }) state-6.2.0/src/facet.ts000066400000000000000000000524221435227466100150770ustar00rootroot00000000000000import {Transaction, StateEffect, StateEffectType} from "./transaction" import {EditorState} from "./state" let nextID = 0 type FacetConfig = { /// How to combine the input values into a single output value. When /// not given, the array of input values becomes the output. This /// function will immediately be called on creating the facet, with /// an empty array, to compute the facet's default value when no /// inputs are present. combine?: (value: readonly Input[]) => Output, /// How to compare output values to determine whether the value of /// the facet changed. Defaults to comparing by `===` or, if no /// `combine` function was given, comparing each element of the /// array with `===`. compare?: (a: Output, b: Output) => boolean, /// How to compare input values to avoid recomputing the output /// value when no inputs changed. Defaults to comparing with `===`. compareInput?: (a: Input, b: Input) => boolean, /// Forbids dynamic inputs to this facet. static?: boolean, /// If given, these extension(s) (or the result of calling the given /// function with the facet) will be added to any state where this /// facet is provided. (Note that, while a facet's default value can /// be read from a state even if the facet wasn't present in the /// state at all, these extensions won't be added in that /// situation.) enables?: Extension | ((self: Facet) => Extension) } /// A facet is a labeled value that is associated with an editor /// state. It takes inputs from any number of extensions, and combines /// those into a single output value. /// /// Examples of uses of facets are the [tab /// size](#state.EditorState^tabSize), [editor /// attributes](#view.EditorView^editorAttributes), and [update /// listeners](#view.EditorView^updateListener). export class Facet { /// @internal readonly id = nextID++ /// @internal readonly default: Output /// @internal readonly extensions: Extension | undefined private constructor( /// @internal readonly combine: (values: readonly Input[]) => Output, /// @internal readonly compareInput: (a: Input, b: Input) => boolean, /// @internal readonly compare: (a: Output, b: Output) => boolean, private isStatic: boolean, enables: Extension | undefined | ((self: Facet) => Extension) ) { this.default = combine([]) this.extensions = typeof enables == "function" ? enables(this) : enables } /// Define a new facet. static define(config: FacetConfig = {}) { return new Facet(config.combine || ((a: any) => a) as any, config.compareInput || ((a, b) => a === b), config.compare || (!config.combine ? sameArray as any : (a, b) => a === b), !!config.static, config.enables) } /// Returns an extension that adds the given value to this facet. of(value: Input): Extension { return new FacetProvider([], this, Provider.Static, value) } /// Create an extension that computes a value for the facet from a /// state. You must take care to declare the parts of the state that /// this value depends on, since your function is only called again /// for a new state when one of those parts changed. /// /// In cases where your value depends only on a single field, you'll /// want to use the [`from`](#state.Facet.from) method instead. compute(deps: readonly Slot[], get: (state: EditorState) => Input): Extension { if (this.isStatic) throw new Error("Can't compute a static facet") return new FacetProvider(deps, this, Provider.Single, get) } /// Create an extension that computes zero or more values for this /// facet from a state. computeN(deps: readonly Slot[], get: (state: EditorState) => readonly Input[]): Extension { if (this.isStatic) throw new Error("Can't compute a static facet") return new FacetProvider(deps, this, Provider.Multi, get) } /// Shorthand method for registering a facet source with a state /// field as input. If the field's type corresponds to this facet's /// input type, the getter function can be omitted. If given, it /// will be used to retrieve the input from the field value. from(field: StateField): Extension from(field: StateField, get: (value: T) => Input): Extension from(field: StateField, get?: (value: T) => Input): Extension { if (!get) get = x => x as any return this.compute([field], state => get!(state.field(field))) } } function sameArray(a: readonly T[], b: readonly T[]) { return a == b || a.length == b.length && a.every((e, i) => e === b[i]) } type Slot = Facet | StateField | "doc" | "selection" const enum Provider { Static, Single, Multi } class FacetProvider { readonly id = nextID++ extension!: Extension // Kludge to convince the type system these count as extensions constructor(readonly dependencies: readonly Slot[], readonly facet: Facet, readonly type: Provider, readonly value: ((state: EditorState) => Input) | ((state: EditorState) => readonly Input[]) | Input) {} dynamicSlot(addresses: {[id: number]: number}): DynamicSlot { let getter: (state: EditorState) => any = this.value as any let compare = this.facet.compareInput let id = this.id, idx = addresses[id] >> 1, multi = this.type == Provider.Multi let depDoc = false, depSel = false, depAddrs: number[] = [] for (let dep of this.dependencies) { if (dep == "doc") depDoc = true else if (dep == "selection") depSel = true else if (((addresses[dep.id] ?? 1) & 1) == 0) depAddrs.push(addresses[dep.id]) } return { create(state) { state.values[idx] = getter(state) return SlotStatus.Changed }, update(state, tr) { if ((depDoc && tr.docChanged) || (depSel && (tr.docChanged || tr.selection)) || ensureAll(state, depAddrs)) { let newVal = getter(state) if (multi ? !compareArray(newVal, state.values[idx], compare) : !compare(newVal, state.values[idx])) { state.values[idx] = newVal return SlotStatus.Changed } } return 0 }, reconfigure: (state, oldState) => { let newVal, oldAddr = oldState.config.address[id] if (oldAddr != null) { let oldVal = getAddr(oldState, oldAddr) if (this.dependencies.every(dep => { return dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) : dep instanceof StateField ? oldState.field(dep, false) == state.field(dep, false) : true }) || (multi ? compareArray(newVal = getter(state), oldVal, compare) : compare(newVal = getter(state), oldVal))) { state.values[idx] = oldVal return 0 } } else { newVal = getter(state) } state.values[idx] = newVal return SlotStatus.Changed } } } } function compareArray(a: readonly T[], b: readonly T[], compare: (a: T, b: T) => boolean) { if (a.length != b.length) return false for (let i = 0; i < a.length; i++) if (!compare(a[i], b[i])) return false return true } function ensureAll(state: EditorState, addrs: readonly number[]) { let changed = false for (let addr of addrs) if (ensureAddr(state, addr) & SlotStatus.Changed) changed = true return changed } function dynamicFacetSlot( addresses: {[id: number]: number}, facet: Facet, providers: readonly FacetProvider[] ): DynamicSlot { let providerAddrs = providers.map(p => addresses[p.id]) let providerTypes = providers.map(p => p.type) let dynamic = providerAddrs.filter(p => !(p & 1)) let idx = addresses[facet.id] >> 1 function get(state: EditorState) { let values: Input[] = [] for (let i = 0; i < providerAddrs.length; i++) { let value = getAddr(state, providerAddrs[i]) if (providerTypes[i] == Provider.Multi) for (let val of value) values.push(val) else values.push(value) } return facet.combine(values) } return { create(state) { for (let addr of providerAddrs) ensureAddr(state, addr) state.values[idx] = get(state) return SlotStatus.Changed }, update(state, tr) { if (!ensureAll(state, dynamic)) return 0 let value = get(state) if (facet.compare(value, state.values[idx])) return 0 state.values[idx] = value return SlotStatus.Changed }, reconfigure(state, oldState) { let depChanged = ensureAll(state, providerAddrs) let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet) if (oldProviders && !depChanged && sameArray(providers, oldProviders)) { state.values[idx] = oldValue return 0 } let value = get(state) if (facet.compare(value, oldValue)) { state.values[idx] = oldValue return 0 } state.values[idx] = value return SlotStatus.Changed } } } type StateFieldSpec = { /// Creates the initial value for the field when a state is created. create: (state: EditorState) => Value, /// Compute a new value from the field's previous value and a /// [transaction](#state.Transaction). update: (value: Value, transaction: Transaction) => Value, /// Compare two values of the field, returning `true` when they are /// the same. This is used to avoid recomputing facets that depend /// on the field when its value did not change. Defaults to using /// `===`. compare?: (a: Value, b: Value) => boolean, /// Provide extensions based on this field. The given function will /// be called once with the initialized field. It will usually want /// to call some facet's [`from`](#state.Facet.from) method to /// create facet inputs from this field, but can also return other /// extensions that should be enabled when the field is present in a /// configuration. provide?: (field: StateField) => Extension /// A function used to serialize this field's content to JSON. Only /// necessary when this field is included in the argument to /// [`EditorState.toJSON`](#state.EditorState.toJSON). toJSON?: (value: Value, state: EditorState) => any /// A function that deserializes the JSON representation of this /// field's content. fromJSON?: (json: any, state: EditorState) => Value } const initField = Facet.define<{field: StateField, create: (state: EditorState) => unknown}>({static: true}) /// Fields can store additional information in an editor state, and /// keep it in sync with the rest of the state. export class StateField { /// @internal public provides: Extension | undefined = undefined private constructor( /// @internal readonly id: number, private createF: (state: EditorState) => Value, private updateF: (value: Value, tr: Transaction) => Value, private compareF: (a: Value, b: Value) => boolean, /// @internal readonly spec: StateFieldSpec ) {} /// Define a state field. static define(config: StateFieldSpec): StateField { let field = new StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config) if (config.provide) field.provides = config.provide(field) return field } private create(state: EditorState) { let init = state.facet(initField).find(i => i.field == this) return (init?.create || this.createF)(state) } /// @internal slot(addresses: {[id: number]: number}): DynamicSlot { let idx = addresses[this.id] >> 1 return { create: (state) => { state.values[idx] = this.create(state) return SlotStatus.Changed }, update: (state, tr) => { let oldVal = state.values[idx] let value = this.updateF(oldVal, tr) if (this.compareF(oldVal, value)) return 0 state.values[idx] = value return SlotStatus.Changed }, reconfigure: (state, oldState) => { if (oldState.config.address[this.id] != null) { state.values[idx] = oldState.field(this) return 0 } state.values[idx] = this.create(state) return SlotStatus.Changed } } } /// Returns an extension that enables this field and overrides the /// way it is initialized. Can be useful when you need to provide a /// non-default starting value for the field. init(create: (state: EditorState) => Value): Extension { return [this, initField.of({field: this as any, create})] } /// State field instances can be used as /// [`Extension`](#state.Extension) values to enable the field in a /// given state. get extension(): Extension { return this } } /// Extension values can be /// [provided](#state.EditorStateConfig.extensions) when creating a /// state to attach various kinds of configuration and behavior /// information. They can either be built-in extension-providing /// objects, such as [state fields](#state.StateField) or [facet /// providers](#state.Facet.of), or objects with an extension in its /// `extension` property. Extensions can be nested in arrays /// arbitrarily deep—they will be flattened when processed. export type Extension = {extension: Extension} | readonly Extension[] const Prec_ = {lowest: 4, low: 3, default: 2, high: 1, highest: 0} function prec(value: number) { return (ext: Extension) => new PrecExtension(ext, value) as Extension } /// By default extensions are registered in the order they are found /// in the flattened form of nested array that was provided. /// Individual extension values can be assigned a precedence to /// override this. Extensions that do not have a precedence set get /// the precedence of the nearest parent with a precedence, or /// [`default`](#state.Prec.default) if there is no such parent. The /// final ordering of extensions is determined by first sorting by /// precedence and then by order within each precedence. export const Prec = { /// The highest precedence level, for extensions that should end up /// near the start of the precedence ordering. highest: prec(Prec_.highest), /// A higher-than-default precedence, for extensions that should /// come before those with default precedence. high: prec(Prec_.high), /// The default precedence, which is also used for extensions /// without an explicit precedence. default: prec(Prec_.default), /// A lower-than-default precedence. low: prec(Prec_.low), /// The lowest precedence level. Meant for things that should end up /// near the end of the extension order. lowest: prec(Prec_.lowest) } class PrecExtension { constructor(readonly inner: Extension, readonly prec: number) {} extension!: Extension } /// Extension compartments can be used to make a configuration /// dynamic. By [wrapping](#state.Compartment.of) part of your /// configuration in a compartment, you can later /// [replace](#state.Compartment.reconfigure) that part through a /// transaction. export class Compartment { /// Create an instance of this compartment to add to your [state /// configuration](#state.EditorStateConfig.extensions). of(ext: Extension): Extension { return new CompartmentInstance(this, ext) } /// Create an [effect](#state.TransactionSpec.effects) that /// reconfigures this compartment. reconfigure(content: Extension): StateEffect { return Compartment.reconfigure.of({compartment: this, extension: content}) } /// Get the current content of the compartment in the state, or /// `undefined` if it isn't present. get(state: EditorState): Extension | undefined { return state.config.compartments.get(this) } /// This is initialized in state.ts to avoid a cyclic dependency /// @internal static reconfigure: StateEffectType<{compartment: Compartment, extension: Extension}> } export class CompartmentInstance { constructor(readonly compartment: Compartment, readonly inner: Extension) {} extension!: Extension } export interface DynamicSlot { create(state: EditorState): SlotStatus update(state: EditorState, tr: Transaction): SlotStatus reconfigure(state: EditorState, oldState: EditorState): SlotStatus } export class Configuration { readonly statusTemplate: SlotStatus[] = [] constructor(readonly base: Extension, readonly compartments: Map, readonly dynamicSlots: DynamicSlot[], readonly address: {[id: number]: number}, readonly staticValues: readonly any[], readonly facets: {[id: number]: readonly FacetProvider[]}) { while (this.statusTemplate.length < dynamicSlots.length) this.statusTemplate.push(SlotStatus.Unresolved) } staticFacet(facet: Facet) { let addr = this.address[facet.id] return addr == null ? facet.default : this.staticValues[addr >> 1] } static resolve(base: Extension, compartments: Map, oldState?: EditorState) { let fields: StateField[] = [] let facets: {[id: number]: FacetProvider[]} = Object.create(null) let newCompartments = new Map() for (let ext of flatten(base, compartments, newCompartments)) { if (ext instanceof StateField) fields.push(ext) else (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext) } let address: {[id: number]: number} = Object.create(null) let staticValues: any[] = [] let dynamicSlots: ((address: {[id: number]: number}) => DynamicSlot)[] = [] for (let field of fields) { address[field.id] = dynamicSlots.length << 1 dynamicSlots.push(a => field.slot(a)) } let oldFacets = oldState?.config.facets for (let id in facets) { let providers = facets[id], facet = providers[0].facet let oldProviders = oldFacets && oldFacets[id] || [] if (providers.every(p => p.type == Provider.Static)) { address[facet.id] = (staticValues.length << 1) | 1 if (sameArray(oldProviders, providers)) { staticValues.push(oldState!.facet(facet)) } else { let value = facet.combine(providers.map(p => p.value)) staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value) } } else { for (let p of providers) { if (p.type == Provider.Static) { address[p.id] = (staticValues.length << 1) | 1 staticValues.push(p.value) } else { address[p.id] = dynamicSlots.length << 1 dynamicSlots.push(a => p.dynamicSlot(a)) } } address[facet.id] = dynamicSlots.length << 1 dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers)) } } let dynamic = dynamicSlots.map(f => f(address)) return new Configuration(base, newCompartments, dynamic, address, staticValues, facets) } } function flatten(extension: Extension, compartments: Map, newCompartments: Map) { let result: (FacetProvider | StateField)[][] = [[], [], [], [], []] let seen = new Map() function inner(ext: Extension, prec: number) { let known = seen.get(ext) if (known != null) { if (known <= prec) return let found = result[known].indexOf(ext as any) if (found > -1) result[known].splice(found, 1) if (ext instanceof CompartmentInstance) newCompartments.delete(ext.compartment) } seen.set(ext, prec) if (Array.isArray(ext)) { for (let e of ext) inner(e, prec) } else if (ext instanceof CompartmentInstance) { if (newCompartments.has(ext.compartment)) throw new RangeError(`Duplicate use of compartment in extensions`) let content = compartments.get(ext.compartment) || ext.inner newCompartments.set(ext.compartment, content) inner(content, prec) } else if (ext instanceof PrecExtension) { inner(ext.inner, ext.prec) } else if (ext instanceof StateField) { result[prec].push(ext) if (ext.provides) inner(ext.provides, prec) } else if (ext instanceof FacetProvider) { result[prec].push(ext) if (ext.facet.extensions) inner(ext.facet.extensions, Prec_.default) } else { let content = (ext as any).extension if (!content) throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`) inner(content, prec) } } inner(extension, Prec_.default) return result.reduce((a, b) => a.concat(b)) } export const enum SlotStatus { Unresolved = 0, Changed = 1, Computed = 2, Computing = 4 } export function ensureAddr(state: EditorState, addr: number) { if (addr & 1) return SlotStatus.Computed let idx = addr >> 1 let status = state.status[idx] if (status == SlotStatus.Computing) throw new Error("Cyclic dependency between fields and/or facets") if (status & SlotStatus.Computed) return status state.status[idx] = SlotStatus.Computing let changed = state.computeSlot!(state, state.config.dynamicSlots[idx]) return state.status[idx] = SlotStatus.Computed | changed } export function getAddr(state: EditorState, addr: number) { return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1] } state-6.2.0/src/index.ts000066400000000000000000000014301435227466100151150ustar00rootroot00000000000000export {EditorStateConfig, EditorState} from "./state" export {StateCommand} from "./extension" export {Facet, StateField, Extension, Prec, Compartment} from "./facet" export {EditorSelection, SelectionRange} from "./selection" export {Transaction, TransactionSpec, Annotation, AnnotationType, StateEffect, StateEffectType} from "./transaction" export {combineConfig} from "./config" export {ChangeSpec, ChangeSet, ChangeDesc, MapMode} from "./change" export {CharCategory} from "./charcategory" export {RangeValue, Range, RangeSet, RangeCursor, RangeSetBuilder, RangeComparator, SpanIterator} from "./rangeset" export {findClusterBreak, codePointAt, fromCodePoint, codePointSize} from "./char" export {countColumn, findColumn} from "./column" export {Line, TextIterator, Text} from "./text" state-6.2.0/src/rangeset.ts000066400000000000000000000767231435227466100156370ustar00rootroot00000000000000import {ChangeDesc, MapMode} from "./change" /// Each range is associated with a value, which must inherit from /// this class. export abstract class RangeValue { /// Compare this value with another value. Used when comparing /// rangesets. The default implementation compares by identity. /// Unless you are only creating a fixed number of unique instances /// of your value type, it is a good idea to implement this /// properly. eq(other: RangeValue) { return this == other } /// The bias value at the start of the range. Determines how the /// range is positioned relative to other ranges starting at this /// position. Defaults to 0. startSide!: number /// The bias value at the end of the range. Defaults to 0. endSide!: number /// The mode with which the location of the range should be mapped /// when its `from` and `to` are the same, to decide whether a /// change deletes the range. Defaults to `MapMode.TrackDel`. mapMode!: MapMode /// Determines whether this value marks a point range. Regular /// ranges affect the part of the document they cover, and are /// meaningless when empty. Point ranges have a meaning on their /// own. When non-empty, a point range is treated as atomic and /// shadows any ranges contained in it. point!: boolean /// Create a [range](#state.Range) with this value. range(from: number, to = from) { return Range.create(from, to, this) } } RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0 RangeValue.prototype.point = false RangeValue.prototype.mapMode = MapMode.TrackDel /// A range associates a value with a range of positions. export class Range { private constructor( /// The range's start position. readonly from: number, /// Its end position. readonly to: number, /// The value associated with this range. readonly value: T) {} /// @internal static create(from: number, to: number, value: T) { return new Range(from, to, value) } } function cmpRange(a: Range, b: Range) { return a.from - b.from || a.value.startSide - b.value.startSide } /// Collection of methods used when comparing range sets. export interface RangeComparator { /// Notifies the comparator that a range (in positions in the new /// document) has the given sets of values associated with it, which /// are different in the old (A) and new (B) sets. compareRange(from: number, to: number, activeA: T[], activeB: T[]): void /// Notification for a changed (or inserted, or deleted) point range. comparePoint(from: number, to: number, pointA: T | null, pointB: T | null): void } /// Methods used when iterating over the spans created by a set of /// ranges. The entire iterated range will be covered with either /// `span` or `point` calls. export interface SpanIterator { /// Called for any ranges not covered by point decorations. `active` /// holds the values that the range is marked with (and may be /// empty). `openStart` indicates how many of those ranges are open /// (continued) at the start of the span. span(from: number, to: number, active: readonly T[], openStart: number): void /// Called when going over a point decoration. The active range /// decorations that cover the point and have a higher precedence /// are provided in `active`. The open count in `openStart` counts /// the number of those ranges that started before the point and. If /// the point started before the iterated range, `openStart` will be /// `active.length + 1` to signal this. point(from: number, to: number, value: T, active: readonly T[], openStart: number, index: number): void } const enum C { // The maximum amount of ranges to store in a single chunk ChunkSize = 250, // A large (fixnum) value to use for max/min values. Far = 1e9 } class Chunk { constructor(readonly from: readonly number[], readonly to: readonly number[], readonly value: readonly T[], // Chunks are marked with the largest point that occurs // in them (or -1 for no points), so that scans that are // only interested in points (such as the // heightmap-related logic) can skip range-only chunks. readonly maxPoint: number) {} get length() { return this.to[this.to.length - 1] } // Find the index of the given position and side. Use the ranges' // `from` pos when `end == false`, `to` when `end == true`. findIndex(pos: number, side: number, end: boolean, startAt = 0) { let arr = end ? this.to : this.from for (let lo = startAt, hi = arr.length;;) { if (lo == hi) return lo let mid = (lo + hi) >> 1 let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side if (mid == lo) return diff >= 0 ? lo : hi if (diff >= 0) hi = mid else lo = mid + 1 } } between(offset: number, from: number, to: number, f: (from: number, to: number, value: T) => void | false): void | false { for (let i = this.findIndex(from, -C.Far, true), e = this.findIndex(to, C.Far, false, i); i < e; i++) if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false) return false } map(offset: number, changes: ChangeDesc) { let value: T[] = [], from = [], to = [], newPos = -1, maxPoint = -1 for (let i = 0; i < this.value.length; i++) { let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo if (curFrom == curTo) { let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode) if (mapped == null) continue newFrom = newTo = mapped if (val.startSide != val.endSide) { newTo = changes.mapPos(curFrom, val.endSide) if (newTo < newFrom) continue } } else { newFrom = changes.mapPos(curFrom, val.startSide) newTo = changes.mapPos(curTo, val.endSide) if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0) continue } if ((newTo - newFrom || val.endSide - val.startSide) < 0) continue if (newPos < 0) newPos = newFrom if (val.point) maxPoint = Math.max(maxPoint, newTo - newFrom) value.push(val) from.push(newFrom - newPos) to.push(newTo - newPos) } return {mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos} } } /// A range cursor is an object that moves to the next range every /// time you call `next` on it. Note that, unlike ES6 iterators, these /// start out pointing at the first element, so you should call `next` /// only after reading the first range (if any). export interface RangeCursor { /// Move the iterator forward. next: () => void /// The next range's value. Holds `null` when the cursor has reached /// its end. value: T | null /// The next range's start position. from: number /// The next end position. to: number } type RangeSetUpdate = { /// An array of ranges to add. If given, this should be sorted by /// `from` position and `startSide` unless /// [`sort`](#state.RangeSet.update^updateSpec.sort) is given as /// `true`. add?: readonly Range[] /// Indicates whether the library should sort the ranges in `add`. /// Defaults to `false`. sort?: boolean /// Filter the ranges already in the set. Only those for which this /// function returns `true` are kept. filter?: (from: number, to: number, value: T) => boolean, /// Can be used to limit the range on which the filter is /// applied. Filtering only a small range, as opposed to the entire /// set, can make updates cheaper. filterFrom?: number /// The end position to apply the filter to. filterTo?: number } /// A range set stores a collection of [ranges](#state.Range) in a /// way that makes them efficient to [map](#state.RangeSet.map) and /// [update](#state.RangeSet.update). This is an immutable data /// structure. export class RangeSet { private constructor( /// @internal readonly chunkPos: readonly number[], /// @internal readonly chunk: readonly Chunk[], /// @internal readonly nextLayer: RangeSet, /// @internal readonly maxPoint: number ) {} /// @internal static create( chunkPos: readonly number[], chunk: readonly Chunk[], nextLayer: RangeSet, maxPoint: number ) { return new RangeSet(chunkPos, chunk, nextLayer, maxPoint) } /// @internal get length(): number { let last = this.chunk.length - 1 return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length) } /// The number of ranges in the set. get size(): number { if (this.isEmpty) return 0 let size = this.nextLayer.size for (let chunk of this.chunk) size += chunk.value.length return size } /// @internal chunkEnd(index: number) { return this.chunkPos[index] + this.chunk[index].length } /// Update the range set, optionally adding new ranges or filtering /// out existing ones. /// /// (Note: The type parameter is just there as a kludge to work /// around TypeScript variance issues that prevented `RangeSet` /// from being a subtype of `RangeSet` when `X` is a subtype of /// `Y`.) update(updateSpec: RangeSetUpdate): RangeSet { let {add = [], sort = false, filterFrom = 0, filterTo = this.length} = updateSpec let filter = updateSpec.filter as undefined | ((from: number, to: number, value: T) => boolean) if (add.length == 0 && !filter) return this if (sort) add = add.slice().sort(cmpRange) if (this.isEmpty) return add.length ? RangeSet.of(add) : this let cur = new LayerCursor(this, null, -1).goto(0), i = 0, spill: Range[] = [] let builder = new RangeSetBuilder() while (cur.value || i < add.length) { if (i < add.length && (cur.from - add[i].from || cur.startSide - add[i].value.startSide) >= 0) { let range = add[i++] if (!builder.addInner(range.from, range.to, range.value)) spill.push(range) } else if (cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length && (i == add.length || this.chunkEnd(cur.chunkIndex) < add[i].from) && (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) && builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex])) { cur.nextChunk() } else { if (!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value!)) { if (!builder.addInner(cur.from, cur.to, cur.value!)) spill.push(Range.create(cur.from, cur.to, cur.value!)) } cur.next() } } return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty : this.nextLayer.update({add: spill, filter, filterFrom, filterTo})) } /// Map this range set through a set of changes, return the new set. map(changes: ChangeDesc): RangeSet { if (changes.empty || this.isEmpty) return this let chunks = [], chunkPos = [], maxPoint = -1 for (let i = 0; i < this.chunk.length; i++) { let start = this.chunkPos[i], chunk = this.chunk[i] let touch = changes.touchesRange(start, start + chunk.length) if (touch === false) { maxPoint = Math.max(maxPoint, chunk.maxPoint) chunks.push(chunk) chunkPos.push(changes.mapPos(start)) } else if (touch === true) { let {mapped, pos} = chunk.map(start, changes) if (mapped) { maxPoint = Math.max(maxPoint, mapped.maxPoint) chunks.push(mapped) chunkPos.push(pos) } } } let next = this.nextLayer.map(changes) return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next || RangeSet.empty, maxPoint) } /// Iterate over the ranges that touch the region `from` to `to`, /// calling `f` for each. There is no guarantee that the ranges will /// be reported in any specific order. When the callback returns /// `false`, iteration stops. between(from: number, to: number, f: (from: number, to: number, value: T) => void | false): void { if (this.isEmpty) return for (let i = 0; i < this.chunk.length; i++) { let start = this.chunkPos[i], chunk = this.chunk[i] if (to >= start && from <= start + chunk.length && chunk.between(start, from - start, to - start, f) === false) return } this.nextLayer.between(from, to, f) } /// Iterate over the ranges in this set, in order, including all /// ranges that end at or after `from`. iter(from: number = 0): RangeCursor { return HeapCursor.from([this]).goto(from) } /// @internal get isEmpty() { return this.nextLayer == this } /// Iterate over the ranges in a collection of sets, in order, /// starting from `from`. static iter(sets: readonly RangeSet[], from: number = 0): RangeCursor { return HeapCursor.from(sets).goto(from) } /// Iterate over two groups of sets, calling methods on `comparator` /// to notify it of possible differences. static compare( oldSets: readonly RangeSet[], newSets: readonly RangeSet[], /// This indicates how the underlying data changed between these /// ranges, and is needed to synchronize the iteration. `from` and /// `to` are coordinates in the _new_ space, after these changes. textDiff: ChangeDesc, comparator: RangeComparator, /// Can be used to ignore all non-point ranges, and points below /// the given size. When -1, all ranges are compared. minPointSize: number = -1 ) { let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize!) let b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize!) let sharedChunks = findSharedChunks(a, b, textDiff) let sideA = new SpanCursor(a, sharedChunks, minPointSize!) let sideB = new SpanCursor(b, sharedChunks, minPointSize!) textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator)) if (textDiff.empty && textDiff.length == 0) compare(sideA, 0, sideB, 0, 0, comparator) } /// Compare the contents of two groups of range sets, returning true /// if they are equivalent in the given range. static eq( oldSets: readonly RangeSet[], newSets: readonly RangeSet[], from = 0, to?: number ) { if (to == null) to = C.Far - 1 let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0) let b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0) if (a.length != b.length) return false if (!a.length) return true let sharedChunks = findSharedChunks(a, b) let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from) for (;;) { if (sideA.to != sideB.to || !sameValues(sideA.active, sideB.active) || sideA.point && (!sideB.point || !sideA.point.eq(sideB.point))) return false if (sideA.to > to) return true sideA.next(); sideB.next() } } /// Iterate over a group of range sets at the same time, notifying /// the iterator about the ranges covering every given piece of /// content. Returns the open count (see /// [`SpanIterator.span`](#state.SpanIterator.span)) at the end /// of the iteration. static spans( sets: readonly RangeSet[], from: number, to: number, iterator: SpanIterator, /// When given and greater than -1, only points of at least this /// size are taken into account. minPointSize: number = -1 ): number { let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from let openRanges = cursor.openStart for (;;) { let curTo = Math.min(cursor.to, to) if (cursor.point) { let active = cursor.activeForPoint(cursor.to) let openCount = cursor.pointFrom < from ? active.length + 1 : Math.min(active.length, openRanges) iterator.point(pos, curTo, cursor.point, active, openCount, cursor.pointRank) openRanges = Math.min(cursor.openEnd(curTo), active.length) } else if (curTo > pos) { iterator.span(pos, curTo, cursor.active, openRanges) openRanges = cursor.openEnd(curTo) } if (cursor.to > to) return openRanges + (cursor.point && cursor.to > to ? 1 : 0) pos = cursor.to cursor.next() } } /// Create a range set for the given range or array of ranges. By /// default, this expects the ranges to be _sorted_ (by start /// position and, if two start at the same position, /// `value.startSide`). You can pass `true` as second argument to /// cause the method to sort them. static of(ranges: readonly Range[] | Range, sort = false): RangeSet { let build = new RangeSetBuilder() for (let range of ranges instanceof Range ? [ranges] : sort ? lazySort(ranges) : ranges) build.add(range.from, range.to, range.value) return build.finish() } /// The empty set of ranges. static empty = new RangeSet([], [], null as any, -1) } function lazySort(ranges: readonly Range[]): readonly Range[] { if (ranges.length > 1) for (let prev = ranges[0], i = 1; i < ranges.length; i++) { let cur = ranges[i] if (cmpRange(prev, cur) > 0) return ranges.slice().sort(cmpRange) prev = cur } return ranges } // Awkward patch-up to create a cyclic structure. ;(RangeSet.empty as any).nextLayer = RangeSet.empty /// A range set builder is a data structure that helps build up a /// [range set](#state.RangeSet) directly, without first allocating /// an array of [`Range`](#state.Range) objects. export class RangeSetBuilder { private chunks: Chunk[] = [] private chunkPos: number[] = [] private chunkStart = -1 private last: T | null = null private lastFrom = -C.Far private lastTo = -C.Far private from: number[] = [] private to: number[] = [] private value: T[] = [] private maxPoint = -1 private setMaxPoint = -1 private nextLayer: RangeSetBuilder | null = null private finishChunk(newArrays: boolean) { this.chunks.push(new Chunk(this.from, this.to, this.value, this.maxPoint)) this.chunkPos.push(this.chunkStart) this.chunkStart = -1 this.setMaxPoint = Math.max(this.setMaxPoint, this.maxPoint) this.maxPoint = -1 if (newArrays) { this.from = []; this.to = []; this.value = [] } } /// Create an empty builder. constructor() {} /// Add a range. Ranges should be added in sorted (by `from` and /// `value.startSide`) order. add(from: number, to: number, value: T) { if (!this.addInner(from, to, value)) (this.nextLayer || (this.nextLayer = new RangeSetBuilder)).add(from, to, value) } /// @internal addInner(from: number, to: number, value: T) { let diff = from - this.lastTo || value.startSide - this.last!.endSide if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last!.startSide) < 0) throw new Error("Ranges must be added sorted by `from` position and `startSide`") if (diff < 0) return false if (this.from.length == C.ChunkSize) this.finishChunk(true) if (this.chunkStart < 0) this.chunkStart = from this.from.push(from - this.chunkStart) this.to.push(to - this.chunkStart) this.last = value this.lastFrom = from this.lastTo = to this.value.push(value) if (value.point) this.maxPoint = Math.max(this.maxPoint, to - from) return true } /// @internal addChunk(from: number, chunk: Chunk) { if ((from - this.lastTo || chunk.value[0].startSide - this.last!.endSide) < 0) return false if (this.from.length) this.finishChunk(true) this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint) this.chunks.push(chunk) this.chunkPos.push(from) let last = chunk.value.length - 1 this.last = chunk.value[last] this.lastFrom = chunk.from[last] + from this.lastTo = chunk.to[last] + from return true } /// Finish the range set. Returns the new set. The builder can't be /// used anymore after this has been called. finish() { return this.finishInner(RangeSet.empty) } /// @internal finishInner(next: RangeSet): RangeSet { if (this.from.length) this.finishChunk(false) if (this.chunks.length == 0) return next let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint) this.from = null as any // Make sure further `add` calls produce errors return result } } function findSharedChunks(a: readonly RangeSet[], b: readonly RangeSet[], textDiff?: ChangeDesc) { let inA = new Map, number>() for (let set of a) for (let i = 0; i < set.chunk.length; i++) if (set.chunk[i].maxPoint <= 0) inA.set(set.chunk[i], set.chunkPos[i]) let shared = new Set>() for (let set of b) for (let i = 0; i < set.chunk.length; i++) { let known = inA.get(set.chunk[i]) if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i] && !textDiff?.touchesRange(known, known + set.chunk[i].length)) shared.add(set.chunk[i]) } return shared } class LayerCursor { from!: number to!: number value!: T | null chunkIndex!: number rangeIndex!: number constructor(readonly layer: RangeSet, readonly skip: Set> | null, readonly minPoint: number, readonly rank = 0) {} get startSide() { return this.value ? this.value.startSide : 0 } get endSide() { return this.value ? this.value.endSide : 0 } goto(pos: number, side: number = -C.Far) { this.chunkIndex = this.rangeIndex = 0 this.gotoInner(pos, side, false) return this } gotoInner(pos: number, side: number, forward: boolean) { while (this.chunkIndex < this.layer.chunk.length) { let next = this.layer.chunk[this.chunkIndex] if (!(this.skip && this.skip.has(next) || this.layer.chunkEnd(this.chunkIndex) < pos || next.maxPoint < this.minPoint)) break this.chunkIndex++ forward = false } if (this.chunkIndex < this.layer.chunk.length) { let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true) if (!forward || this.rangeIndex < rangeIndex) this.setRangeIndex(rangeIndex) } this.next() } forward(pos: number, side: number) { if ((this.to - pos || this.endSide - side) < 0) this.gotoInner(pos, side, true) } next() { for (;;) { if (this.chunkIndex == this.layer.chunk.length) { this.from = this.to = C.Far this.value = null break } else { let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex] let from = chunkPos + chunk.from[this.rangeIndex] this.from = from this.to = chunkPos + chunk.to[this.rangeIndex] this.value = chunk.value[this.rangeIndex] this.setRangeIndex(this.rangeIndex + 1) if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint) break } } } setRangeIndex(index: number) { if (index == this.layer.chunk[this.chunkIndex].value.length) { this.chunkIndex++ if (this.skip) { while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex])) this.chunkIndex++ } this.rangeIndex = 0 } else { this.rangeIndex = index } } nextChunk() { this.chunkIndex++ this.rangeIndex = 0 this.next() } compare(other: LayerCursor) { return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank || this.to - other.to || this.endSide - other.endSide } } class HeapCursor { from!: number to!: number value!: T | null rank!: number constructor(readonly heap: LayerCursor[]) {} static from( sets: readonly RangeSet[], skip: Set> | null = null, minPoint: number = -1 ): HeapCursor | LayerCursor { let heap = [] for (let i = 0; i < sets.length; i++) { for (let cur = sets[i]; !cur.isEmpty; cur = cur.nextLayer) { if (cur.maxPoint >= minPoint) heap.push(new LayerCursor(cur, skip, minPoint, i)) } } return heap.length == 1 ? heap[0] : new HeapCursor(heap) } get startSide() { return this.value ? this.value.startSide : 0 } goto(pos: number, side: number = -C.Far) { for (let cur of this.heap) cur.goto(pos, side) for (let i = this.heap.length >> 1; i >= 0; i--) heapBubble(this.heap, i) this.next() return this } forward(pos: number, side: number) { for (let cur of this.heap) cur.forward(pos, side) for (let i = this.heap.length >> 1; i >= 0; i--) heapBubble(this.heap, i) if ((this.to - pos || this.value!.endSide - side) < 0) this.next() } next() { if (this.heap.length == 0) { this.from = this.to = C.Far this.value = null this.rank = -1 } else { let top = this.heap[0] this.from = top.from this.to = top.to this.value = top.value this.rank = top.rank if (top.value) top.next() heapBubble(this.heap, 0) } } } function heapBubble(heap: LayerCursor[], index: number) { for (let cur = heap[index];;) { let childIndex = (index << 1) + 1 if (childIndex >= heap.length) break let child = heap[childIndex] if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) { child = heap[childIndex + 1] childIndex++ } if (cur.compare(child) < 0) break heap[childIndex] = cur heap[index] = child index = childIndex } } class SpanCursor { cursor: HeapCursor | LayerCursor active: T[] = [] activeTo: number[] = [] activeRank: number[] = [] minActive = -1 // A currently active point range, if any point: T | null = null pointFrom = 0 pointRank = 0 to = -C.Far endSide = 0 // The amount of open active ranges at the start of the iterator. // Not including points. openStart = -1 constructor(sets: readonly RangeSet[], skip: Set> | null, readonly minPoint: number) { this.cursor = HeapCursor.from(sets, skip, minPoint) } goto(pos: number, side: number = -C.Far) { this.cursor.goto(pos, side) this.active.length = this.activeTo.length = this.activeRank.length = 0 this.minActive = -1 this.to = pos this.endSide = side this.openStart = -1 this.next() return this } forward(pos: number, side: number) { while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0) this.removeActive(this.minActive) this.cursor.forward(pos, side) } removeActive(index: number) { remove(this.active, index) remove(this.activeTo, index) remove(this.activeRank, index) this.minActive = findMinIndex(this.active, this.activeTo) } addActive(trackOpen: number[] | null) { let i = 0, {value, to, rank} = this.cursor while (i < this.activeRank.length && this.activeRank[i] <= rank) i++ insert(this.active, i, value) insert(this.activeTo, i, to) insert(this.activeRank, i, rank) if (trackOpen) insert(trackOpen, i, this.cursor.from) this.minActive = findMinIndex(this.active, this.activeTo) } // After calling this, if `this.point` != null, the next range is a // point. Otherwise, it's a regular range, covered by `this.active`. next() { let from = this.to, wasPoint = this.point this.point = null let trackOpen = this.openStart < 0 ? [] : null for (;;) { let a = this.minActive if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) { if (this.activeTo[a] > from) { this.to = this.activeTo[a] this.endSide = this.active[a].endSide break } this.removeActive(a) if (trackOpen) remove(trackOpen, a) } else if (!this.cursor.value) { this.to = this.endSide = C.Far break } else if (this.cursor.from > from) { this.to = this.cursor.from this.endSide = this.cursor.startSide break } else { let nextVal = this.cursor.value if (!nextVal.point) { // Opening a range this.addActive(trackOpen) this.cursor.next() } else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) { // Ignore any non-empty points that end precisely at the end of the prev point this.cursor.next() } else { // New point this.point = nextVal this.pointFrom = this.cursor.from this.pointRank = this.cursor.rank this.to = this.cursor.to this.endSide = nextVal.endSide this.cursor.next() this.forward(this.to, this.endSide) break } } } if (trackOpen) { this.openStart = 0 for (let i = trackOpen.length - 1; i >= 0 && trackOpen[i] < from; i--) this.openStart++ } } activeForPoint(to: number) { if (!this.active.length) return this.active let active = [] for (let i = this.active.length - 1; i >= 0; i--) { if (this.activeRank[i] < this.pointRank) break if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide >= this.point!.endSide) active.push(this.active[i]) } return active.reverse() } openEnd(to: number) { let open = 0 for (let i = this.activeTo.length - 1; i >= 0 && this.activeTo[i] > to; i--) open++ return open } } function compare(a: SpanCursor, startA: number, b: SpanCursor, startB: number, length: number, comparator: RangeComparator) { a.goto(startA) b.goto(startB) let endB = startB + length let pos = startB, dPos = startB - startA for (;;) { let diff = (a.to + dPos) - b.to || a.endSide - b.endSide let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB) if (a.point || b.point) { if (!(a.point && b.point && (a.point == b.point || a.point.eq(b.point)) && sameValues(a.activeForPoint(a.to + dPos), b.activeForPoint(b.to)))) comparator.comparePoint(pos, clipEnd, a.point, b.point) } else { if (clipEnd > pos && !sameValues(a.active, b.active)) comparator.compareRange(pos, clipEnd, a.active, b.active) } if (end > endB) break pos = end if (diff <= 0) a.next() if (diff >= 0) b.next() } } function sameValues(a: T[], b: T[]) { if (a.length != b.length) return false for (let i = 0; i < a.length; i++) if (a[i] != b[i] && !a[i].eq(b[i])) return false return true } function remove(array: T[], index: number) { for (let i = index, e = array.length - 1; i < e; i++) array[i] = array[i + 1] array.pop() } function insert(array: T[], index: number, value: T) { for (let i = array.length - 1; i >= index; i--) array[i + 1] = array[i] array[index] = value } function findMinIndex(value: RangeValue[], array: number[]) { let found = -1, foundPos = C.Far for (let i = 0; i < array.length; i++) if ((array[i] - foundPos || value[i].endSide - value[found].endSide) < 0) { found = i foundPos = array[i] } return found } state-6.2.0/src/selection.ts000066400000000000000000000220261435227466100157770ustar00rootroot00000000000000import {ChangeDesc} from "./change" // A range's flags field is used like this: // - 2 bits for bidi level (3 means unset) (only meaningful for // cursors) // - 2 bits to indicate the side the cursor is associated with (only // for cursors) // - 1 bit to indicate whether the range is inverted (head before // anchor) (only meaningful for non-empty ranges) // - Any further bits hold the goal column (only for ranges // produced by vertical motion) const enum RangeFlag { BidiLevelMask = 3, AssocBefore = 4, AssocAfter = 8, Inverted = 16, GoalColumnOffset = 5, NoGoalColumn = 0x1ffffff } /// A single selection range. When /// [`allowMultipleSelections`](#state.EditorState^allowMultipleSelections) /// is enabled, a [selection](#state.EditorSelection) may hold /// multiple ranges. By default, selections hold exactly one range. export class SelectionRange { private constructor( /// The lower boundary of the range. readonly from: number, /// The upper boundary of the range. readonly to: number, private flags: number ) {} /// The anchor of the range—the side that doesn't move when you /// extend it. get anchor() { return this.flags & RangeFlag.Inverted ? this.to : this.from } /// The head of the range, which is moved when the range is /// [extended](#state.SelectionRange.extend). get head() { return this.flags & RangeFlag.Inverted ? this.from : this.to } /// True when `anchor` and `head` are at the same position. get empty(): boolean { return this.from == this.to } /// If this is a cursor that is explicitly associated with the /// character on one of its sides, this returns the side. -1 means /// the character before its position, 1 the character after, and 0 /// means no association. get assoc(): -1 | 0 | 1 { return this.flags & RangeFlag.AssocBefore ? -1 : this.flags & RangeFlag.AssocAfter ? 1 : 0 } /// The bidirectional text level associated with this cursor, if /// any. get bidiLevel(): number | null { let level = this.flags & RangeFlag.BidiLevelMask return level == 3 ? null : level } /// The goal column (stored vertical offset) associated with a /// cursor. This is used to preserve the vertical position when /// [moving](#view.EditorView.moveVertically) across /// lines of different length. get goalColumn() { let value = this.flags >> RangeFlag.GoalColumnOffset return value == RangeFlag.NoGoalColumn ? undefined : value } /// Map this range through a change, producing a valid range in the /// updated document. map(change: ChangeDesc, assoc = -1): SelectionRange { let from, to if (this.empty) { from = to = change.mapPos(this.from, assoc) } else { from = change.mapPos(this.from, 1) to = change.mapPos(this.to, -1) } return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags) } /// Extend this range to cover at least `from` to `to`. extend(from: number, to: number = from) { if (from <= this.anchor && to >= this.anchor) return EditorSelection.range(from, to) let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to return EditorSelection.range(this.anchor, head) } /// Compare this range to another range. eq(other: SelectionRange): boolean { return this.anchor == other.anchor && this.head == other.head } /// Return a JSON-serializable object representing the range. toJSON(): any { return {anchor: this.anchor, head: this.head} } /// Convert a JSON representation of a range to a `SelectionRange` /// instance. static fromJSON(json: any): SelectionRange { if (!json || typeof json.anchor != "number" || typeof json.head != "number") throw new RangeError("Invalid JSON representation for SelectionRange") return EditorSelection.range(json.anchor, json.head) } /// @internal static create(from: number, to: number, flags: number) { return new SelectionRange(from, to, flags) } } /// An editor selection holds one or more selection ranges. export class EditorSelection { private constructor( /// The ranges in the selection, sorted by position. Ranges cannot /// overlap (but they may touch, if they aren't empty). readonly ranges: readonly SelectionRange[], /// The index of the _main_ range in the selection (which is /// usually the range that was added last). readonly mainIndex: number ) {} /// Map a selection through a change. Used to adjust the selection /// position for changes. map(change: ChangeDesc, assoc = -1): EditorSelection { if (change.empty) return this return EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex) } /// Compare this selection to another selection. eq(other: EditorSelection): boolean { if (this.ranges.length != other.ranges.length || this.mainIndex != other.mainIndex) return false for (let i = 0; i < this.ranges.length; i++) if (!this.ranges[i].eq(other.ranges[i])) return false return true } /// Get the primary selection range. Usually, you should make sure /// your code applies to _all_ ranges, by using methods like /// [`changeByRange`](#state.EditorState.changeByRange). get main(): SelectionRange { return this.ranges[this.mainIndex] } /// Make sure the selection only has one range. Returns a selection /// holding only the main range from this selection. asSingle() { return this.ranges.length == 1 ? this : new EditorSelection([this.main], 0) } /// Extend this selection with an extra range. addRange(range: SelectionRange, main: boolean = true) { return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1) } /// Replace a given range with another range, and then normalize the /// selection to merge and sort ranges if necessary. replaceRange(range: SelectionRange, which: number = this.mainIndex) { let ranges = this.ranges.slice() ranges[which] = range return EditorSelection.create(ranges, this.mainIndex) } /// Convert this selection to an object that can be serialized to /// JSON. toJSON(): any { return {ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex} } /// Create a selection from a JSON representation. static fromJSON(json: any): EditorSelection { if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length) throw new RangeError("Invalid JSON representation for EditorSelection") return new EditorSelection(json.ranges.map((r: any) => SelectionRange.fromJSON(r)), json.main) } /// Create a selection holding a single range. static single(anchor: number, head: number = anchor) { return new EditorSelection([EditorSelection.range(anchor, head)], 0) } /// Sort and merge the given set of ranges, creating a valid /// selection. static create(ranges: readonly SelectionRange[], mainIndex: number = 0) { if (ranges.length == 0) throw new RangeError("A selection needs at least one range") for (let pos = 0, i = 0; i < ranges.length; i++) { let range = ranges[i] if (range.empty ? range.from <= pos : range.from < pos) return EditorSelection.normalized(ranges.slice(), mainIndex) pos = range.to } return new EditorSelection(ranges, mainIndex) } /// Create a cursor selection range at the given position. You can /// safely ignore the optional arguments in most situations. static cursor(pos: number, assoc = 0, bidiLevel?: number, goalColumn?: number) { return SelectionRange.create( pos, pos, (assoc == 0 ? 0 : assoc < 0 ? RangeFlag.AssocBefore : RangeFlag.AssocAfter) | (bidiLevel == null ? 3 : Math.min(2, bidiLevel)) | ((goalColumn ?? RangeFlag.NoGoalColumn) << RangeFlag.GoalColumnOffset)) } /// Create a selection range. static range(anchor: number, head: number, goalColumn?: number, bidiLevel?: number) { let flags = ((goalColumn ?? RangeFlag.NoGoalColumn) << RangeFlag.GoalColumnOffset) | (bidiLevel == null ? 3 : Math.min(2, bidiLevel)) return head < anchor ? SelectionRange.create(head, anchor, RangeFlag.Inverted | RangeFlag.AssocAfter | flags) : SelectionRange.create(anchor, head, (head > anchor ? RangeFlag.AssocBefore : 0) | flags) } /// @internal static normalized(ranges: SelectionRange[], mainIndex: number = 0): EditorSelection { let main = ranges[mainIndex] ranges.sort((a, b) => a.from - b.from) mainIndex = ranges.indexOf(main) for (let i = 1; i < ranges.length; i++) { let range = ranges[i], prev = ranges[i - 1] if (range.empty ? range.from <= prev.to : range.from < prev.to) { let from = prev.from, to = Math.max(range.to, prev.to) if (i <= mainIndex) mainIndex-- ranges.splice(--i, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to)) } } return new EditorSelection(ranges, mainIndex) } } export function checkSelection(selection: EditorSelection, docLength: number) { for (let range of selection.ranges) if (range.to > docLength) throw new RangeError("Selection points outside of document") } state-6.2.0/src/state.ts000066400000000000000000000461441435227466100151410ustar00rootroot00000000000000import {Text} from "./text" import {findClusterBreak} from "./char" import {ChangeSet, ChangeSpec, DefaultSplit} from "./change" import {EditorSelection, SelectionRange, checkSelection} from "./selection" import {Transaction, TransactionSpec, resolveTransaction, asArray, StateEffect} from "./transaction" import {allowMultipleSelections, changeFilter, transactionFilter, transactionExtender, lineSeparator, languageData, readOnly} from "./extension" import {Configuration, Facet, Extension, StateField, SlotStatus, ensureAddr, getAddr, Compartment, DynamicSlot} from "./facet" import {CharCategory, makeCategorizer} from "./charcategory" /// Options passed when [creating](#state.EditorState^create) an /// editor state. export interface EditorStateConfig { /// The initial document. Defaults to an empty document. Can be /// provided either as a plain string (which will be split into /// lines according to the value of the [`lineSeparator` /// facet](#state.EditorState^lineSeparator)), or an instance of /// the [`Text`](#state.Text) class (which is what the state will use /// to represent the document). doc?: string | Text /// The starting selection. Defaults to a cursor at the very start /// of the document. selection?: EditorSelection | {anchor: number, head?: number} /// [Extension(s)](#state.Extension) to associate with this state. extensions?: Extension } /// The editor state class is a persistent (immutable) data structure. /// To update a state, you [create](#state.EditorState.update) a /// [transaction](#state.Transaction), which produces a _new_ state /// instance, without modifying the original object. /// /// As such, _never_ mutate properties of a state directly. That'll /// just break things. export class EditorState { /// @internal readonly status: SlotStatus[] /// @internal computeSlot: null | ((state: EditorState, slot: DynamicSlot) => SlotStatus) private constructor( /// @internal readonly config: Configuration, /// The current document. readonly doc: Text, /// The current selection. readonly selection: EditorSelection, /// @internal readonly values: any[], computeSlot: (state: EditorState, slot: DynamicSlot) => SlotStatus, tr: Transaction | null ) { this.status = config.statusTemplate.slice() this.computeSlot = computeSlot // Fill in the computed state immediately, so that further queries // for it made during the update return this state if (tr) tr._state = this for (let i = 0; i < this.config.dynamicSlots.length; i++) ensureAddr(this, i << 1) this.computeSlot = null } /// Retrieve the value of a [state field](#state.StateField). Throws /// an error when the state doesn't have that field, unless you pass /// `false` as second parameter. field(field: StateField): T field(field: StateField, require: false): T | undefined field(field: StateField, require: boolean = true): T | undefined { let addr = this.config.address[field.id] if (addr == null) { if (require) throw new RangeError("Field is not present in this state") return undefined } ensureAddr(this, addr) return getAddr(this, addr) } /// Create a [transaction](#state.Transaction) that updates this /// state. Any number of [transaction specs](#state.TransactionSpec) /// can be passed. Unless /// [`sequential`](#state.TransactionSpec.sequential) is set, the /// [changes](#state.TransactionSpec.changes) (if any) of each spec /// are assumed to start in the _current_ document (not the document /// produced by previous specs), and its /// [selection](#state.TransactionSpec.selection) and /// [effects](#state.TransactionSpec.effects) are assumed to refer /// to the document created by its _own_ changes. The resulting /// transaction contains the combined effect of all the different /// specs. For [selection](#state.TransactionSpec.selection), later /// specs take precedence over earlier ones. update(...specs: readonly TransactionSpec[]): Transaction { return resolveTransaction(this, specs, true) } /// @internal applyTransaction(tr: Transaction) { let conf: Configuration | null = this.config, {base, compartments} = conf for (let effect of tr.effects) { if (effect.is(Compartment.reconfigure)) { if (conf) { compartments = new Map conf.compartments.forEach((val, key) => compartments!.set(key, val)) conf = null } compartments.set(effect.value.compartment, effect.value.extension) } else if (effect.is(StateEffect.reconfigure)) { conf = null base = effect.value } else if (effect.is(StateEffect.appendConfig)) { conf = null base = asArray(base).concat(effect.value) } } let startValues if (!conf) { conf = Configuration.resolve(base, compartments, this) let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null) startValues = intermediateState.values } else { startValues = tr.startState.values.slice() } new EditorState(conf, tr.newDoc, tr.newSelection, startValues, (state, slot) => slot.update(state, tr), tr) } /// Create a [transaction spec](#state.TransactionSpec) that /// replaces every selection range with the given content. replaceSelection(text: string | Text): TransactionSpec { if (typeof text == "string") text = this.toText(text) return this.changeByRange(range => ({changes: {from: range.from, to: range.to, insert: text}, range: EditorSelection.cursor(range.from + text.length)})) } /// Create a set of changes and a new selection by running the given /// function for each range in the active selection. The function /// can return an optional set of changes (in the coordinate space /// of the start document), plus an updated range (in the coordinate /// space of the document produced by the call's own changes). This /// method will merge all the changes and ranges into a single /// changeset and selection, and return it as a [transaction /// spec](#state.TransactionSpec), which can be passed to /// [`update`](#state.EditorState.update). changeByRange(f: (range: SelectionRange) => { range: SelectionRange, changes?: ChangeSpec, effects?: StateEffect | readonly StateEffect[] }): { changes: ChangeSet, selection: EditorSelection, effects: readonly StateEffect[] } { let sel = this.selection let result1 = f(sel.ranges[0]) let changes = this.changes(result1.changes), ranges = [result1.range] let effects = asArray(result1.effects) for (let i = 1; i < sel.ranges.length; i++) { let result = f(sel.ranges[i]) let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes) for (let j = 0; j < i; j++) ranges[j] = ranges[j].map(newMapped) let mapBy = changes.mapDesc(newChanges, true) ranges.push(result.range.map(mapBy)) changes = changes.compose(newMapped) effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray(result.effects), mapBy)) } return { changes, selection: EditorSelection.create(ranges, sel.mainIndex), effects } } /// Create a [change set](#state.ChangeSet) from the given change /// description, taking the state's document length and line /// separator into account. changes(spec: ChangeSpec = []) { if (spec instanceof ChangeSet) return spec return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator)) } /// Using the state's [line /// separator](#state.EditorState^lineSeparator), create a /// [`Text`](#state.Text) instance from the given string. toText(string: string): Text { return Text.of(string.split(this.facet(EditorState.lineSeparator) || DefaultSplit)) } /// Return the given range of the document as a string. sliceDoc(from = 0, to = this.doc.length) { return this.doc.sliceString(from, to, this.lineBreak) } /// Get the value of a state [facet](#state.Facet). facet(facet: Facet): Output { let addr = this.config.address[facet.id] if (addr == null) return facet.default ensureAddr(this, addr) return getAddr(this, addr) } /// Convert this state to a JSON-serializable object. When custom /// fields should be serialized, you can pass them in as an object /// mapping property names (in the resulting object, which should /// not use `doc` or `selection`) to fields. toJSON(fields?: {[prop: string]: StateField}): any { let result: any = { doc: this.sliceDoc(), selection: this.selection.toJSON() } if (fields) for (let prop in fields) { let value = fields[prop] if (value instanceof StateField && this.config.address[value.id] != null) result[prop] = value.spec.toJSON!(this.field(fields[prop]), this) } return result } /// Deserialize a state from its JSON representation. When custom /// fields should be deserialized, pass the same object you passed /// to [`toJSON`](#state.EditorState.toJSON) when serializing as /// third argument. static fromJSON(json: any, config: EditorStateConfig = {}, fields?: {[prop: string]: StateField}): EditorState { if (!json || typeof json.doc != "string") throw new RangeError("Invalid JSON representation for EditorState") let fieldInit = [] if (fields) for (let prop in fields) { if (Object.prototype.hasOwnProperty.call(json, prop)) { let field = fields[prop], value = json[prop] fieldInit.push(field.init(state => field.spec.fromJSON!(value, state))) } } return EditorState.create({ doc: json.doc, selection: EditorSelection.fromJSON(json.selection), extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit }) } /// Create a new state. You'll usually only need this when /// initializing an editor—updated states are created by applying /// transactions. static create(config: EditorStateConfig = {}): EditorState { let configuration = Configuration.resolve(config.extensions || [], new Map) let doc = config.doc instanceof Text ? config.doc : Text.of((config.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit)) let selection = !config.selection ? EditorSelection.single(0) : config.selection instanceof EditorSelection ? config.selection : EditorSelection.single(config.selection.anchor, config.selection.head) checkSelection(selection, doc.length) if (!configuration.staticFacet(allowMultipleSelections)) selection = selection.asSingle() return new EditorState(configuration, doc, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null) } /// A facet that, when enabled, causes the editor to allow multiple /// ranges to be selected. Be careful though, because by default the /// editor relies on the native DOM selection, which cannot handle /// multiple selections. An extension like /// [`drawSelection`](#view.drawSelection) can be used to make /// secondary selections visible to the user. static allowMultipleSelections = allowMultipleSelections /// Configures the tab size to use in this state. The first /// (highest-precedence) value of the facet is used. If no value is /// given, this defaults to 4. static tabSize = Facet.define({ combine: values => values.length ? values[0] : 4 }) /// The size (in columns) of a tab in the document, determined by /// the [`tabSize`](#state.EditorState^tabSize) facet. get tabSize() { return this.facet(EditorState.tabSize) } /// The line separator to use. By default, any of `"\n"`, `"\r\n"` /// and `"\r"` is treated as a separator when splitting lines, and /// lines are joined with `"\n"`. /// /// When you configure a value here, only that precise separator /// will be used, allowing you to round-trip documents through the /// editor without normalizing line separators. static lineSeparator = lineSeparator /// Get the proper [line-break](#state.EditorState^lineSeparator) /// string for this state. get lineBreak() { return this.facet(EditorState.lineSeparator) || "\n" } /// This facet controls the value of the /// [`readOnly`](#state.EditorState.readOnly) getter, which is /// consulted by commands and extensions that implement editing /// functionality to determine whether they should apply. It /// defaults to false, but when its highest-precedence value is /// `true`, such functionality disables itself. /// /// Not to be confused with /// [`EditorView.editable`](#view.EditorView^editable), which /// controls whether the editor's DOM is set to be editable (and /// thus focusable). static readOnly = readOnly /// Returns true when the editor is /// [configured](#state.EditorState^readOnly) to be read-only. get readOnly() { return this.facet(readOnly) } /// Registers translation phrases. The /// [`phrase`](#state.EditorState.phrase) method will look through /// all objects registered with this facet to find translations for /// its argument. static phrases = Facet.define<{[key: string]: string}>({ compare(a, b) { let kA = Object.keys(a), kB = Object.keys(b) return kA.length == kB.length && kA.every(k => a[k as any] == b[k as any]) } }) /// Look up a translation for the given phrase (via the /// [`phrases`](#state.EditorState^phrases) facet), or return the /// original string if no translation is found. /// /// If additional arguments are passed, they will be inserted in /// place of markers like `$1` (for the first value) and `$2`, etc. /// A single `$` is equivalent to `$1`, and `$$` will produce a /// literal dollar sign. phrase(phrase: string, ...insert: any[]): string { for (let map of this.facet(EditorState.phrases)) if (Object.prototype.hasOwnProperty.call(map, phrase)) { phrase = map[phrase]; break } if (insert.length) phrase = phrase.replace(/\$(\$|\d*)/g, (m, i) => { if (i == "$") return "$" let n = +(i || 1) return !n || n > insert.length ? m : insert[n - 1] }) return phrase } /// A facet used to register [language /// data](#state.EditorState.languageDataAt) providers. static languageData = languageData /// Find the values for a given language data field, provided by the /// the [`languageData`](#state.EditorState^languageData) facet. /// /// Examples of language data fields are... /// /// - [`"commentTokens"`](#commands.CommentTokens) for specifying /// comment syntax. /// - [`"autocomplete"`](#autocomplete.autocompletion^config.override) /// for providing language-specific completion sources. /// - [`"wordChars"`](#state.EditorState.charCategorizer) for adding /// characters that should be considered part of words in this /// language. /// - [`"closeBrackets"`](#autocomplete.CloseBracketConfig) controls /// bracket closing behavior. languageDataAt(name: string, pos: number, side: -1 | 0 | 1 = -1): readonly T[] { let values: T[] = [] for (let provider of this.facet(languageData)) { for (let result of provider(this, pos, side)) { if (Object.prototype.hasOwnProperty.call(result, name)) values.push(result[name]) } } return values } /// Return a function that can categorize strings (expected to /// represent a single [grapheme cluster](#state.findClusterBreak)) /// into one of: /// /// - Word (contains an alphanumeric character or a character /// explicitly listed in the local language's `"wordChars"` /// language data, which should be a string) /// - Space (contains only whitespace) /// - Other (anything else) charCategorizer(at: number): (char: string) => CharCategory { return makeCategorizer(this.languageDataAt("wordChars", at).join("")) } /// Find the word at the given position, meaning the range /// containing all [word](#state.CharCategory.Word) characters /// around it. If no word characters are adjacent to the position, /// this returns null. wordAt(pos: number): SelectionRange | null { let {text, from, length} = this.doc.lineAt(pos) let cat = this.charCategorizer(pos) let start = pos - from, end = pos - from while (start > 0) { let prev = findClusterBreak(text, start, false) if (cat(text.slice(prev, start)) != CharCategory.Word) break start = prev } while (end < length) { let next = findClusterBreak(text, end) if (cat(text.slice(end, next)) != CharCategory.Word) break end = next } return start == end ? null : EditorSelection.range(start + from, end + from) } /// Facet used to register change filters, which are called for each /// transaction (unless explicitly /// [disabled](#state.TransactionSpec.filter)), and can suppress /// part of the transaction's changes. /// /// Such a function can return `true` to indicate that it doesn't /// want to do anything, `false` to completely stop the changes in /// the transaction, or a set of ranges in which changes should be /// suppressed. Such ranges are represented as an array of numbers, /// with each pair of two numbers indicating the start and end of a /// range. So for example `[10, 20, 100, 110]` suppresses changes /// between 10 and 20, and between 100 and 110. static changeFilter = changeFilter /// Facet used to register a hook that gets a chance to update or /// replace transaction specs before they are applied. This will /// only be applied for transactions that don't have /// [`filter`](#state.TransactionSpec.filter) set to `false`. You /// can either return a single transaction spec (possibly the input /// transaction), or an array of specs (which will be combined in /// the same way as the arguments to /// [`EditorState.update`](#state.EditorState.update)). /// /// When possible, it is recommended to avoid accessing /// [`Transaction.state`](#state.Transaction.state) in a filter, /// since it will force creation of a state that will then be /// discarded again, if the transaction is actually filtered. /// /// (This functionality should be used with care. Indiscriminately /// modifying transaction is likely to break something or degrade /// the user experience.) static transactionFilter = transactionFilter /// This is a more limited form of /// [`transactionFilter`](#state.EditorState^transactionFilter), /// which can only add /// [annotations](#state.TransactionSpec.annotations) and /// [effects](#state.TransactionSpec.effects). _But_, this type /// of filter runs even if the transaction has disabled regular /// [filtering](#state.TransactionSpec.filter), making it suitable /// for effects that don't need to touch the changes or selection, /// but do want to process every transaction. /// /// Extenders run _after_ filters, when both are present. static transactionExtender = transactionExtender } Compartment.reconfigure = StateEffect.define<{compartment: Compartment, extension: Extension}>() state-6.2.0/src/text.ts000066400000000000000000000465011435227466100150020ustar00rootroot00000000000000const enum Tree { // The branch factor as an exponent of 2 BranchShift = 5, // The approximate branch factor of the tree (both in leaf and // branch nodes) Branch = 1 << Tree.BranchShift } // Flags passed to decompose const enum Open { From = 1, To = 2 } /// A text iterator iterates over a sequence of strings. When /// iterating over a [`Text`](#state.Text) document, result values will /// either be lines or line breaks. export interface TextIterator extends Iterator, Iterable { /// Retrieve the next string. Optionally skip a given number of /// positions after the current position. Always returns the object /// itself. next(skip?: number): this /// The current string. Will be the empty string when the cursor is /// at its end or `next` hasn't been called on it yet. value: string /// Whether the end of the iteration has been reached. You should /// probably check this right after calling `next`. done: boolean /// Whether the current string represents a line break. lineBreak: boolean } /// The data structure for documents. @nonabstract export abstract class Text implements Iterable { /// The length of the string. abstract readonly length: number /// The number of lines in the string (always >= 1). abstract readonly lines: number /// Get the line description around the given position. lineAt(pos: number): Line { if (pos < 0 || pos > this.length) throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`) return this.lineInner(pos, false, 1, 0) } /// Get the description for the given (1-based) line number. line(n: number): Line { if (n < 1 || n > this.lines) throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`) return this.lineInner(n, true, 1, 0) } /// @internal abstract lineInner(target: number, isLine: boolean, line: number, offset: number): Line /// Replace a range of the text with the given content. replace(from: number, to: number, text: Text): Text { let parts: Text[] = [] this.decompose(0, from, parts, Open.To) if (text.length) text.decompose(0, text.length, parts, Open.From | Open.To) this.decompose(to, this.length, parts, Open.From) return TextNode.from(parts, this.length - (to - from) + text.length) } /// Append another document to this one. append(other: Text) { return this.replace(this.length, this.length, other) } /// Retrieve the text between the given points. slice(from: number, to: number = this.length): Text { let parts: Text[] = [] this.decompose(from, to, parts, 0) return TextNode.from(parts, to - from) } /// Retrieve a part of the document as a string abstract sliceString(from: number, to?: number, lineSep?: string): string /// @internal abstract flatten(target: string[]): void /// @internal abstract scanIdentical(other: Text, dir: 1 | -1): number /// Test whether this text is equal to another instance. eq(other: Text): boolean { if (other == this) return true if (other.length != this.length || other.lines != this.lines) return false let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1) let a = new RawTextCursor(this), b = new RawTextCursor(other) for (let skip = start, pos = start;;) { a.next(skip) b.next(skip) skip = 0 if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value) return false pos += a.value.length if (a.done || pos >= end) return true } } /// Iterate over the text. When `dir` is `-1`, iteration happens /// from end to start. This will return lines and the breaks between /// them as separate strings. iter(dir: 1 | -1 = 1): TextIterator { return new RawTextCursor(this, dir) } /// Iterate over a range of the text. When `from` > `to`, the /// iterator will run in reverse. iterRange(from: number, to: number = this.length): TextIterator { return new PartialTextCursor(this, from, to) } /// Return a cursor that iterates over the given range of lines, /// _without_ returning the line breaks between, and yielding empty /// strings for empty lines. /// /// When `from` and `to` are given, they should be 1-based line numbers. iterLines(from?: number, to?: number): TextIterator { let inner if (from == null) { inner = this.iter() } else { if (to == null) to = this.lines + 1 let start = this.line(from).from inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to)) } return new LineCursor(inner) } /// @internal abstract decompose(from: number, to: number, target: Text[], open: Open): void /// @internal toString() { return this.sliceString(0) } /// Convert the document to an array of lines (which can be /// deserialized again via [`Text.of`](#state.Text^of)). toJSON() { let lines: string[] = [] this.flatten(lines) return lines } /// @internal protected constructor() {} /// If this is a branch node, `children` will hold the `Text` /// objects that it is made up of. For leaf nodes, this holds null. abstract readonly children: readonly Text[] | null [Symbol.iterator]!: () => Iterator /// Create a `Text` instance for the given array of lines. static of(text: readonly string[]): Text { if (text.length == 0) throw new RangeError("A document must have at least one line") if (text.length == 1 && !text[0]) return Text.empty return text.length <= Tree.Branch ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, [])) } /// The empty document. static empty: Text } // Leaves store an array of line strings. There are always line breaks // between these strings. Leaves are limited in size and have to be // contained in TextNode instances for bigger documents. class TextLeaf extends Text { constructor(readonly text: readonly string[], readonly length: number = textLength(text)) { super() } get lines(): number { return this.text.length } get children() { return null } lineInner(target: number, isLine: boolean, line: number, offset: number): Line { for (let i = 0;; i++) { let string = this.text[i], end = offset + string.length if ((isLine ? line : end) >= target) return new Line(offset, end, line, string) offset = end + 1 line++ } } decompose(from: number, to: number, target: Text[], open: Open) { let text = from <= 0 && to >= this.length ? this : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from)) if (open & Open.From) { let prev = target.pop() as TextLeaf let joined = appendText(text.text, prev.text.slice(), 0, text.length) if (joined.length <= Tree.Branch) { target.push(new TextLeaf(joined, prev.length + text.length)) } else { let mid = joined.length >> 1 target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid))) } } else { target.push(text) } } replace(from: number, to: number, text: Text): Text { if (!(text instanceof TextLeaf)) return super.replace(from, to, text) let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to) let newLen = this.length + text.length - (to - from) if (lines.length <= Tree.Branch) return new TextLeaf(lines, newLen) return TextNode.from(TextLeaf.split(lines, []), newLen) } sliceString(from: number, to = this.length, lineSep = "\n") { let result = "" for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) { let line = this.text[i], end = pos + line.length if (pos > from && i) result += lineSep if (from < end && to > pos) result += line.slice(Math.max(0, from - pos), to - pos) pos = end + 1 } return result } flatten(target: string[]) { for (let line of this.text) target.push(line) } scanIdentical() { return 0 } static split(text: readonly string[], target: Text[]): Text[] { let part = [], len = -1 for (let line of text) { part.push(line) len += line.length + 1 if (part.length == Tree.Branch) { target.push(new TextLeaf(part, len)) part = [] len = -1 } } if (len > -1) target.push(new TextLeaf(part, len)) return target } } // Nodes provide the tree structure of the `Text` type. They store a // number of other nodes or leaves, taking care to balance themselves // on changes. There are implied line breaks _between_ the children of // a node (but not before the first or after the last child). class TextNode extends Text { readonly lines = 0 constructor(readonly children: readonly Text[], readonly length: number) { super() for (let child of children) this.lines += child.lines } lineInner(target: number, isLine: boolean, line: number, offset: number): Line { for (let i = 0;; i++) { let child = this.children[i], end = offset + child.length, endLine = line + child.lines - 1 if ((isLine ? endLine : end) >= target) return child.lineInner(target, isLine, line, offset) offset = end + 1 line = endLine + 1 } } decompose(from: number, to: number, target: Text[], open: Open) { for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) { let child = this.children[i], end = pos + child.length if (from <= end && to >= pos) { let childOpen = open & ((pos <= from ? Open.From : 0) | (end >= to ? Open.To : 0)) if (pos >= from && end <= to && !childOpen) target.push(child) else child.decompose(from - pos, to - pos, target, childOpen) } pos = end + 1 } } replace(from: number, to: number, text: Text): Text { if (text.lines < this.lines) for (let i = 0, pos = 0; i < this.children.length; i++) { let child = this.children[i], end = pos + child.length // Fast path: if the change only affects one child and the // child's size remains in the acceptable range, only update // that child if (from >= pos && to <= end) { let updated = child.replace(from - pos, to - pos, text) let totalLines = this.lines - child.lines + updated.lines if (updated.lines < (totalLines >> (Tree.BranchShift - 1)) && updated.lines > (totalLines >> (Tree.BranchShift + 1))) { let copy = this.children.slice() copy[i] = updated return new TextNode(copy, this.length - (to - from) + text.length) } return super.replace(pos, end, updated) } pos = end + 1 } return super.replace(from, to, text) } sliceString(from: number, to = this.length, lineSep = "\n") { let result = "" for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) { let child = this.children[i], end = pos + child.length if (pos > from && i) result += lineSep if (from < end && to > pos) result += child.sliceString(from - pos, to - pos, lineSep) pos = end + 1 } return result } flatten(target: string[]) { for (let child of this.children) child.flatten(target) } scanIdentical(other: Text, dir: -1 | 1): number { if (!(other instanceof TextNode)) return 0 let length = 0 let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length] : [this.children.length - 1, other.children.length - 1, -1, -1] for (;; iA += dir, iB += dir) { if (iA == eA || iB == eB) return length let chA = this.children[iA], chB = other.children[iB] if (chA != chB) return length + chA.scanIdentical(chB, dir) length += chA.length + 1 } } static from(children: Text[], length: number = children.reduce((l, ch) => l + ch.length + 1, -1)): Text { let lines = 0 for (let ch of children) lines += ch.lines if (lines < Tree.Branch) { let flat: string[] = [] for (let ch of children) ch.flatten(flat) return new TextLeaf(flat, length) } let chunk = Math.max(Tree.Branch, lines >> Tree.BranchShift), maxChunk = chunk << 1, minChunk = chunk >> 1 let chunked: Text[] = [], currentLines = 0, currentLen = -1, currentChunk: Text[] = [] function add(child: Text) { let last if (child.lines > maxChunk && child instanceof TextNode) { for (let node of child.children) add(node) } else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) { flush() chunked.push(child) } else if (child instanceof TextLeaf && currentLines && (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf && child.lines + last.lines <= Tree.Branch) { currentLines += child.lines currentLen += child.length + 1 currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length) } else { if (currentLines + child.lines > chunk) flush() currentLines += child.lines currentLen += child.length + 1 currentChunk.push(child) } } function flush() { if (currentLines == 0) return chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen)) currentLen = -1 currentLines = currentChunk.length = 0 } for (let child of children) add(child) flush() return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length) } } Text.empty = new TextLeaf([""], 0) function textLength(text: readonly string[]) { let length = -1 for (let line of text) length += line.length + 1 return length } function appendText(text: readonly string[], target: string[], from = 0, to = 1e9): string[] { for (let pos = 0, i = 0, first = true; i < text.length && pos <= to; i++) { let line = text[i], end = pos + line.length if (end >= from) { if (end > to) line = line.slice(0, to - pos) if (pos < from) line = line.slice(from - pos) if (first) { target[target.length - 1] += line; first = false } else target.push(line) } pos = end + 1 } return target } function sliceText(text: readonly string[], from?: number, to?: number): string[] { return appendText(text, [""], from, to) } class RawTextCursor implements TextIterator { public done: boolean = false public lineBreak: boolean = false public value: string = "" private nodes: Text[] // The offset into the node at each level, shifted one to the left // with the top bit indicating whether the position is before (0) or // after(1) the line break between the adjacent nodes. private offsets: number[] constructor(text: Text, readonly dir: 1 | -1 = 1) { this.nodes = [text] this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children!.length) << 1] } nextInner(skip: number, dir: 1 | -1): this { this.done = this.lineBreak = false for (;;) { let last = this.nodes.length - 1 let top = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1 let size = top instanceof TextLeaf ? top.text.length : top.children!.length if (offset == (dir > 0 ? size : 0)) { if (last == 0) { this.done = true this.value = "" return this } if (dir > 0) this.offsets[last - 1]++ this.nodes.pop() this.offsets.pop() } else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) { this.offsets[last] += dir if (skip == 0) { this.lineBreak = true this.value = "\n" return this } skip-- } else if (top instanceof TextLeaf) { // Move to the next string let next = top.text[offset + (dir < 0 ? -1 : 0)] this.offsets[last] += dir if (next.length > Math.max(0, skip)) { this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip) return this } skip -= next.length } else { let next = top.children![offset + (dir < 0 ? -1 : 0)] if (skip > next.length) { skip -= next.length this.offsets[last] += dir } else { if (dir < 0) this.offsets[last]-- this.nodes.push(next) this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children!.length) << 1) } } } } next(skip: number = 0) { if (skip < 0) { this.nextInner(-skip, (-this.dir) as -1 | 1) skip = this.value.length } return this.nextInner(skip, this.dir) } /// @internal [Symbol.iterator]!: () => Iterator } class PartialTextCursor implements TextIterator { cursor: RawTextCursor value: string = "" pos: number from: number to: number done = false constructor(text: Text, start: number, end: number) { this.cursor = new RawTextCursor(text, start > end ? -1 : 1) this.pos = start > end ? text.length : 0 this.from = Math.min(start, end) this.to = Math.max(start, end) } nextInner(skip: number, dir: -1 | 1): this { if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) { this.value = "" this.done = true return this } skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos) let limit = dir < 0 ? this.pos - this.from : this.to - this.pos if (skip > limit) skip = limit limit -= skip let {value} = this.cursor.next(skip) this.pos += (value.length + skip) * dir this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit) this.done = !this.value return this } next(skip = 0) { if (skip < 0) skip = Math.max(skip, this.from - this.pos) else if (skip > 0) skip = Math.min(skip, this.to - this.pos) return this.nextInner(skip, this.cursor.dir) } get lineBreak() { return this.cursor.lineBreak && this.value != "" } /// @internal [Symbol.iterator]!: () => Iterator } class LineCursor implements TextIterator { afterBreak = true value = "" done = false constructor(readonly inner: TextIterator) {} next(skip = 0) { let {done, lineBreak, value} = this.inner.next(skip) if (done) { this.done = true this.value = "" } else if (lineBreak) { if (this.afterBreak) { this.value = "" } else { this.afterBreak = true this.next() } } else { this.value = value this.afterBreak = false } return this } get lineBreak() { return false } /// @internal [Symbol.iterator]!: () => Iterator } if (typeof Symbol != "undefined") { Text.prototype[Symbol.iterator] = function() { return this.iter() } RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] = LineCursor.prototype[Symbol.iterator] = function(this: Iterator) { return this } } /// This type describes a line in the document. It is created /// on-demand when lines are [queried](#state.Text.lineAt). export class Line { /// @internal constructor( /// The position of the start of the line. readonly from: number, /// The position at the end of the line (_before_ the line break, /// or at the end of document for the last line). readonly to: number, /// This line's line number (1-based). readonly number: number, /// The line's content. readonly text: string ) {} /// The length of the line (not including any line break after it). get length() { return this.to - this.from } } state-6.2.0/src/transaction.ts000066400000000000000000000421141435227466100163370ustar00rootroot00000000000000import {ChangeSet, ChangeDesc, ChangeSpec} from "./change" import {EditorState} from "./state" import {EditorSelection, checkSelection} from "./selection" import {changeFilter, transactionFilter, transactionExtender, lineSeparator} from "./extension" import {Extension} from "./facet" import {Text} from "./text" /// Annotations are tagged values that are used to add metadata to /// transactions in an extensible way. They should be used to model /// things that effect the entire transaction (such as its [time /// stamp](#state.Transaction^time) or information about its /// [origin](#state.Transaction^userEvent)). For effects that happen /// _alongside_ the other changes made by the transaction, [state /// effects](#state.StateEffect) are more appropriate. export class Annotation { /// @internal constructor( /// The annotation type. readonly type: AnnotationType, /// The value of this annotation. readonly value: T ) {} /// Define a new type of annotation. static define() { return new AnnotationType() } // This is just to get less sloppy typing (where StateEffect is a subtype of Annotation) // @ts-ignore private _isAnnotation!: true } /// Marker that identifies a type of [annotation](#state.Annotation). export class AnnotationType { /// Create an instance of this annotation. of(value: T): Annotation { return new Annotation(this, value) } } interface StateEffectSpec { /// Provides a way to map an effect like this through a position /// mapping. When not given, the effects will simply not be mapped. /// When the function returns `undefined`, that means the mapping /// deletes the effect. map?: (value: Value, mapping: ChangeDesc) => Value | undefined } /// Representation of a type of state effect. Defined with /// [`StateEffect.define`](#state.StateEffect^define). export class StateEffectType { /// @internal constructor( // The `any` types in these function types are there to work // around TypeScript issue #37631, where the type guard on // `StateEffect.is` mysteriously stops working when these properly // have type `Value`. /// @internal readonly map: (value: any, mapping: ChangeDesc) => any | undefined ) {} /// Create a [state effect](#state.StateEffect) instance of this /// type. of(value: Value): StateEffect { return new StateEffect(this, value) } } /// State effects can be used to represent additional effects /// associated with a [transaction](#state.Transaction.effects). They /// are often useful to model changes to custom [state /// fields](#state.StateField), when those changes aren't implicit in /// document or selection changes. export class StateEffect { /// @internal constructor( /// @internal readonly type: StateEffectType, /// The value of this effect. readonly value: Value) {} /// Map this effect through a position mapping. Will return /// `undefined` when that ends up deleting the effect. map(mapping: ChangeDesc): StateEffect | undefined { let mapped = this.type.map(this.value, mapping) return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped) } /// Tells you whether this effect object is of a given /// [type](#state.StateEffectType). is(type: StateEffectType): this is StateEffect { return this.type == type as any } /// Define a new effect type. The type parameter indicates the type /// of values that his effect holds. static define(spec: StateEffectSpec = {}): StateEffectType { return new StateEffectType(spec.map || (v => v)) } /// Map an array of effects through a change set. static mapEffects(effects: readonly StateEffect[], mapping: ChangeDesc) { if (!effects.length) return effects let result = [] for (let effect of effects) { let mapped = effect.map(mapping) if (mapped) result.push(mapped) } return result } /// This effect can be used to reconfigure the root extensions of /// the editor. Doing this will discard any extensions /// [appended](#state.StateEffect^appendConfig), but does not reset /// the content of [reconfigured](#state.Compartment.reconfigure) /// compartments. static reconfigure = StateEffect.define() /// Append extensions to the top-level configuration of the editor. static appendConfig = StateEffect.define() } /// Describes a [transaction](#state.Transaction) when calling the /// [`EditorState.update`](#state.EditorState.update) method. export interface TransactionSpec { /// The changes to the document made by this transaction. changes?: ChangeSpec /// When set, this transaction explicitly updates the selection. /// Offsets in this selection should refer to the document as it is /// _after_ the transaction. selection?: EditorSelection | {anchor: number, head?: number}, /// Attach [state effects](#state.StateEffect) to this transaction. /// Again, when they contain positions and this same spec makes /// changes, those positions should refer to positions in the /// updated document. effects?: StateEffect | readonly StateEffect[], /// Set [annotations](#state.Annotation) for this transaction. annotations?: Annotation | readonly Annotation[], /// Shorthand for `annotations:` [`Transaction.userEvent`](#state.Transaction^userEvent)`.of(...)`. userEvent?: string, /// When set to `true`, the transaction is marked as needing to /// scroll the current selection into view. scrollIntoView?: boolean, /// By default, transactions can be modified by [change /// filters](#state.EditorState^changeFilter) and [transaction /// filters](#state.EditorState^transactionFilter). You can set this /// to `false` to disable that. This can be necessary for /// transactions that, for example, include annotations that must be /// kept consistent with their changes. filter?: boolean, /// Normally, when multiple specs are combined (for example by /// [`EditorState.update`](#state.EditorState.update)), the /// positions in `changes` are taken to refer to the document /// positions in the initial document. When a spec has `sequental` /// set to true, its positions will be taken to refer to the /// document created by the specs before it instead. sequential?: boolean } /// Changes to the editor state are grouped into transactions. /// Typically, a user action creates a single transaction, which may /// contain any number of document changes, may change the selection, /// or have other effects. Create a transaction by calling /// [`EditorState.update`](#state.EditorState.update), or immediately /// dispatch one by calling /// [`EditorView.dispatch`](#view.EditorView.dispatch). export class Transaction { /// @internal _doc: Text | null = null /// @internal _state: EditorState | null = null private constructor( /// The state from which the transaction starts. readonly startState: EditorState, /// The document changes made by this transaction. readonly changes: ChangeSet, /// The selection set by this transaction, or undefined if it /// doesn't explicitly set a selection. readonly selection: EditorSelection | undefined, /// The effects added to the transaction. readonly effects: readonly StateEffect[], /// @internal readonly annotations: readonly Annotation[], /// Whether the selection should be scrolled into view after this /// transaction is dispatched. readonly scrollIntoView: boolean ) { if (selection) checkSelection(selection, changes.newLength) if (!annotations.some((a: Annotation) => a.type == Transaction.time)) this.annotations = annotations.concat(Transaction.time.of(Date.now())) } /// @internal static create(startState: EditorState, changes: ChangeSet, selection: EditorSelection | undefined, effects: readonly StateEffect[], annotations: readonly Annotation[], scrollIntoView: boolean) { return new Transaction(startState, changes, selection, effects, annotations, scrollIntoView) } /// The new document produced by the transaction. Contrary to /// [`.state`](#state.Transaction.state)`.doc`, accessing this won't /// force the entire new state to be computed right away, so it is /// recommended that [transaction /// filters](#state.EditorState^transactionFilter) use this getter /// when they need to look at the new document. get newDoc() { return this._doc || (this._doc = this.changes.apply(this.startState.doc)) } /// The new selection produced by the transaction. If /// [`this.selection`](#state.Transaction.selection) is undefined, /// this will [map](#state.EditorSelection.map) the start state's /// current selection through the changes made by the transaction. get newSelection() { return this.selection || this.startState.selection.map(this.changes) } /// The new state created by the transaction. Computed on demand /// (but retained for subsequent access), so it is recommended not to /// access it in [transaction /// filters](#state.EditorState^transactionFilter) when possible. get state() { if (!this._state) this.startState.applyTransaction(this) return this._state! } /// Get the value of the given annotation type, if any. annotation(type: AnnotationType): T | undefined { for (let ann of this.annotations) if (ann.type == type) return ann.value return undefined } /// Indicates whether the transaction changed the document. get docChanged(): boolean { return !this.changes.empty } /// Indicates whether this transaction reconfigures the state /// (through a [configuration compartment](#state.Compartment) or /// with a top-level configuration /// [effect](#state.StateEffect^reconfigure). get reconfigured(): boolean { return this.startState.config != this.state.config } /// Returns true if the transaction has a [user /// event](#state.Transaction^userEvent) annotation that is equal to /// or more specific than `event`. For example, if the transaction /// has `"select.pointer"` as user event, `"select"` and /// `"select.pointer"` will match it. isUserEvent(event: string): boolean { let e = this.annotation(Transaction.userEvent) return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == ".")) } /// Annotation used to store transaction timestamps. Automatically /// added to every transaction, holding `Date.now()`. static time = Annotation.define() /// Annotation used to associate a transaction with a user interface /// event. Holds a string identifying the event, using a /// dot-separated format to support attaching more specific /// information. The events used by the core libraries are: /// /// - `"input"` when content is entered /// - `"input.type"` for typed input /// - `"input.type.compose"` for composition /// - `"input.paste"` for pasted input /// - `"input.drop"` when adding content with drag-and-drop /// - `"input.complete"` when autocompleting /// - `"delete"` when the user deletes content /// - `"delete.selection"` when deleting the selection /// - `"delete.forward"` when deleting forward from the selection /// - `"delete.backward"` when deleting backward from the selection /// - `"delete.cut"` when cutting to the clipboard /// - `"move"` when content is moved /// - `"move.drop"` when content is moved within the editor through drag-and-drop /// - `"select"` when explicitly changing the selection /// - `"select.pointer"` when selecting with a mouse or other pointing device /// - `"undo"` and `"redo"` for history actions /// /// Use [`isUserEvent`](#state.Transaction.isUserEvent) to check /// whether the annotation matches a given event. static userEvent = Annotation.define() /// Annotation indicating whether a transaction should be added to /// the undo history or not. static addToHistory = Annotation.define() /// Annotation indicating (when present and true) that a transaction /// represents a change made by some other actor, not the user. This /// is used, for example, to tag other people's changes in /// collaborative editing. static remote = Annotation.define() } function joinRanges(a: readonly number[], b: readonly number[]) { let result = [] for (let iA = 0, iB = 0;;) { let from, to if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) { from = a[iA++]; to = a[iA++] } else if (iB < b.length) { from = b[iB++]; to = b[iB++] } else return result if (!result.length || result[result.length - 1] < from) result.push(from, to) else if (result[result.length - 1] < to) result[result.length - 1] = to } } type ResolvedSpec = { changes: ChangeSet, selection: EditorSelection | undefined, effects: readonly StateEffect[], annotations: readonly Annotation[], scrollIntoView: boolean } function mergeTransaction(a: ResolvedSpec, b: ResolvedSpec, sequential: boolean): ResolvedSpec { let mapForA, mapForB, changes if (sequential) { mapForA = b.changes mapForB = ChangeSet.empty(b.changes.length) changes = a.changes.compose(b.changes) } else { mapForA = b.changes.map(a.changes) mapForB = a.changes.mapDesc(b.changes, true) changes = a.changes.compose(mapForA) } return { changes, selection: b.selection ? b.selection.map(mapForB) : a.selection?.map(mapForA), effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)), annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations, scrollIntoView: a.scrollIntoView || b.scrollIntoView } } function resolveTransactionInner(state: EditorState, spec: TransactionSpec, docSize: number): ResolvedSpec { let sel = spec.selection, annotations = asArray(spec.annotations) if (spec.userEvent) annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent)) return { changes: spec.changes instanceof ChangeSet ? spec.changes : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)), selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)), effects: asArray(spec.effects), annotations, scrollIntoView: !!spec.scrollIntoView } } export function resolveTransaction(state: EditorState, specs: readonly TransactionSpec[], filter: boolean): Transaction { let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length) if (specs.length && specs[0].filter === false) filter = false for (let i = 1; i < specs.length; i++) { if (specs[i].filter === false) filter = false let seq = !!specs[i].sequential s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq) } let tr = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView) return extendTransaction(filter ? filterTransaction(tr) : tr) } // Finish a transaction by applying filters if necessary. function filterTransaction(tr: Transaction) { let state = tr.startState // Change filters let result: boolean | readonly number[] = true for (let filter of state.facet(changeFilter)) { let value = filter(tr) if (value === false) { result = false; break } if (Array.isArray(value)) result = result === true ? value : joinRanges(result, value) } if (result !== true) { let changes, back if (result === false) { back = tr.changes.invertedDesc changes = ChangeSet.empty(state.doc.length) } else { let filtered = tr.changes.filter(result) changes = filtered.changes back = filtered.filtered.mapDesc(filtered.changes).invertedDesc } tr = Transaction.create(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView) } // Transaction filters let filters = state.facet(transactionFilter) for (let i = filters.length - 1; i >= 0; i--) { let filtered = filters[i](tr) if (filtered instanceof Transaction) tr = filtered else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction) tr = filtered[0] else tr = resolveTransaction(state, asArray(filtered as any), false) } return tr } function extendTransaction(tr: Transaction) { let state = tr.startState, extenders = state.facet(transactionExtender), spec: ResolvedSpec = tr for (let i = extenders.length - 1; i >= 0; i--) { let extension = extenders[i](tr) if (extension && Object.keys(extension).length) spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr.changes.newLength), true) } return spec == tr ? tr : Transaction.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView) } const none: readonly any[] = [] export function asArray(value: undefined | T | readonly T[]): readonly T[] { return value == null ? none : Array.isArray(value) ? value : [value] } state-6.2.0/test/000077500000000000000000000000001435227466100136305ustar00rootroot00000000000000state-6.2.0/test/test-change.ts000066400000000000000000000276701435227466100164160ustar00rootroot00000000000000import {ChangeDesc, ChangeSet, Text, MapMode} from "@codemirror/state" import ist from "ist" function mk(spec: string): ChangeDesc { let sections: number[] = [] while (spec.length) { let next = /^(\d+)(?::(\d+))?\s*/.exec(spec)! spec = spec.slice(next[0].length) sections.push(+next[1], next[2] == null ? -1 : +next[2]) } return new (ChangeDesc as any)(sections) } // ('r' for random) function r(n: number) { return Math.floor(Math.random() * n) } function rStr(l: number) { let result = "" for (let i = 0; i < l; i++) result += String.fromCharCode(97 + r(26)) return result } function rChange(len: number): {from: number, to?: number, insert?: string} { if (len == 0 || r(3) == 0) return {insert: rStr(r(5) + 1), from: r(len)} let from = r(len - 1) return {from, to: Math.min(from + r(5) + 1, len), insert: r(2) == 0 ? rStr(r(2) + 1) : undefined} } function rChanges(len: number, count: number): {from: number, to?: number, insert?: string}[] { let result = [] for (let i = 0; i < count; i++) result.push(rChange(len)) return result } describe("ChangeDesc", () => { describe("composition", () => { function comp(...specs: string[]) { let result = specs.pop(), sets = specs.map(mk) ist(String(sets.reduce((a, b) => a.composeDesc(b))), result) } it("can compose unrelated changes", () => comp("5 0:2", "1 2:0 4", "1 2:0 2 0:2")) it("cancels insertions with deletions", () => comp("2 0:2 2", "2 2:0 2", "4")) it("joins adjacent insertions", () => comp("2 0:2 2", "4 0:3 2", "2 0:5 2")) it("joins adjacent deletions", () => comp("2 5:0", "1 1:0", "1 6:0")) it("allows a delete to shadow multiple operations", () => comp("2 2:0 0:3", "5:0", "4:0")) it("can handle empty sets", () => comp("", "0:8", "8:0", "", "")) it("can join multiple replaces", () => { comp("2 2:2 2:2 2", "1 2:2 2:2 2:2 1", "1 6:6 1") comp("1 2:2 2:2 2:2 1", "2 2:2 2:2 2", "1 6:6 1") comp("1 2:3 3:2 1", "2 3:1 2", "1 5:3 1") }) it("throws for inconsistent lengths", () => { ist.throws(() => mk("2 0:2").composeDesc(mk("1 0:1"))) ist.throws(() => mk("2 0:2").composeDesc(mk("30 0:1"))) ist.throws(() => mk("2 2:0 0:3").composeDesc(mk("7:0"))) }) }) describe("mapping", () => { function over(a: string, b: string, result: string) { ist(String(mk(a).mapDesc(mk(b))), result) } function under(a: string, b: string, result: string) { ist(String(mk(a).mapDesc(mk(b), true)), result) } it("can map over an insertion", () => over("4 0:1", "0:3 4" , "7 0:1")) it("can map over a deletion", () => over("4 0:1", "2:0 2", "2 0:1")) it("orders insertions", () => { over("2 0:1 2", "2 0:1 2", "3 0:1 2") under("2 0:1 2", "2 0:1 2", "2 0:1 3") }) it("can map a deletion over an overlapping replace", () => { over("2 2:0", "2 1:2 1", "4 1:0") under("2 2:0", "2 1:2 1", "4 1:0") }) it("can handle changes after", () => over("0:1 2:0 8", "6 1:0 0:5 3", "0:1 2:0 12")) it("joins deletions", () => over("5:0 2 3:0 2", "4 4:0 4", "6:0 2")) it("keeps insertions in deletions", () => { under("2 0:1 2", "4:0", "0:1") over("4 0:1 4", "2 4:0 2", "2 0:1 2") }) it("keeps replacements", () => { over("2 2:2 2", "0:2 6", "4 2:2 2") over("2 2:2 2", "3:0 3", "1:2 2") over("1 4:4 1", "3 0:2 3", "1 2:4 2 2:0 1") over("1 4:4 1", "2 2:0 2", "1 2:4 1") over("2 2:2 2", "3 2:0 1", "2 1:2 1") }) it("doesn't join replacements", () => { over("2:2 2 2:2", "2 2:0 2", "2:2 2:2") }) it("drops duplicate deletion", () => { under("2 2:0 2", "2 2:0 2", "4") over("2 2:0 2", "2 2:0 2", "4") }) it("handles overlapping replaces", () => { over("1 1:2 1", "1 1:1 1", "2 0:2 1") under("1 1:2 1", "1 1:1 1", "1 0:2 2") over("1 1:2 2", "1 2:1 1", "1 0:2 2") over("2 1:2 1", "1 2:1 1", "2 0:2 1") over("2:1 1", "1 2:2", "1:1 2") over("1 2:1", "2:2 1", "2 1:1") }) }) describe("mapPos", () => { function map(spec: string, ...cases: [number, number | null, (number | string)?][]) { let set = mk(spec) for (let [from, to, opt] of cases) { let assoc = typeof opt == "number" ? opt : -1 let mode = ({D: MapMode.TrackDel, A: MapMode.TrackAfter, B: MapMode.TrackBefore} as any)[opt as any] ist(set.mapPos(from, assoc, mode), to) } } it("maps through an insertion", () => map("4 0:2 4", [0, 0], [4, 4], [4, 6, 1], [5, 7], [8, 10])) it("maps through deletion", () => map("4 4:0 4", [0, 0], [4, 4], [4, 4, "D"], [4, 4, "B"], [4, null, "A"], [5, 4], [5, null, "D"], [5, null, "B"], [5, null, "A"], [7, 4], [8, 4], [8, 4, "D"], [8, null, "B"], [8, 4, "A"], [9, 5], [12, 8])) it("maps through multiple insertions", () => map("0:2 2 0:2 2 0:2", [0, 0], [0, 2, 1], [1, 3], [2, 4], [2, 6, 1], [3, 7], [4, 8], [4, 10, 1])) it("maps through multiple deletions", () => map("2:0 2 2:0 2 2:0", [0, 0], [1, 0], [2, 0], [3, 1], [4, 2], [5, 2], [6, 2], [7, 3], [8, 4], [9, 4], [10, 4])) it("maps through mixed edits", () => map("2 0:2 2:0 0:2 2 2:0 0:2", [0, 0], [2, 2], [2, 4, 1], [3, 4], [4, 4], [4, 6, 1], [5, 7], [6, 8], [7, 8], [8, 8], [8, 10, 1])) it("stays on its own side of replacements", () => map("2 2:2 2", [2, 2, 1], [2, 2, -1], [2, 2, "D"], [2, 2, "B"], [2, null, "A"], [3, 2, -1], [3, 4, 1], [3, null, "D"], [3, null, "B"], [3, null, "A"], [4, 4, 1], [4, 4, -1], [4, 4, "D"], [4, null, "B"], [4, 4, "A"])) it("maps through insertions around replacements", () => map("0:1 2:2 0:1", [0, 0, -1], [0, 1, 1], [1, 1, -1], [1, 3, 1], [2, 3, -1], [2, 4, 1])) it("stays in between replacements", () => map("2:2 2:2", [2, 2, -1], [2, 2, 1])) }) }) describe("ChangeSet", () => { it("can create change sets", () => { ist(ChangeSet.of([{insert: "hi", from: 5}], 10).desc.toString(), "5 0:2 5") ist(ChangeSet.of([{from: 5, to: 7}], 10).desc.toString(), "5 2:0 3") ist(ChangeSet.of([ {insert: "hi", from: 5}, {insert: "ok", from: 5}, {from: 0, to: 3}, {from: 4, to: 6}, {insert: "boo", from: 8} ], 10).desc.toString(), "3:0 1 1:0 0:4 1:0 2 0:3 2") }) let doc10 = Text.of(["0123456789"]) it("can apply change sets", () => { ist(ChangeSet.of([{insert: "ok", from: 2}], 10).apply(doc10).toString(), "01ok23456789") ist(ChangeSet.of([{from: 1, to: 9}], 10).apply(doc10).toString(), "09") ist(ChangeSet.of([{from: 2, to: 8}, {insert: "hi", from: 1}], 10).apply(doc10).toString(), "0hi189") }) it("can apply composed sets", () => { ist(ChangeSet.of([{insert: "ABCD", from: 8}], 10) .compose(ChangeSet.of([{from: 8, to: 11}], 14)) .apply(doc10).toString(), "01234567D89") ist(ChangeSet.of([{insert: "hi", from: 2}, {insert: "ok", from: 8}], 10) .compose(ChangeSet.of([{insert: "!", from: 4}, {from: 6, to: 8}, {insert: "?", from: 12}], 14)) .apply(doc10).toString(), "01hi!2367ok?89") }) it("can clip inserted strings on compose", () => { ist(ChangeSet.of([{insert: "abc", from: 2}, {insert: "def", from: 4}], 10) .compose(ChangeSet.of([{from: 4, to: 8}], 16)) .apply(doc10).toString(), "01abef456789") }) it("can apply mapped sets", () => { let set0 = ChangeSet.of([{insert: "hi", from: 5}, {from: 8, to: 10}], 10) let set1 = ChangeSet.of([{insert: "ok", from: 10}, {from: 6, to: 7}], 10) ist(set0.compose(set1.map(set0)).apply(doc10).toString(), "01234hi57ok") }) it("can apply inverted sets", () => { let set0 = ChangeSet.of([{insert: "hi", from: 5}, {from: 8, to: 10}], 10) ist(set0.invert(doc10).apply(set0.apply(doc10)).toString(), doc10.toString()) }) it("can be iterated", () => { let set = ChangeSet.of([{insert: "ok", from: 4}, {from: 6, to: 8}], 10) let result: any[] = [] set.iterChanges((fromA, toA, fromB, toB, inserted) => result.push([fromA, toA, fromB, toB, inserted.toString()])) ist(JSON.stringify(result), JSON.stringify([[4, 4, 4, 6, "ok"], [6, 8, 8, 8, ""]])) result = [] set.iterGaps((fromA, toA, len) => result.push([fromA, toA, len])) ist(JSON.stringify(result), JSON.stringify([[0, 0, 4], [4, 6, 2], [8, 8, 2]])) }) it("mapping before produces the same result as mapping the other after", () => { for (let i = 0, total = 100; i < total; i++) { let size = r(20), count = Math.floor(i / (total / 10)) + 1 let a = rChanges(size, count), b = rChanges(size, count) try { let setA = ChangeSet.of(a, size), setB = ChangeSet.of(b, size) let setA1 = setA.map(setB, true), setB1 = setB.map(setA, false) let doc = Text.of([rStr(size)]) let setAB = setA.compose(setB1), setBA = setB.compose(setA1) ist(setAB.apply(doc).toString(), setBA.apply(doc).toString()) } catch (e) { console.log(`size = ${size}\na = ${JSON.stringify(a)}\nb = ${JSON.stringify(b)}`) throw e } } }) it("mapping still converges when mapping through multiple changes", () => { for (let i = 0, total = 100; i < total; i++) { let size = r(20), count = Math.floor(i / (total / 10)) + 1 let a = ChangeSet.of(rChanges(size, count), size) let b = ChangeSet.of(rChanges(a.newLength, count), a.newLength) let c = ChangeSet.of(rChanges(size, count), size) let c$a = c.map(a), c$ab = c$a.map(b) let a$c = a.map(c, true), b$ca = b.map(c$a, true) let doc = Text.of([rStr(size)]) ist(a.compose(b).compose(c$ab).apply(doc).toString(), c.compose(a$c).compose(b$ca).apply(doc).toString()) } }) it("compose produces the same result as individual changes", () => { for (let i = 0; i < 100; i++) { let size = r(20), doc = Text.of([rStr(size)]) let a = ChangeSet.of(rChanges(size, r(5) + 1), size) let b = ChangeSet.of(rChanges(a.newLength, r(6)), a.newLength) ist(b.apply(a.apply(doc)).toString(), a.compose(b).apply(doc).toString()) } }) it("composing is associative", () => { for (let i = 0; i < 100; i++) { let size = r(20), doc = Text.of([rStr(size)]) let a = ChangeSet.of(rChanges(size, r(5) + 1), size) let b = ChangeSet.of(rChanges(a.newLength, r(6)), a.newLength) let c = ChangeSet.of(rChanges(b.newLength, r(5) + 1), b.newLength) let left = a.compose(b).compose(c), right = a.compose(b.compose(c)) ist(left.apply(doc).toString(), right.apply(doc).toString()) } }) it("survives random sequences of changes", () => { for (let i = 0; i < 50; i++) { let doc = doc10, txt = doc.toString(), all: ChangeSet[] = [], inv: ChangeSet[] = [] let log = [] try { for (let j = 0; j < 50; j++) { let set: ChangeSet, change = rChange(doc.length) log.push(`ChangeSet.of([${JSON.stringify(change)}], ${doc.length})`) let {from, to = from, insert = ""} = change txt = txt.slice(0, from) + insert + txt.slice(to) set = ChangeSet.of([change], doc.length) all.push(set) inv.push(set.invert(doc)) doc = set.apply(doc) ist(doc.toString(), txt) } let composed = all.reduce((a, b) => a.compose(b), ChangeSet.of([], doc10.length)) ist(composed.apply(doc10).toString(), txt) ist(composed.invert(doc10).apply(doc).toString(), doc10.toString()) for (let i = inv.length - 1; i >= 0; i--) doc = inv[i].apply(doc) ist(doc.toString(), doc10.toString()) } catch(e) { console.log("With changes: ", log.join(", ")) throw e } } }) it("can be serialized to JSON", () => { for (let i = 0; i < 100; i++) { let size = r(20) + 1, set = ChangeSet.of(rChanges(size, r(4)), size) ist(String(ChangeSet.fromJSON(set.toJSON())), String(set)) } }) }) state-6.2.0/test/test-charcategory.ts000066400000000000000000000013071435227466100176310ustar00rootroot00000000000000import {EditorState, Extension, CharCategory} from "@codemirror/state" import ist from "ist" function mk(...extensions: Extension[]) { return EditorState.create({extensions}) } describe("EditorState char categorizer", () => { it("categorises into alphanumeric", () => { let st = mk() ist(st.charCategorizer(0)("1"), CharCategory.Word) ist(st.charCategorizer(0)("a"), CharCategory.Word) }) it("categorises into whitespace", () => { let st = mk() ist(st.charCategorizer(0)(" "), CharCategory.Space) }) it("categorises into other", () => { let st = mk() ist(st.charCategorizer(0)("/"), CharCategory.Other) ist(st.charCategorizer(0)("<"), CharCategory.Other) }) }) state-6.2.0/test/test-cluster.ts000066400000000000000000000023431435227466100166400ustar00rootroot00000000000000import {findClusterBreak, countColumn, findColumn} from "@codemirror/state" import ist from "ist" describe("findClusterBreak", () => { function test(spec: string) { it(spec, () => { let breaks = [], next: number while ((next = spec.indexOf("|")) > -1) { breaks.push(next) spec = spec.slice(0, next) + spec.slice(next + 1) } let found = [] for (let i = 0;;) { let next = findClusterBreak(spec, i) if (next == spec.length) break found.push(i = next) } ist(found.join(","), breaks.join(",")) }) } test("a|b|c|d") test("a|é̠|ő|x") test("😎|🙉") test("👨‍🎤|💪🏽|👩‍👩‍👧‍👦|❤") test("🇩🇪|🇫🇷|🇪🇸|x|🇮🇹") }) describe("countColumn", () => { it("counts characters", () => ist(countColumn("abc", 4), 3)) it("counts tabs correctly", () => ist(countColumn("a\t\tbc\tx", 4), 13)) it("handles clusters", () => ist(countColumn("a😎🇫🇷", 4), 3)) }) describe("findColumn", () => { it("finds positions", () => ist(findColumn("abc", 3, 4), 3)) it("counts tabs", () => ist(findColumn("a\tbc", 4, 4), 2)) it("handles clusters", () => ist(findColumn("a😎🇫🇷bc", 4, 4), 8)) }) state-6.2.0/test/test-facet.ts000066400000000000000000000150121435227466100162360ustar00rootroot00000000000000import ist from "ist" import {EditorState, Facet, Extension, Prec, StateField, StateEffect} from "@codemirror/state" function mk(...extensions: Extension[]) { return EditorState.create({extensions}) } let num = Facet.define(), str = Facet.define(), bool = Facet.define() describe("EditorState facets", () => { it("allows querying of facets", () => { let st = mk(num.of(10), num.of(20), str.of("x"), str.of("y")) ist(st.facet(num).join(), "10,20") ist(st.facet(str).join(), "x,y") }) it("includes sub-extenders", () => { let e = (s: string) => [num.of(s.length), num.of(+s)] let st = mk(num.of(5), e("20"), num.of(40), e("100")) ist(st.facet(num).join(), "5,2,20,40,3,100") }) it("only includes duplicated extensions once", () => { let e = num.of(50) let st = mk(num.of(1), e, num.of(4), e) ist(st.facet(num).join(), "1,50,4") }) it("returns an empty array for absent facet", () => { let st = mk() ist(JSON.stringify(st.facet(num)), "[]") }) it("sorts extensions by priority", () => { let st = mk(str.of("a"), str.of("b"), Prec.high(str.of("c")), Prec.highest(str.of("d")), Prec.low(str.of("e")), Prec.high(str.of("f")), str.of("g")) ist(st.facet(str).join(), "d,c,f,a,b,g,e") }) it("lets sub-extensions inherit their parent's priority", () => { let e = (n: number) => num.of(n) let st = mk(num.of(1), Prec.highest(e(2)), e(4)) ist(st.facet(num).join(), "2,1,4") }) it("supports dynamic facet", () => { let st = mk(num.of(1), num.compute([], () => 88)) ist(st.facet(num).join(), "1,88") }) it("only recomputes a facet value when necessary", () => { let st = mk(num.of(1), num.compute([str], s => s.facet(str).join().length), str.of("hello")) let array = st.facet(num) ist(array.join(), "1,5") ist(st.update({}).state.facet(num), array) }) it("can handle dependencies on facets that aren't present in the state", () => { let st = mk(num.compute([str], s => s.facet(str).join().length), str.compute([bool], s => s.facet(bool).toString())) ist(st.update({}).state.facet(num).join(), "0") }) it("can specify a dependency on the document", () => { let count = 0 let st = mk(num.compute(["doc"], _ => count++)) ist(st.facet(num).join(), "0") st = st.update({changes: {insert: "hello", from: 0}}).state ist(st.facet(num).join(), "1") st = st.update({}).state ist(st.facet(num).join(), "1") }) it("can specify a dependency on the selection", () => { let count = 0 let st = mk(num.compute(["selection"], _ => count++)) ist(st.facet(num).join(), "0") st = st.update({changes: {insert: "hello", from: 0}}).state ist(st.facet(num).join(), "1") st = st.update({selection: {anchor: 2}}).state ist(st.facet(num).join(), "2") st = st.update({}).state ist(st.facet(num).join(), "2") }) it("can provide multiple values at once", () => { let st = mk(num.computeN(["doc"], s => s.doc.length % 2 ? [100, 10] : []), num.of(1)) ist(st.facet(num).join(), "1") st = st.update({changes: {insert: "hello", from: 0}}).state ist(st.facet(num).join(), "100,10,1") }) it("works with a static combined facet", () => { let f = Facet.define({combine: ns => ns.reduce((a, b) => a + b, 0)}) let st = mk(f.of(1), f.of(2), f.of(3)) ist(st.facet(f), 6) }) it("works with a dynamic combined facet", () => { let f = Facet.define({combine: ns => ns.reduce((a, b) => a + b, 0)}) let st = mk(f.of(1), f.compute(["doc"], s => s.doc.length), f.of(3)) ist(st.facet(f), 4) st = st.update({changes: {insert: "hello", from: 0}}).state ist(st.facet(f), 9) }) it("survives reconfiguration", () => { let st = mk(num.compute(["doc"], s => s.doc.length), num.of(2), str.of("3")) let st2 = st.update({effects: StateEffect.reconfigure.of([num.compute(["doc"], s => s.doc.length), num.of(2)])}).state ist(st.facet(num), st2.facet(num)) ist(st2.facet(str).length, 0) }) it("survives unrelated reconfiguration even without deep-compare", () => { let f = Facet.define({ combine: v => ({count: v.length}) }) let st = mk(f.compute(["doc"], s => s.doc.length), f.of(2)) let st2 = st.update({effects: StateEffect.appendConfig.of(str.of("hi"))}).state ist(st.facet(f), st2.facet(f)) }) it("preserves static facets across reconfiguration", () => { let st = mk(num.of(1), num.of(2), str.of("3")) let st2 = st.update({effects: StateEffect.reconfigure.of([num.of(1), num.of(2)])}).state ist(st.facet(num), st2.facet(num)) }) it("creates newly added fields when reconfiguring", () => { let st = mk(num.of(2)) let events: string[] = [] let field = StateField.define({ create() { events.push("create") return 0 }, update(val: number) { events.push("update " + val) return val + 1 } }) st = st.update({effects: StateEffect.appendConfig.of(field)}).state ist(events.join(", "), "create, update 0") ist(st.field(field), 1) }) it("applies effects from reconfiguring transaction to new fields", () => { let st = mk() let effect = StateEffect.define() let field = StateField.define({ create(state) { return state.facet(num)[0] ?? 0 }, update(val, tr) { return tr.effects.reduce((val, e) => e.is(effect) ? val + e.value : val, val) } }) st = st.update({effects: [ StateEffect.appendConfig.of([field, num.of(10)]), effect.of(5) ]}).state ist(st.field(field), 15) }) it("errors on cyclic dependencies", () => { ist.throws(() => mk(num.compute([str], s => s.facet(str).length), str.compute([num], s => s.facet(num).join())), /cyclic/i) }) it("updates facets computed from static values on reconfigure", () => { let st = mk(num.compute([str], state => state.facet(str).length), str.of("A")) st = st.update({effects: StateEffect.appendConfig.of(str.of("B"))}).state ist(st.facet(num).join(","), "2") ist(st.facet(num), st.update({effects: StateEffect.appendConfig.of(bool.of(false))}).state.facet(num)) }) it("preserves dynamic facet values when dependencies stay the same", () => { let f = Facet.define<{a: number}>() let st1 = mk(f.compute([], state => ({a: 1})), str.of("A")) let st2 = st1.update({effects: StateEffect.appendConfig.of(bool.of(true))}).state ist(st1.facet(f), st2.facet(f)) }) }) state-6.2.0/test/test-rangeset.ts000066400000000000000000000317531435227466100167760ustar00rootroot00000000000000import {ChangeSet, Range, RangeSet, RangeValue, RangeComparator, SpanIterator} from "@codemirror/state" import ist from "ist" class Value extends RangeValue { startSide: number endSide: number point: boolean name: string | null pos: number | null constructor(spec: any = {}, empty: boolean) { super() this.startSide = spec.startSide || 1 this.endSide = spec.endSide || (empty ? 1 : -1) this.point = empty || !!spec.point this.name = spec.name || null this.pos = spec.pos == null ? null : spec.pos } eq(other: RangeValue): boolean { return other instanceof Value && other.name == this.name } static names(v: readonly Value[]): string { let result = [] for (let val of v) if (val.name || val.point) result.push(val.name || "POINT") return result.join("/") } } function cmp(a: Range, b: Range) { return a.from - b.from } function mk(from: number, to?: any, spec?: any): Range { if (typeof to != "number") { spec = to; to = from } if (typeof spec == "string") spec = {name: spec} return new Value(spec, from == to).range(from, to) } function mkSet(ranges: Range[]) { return RangeSet.of(ranges) } function changeSet(changes: [number, number, number][]) { let collect: any[] = [] for (let [from, to, len] of changes) { if (len) collect.push({insert: "x".repeat(len), from, to}) if (from < to) collect.push({from, to}) } return ChangeSet.of(collect, 5100) } let smallRanges: Range[] = [] for (let i = 0; i < 5000; i++) smallRanges.push(mk(i, i + 1 + (i % 4), {pos: i})) let _set0: RangeSet | null = null function set0() { return _set0 || (_set0 = mkSet(smallRanges)) } function checkSet(set: RangeSet) { let count = 0 set.between(0, set.length, (from, _, value) => { count++ if (value.pos != null) ist(from, value.pos) }) ist(count, set.size) } describe("RangeSet", () => { it("divides a set into chunks and layers", () => { let set = mkSet(smallRanges.concat([mk(1000, 4000, {pos: 1000}), mk(2000, 3000, {pos: 2000})]).sort(cmp)) ist(set.size, 5002) ist(set.chunk.length, 1, ">") ist(set.nextLayer.size) checkSet(set) }) it("complains about misordered ranges", () => { ist.throws(() => mkSet([mk(8, 9), mk(7, 10)]), /sorted/) ist.throws(() => mkSet([mk(1, 1, {startSide: 1}), mk(1, 1, {startSide: -1})]), /sorted/) }) describe("update", () => { it("can add ranges", () => { let set = set0().update({add: [mk(4000, {pos: 4000})]}) ist(set.size, 5001) ist(set.chunk[0], set0().chunk[0]) }) it("can add a large amount of ranges", () => { let ranges = [] for (let i = 0; i < 4000; i += 2) ranges.push(mk(i)) let set = set0().update({add: ranges}) ist(set.size, 2000 + set0().size) checkSet(set) }) it("can filter ranges", () => { let set = set0().update({filter: from => from >= 2500}) ist(set.size, 2500) ist(set.chunk.length, set0().chunk.length, "<") checkSet(set) }) it("can filter all over", () => { let set = set0().update({filter: from => (from % 200) >= 100}) ist(set.size, 2500) checkSet(set) }) it("collapses the chunks when removing almost all ranges", () => { let set = set0().update({filter: from => from == 500 || from == 501}) ist(set.size, 2) ist(set.chunk.length, 1) }) it("calls filter on precisely those ranges touching the filter range", () => { let ranges = [] for (let i = 0; i < 1000; i++) ranges.push(mk(i, i + 1, {pos: i})) let set = mkSet(ranges) let called: [number, number][] = [] set.update({filter: (from, to) => (called.push([from, to]), true), filterFrom: 400, filterTo: 600}) ist(called.length, 202) for (let i = 399, j = 0; i <= 600; i++, j++) ist(called[j].join(), `${i},${i+1}`) }) it("returns the empty set when filter removes everything", () => { ist(set0().update({filter: () => false}), RangeSet.empty) }) }) describe("map", () => { function test(positions: Range[], changes: [number, number, number][], newPositions: (number | [number, number])[]) { let set = mkSet(positions) let mapped = set.map(changeSet(changes)) let out: string[] = [] for (let iter = mapped.iter(); iter.value; iter.next()) out.push(iter.from + "-" + iter.to) ist(JSON.stringify(out), JSON.stringify(newPositions.map(p => Array.isArray(p) ? p[0] + "-" + p[1] : p + "-" + p))) } it("can map through changes", () => test([mk(1), mk(4), mk(10)], [[0, 0, 1], [2, 3, 0], [8, 8, 20]], [2, 4, 30])) it("takes inclusivity into account", () => test([mk(1, 2, {startSide: -1, endSide: 1})], [[1, 1, 2], [2, 2, 2]], [[1, 6]])) it("uses side to determine mapping of points", () => test([mk(1, 1, {startSide: -1, endSide: -1}), mk(1, 1, {startSide: 1, endSide: 1})], [[1, 1, 2]], [1, 3])) it("defaults to exclusive on both sides", () => test([mk(1, 2)], [[1, 1, 2], [4, 4, 2]], [[3, 4]])) it("drops point ranges", () => test([mk(1, 2)], [[1, 2, 0], [1, 1, 1]], [])) it("drops ranges in deleted regions", () => test([mk(1, 2), mk(3)], [[0, 4, 0]], [])) it("shrinks ranges", () => test([mk(2, 4), mk(2, 8), mk(6, 8)], [[3, 7, 0]], [[2, 3], [2, 4], [3, 4]])) it("leaves point ranges on change boundaries", () => test([mk(2), mk(4)], [[2, 4, 6]], [2, 8])) it("can collapse chunks", () => { let smaller = set0().map(changeSet([[30, 4500, 0]])) ist(smaller.chunk.length, set0().chunk.length, "<") let empty = smaller.map(changeSet([[0, 1000, 0]])) ist(empty, RangeSet.empty) }) }) class Comparator implements RangeComparator { ranges: number[] = [] addRange(from: number, to: number) { if (this.ranges.length && this.ranges[this.ranges.length - 1] == from) this.ranges[this.ranges.length - 1] = to else this.ranges.push(from, to) } compareRange(from: number, to: number) { this.addRange(from, to) } comparePoint(from: number, to: number) { this.addRange(from, to) } } describe("compare", () => { function test(ranges: RangeSet | Range[], update: any, changes: number[]) { let set = Array.isArray(ranges) ? mkSet(ranges) : ranges let newSet = set, docChanges = changeSet(update.changes || []) if (update.changes) newSet = newSet.map(docChanges) if (update.filter || update.add) newSet = newSet.update(update) if (update.prepare) update.prepare(newSet) let comp = new Comparator RangeSet.compare([set], [newSet], docChanges, comp) ist(JSON.stringify(comp.ranges), JSON.stringify(changes)) } it("notices added ranges", () => test([mk(2, 4, "a"), mk(8, 11, "a")], { add: [mk(3, 9, "b"), mk(106, 107, "b")] }, [3, 9, 106, 107])) it("notices deleted ranges", () => test([mk(4, 6, "a"), mk(5, 7, "b"), mk(6, 8, "c"), mk(20, 30, "d")], { filter: (from: number) => from != 5 && from != 20 }, [5, 7, 20, 30])) it("recognizes identical ranges", () => test([mk(0, 50, "a")], { add: [mk(10, 40, "a")], filter: () => false }, [0, 10, 40, 50])) it("skips changes", () => test([mk(0, 20, "a")], { changes: [[5, 15, 20]], filter: () => false }, [0, 5, 25, 30])) it("ignores identical sub-nodes", () => { let ranges = [] for (let i = 0; i < 1000; i++) ranges.push(mk(i, i + 1, "a")) test(ranges, { changes: [[900, 1000, 0]], add: [mk(850, 860, "b")], prepare: (set: RangeSet) => Object.defineProperty(set.chunk[0], "value", {get() { throw new Error("NO TOUCH") }}) }, [850, 860]) }) it("ignores changes in points", () => { let ranges = [mk(3, 997, {point: true})] for (let i = 0; i < 1000; i += 2) ranges.push(mk(i, i + 1, "a")) let set = mkSet(ranges.sort(cmp)) test(set, { changes: [[300, 500, 100]] }, []) }) it("notices adding a point", () => { test([mk(3, 50, {point: true})], { add: [mk(40, 80, {point: true})] }, [50, 80]) }) it("notices removing a point", () => { test([mk(3, 50, {point: true})], { filter: () => false }, [3, 50]) }) it("can handle multiple changes", () => { let ranges = [] for (let i = 0; i < 200; i += 2) { let end = i + 1 + Math.ceil(i / 50) ranges.push(mk(i, end, `${i}-${end}`)) } test(ranges, { changes: [[0, 0, 50], [50, 100, 0], [150, 200, 0]], filter: (from: number) => from % 50 > 0 }, [50, 51, 100, 103, 150, 153]) }) it("reports point decorations with different cover", () => { test([ mk(0, 4, {startSide: 1, endSide: -1}), mk(1, 3, {point: true, startSide: -1, endSide: 1}) ], { changes: [[2, 4, 0]] }, [1, 2]) }) }) describe("spans", () => { class Builder implements SpanIterator { spans: string[] = [] span(from: number, to: number, active: readonly Value[]) { let name = Value.names(active) this.spans.push((to - from) + (name ? "=" + name : "")) } point(from: number, to: number, value: Value) { this.spans.push((to > from ? (to - from) + "=" : "") + (value.name ? "[" + value.name + "]" : "ø")) } } function test(set: RangeSet | RangeSet[], start: number, end: number, expected: string) { let builder = new Builder RangeSet.spans(Array.isArray(set) ? set : [set], start, end, builder) ist(builder.spans.join(" "), expected) } it("separates the range in covering spans", () => { test(mkSet([mk(3, 8, "one"), mk(5, 8, "two"), mk(10, 12, "three")]), 0, 15, "3 2=one 3=one/two 2 2=three 3") }) it("can retrieve a limited range", () => { let decos = [mk(0, 200, "wide")] for (let i = 0; i < 100; i++) decos.push(mk(i * 2, i * 2 + 2, "span" + i)) let set = mkSet(decos), start = 20, end = start + 6 let expected = "" for (let pos = start; pos < end; pos += (pos % 2 ? 1 : 2)) expected += (expected ? " " : "") + (Math.min(end, pos + (pos % 2 ? 1 : 2)) - pos) + "=wide/span" + Math.floor(pos / 2) test(set, start, end, expected) }) it("reads from multiple sets at once", () => { let one = mkSet([mk(2, 3, "x"), mk(5, 10, "y"), mk(10, 12, "z")]) let two = mkSet([mk(0, 6, "a"), mk(10, 12, "b")]) test([one, two], 0, 12, "2=a 1=x/a 2=a 1=y/a 4=y 2=z/b") }) it("orders active ranges by origin set", () => { let one = mkSet([mk(2, 10, "a"), mk(20, 30, "a")]) let two = mkSet([mk(3, 4, "b"), mk(8, 12, "b"), mk(18, 22, "b")]) let three = mkSet([mk(0, 25, "c")]) test([one, two, three], 0, 25, "2=c 1=a/c 1=a/b/c 4=a/c 2=a/b/c 2=b/c 6=c 2=b/c 2=a/b/c 3=a/c") }) it("doesn't get confused by same-place points", () => { test(mkSet([mk(1, "a"), mk(1, "b"), mk(1, "c")]), 0, 2, "1 [a] [b] [c] 1") }) it("properly resyncs active ranges after points", () => { test(mkSet([mk(0, 20, "r1"), mk(1, 10, "r2"), mk(3, 12, {name: "p", point: true}), mk(4, 8, "r3"), mk(5, 20, "r4")]), 0, 20, "1=r1 2=r1/r2 9=[p] 8=r1/r4") }) it("doesn't split spans on ignored ranges", () => { let ranges: number[] = [] RangeSet.spans([mkSet([mk(0, 10, "a"), mk(20, 30, {name: "b", point: true})])], 0, 30, { span(from, to) { ranges.push(from, to) }, point(from, to) { ranges.push(from, to) }, }, 0) ist(ranges.join(), "0,20,20,30") }) it("omits points that are covered by the previous point", () => { let points = 0 RangeSet.spans([mkSet([mk(0, 4, {point: true}), mk(1, 5, {name: "a"}), mk(2, 4, {point: true})])], 0, 10, { span() {}, point() { points++ } }) ist(points, 1) }) }) describe("iter", () => { it("iterates over ranges", () => { const set = mkSet(smallRanges.concat([mk(1000, 4000, {pos: 1000}), mk(2000, 3000, {pos: 2000})]).sort(cmp)) let count = 0 for(let iter = set.iter(); iter.value; iter.next(), count++) { ist(iter.from, count > 2001 ? count - 2 : (count > 1000 ? count - 1 : count)) } ist(count, 5002) }) it("can iterate over a subset", () => { let count = 0 for (let iter = set0().iter(1000); iter.value; iter.next(), count++) { if (iter.from > 2000) break ist(iter.to, iter.from + 1 + (iter.from % 4)) } ist(count, 1003) }) }) describe("between", () => { it("iterates over ranges", () => { let found = 0 set0().between(100, 200, (from, to) => { ist(to, from + 1 + (from % 4)) ist(to, 100, ">=") ist(from, 200, "<=") found++ }) ist(found, 103) }) it("returns ranges in a zero-length set", () => { let set = RangeSet.of([mk(0, 0)]), found: number[] = [] set.between(0, 0, (from, to) => { found.push(from, to) }) ist(found.toString(), "0,0") }) }) }) state-6.2.0/test/test-selection.ts000066400000000000000000000030701435227466100171420ustar00rootroot00000000000000import ist from "ist" import {EditorSelection} from "@codemirror/state" describe("EditorSelection", () => { it("stores ranges with a primary range", () => { let sel = EditorSelection.create([EditorSelection.range(0, 1), EditorSelection.range(3, 2), EditorSelection.range(4, 5)], 1) ist(sel.main.from, 2) ist(sel.main.to, 3) ist(sel.main.anchor, 3) ist(sel.main.head, 2) ist(sel.ranges.map(r => r.anchor + "/" + r.head).join(","), "0/1,3/2,4/5") }) it("merges and sorts ranges when normalizing", () => { let sel = EditorSelection.create([ EditorSelection.range(10, 12), EditorSelection.range(6, 7), EditorSelection.range(4, 5), EditorSelection.range(3, 4), EditorSelection.range(0, 6), EditorSelection.range(7, 8), EditorSelection.range(9, 13), EditorSelection.range(13, 14) ]) ist(sel.ranges.map(r => r.anchor + "/" + r.head).join(","), "0/6,6/7,7/8,9/13,13/14") }) it("merges adjacent point ranges when normalizing", () => { let sel = EditorSelection.create([ EditorSelection.range(10, 12), EditorSelection.range(12, 12), EditorSelection.range(12, 12), EditorSelection.range(10, 10), EditorSelection.range(8, 10) ]) ist(sel.ranges.map(r => r.anchor + "/" + r.head).join(","), "8/10,10/12") }) it("preserves the direction of the last range when merging ranges", () => { let sel = EditorSelection.create([EditorSelection.range(0, 2), EditorSelection.range(10, 1)]) ist(sel.ranges.map(r => r.anchor + "/" + r.head).join(","), "10/0") }) }) state-6.2.0/test/test-state.ts000066400000000000000000000270531435227466100163040ustar00rootroot00000000000000import ist from "ist" import {EditorState, StateField, Facet, Compartment, StateEffect, EditorSelection, Annotation} from "@codemirror/state" describe("EditorState", () => { it("holds doc and selection properties", () => { let state = EditorState.create({doc: "hello"}) ist(state.doc.toString(), "hello") ist(state.selection.main.from, 0) }) it("can apply changes", () => { let state = EditorState.create({doc: "hello"}) let transaction = state.update({changes: [{from: 2, to: 4, insert: "w"}, {from: 5, insert: "!"}]}) ist(transaction.state.doc.toString(), "hewo!") }) it("maps selection through changes", () => { let state = EditorState.create({doc: "abcdefgh", extensions: [EditorState.allowMultipleSelections.of(true)], selection: EditorSelection.create([0, 4, 8].map(n => EditorSelection.cursor(n)))}) let newState = state.update(state.replaceSelection("Q")).state ist(newState.doc.toString(), "QabcdQefghQ") ist(newState.selection.ranges.map(r => r.from).join("/"), "1/6/11") }) const someAnnotation = Annotation.define() it("can store annotations on transactions", () => { let tr = EditorState.create({doc: "foo"}).update({annotations: someAnnotation.of(55)}) ist(tr.annotation(someAnnotation), 55) }) it("throws when a change's bounds are invalid", () => { let state = EditorState.create({doc: "1234"}) ist.throws(() => state.update({changes: {from: -1, to: 1}})) ist.throws(() => state.update({changes: {from: 2, to: 1}})) ist.throws(() => state.update({changes: {from: 2, to: 10, insert: "x"}})) }) it("stores and updates tab size", () => { let deflt = EditorState.create({}), two = EditorState.create({extensions: [EditorState.tabSize.of(2)]}) ist(deflt.tabSize, 4) ist(two.tabSize, 2) let updated = deflt.update({effects: StateEffect.reconfigure.of(EditorState.tabSize.of(8))}).state ist(updated.tabSize, 8) }) it("stores and updates the line separator", () => { let deflt = EditorState.create({}), crlf = EditorState.create({extensions: [EditorState.lineSeparator.of("\r\n")]}) ist(deflt.facet(EditorState.lineSeparator), null) ist(deflt.toText("a\nb").lines, 2) ist(crlf.facet(EditorState.lineSeparator), "\r\n") ist(crlf.toText("a\nb").lines, 1) let updated = crlf.update({effects: StateEffect.reconfigure.of(EditorState.lineSeparator.of("\n"))}).state ist(updated.facet(EditorState.lineSeparator), "\n") }) it("stores and updates fields", () => { let field1 = StateField.define({create: () => 0, update: val => val + 1}) let field2 = StateField.define({create: state => state.field(field1) + 10, update: val => val}) let state = EditorState.create({extensions: [field1, field2]}) ist(state.field(field1), 0) ist(state.field(field2), 10) let newState = state.update({}).state ist(newState.field(field1), 1) ist(newState.field(field2), 10) }) it("allows fields to have an initializer", () => { let field = StateField.define({create: () => 0, update: val => val + 1}) let state = EditorState.create({extensions: field.init(() => 10)}) ist(state.field(field), 10) ist(state.update({}).state.field(field), 11) }) it("can be serialized to JSON", () => { let field = StateField.define<{n: number}>({ create() { return {n: 0} }, update({n}) { return {n: n + 1} }, toJSON(v) { return {number: v.n} }, fromJSON(j) { return {n: j.number} } }) let fields = {f: field} let state = EditorState.create({extensions: field}).update({}).state let json = state.toJSON(fields) ist(JSON.stringify(json.f), '{"number":1}') let state2 = EditorState.fromJSON(json, {}, fields) ist(JSON.stringify(state2.field(field)), '{"n":1}') }) it("can preserve fields across reconfiguration", () => { let field = StateField.define({create: () => 0, update: val => val + 1}) let start = EditorState.create({extensions: [field]}).update({}).state ist(start.field(field), 1) ist(start.update({effects: StateEffect.reconfigure.of(field)}).state.field(field), 2) ist(start.update({effects: StateEffect.reconfigure.of([])}).state.field(field, false), undefined) }) it("can replace extension groups", () => { let comp = new Compartment, f = Facet.define(), content = f.of(10) let state = EditorState.create({extensions: [comp.of(content), f.of(20)]}) ist(comp.get(state), content) ist(state.facet(f).join(), "10,20") let content2 = [f.of(1), f.of(2)] let state2 = state.update({effects: comp.reconfigure(content2)}).state ist(comp.get(state2), content2) ist(state2.facet(f).join(), "1,2,20") let state3 = state2.update({effects: comp.reconfigure(f.of(3))}).state ist(state3.facet(f).join(), "3,20") }) it("raises an error on duplicate extension groups", () => { let comp = new Compartment, f = Facet.define() ist.throws(() => EditorState.create({extensions: [comp.of(f.of(1)), comp.of(f.of(2))]}), /duplicate use of compartment/i) ist.throws(() => EditorState.create({extensions: comp.of(comp.of(f.of(1)))}), /duplicate use of compartment/i) }) it("preserves compartments on reconfigure", () => { let comp = new Compartment, f = Facet.define(), init = comp.of(f.of(10)) let state = EditorState.create({extensions: [init, f.of(20)]}) state = state.update({effects: comp.reconfigure(f.of(0))}).state ist(state.facet(f).join(), "0,20") state = state.update({effects: StateEffect.reconfigure.of([init, f.of(2)])}).state ist(state.facet(f).join(), "0,2") }) it("forgets dropped compartments", () => { let comp = new Compartment, f = Facet.define(), init = comp.of(f.of(10)) let state = EditorState.create({extensions: [init, f.of(20)]}) state = state.update({effects: comp.reconfigure(f.of(0))}).state ist(state.facet(f).join(), "0,20") state = state.update({effects: StateEffect.reconfigure.of(f.of(2))}).state ist(state.facet(f).join(), "2") ist(comp.get(state), undefined) state = state.update({effects: StateEffect.reconfigure.of([init, f.of(2)])}).state ist(state.facet(f).join(), "10,2") }) it("allows facets computed from fields", () => { let field = StateField.define({create: () => [0], update: (v, tr) => tr.docChanged ? [tr.state.doc.length] : v}) let facet = Facet.define() let state = EditorState.create({ extensions: [field, facet.compute([field], state => state.field(field)[0]), facet.of(1)] }) ist(state.facet(facet).join(), "0,1") let state2 = state.update({}).state ist(state2.facet(facet), state.facet(facet)) let state3 = state.update({changes: {insert: "hi", from: 0}}).state ist(state3.facet(facet).join(), "2,1") }) describe("changeByRange", () => { it("can make simple changes", () => { let state = EditorState.create({doc: "hi"}) state = state.update(state.changeByRange(r => ({changes: {from: r.from, to: r.from + 1, insert: "q"}, range: EditorSelection.cursor(r.from + 1)}))).state ist(state.doc.toString(), "qi") ist(state.selection.main.from, 1) }) it("does the right thing when there are multiple selections", () => { let state = EditorState.create({ doc: "1 2 3 4", selection: EditorSelection.create([EditorSelection.range(0, 1), EditorSelection.range(2, 3), EditorSelection.range(4, 5), EditorSelection.range(6, 7)]), extensions: EditorState.allowMultipleSelections.of(true) }) state = state.update(state.changeByRange(r => ({changes: {from: r.from, to: r.to, insert: "-".repeat((r.from >> 1) + 1)}, range: EditorSelection.range(r.from, r.from + 1 + (r.from >> 1))}))).state ist(state.doc.toString(), "- -- --- ----") ist(state.selection.ranges.map(r => r.from + "-" + r.to).join(" "), "0-1 2-4 5-8 9-13") }) }) describe("changeFilter", () => { it("can cancel changes", () => { // Cancels all changes that add length let state = EditorState.create({extensions: [ EditorState.changeFilter.of(({changes}) => changes.newLength <= changes.length) ], doc: "one two"}) let tr1 = state.update({changes: {from: 3, insert: " three"}, selection: {anchor: 13}}) ist(tr1.state.doc.toString(), "one two") ist(tr1.state.selection.main.head, 7) let tr2 = state.update({changes: {from: 4, to: 7, insert: "2"}}) ist(tr2.state.doc.toString(), "one 2") }) it("can split changes", () => { // Disallows changes in the middle third of the document let state = EditorState.create({extensions: [ EditorState.changeFilter.of(tr => [Math.floor(tr.startState.doc.length / 3), Math.floor(2 * tr.startState.doc.length / 3)]) ], doc: "onetwo"}) ist(state.update({changes: {from: 0, to: 6}}).state.doc.toString(), "et") }) it("combines filter masks", () => { let state = EditorState.create({extensions: [ EditorState.changeFilter.of(() => [0, 2]), EditorState.changeFilter.of(() => [4, 6]) ], doc: "onetwo"}) ist(state.update({changes: {from: 0, to: 6}}).state.doc.toString(), "onwo") }) it("can be turned off", () => { let state = EditorState.create({extensions: [EditorState.changeFilter.of(() => false)]}) ist(state.update({changes: {from: 0, insert: "hi"}}).state.doc.length, 0) ist(state.update({changes: {from: 0, insert: "hi"}, filter: false}).state.doc.length, 2) }) }) describe("transactionFilter", () => { it("can constrain the selection", () => { let state = EditorState.create({ extensions: EditorState.transactionFilter.of(tr => { if (tr.selection && tr.selection.main.to > 4) return [tr, {selection: {anchor: 4}}] else return tr }), doc: "one two" }) ist(state.update({selection: {anchor: 3}}).selection!.main.to, 3) ist(state.update({selection: {anchor: 7}}).selection!.main.to, 4) }), it("can append sequential changes", () => { let state = EditorState.create({ extensions: EditorState.transactionFilter.of(tr => { return [tr, {changes: {from: tr.changes.newLength, insert: "!"}, sequential: true}] }), doc: "one two" }) ist(state.update({changes: {from: 3, insert: ","}}).state.doc.toString(), "one, two!") }) }) describe("transactionExtender", () => { it("can add annotations", () => { let ann = Annotation.define() let state = EditorState.create({ extensions: EditorState.transactionExtender.of(() => ({annotations: ann.of(100)})) }) let tr = state.update({changes: {from: 0, insert: "!"}}) ist(tr.annotation(ann), 100) let trNoFilter = state.update({changes: {from: 0, insert: "!"}, filter: false}) ist(trNoFilter.annotation(ann), 100) }) it("allows multipe extenders to take effect", () => { let eff = StateEffect.define() let state = EditorState.create({ extensions: [ EditorState.transactionExtender.of(() => ({effects: eff.of(1)})), EditorState.transactionExtender.of(() => ({effects: eff.of(2)})) ] }) let tr = state.update({scrollIntoView: true}) ist(tr.effects.map(e => e.is(eff) ? e.value : 0).join(), "2,1") }) }) }) state-6.2.0/test/test-text.ts000066400000000000000000000172731435227466100161530ustar00rootroot00000000000000import {Text} from "@codemirror/state" import ist from "ist" function depth(node: Text): number { return !node.children ? 1 : 1 + Math.max(...node.children.map(depth)) } const line = "1234567890".repeat(10) const lines = new Array(200).fill(line), text0 = lines.join("\n") const doc0 = Text.of(lines) describe("Text", () => { it("handles basic replacement", () => { let doc = Text.of(["one", "two", "three"]) ist(doc.replace(2, 5, Text.of(["foo", "bar"])).toString(), "onfoo\nbarwo\nthree") }) it("can append documents", () => { ist(Text.of(["one", "two", "three"]).append(Text.of(["!", "ok"])).toString(), "one\ntwo\nthree!\nok") }) it("preserves length", () => { ist(doc0.length, text0.length) }) it("creates a balanced tree when loading a document", () => { let doc = Text.of(new Array(2000).fill(line)), d = depth(doc) ist(d, 2, "<=") }) it("rebalances on insert", () => { let doc = doc0 let insert = "abc".repeat(200), at = Math.floor(doc.length / 2) for (let i = 0; i < 10; i++) doc = doc.replace(at, at, Text.of([insert])) ist(depth(doc), 2, "<=") ist(doc.toString(), text0.slice(0, at) + "abc".repeat(2000) + text0.slice(at)) }) it("collapses on delete", () => { let doc = doc0.replace(10, text0.length - 10, Text.empty) ist(depth(doc), 1) ist(doc.length, 20) ist(doc.toString(), line.slice(0, 20)) }) it("handles deleting at start", () => { ist(Text.of(lines.slice(0, -1).concat([line + "!"])).replace(0, 9500, Text.empty).toString(), text0.slice(9500) + "!") }) it("handles deleting at end", () => { ist(Text.of(["?" + line].concat(lines.slice(1))).replace(9500, text0.length + 1, Text.empty).toString(), "?" + text0.slice(0, 9499)) }) it("can handle deleting the entire document", () => { ist(doc0.replace(0, doc0.length, Text.empty).toString(), "") }) it("can insert on node boundaries", () => { let doc = doc0, pos = doc.children![0].length ist(doc.replace(pos, pos, Text.of(["abc"])).slice(pos, pos + 3).toString(), "abc") }) it("can build up a doc by repeated appending", () => { let doc = Text.of([""]), text = "" for (let i = 1; i < 1000; ++i) { let add = "newtext" + i + " " doc = doc.replace(doc.length, doc.length, Text.of([add])) text += add } ist(doc.toString(), text) }) it("properly maintains content during editing", () => { let str = text0, doc = doc0 for (let i = 0; i < 200; i++) { let insPos = Math.floor(Math.random() * doc.length) let insChar = String.fromCharCode("A".charCodeAt(0) + Math.floor(Math.random() * 26)) str = str.slice(0, insPos) + insChar + str.slice(insPos) doc = doc.replace(insPos, insPos, Text.of([insChar])) let delFrom = Math.floor(Math.random() * doc.length) let delTo = Math.min(doc.length, delFrom + Math.floor(Math.random() * 20)) str = str.slice(0, delFrom) + str.slice(delTo) doc = doc.replace(delFrom, delTo, Text.empty) } ist(doc.toString(), str) }) it("returns the correct strings for slice", () => { let text = [] for (let i = 0; i < 1000; i++) text.push("0".repeat(4 - String(i).length) + i) let doc = Text.of(text) let str = text.join("\n") for (let i = 0; i < 400; i++) { let start = i == 0 ? 0 : Math.floor(Math.random() * doc.length) let end = i == 399 ? doc.length : start + Math.floor(Math.random() * (doc.length - start)) start = 4150; end = 4160 ist(doc.slice(start, end).toString(), str.slice(start, end)) } }) it("can be compared", () => { let doc = doc0, doc2 = Text.of(lines) ist(doc.eq(doc)) ist(doc.eq(doc2)) ist(doc2.eq(doc)) ist(!doc.eq(doc2.replace(5000, 5000, Text.of(["y"])))) ist(!doc.eq(doc2.replace(5000, 5001, Text.of(["y"])))) ist(doc.eq(doc.replace(5000, 5001, doc.slice(5000, 5001)))) ist(!doc.eq(doc.replace(5000, 5001, Text.of(["y"])))) }) it("can be compared despite different tree shape", () => { ist(doc0.replace(100, 201, Text.of(["abc"])).eq(Text.of([line + "abc"].concat(lines.slice(2))))) }) it("can compare small documents", () => { ist(Text.of(["foo", "bar"]).eq(Text.of(["foo", "bar"]))) ist(!Text.of(["foo", "bar"]).eq(Text.of(["foo", "baz"]))) }) it("is iterable", () => { for (let iter = doc0.iter(), build = "";;) { let {value, lineBreak, done} = iter.next() if (done) { ist(build, text0) break } if (lineBreak) { build += "\n" } else { ist(value.indexOf("\n"), -1) build += value } } }) it("is iterable in reverse", () => { let found = "" for (let iter = doc0.iter(-1); !iter.next().done;) found = iter.value + found ist(found, text0) }) it("allows negative skip values in iteration", () => { let iter = Text.of(["one", "two", "three", "four"]).iter() ist(iter.next(12).value, "e") ist(iter.next(-12).value, "ne") ist(iter.next(12).value, "our") ist(iter.next(-1000).value, "one") }) it("is partially iterable", () => { let found = "" for (let iter = doc0.iterRange(500, doc0.length - 500); !iter.next().done;) found += iter.value ist(JSON.stringify(found), JSON.stringify(text0.slice(500, text0.length - 500).toString())) }) it("is partially iterable in reverse", () => { let found = "" for (let iter = doc0.iterRange(doc0.length - 500, 500); !iter.next().done;) found = iter.value + found ist(found, text0.slice(500, text0.length - 500).toString()) }) it("can partially iter over subsections at the start and end", () => { ist(doc0.iterRange(0, 1).next().value, "1") ist(doc0.iterRange(1, 2).next().value, "2") ist(doc0.iterRange(doc0.length - 1, doc0.length).next().value, "0") ist(doc0.iterRange(doc0.length - 2, doc0.length - 1).next().value, "9") }) it("can iterate over lines", () => { let doc = Text.of(["ab", "cde", "", "", "f", "", "g"]) function get(from?: number, to?: number) { let result = [] for (let i = doc.iterLines(from, to); !i.next().done;) result.push(i.value) return result.join("\n") } ist(get(), "ab\ncde\n\n\nf\n\ng") ist(get(1, doc.lines + 1), "ab\ncde\n\n\nf\n\ng") ist(get(2, 3), "cde") ist(get(1, 1), "") ist(get(2, 1), "") ist(get(3), "\n\nf\n\ng") }) it("can convert to JSON", () => { for (let i = 0; i < 200; i++) lines.push("line " + i) let text = Text.of(lines) ist(Text.of(text.toJSON()).eq(text)) }) it("can get line info by line number", () => { ist.throws(() => doc0.line(0), /Invalid line/) ist.throws(() => doc0.line(doc0.lines + 1), /Invalid line/) for (let i = 1; i < doc0.lines; i += 5) { let l = doc0.line(i) ist(l.from, (i - 1) * 101) ist(l.to, i * 101 - 1) ist(l.number, i) ist(l.text, line) } }) it("can get line info by position", () => { ist.throws(() => doc0.lineAt(-10), /Invalid position/) ist.throws(() => doc0.lineAt(doc0.length + 1), /Invalid position/) for (let i = 0; i < doc0.length; i += 5) { let l = doc0.lineAt(i) ist(l.from, i - (i % 101)) ist(l.to, i - (i % 101) + 100) ist(l.number, Math.floor(i / 101) + 1) ist(l.text, line) } }) it("can delete a range at the start of a child node", () => { ist(doc0.replace(0, 100, Text.of(["x"])).toString(), "x" + text0.slice(100)) }) it("can retrieve pieces of text", () => { for (let i = 0; i < 500; i++) { let from = Math.floor(Math.random() * (doc0.length - 1)) let to = Math.random() < .5 ? from + 2 : from + Math.floor(Math.random() * (doc0.length - 1 - from)) + 1 ist(doc0.sliceString(from, to), text0.slice(from, to)) ist(doc0.slice(from, to).toString(), text0.slice(from, to)) } }) })