pax_global_header00006660000000000000000000000064141354473270014524gustar00rootroot0000000000000052 comment=ce7fbbba5b023a3cfe7c74d14667611eb93593ee prosemirror-model-1.15.0/000077500000000000000000000000001413544732700152715ustar00rootroot00000000000000prosemirror-model-1.15.0/.gitignore000066400000000000000000000000371413544732700172610ustar00rootroot00000000000000/node_modules .tern-port /dist prosemirror-model-1.15.0/.npmignore000066400000000000000000000000371413544732700172700ustar00rootroot00000000000000/node_modules .tern-port /test prosemirror-model-1.15.0/.npmrc000066400000000000000000000000231413544732700164040ustar00rootroot00000000000000package-lock=false prosemirror-model-1.15.0/.tern-project000066400000000000000000000001571413544732700177110ustar00rootroot00000000000000{ "libs": ["browser"], "plugins": { "node": {}, "complete_strings": {}, "es_modules": {} } } prosemirror-model-1.15.0/CHANGELOG.md000066400000000000000000000563011413544732700171070ustar00rootroot00000000000000## 1.15.0 (2021-10-25) ### New features `textBetween` now allows its leaf text argument to be a function. ## 1.14.3 (2021-07-22) ### Bug fixes `DOMSerializer.serializeNode` will no longer ignore the node's marks. ## 1.14.2 (2021-06-16) ### Bug fixes Be less agressive about dropping whitespace when the context isn't know in `DOMParser.parseSlice`. ## 1.14.1 (2021-04-26) ### Bug fixes DOM parsing with `preserveWhitespace: "full"` will no longer ignore whitespace-only nodes. ## 1.14.0 (2021-04-06) ### Bug fixes `Node.check` will now error if a node has an invalid combination of marks. Don't leave carriage return characters in parsed DOM content, since they confuse Chrome's cursor motion. ### New features `Fragment.textBetween` is now public. ## 1.13.3 (2021-02-04) ### Bug fixes Fix an issue where nested tags that match mark parser rules could cause the parser to apply marks in invalid places. ## 1.13.2 (2021-02-04) ### Bug fixes `MarkType.removeFromSet` now removes all instances of the mark, not just the first one. ## 1.13.1 (2020-12-20) ### Bug fixes Fix a bug where nested marks of the same type would be applied to the wrong node when parsing from DOM. ## 1.13.0 (2020-12-11) ### New features Parse rules can now have a `consuming: false` property which allows other rules to match their tag or style even when they apply. ## 1.12.0 (2020-10-11) ### New features The output of `toDOM` functions can now be a `{dom, contentDOM}` object specifying the precise parent and content DOM elements. ## 1.11.2 (2020-09-12) ### Bug fixes Fix issue where 1.11.1 uses an array method not available on Internet Explorer. ## 1.11.1 (2020-09-11) ### Bug fixes Fix an issue where an inner node's mark information could reset the same mark provided by an outer node in the DOM parser. ## 1.11.0 (2020-07-08) ### New features Resolved positions have a new convenience method, `posAtIndex`, which can resolve a depth and index to a position. ## 1.10.1 (2020-07-08) ### Bug fixes Fix a bug that prevented non-canonical list structure from being normalized. ## 1.10.0 (2020-05-25) ### Bug fixes Avoid fixing directly nested list nodes during DOM parsing when it looks like the schema allows those. ### New features DOM parser rules can now specify `closeParent: true` to have the effect of closing their parent node when matched. ## 1.9.1 (2020-01-17) ### Bug fixes Marks found in the DOM at the wrong level (for example, a bold style on a block node) are now properly moved to the node content. ## 1.9.0 (2020-01-07) ### New features The `NodeType` method [`hasRequiredAttrs`](https://prosemirror.net/docs/ref/#model.NodeType.hasRequiredAttrs) is now public. Element and attribute names in [`DOMOutputSpec`](https://prosemirror.net/docs/ref/#model.DOMOutputSpec) structures can now contain namespaces. ## 1.8.2 (2019-11-20) ### Bug fixes Rename ES module files to use a .js extension, since Webpack gets confused by .mjs ## 1.8.1 (2019-11-19) ### Bug fixes The file referred to in the package's `module` field now is compiled down to ES5. ## 1.8.0 (2019-11-08) ### New features Add a `module` field to package json file. Add a `module` field to package json file. Add a `module` field to package json file. Add a `module` field to package json file. Add a `module` field to package json file. Add a `module` field to package json file. Add a `module` field to package json file. Add a `module` field to package json file. Add a `module` field to package json file. Add a `module` field to package json file. Add a `module` field to package json file. Add a `module` field to package json file. Add a `module` field to package json file. Add a `module` field to package json file. Add a `module` field to package json file. Add a `module` field to package json file. Add a `module` field to package json file. ## 1.7.5 (2019-11-07) ### Bug fixes `ContentMatch.edge` now throws, as it is supposed to, when you try to access the edge past the last one. ## 1.7.4 (2019-10-10) ### Bug fixes Fix an issue where `fillBefore` would in some cases insert unneccesary optional child nodes in the generated content. ## 1.7.3 (2019-10-03) ### Bug fixes Fix an issue where _any_ whitespace (not just the characters that HTML collapses) was collapsed by the parser in non-whitespace-preserving mode. ## 1.7.2 (2019-09-04) ### Bug fixes When `
` DOM nodes can't be parsed normally, the parser now converts them to newlines. This should improve parsing of some forms of source code HTML. ## 1.7.1 (2019-05-31) ### Bug fixes Using `Fragment.from` on an invalid value, including a `Fragment` instance from a different version/instance of the library, now raises a meaningful error rather than getting confused. Fix a bug in parsing overlapping marks of the same non-self-exclusive type. ## 1.7.0 (2019-01-29) ### New features Mark specs now support a property [`spanning`](https://prosemirror.net/docs/ref/#model.MarkSpec.spanning) which, when set to `false`, prevents the mark's DOM markup from spanning multiple nodes, so that a separate wrapper is created for each adjacent marked node. ## 1.6.4 (2019-01-05) ### Bug fixes Don't output empty style attributes when a style property with a null value is present in `renderSpec`. ## 1.6.3 (2018-10-26) ### Bug fixes The DOM parser now drops whitespace after BR nodes when not in whitespace-preserving mode. ## 1.6.2 (2018-10-01) ### Bug fixes Prevent [`ContentMatch.findWrapping`](https://prosemirror.net/docs/ref/#model.ContentMatch.findWrapping) from returning node types with required attributes. ## 1.6.1 (2018-07-24) ### Bug fixes Fix a bug where marks were sometimes parsed incorrectly. ## 1.6.0 (2018-07-20) ### Bug fixes Fix issue where marks would be applied to the wrong node when parsing a slice from DOM. ### New features Adds a new node spec property, [`toDebugString`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDebugString), making it possible to customize your nodes' `toString` behavior. ## 1.5.0 (2018-05-31) ### New features [`ParseRule.getContent`](https://prosemirror.net/docs/ref/#model.ParseRule.getContent) is now passed the parser schema as second argument. ## 1.4.4 (2018-05-03) ### Bug fixes Fix a regression where `DOMParser.parse` would fail to apply mark nodes directly at the start of the input. ## 1.4.3 (2018-04-27) ### Bug fixes [`DOMParser.parseSlice`](https://prosemirror.net/docs/ref/#model.DOMParser.parseSlice) can now correctly parses marks at the top level again. ## 1.4.2 (2018-04-15) ### Bug fixes Remove a `console.log` that was accidentally left in the previous release. ## 1.4.1 (2018-04-13) ### Bug fixes `DOMParser` can now parse marks on block nodes. ## 1.4.0 (2018-03-22) ### New features [`ContentMatch.defaultType`](https://prosemirror.net/docs/ref/#model.ContentMatch.defaultType), a way to get a matching node type at a content match position, is now public. ## 1.3.0 (2018-03-22) ### New features `ContentMatch` objects now have an [`edgeCount`](https://prosemirror.net/docs/ref/#model.ContentMatch.edgeCount) property and an [`edge`](https://prosemirror.net/docs/ref/#model.ContentMatch.edge) method, providing direct access to the finite automaton structure. ## 1.2.2 (2018-03-15) ### Bug fixes Throw errors, rather than constructing invalid objects, when deserializing from invalid JSON data. ## 1.2.1 (2018-03-15) ### Bug fixes Content expressions with text nodes in required positions now raise the appropriate error about being unable to generate such nodes. ## 1.2.0 (2018-03-14) ### Bug fixes [`rangeHasMark`](https://prosemirror.net/docs/ref/#model.Node.rangeHasMark) now always returns false for empty ranges. The DOM renderer no longer needlessly splits mark nodes when starting a non-rendered mark. ### New features [`DOMSerializer`](https://prosemirror.net/docs/ref/#model.DOMSerializer) now allows [DOM specs](https://prosemirror.net/docs/ref/#model.DOMOutputSpec) for marks to have holes in them, to specify the precise position where their content should be rendered. The base position parameter to [`Node.nodesBetween`](https://prosemirror.net/docs/ref/#model.Node.nodesBetween) and [`Fragment.nodesBetween`](https://prosemirror.net/docs/ref/#model.Fragment.nodesBetween) is now part of the public interface. ## 1.1.0 (2018-01-05) ### New features [`Slice.maxOpen`](https://prosemirror.net/docs/ref/#model.Slice^maxOpen) now has a second argument that can be used to prevent it from opening isolating nodes. ## 1.0.1 (2017-11-10) ### Bug fixes [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) instances now properly inherit from `Error`. ## 1.0.0 (2017-10-13) ### New features [`ParseRule.context`](https://prosemirror.net/docs/ref/#model.ParseRule.context) may now include multiple, pipe-separated context expressions. ## 0.23.1 (2017-09-21) ### Bug fixes `NodeType.allowsMarks` and `allowedMarks` now actually work for nodes that allow only specific marks. ## 0.23.0 (2017-09-13) ### Breaking changes [`ResolvedPos.marks`](https://prosemirror.net/docs/ref/version/0.23.0.html#model.ResolvedPos.marks) no longer takes a parameter (you probably want [`marksAcross`](https://prosemirror.net/doc/ref/version/0.23.0.html#model.ResolvedPos.marksAcross) if you were passing true there). Attribute and mark constraints in [content expressions](https://prosemirror.net/docs/ref/version/0.23.0.html#model.NodeSpec.content) are no longer supported (this also means the `prosemirror-schema-table` package, which relied on them, is no longer supported). In this release, mark constraints are still (approximately) recognized with a warning, when present. [`ContentMatch`](https://prosemirror.net/docs/ref/version/0.23.0.html#model.ContentMatch) objects lost a number of methods: `matchNode`, `matchToEnd`, `findWrappingFor` (which can be easily emulated using the remaining API), and `allowsMark`, which is now the responsibility of [node types](https://prosemirror.net/docs/ref/version/0.23.0.html#model.NodeType.allowsMarkType) instead. [`ContentMatch.validEnd`](https://prosemirror.net/docs/ref/version/0.23.0.html#model.ContentMatch.validEnd) is now a property rather than a method. [`ContentMatch.findWrapping`](https://prosemirror.net/docs/ref/version/0.23.0.html#model.ContentMatch.findWrapping) now returns an array of plain node types, with no attribute information (since this is no longer necessary). The `compute` method for attributes is no longer supported. Fragments no longer have an `offsetAt` method. `DOMParser.schemaRules` is no longer public (use [`fromSchema`](https://prosemirror.net/docs/ref/version/0.23.0.html#model.DOMParser^fromSchema) and get the resulting parser's `rules` property instead). The DOM parser option `topStart` has been replaced by [`topMatch`](https://prosemirror.net/docs/ref/version/0.23.0.html#model.ParseOptions.topMatch). The `DOMSerializer` methods `nodesFromSchema` and `marksFromSchema` are no longer public (construct a serializer with [`fromSchema`](https://prosemirror.net/docs/ref/version/0.23.0.html#model.DOMSerializer^fromSchema) and read its `nodes` and `marks` properties instead). ### Bug fixes Fix issue where whitespace at node boundaries was sometimes dropped during content parsing. Attribute default values of `undefined` are now allowed. ### New features [`contentElement`](https://prosemirror.net/docs/ref/version/0.23.0.html#model.ParseRule.contentElement) in parse rules may now be a function. The new method [`ResolvedPos.marksAcross`](https://prosemirror.net/docs/ref/version/0.23.0.html#model.ResolvedPos.marksAcross) can be used to find the set of marks that should be preserved after a deletion. [Content expressions](https://prosemirror.net/docs/ref/version/0.23.0.html#model.NodeSpec.content) are now a regular language, meaning all the operators can be nested and composed as desired, and a bunch of constraints on what could appear next to what have been lifted. The starting content match for a node type now lives in [`NodeType.contentMatch`](https://prosemirror.net/docs/ref/version/0.23.0.html#model.NodeType.contentMatch). Allowed marks are now specified per node, rather than in content expressions, using the [`marks`](https://prosemirror.net/docs/ref/version/0.23.0.html#model.NodeSpec.marks) property on the node spec. Node types received new methods [`allowsMarkType`](https://prosemirror.net/docs/ref/version/0.23.0.html#model.NodeType.allowsMarkType), [`allowsMarks`](https://prosemirror.net/docs/ref/version/0.23.0.html#model.NodeType.allowsMarks), and [`allowedMarks`](https://prosemirror.net/docs/ref/version/0.23.0.html#model.NodeType.allowedMarks), which tell you about the marks that node supports. The [`style`](https://prosemirror.net/docs/ref/version/0.23.0.html#model.ParseRule.style) property on parse rules may now have the form `"font-style=italic"` to only match styles that have the value after the equals sign. ## 0.22.0 (2017-06-29) ### Bug fixes When using [`parseSlice`](https://prosemirror.net/docs/ref/version/0.22.0.html#model.DOMParser.parseSlice), inline DOM content wrapped in block elements for which no parse rule is defined will now be properly wrapped in a textblock node. ### New features [Resolved positions](https://prosemirror.net/docs/ref/version/0.22.0.html#model.ResolvedPos) now have a [`doc`](https://prosemirror.net/docs/ref/version/0.22.0.html#model.ResolvedPos.doc) accessor to easily get their root node. Parse rules now support a [`namespace` property](https://prosemirror.net/docs/ref/version/0.22.0.html#model.ParseRule.namespace) to match XML namespaces. The [`NodeRange`](https://prosemirror.net/docs/ref/version/0.22.0.html#model.NodeRange) constructor is now public (whereas before you could only construct these through [`blockRange`](https://prosemirror.net/docs/ref/version/0.22.0.html#model.ResolvedPos.blockRange)). ## 0.21.0 (2017-05-03) ### Breaking changes The `openLeft` and `openRight` properties of `Slice` objects have been renamed to [`openStart`](https://prosemirror.net/docs/ref/version/0.21.0.html#model.Slice.openStart) and [`openEnd`](https://prosemirror.net/docs/ref/version/0.21.0.html#model.Slice.openEnd) to avoid confusion in right-to-left text. The old names will continue to work with a warning until the next release. ### New features Mark [serializing functions](https://prosemirror.net/docs/ref/version/0.21.0.html#model.MarkSpec.toDOM) now get a second parameter that indicates whether the mark's content is inline or block nodes. Setting a mark serializer to `null` in a [`DOMSerializer`](https://prosemirror.net/docs/ref/version/0.21.0.html#model.DOMSerializer) can now be used to omit that mark when serializing. Node specs support a new property [`isolating`](https://prosemirror.net/docs/ref/version/0.21.0.html#model.NodeSpec.isolating), which is used to disable editing actions like backspacing and lifting across such a node's boundaries. ## 0.20.0 (2017-04-03) ### Breaking changes Newlines in the text are now normalized to spaces when parsing except when you set `preserveWhitespace` to `"full"` in your [options](https://prosemirror.net/docs/ref/version/0.20.0.html#model.DOMParser.parse) or in a [parse rule](https://prosemirror.net/docs/ref/version/0.20.0.html#model.ParseRule.preserveWhitespace). ### Bug fixes Fix crash in IE when parsing DOM content. ### New features Fragments now have [`nodesBetween`](https://prosemirror.net/docs/ref/version/0.20.0.html#model.Fragment.nodesBetween) and [`descendants`](https://prosemirror.net/docs/ref/version/0.20.0.html#model.Fragments.descendants) methods, providing the same functionality as the methods by the same name on nodes. Resolved positions now have [`max`](https://prosemirror.net/docs/ref/version/0.20.0.html#model.ResolvedPos.max) and [`min`](https://prosemirror.net/docs/ref/version/0.20.0.html#model.ResolvedPos.min) methods to easily find a maximum or minimum position. ## 0.19.0 (2017-03-16) ### Breaking changes `MarkSpec.inclusiveRight` was replaced by [`inclusive`](https://prosemirror.net/docs/ref/version/0.19.0.html#model.MarkSpec.inclusive), which behaves slightly differently. `inclusiveRight` will be interpreted as `inclusive` (with a warning) until the next release. ### New features The new [`inlineContent`](https://prosemirror.net/docs/ref/version/0.19.0.html#model.Node.inlineContent) property on nodes and node types tells you whether a node type supports inline content. [`MarkSpec.inclusive`](https://prosemirror.net/docs/ref/version/0.19.0.html#model.MarkSpec.inclusive) can now be used to control whether content inserted at the boundary of a mark receives that mark. Parse rule [`context`](https://prosemirror.net/docs/ref/version/0.19.0.html#model.ParseRule.context) restrictions can now use node [groups](https://prosemirror.net/docs/ref/version/0.19.0.html#model.NodeSpec.group), not just node names, to specify valid context. ## 0.18.0 (2017-02-24) ### Breaking changes `schema.nodeSpec` and `schema.markSpec` have been deprecated in favor of [`schema.spec`](https://prosemirror.net/docs/ref/version/0.18.0.html#model.Schema.spec). The properties still work with a warning in this release, but will be dropped in the next. ### New features `Node` objects now have a [`check`](https://prosemirror.net/docs/ref/version/0.18.0.html#model.Node.check) method which can be used to assert that they conform to the schema. Node specs now support an [`atom` property](https://prosemirror.net/docs/ref/version/0.18.0.html#model.NodeSpec.atom), and nodes an [`isAtom` accessor](https://prosemirror.net/docs/ref/version/0.18.0.html#model.Node.isAtom), which is currently only used to determine whether such nodes should be directly selectable (for example when they are rendered as an uneditable node view). The new [`excludes`](https://prosemirror.net/docs/ref/version/0.18.0.html#model.MarkSpec.excludes) field on mark specs can be used to control the marks that this mark may coexist with. Mark type objects also gained an [`excludes` _method_](https://prosemirror.net/docs/ref/version/0.18.0.html#model.MarkType.excludes) to querty this relation. Mark specs now support a [`group`](https://prosemirror.net/docs/ref/version/0.18.0.html#model.MarkSpec.group) property, and marks can be referred to by group name in content specs. The `Schema` class now provides its whole [spec](https://prosemirror.net/docs/ref/version/0.18.0.html#model.SchemaSpec) under its [`spec`](https://prosemirror.net/docs/ref/version/0.18.0.html#model.Schema.spec) property. The name of a schema's default top-level node is now [configurable](https://prosemirror.net/docs/ref/version/0.18.0.html#model.SchemaSpec.topNode). You can use [`schema.topNodeType`](https://prosemirror.net/docs/ref/version/0.18.0.html#model.Schema.topNodeType) to retrieve the top node type. [Parse rules](https://prosemirror.net/docs/ref/version/0.18.0.html#model.ParseRule) now support a [`context` field](https://prosemirror.net/docs/ref/version/0.18.0.html#model.ParseRule.context) that can be used to only make the rule match inside certain ancestor nodes. ## 0.17.0 (2017-01-05) ### Breaking changes `Node.marksAt` was replaced with [`ResolvedPos.marks`](https://prosemirror.net/docs/ref/version/0.17.0.html#model.ResolvedPos.marks). It still works (with a warning) in this release, but will be removed in the next one. ## 0.15.0 (2016-12-10) ### Breaking changes `ResolvedPos.atNodeBoundary` is deprecated and will be removed in the next release. Use `textOffset > 0` instead. ### New features Parse rules associated with a schema can now specify a [`priority`](https://prosemirror.net/docs/ref/version/0.15.0.html#model.ParseRule.priority) to influence the order in which they are applied. Resolved positions have a new getter [`textOffset`](https://prosemirror.net/docs/ref/version/0.15.0.html#model.ResolvedPos.textOffset) to find their position within a text node (if any). ## 0.14.1 (2016-11-30) ### Bug fixes [`DOMParser.parseSlice`](https://prosemirror.net/docs/ref/version/0.14.0.html#model.DOMParser.parseSlice) will now ignore whitespace-only text nodes at the top of the slice. ## 0.14.0 (2016-11-28) ### New features Parse rules now support [`skip`](https://prosemirror.net/docs/ref/version/0.14.0.html#model.ParseRule.skip) (skip outer element, parse content) and [`getContent`](https://prosemirror.net/docs/ref/version/0.14.0.html#model.ParseRule.getContent) (compute content using custom code) properties. The `DOMSerializer` class now exports a static [`renderSpec`](https://prosemirror.net/docs/ref/version/0.14.0.html#model.DOMSerializer^renderSpec) method that can help render DOM spec arrays. ## 0.13.0 (2016-11-11) ### Breaking changes `ResolvedPos.sameDepth` is now called [`ResolvedPos.sharedDepth`](https://prosemirror.net/docs/ref/version/0.13.0.html#model.ResolvedPos.sharedDepth), and takes a raw, unresolved position as argument. ### New features [`DOMSerializer`](https://prosemirror.net/docs/ref/version/0.13.0.html#model.DOMSerializer)'s `nodes` and `marks` properties are now public. [`ContentMatch.findWrapping`](https://prosemirror.net/docs/ref/version/0.13.0.html#model.ContentMatch.findWrapping) now takes a third argument, `marks`. There's a new method [`findWrappingFor`](https://prosemirror.net/docs/ref/version/0.13.0.html#model.ContentMatch.findWrappingFor) that accepts a whole node. Adds [`Slice.maxOpen`](https://prosemirror.net/docs/ref/version/0.13.0.html#model.Slice^maxOpen) static method to create maximally open slices. DOM parser objects now have a [`parseSlice`](https://prosemirror.net/docs/ref/version/0.13.0.html#model.DOMParser.parseSlice) method which parses an HTML fragment into a [`Slice`](https://prosemirror.net/docs/ref/version/0.13.0.html#model.Slice), rather than trying to create a whole document from it. ## 0.12.0 (2016-10-21) ### Breaking changes Drops support for some undocumented options to the DOM serializer that were used by the view. ### Bug fixes When rendering DOM attributes, only ignore null values, not all falsy values. ## 0.11.0 (2016-09-21) ### Breaking changes Moved into a separate module. The JSON representation of [marks](https://prosemirror.net/docs/ref/version/0.11.0.html#model.Mark) has changed from `{"_": "type", "attr1": "value"}` to `{"type": "type", "attrs": {"attr1": "value"}}`, where `attrs` may be omitted when the mark has no attributes. Mark-related JSON methods now live on the [`Mark` class](https://prosemirror.net/docs/ref/version/0.11.0.html#model.Mark^fromJSON). The way node and mark types in a schema are defined was changed from defining subclasses to passing plain objects ([`NodeSpec`](https://prosemirror.net/docs/ref/version/0.11.0.html#model.NodeSpec) and [`MarkSpec`](https://prosemirror.net/docs/ref/version/0.11.0.html#model.MarkSpec)). DOM serialization and parsing logic is now done through dedicated objects ([`DOMSerializer`](https://prosemirror.net/docs/ref/version/0.11.0.html#model.DOMSerializer) and [`DOMParser`](https://prosemirror.net/docs/ref/version/0.11.0.html#model.DOMParser)), rather than through the schema. It is now possible to define alternative parsing and serializing strategies without touching the schema. ### New features The [`Slice`](https://prosemirror.net/docs/ref/version/0.11.0.html#model.Slice) class now has an [`eq` method](https://prosemirror.net/docs/ref/version/0.11.0.html#model.Slice.eq). The [`Node.marksAt`](https://prosemirror.net/docs/ref/version/0.11.0.html#model.Node.marksAt) method got a second parameter to indicate you're interested in the marks _after_ the position. prosemirror-model-1.15.0/CONTRIBUTING.md000066400000000000000000000075161413544732700175330ustar00rootroot00000000000000# How to contribute - [Getting help](#getting-help) - [Submitting bug reports](#submitting-bug-reports) - [Contributing code](#contributing-code) ## Getting help Community discussion, questions, and informal bug reporting is done on the [discuss.ProseMirror forum](http://discuss.prosemirror.net). ## Submitting bug reports Report bugs on the [GitHub issue tracker](http://github.com/prosemirror/prosemirror/issues). Before reporting a bug, please read these pointers. - The issue tracker is for *bugs*, not requests for help. Questions should be asked on the [forum](http://discuss.prosemirror.net). - Include information about the version of the code that exhibits the problem. For browser-related issues, include the browser and browser version on which the problem occurred. - Mention very precisely what went wrong. "X is broken" is not a good bug report. What did you expect to happen? What happened instead? Describe the exact steps a maintainer has to take to make the problem occur. A screencast can be useful, but is no substitute for a textual description. - A great way to make it easy to reproduce your problem, if it can not be trivially reproduced on the website demos, is to submit a script that triggers the issue. ## Contributing code If you want to make a change that involves a significant overhaul of the code or introduces a user-visible new feature, create an [RFC](https://github.com/ProseMirror/rfcs/) first with your proposal. - Make sure you have a [GitHub Account](https://github.com/signup/free) - Fork the relevant repository ([how to fork a repo](https://help.github.com/articles/fork-a-repo)) - Create a local checkout of the code. You can use the [main repository](https://github.com/prosemirror/prosemirror) to easily check out all core modules. - Make your changes, and commit them - Follow the code style of the rest of the project (see below). Run `npm run lint` (in the main repository checkout) to make sure that the linter is happy. - If your changes are easy to test or likely to regress, add tests in the relevant `test/` directory. Either put them in an existing `test-*.js` file, if they fit there, or add a new file. - Make sure all tests pass. Run `npm run test` to verify tests pass (you will need Node.js v6+). - Submit a pull request ([how to create a pull request](https://help.github.com/articles/fork-a-repo)). Don't put more than one feature/fix in a single pull request. By contributing code to ProseMirror you - Agree to license the contributed code under the project's [MIT license](https://github.com/ProseMirror/prosemirror/blob/master/LICENSE). - Confirm that you have the right to contribute and license the code in question. (Either you hold all rights on the code, or the rights holder has explicitly granted the right to use it like this, through a compatible open source license or through a direct agreement with you.) ### Coding standards - ES6 syntax, targeting an ES5 runtime (i.e. don't use library elements added by ES6, don't use ES7/ES.next syntax). - 2 spaces per indentation level, no tabs. - No semicolons except when necessary. - Follow the surrounding code when it comes to spacing, brace placement, etc. - Brace-less single-statement bodies are encouraged (whenever they don't impact readability). - [getdocs](https://github.com/marijnh/getdocs)-style doc comments above items that are part of the public API. - When documenting non-public items, you can put the type after a single colon, so that getdocs doesn't pick it up and add it to the API reference. - The linter (`npm run lint`) complains about unused variables and functions. Prefix their names with an underscore to muffle it. - ProseMirror does *not* follow JSHint or JSLint prescribed style. Patches that try to 'fix' code to pass one of these linters will not be accepted. prosemirror-model-1.15.0/LICENSE000066400000000000000000000021131413544732700162730ustar00rootroot00000000000000Copyright (C) 2015-2017 by Marijn Haverbeke and others Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. prosemirror-model-1.15.0/README.md000066400000000000000000000027651413544732700165620ustar00rootroot00000000000000# prosemirror-model [ [**WEBSITE**](https://prosemirror.net) | [**ISSUES**](https://github.com/prosemirror/prosemirror/issues) | [**FORUM**](https://discuss.prosemirror.net) | [**GITTER**](https://gitter.im/ProseMirror/prosemirror) | [**CHANGELOG**](https://github.com/ProseMirror/prosemirror-model/blob/master/CHANGELOG.md) ] This is a [core module](https://prosemirror.net/docs/ref/#model) of [ProseMirror](https://prosemirror.net). ProseMirror is a well-behaved rich semantic content editor based on contentEditable, with support for collaborative editing and custom document schemas. This [module](https://prosemirror.net/docs/ref/#model) implements ProseMirror's [document model](https://prosemirror.net/docs/guide/#doc), along with the mechanisms needed to support [schemas](https://prosemirror.net/docs/guide/#schema). The [project page](https://prosemirror.net) has more information, a number of [examples](https://prosemirror.net/examples/) and the [documentation](https://prosemirror.net/docs/). This code is released under an [MIT license](https://github.com/prosemirror/prosemirror/tree/master/LICENSE). There's a [forum](http://discuss.prosemirror.net) for general discussion and support requests, and the [Github bug tracker](https://github.com/prosemirror/prosemirror/issues) is the place to report issues. We aim to be an inclusive, welcoming community. To make that explicit, we have a [code of conduct](http://contributor-covenant.org/version/1/1/0/) that applies to communication around the project. prosemirror-model-1.15.0/etc/000077500000000000000000000000001413544732700160445ustar00rootroot00000000000000prosemirror-model-1.15.0/etc/link-self.js000066400000000000000000000005231413544732700202660ustar00rootroot00000000000000const {lstatSync, symlinkSync, renameSync} = require("fs") let stats try { stats = lstatSync("node_modules/prosemirror-model") } catch(_) { return } if (!stats.isSymbolicLink()) { renameSync("node_modules/prosemirror-model", "node_modules/prosemirror-model.disabled") symlinkSync("..", "node_modules/prosemirror-model", "dir") } prosemirror-model-1.15.0/package.json000066400000000000000000000015321413544732700175600ustar00rootroot00000000000000{ "name": "prosemirror-model", "version": "1.15.0", "description": "ProseMirror's document model", "main": "dist/index.js", "module": "dist/index.es.js", "license": "MIT", "maintainers": [ { "name": "Marijn Haverbeke", "email": "marijnh@gmail.com", "web": "http://marijnhaverbeke.nl" } ], "repository": { "type": "git", "url": "git://github.com/prosemirror/prosemirror-model.git" }, "dependencies": { "orderedmap": "^1.1.0" }, "devDependencies": { "mocha": "^9.1.2", "ist": "^1.0.0", "jsdom": "^10.1.0", "prosemirror-test-builder": "^1.0.0", "rollup": "^2.26.3", "@rollup/plugin-buble": "^0.21.3" }, "scripts": { "test": "node etc/link-self.js && mocha test/test-*.js", "build": "rollup -c", "watch": "rollup -c -w", "prepare": "npm run build" } } prosemirror-model-1.15.0/rollup.config.js000066400000000000000000000005121413544732700204060ustar00rootroot00000000000000module.exports = { input: './src/index.js', output: [{ file: 'dist/index.js', format: 'cjs', sourcemap: true }, { file: 'dist/index.es.js', format: 'es', sourcemap: true }], plugins: [require('@rollup/plugin-buble')()], external(id) { return id[0] != "." && !require("path").isAbsolute(id) } } prosemirror-model-1.15.0/src/000077500000000000000000000000001413544732700160605ustar00rootroot00000000000000prosemirror-model-1.15.0/src/README.md000066400000000000000000000024271413544732700173440ustar00rootroot00000000000000This module defines ProseMirror's content model, the data structures used to represent and work with documents. ### Document Structure A ProseMirror document is a tree. At each level, a [node](#model.Node) describes the type of the content, and holds a [fragment](#model.Fragment) containing its children. @Node @Fragment @Mark @Slice @ReplaceError ### Resolved Positions Positions in a document can be represented as integer [offsets](/docs/guide/#doc.indexing). But you'll often want to use a more convenient representation. @ResolvedPos @NodeRange ### Document Schema Every ProseMirror document conforms to a [schema](/docs/guide/#schema), which describes the set of nodes and marks that it is made out of, along with the relations between those, such as which node may occur as a child node of which other nodes. @Schema @SchemaSpec @NodeSpec @MarkSpec @AttributeSpec @NodeType @MarkType @ContentMatch ### DOM Representation Because representing a document as a tree of DOM nodes is central to the way ProseMirror operates, DOM [parsing](#model.DOMParser) and [serializing](#model.DOMSerializer) is integrated with the model. (But note that you do _not_ need to have a DOM implementation loaded to use this module.) @DOMParser @ParseOptions @ParseRule @DOMSerializer @DOMOutputSpec prosemirror-model-1.15.0/src/comparedeep.js000066400000000000000000000010141413544732700206760ustar00rootroot00000000000000export function compareDeep(a, b) { if (a === b) return true if (!(a && typeof a == "object") || !(b && typeof b == "object")) return false let array = Array.isArray(a) if (Array.isArray(b) != array) return false if (array) { if (a.length != b.length) return false for (let i = 0; i < a.length; i++) if (!compareDeep(a[i], b[i])) return false } else { for (let p in a) if (!(p in b) || !compareDeep(a[p], b[p])) return false for (let p in b) if (!(p in a)) return false } return true } prosemirror-model-1.15.0/src/content.js000066400000000000000000000306271413544732700201000ustar00rootroot00000000000000import {Fragment} from "./fragment" // ::- Instances of this class represent a match state of a node // type's [content expression](#model.NodeSpec.content), and can be // used to find out whether further content matches here, and whether // a given position is a valid end of the node. export class ContentMatch { constructor(validEnd) { // :: bool // True when this match state represents a valid end of the node. this.validEnd = validEnd this.next = [] this.wrapCache = [] } static parse(string, nodeTypes) { let stream = new TokenStream(string, nodeTypes) if (stream.next == null) return ContentMatch.empty let expr = parseExpr(stream) if (stream.next) stream.err("Unexpected trailing text") let match = dfa(nfa(expr)) checkForDeadEnds(match, stream) return match } // :: (NodeType) → ?ContentMatch // Match a node type, returning a match after that node if // successful. matchType(type) { for (let i = 0; i < this.next.length; i += 2) if (this.next[i] == type) return this.next[i + 1] return null } // :: (Fragment, ?number, ?number) → ?ContentMatch // Try to match a fragment. Returns the resulting match when // successful. matchFragment(frag, start = 0, end = frag.childCount) { let cur = this for (let i = start; cur && i < end; i++) cur = cur.matchType(frag.child(i).type) return cur } get inlineContent() { let first = this.next[0] return first ? first.isInline : false } // :: ?NodeType // Get the first matching node type at this match position that can // be generated. get defaultType() { for (let i = 0; i < this.next.length; i += 2) { let type = this.next[i] if (!(type.isText || type.hasRequiredAttrs())) return type } } compatible(other) { for (let i = 0; i < this.next.length; i += 2) for (let j = 0; j < other.next.length; j += 2) if (this.next[i] == other.next[j]) return true return false } // :: (Fragment, bool, ?number) → ?Fragment // Try to match the given fragment, and if that fails, see if it can // be made to match by inserting nodes in front of it. When // successful, return a fragment of inserted nodes (which may be // empty if nothing had to be inserted). When `toEnd` is true, only // return a fragment if the resulting match goes to the end of the // content expression. fillBefore(after, toEnd = false, startIndex = 0) { let seen = [this] function search(match, types) { let finished = match.matchFragment(after, startIndex) if (finished && (!toEnd || finished.validEnd)) return Fragment.from(types.map(tp => tp.createAndFill())) for (let i = 0; i < match.next.length; i += 2) { let type = match.next[i], next = match.next[i + 1] if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) { seen.push(next) let found = search(next, types.concat(type)) if (found) return found } } } return search(this, []) } // :: (NodeType) → ?[NodeType] // Find a set of wrapping node types that would allow a node of the // given type to appear at this position. The result may be empty // (when it fits directly) and will be null when no such wrapping // exists. findWrapping(target) { for (let i = 0; i < this.wrapCache.length; i += 2) if (this.wrapCache[i] == target) return this.wrapCache[i + 1] let computed = this.computeWrapping(target) this.wrapCache.push(target, computed) return computed } computeWrapping(target) { let seen = Object.create(null), active = [{match: this, type: null, via: null}] while (active.length) { let current = active.shift(), match = current.match if (match.matchType(target)) { let result = [] for (let obj = current; obj.type; obj = obj.via) result.push(obj.type) return result.reverse() } for (let i = 0; i < match.next.length; i += 2) { let type = match.next[i] if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || match.next[i + 1].validEnd)) { active.push({match: type.contentMatch, type, via: current}) seen[type.name] = true } } } } // :: number // The number of outgoing edges this node has in the finite // automaton that describes the content expression. get edgeCount() { return this.next.length >> 1 } // :: (number) → {type: NodeType, next: ContentMatch} // Get the _n_​th outgoing edge from this node in the finite // automaton that describes the content expression. edge(n) { let i = n << 1 if (i >= this.next.length) throw new RangeError(`There's no ${n}th edge in this content match`) return {type: this.next[i], next: this.next[i + 1]} } toString() { let seen = [] function scan(m) { seen.push(m) for (let i = 1; i < m.next.length; i += 2) if (seen.indexOf(m.next[i]) == -1) scan(m.next[i]) } scan(this) return seen.map((m, i) => { let out = i + (m.validEnd ? "*" : " ") + " " for (let i = 0; i < m.next.length; i += 2) out += (i ? ", " : "") + m.next[i].name + "->" + seen.indexOf(m.next[i + 1]) return out }).join("\n") } } ContentMatch.empty = new ContentMatch(true) class TokenStream { constructor(string, nodeTypes) { this.string = string this.nodeTypes = nodeTypes this.inline = null this.pos = 0 this.tokens = string.split(/\s*(?=\b|\W|$)/) if (this.tokens[this.tokens.length - 1] == "") this.tokens.pop() if (this.tokens[0] == "") this.tokens.shift() } get next() { return this.tokens[this.pos] } eat(tok) { return this.next == tok && (this.pos++ || true) } err(str) { throw new SyntaxError(str + " (in content expression '" + this.string + "')") } } function parseExpr(stream) { let exprs = [] do { exprs.push(parseExprSeq(stream)) } while (stream.eat("|")) return exprs.length == 1 ? exprs[0] : {type: "choice", exprs} } function parseExprSeq(stream) { let exprs = [] do { exprs.push(parseExprSubscript(stream)) } while (stream.next && stream.next != ")" && stream.next != "|") return exprs.length == 1 ? exprs[0] : {type: "seq", exprs} } function parseExprSubscript(stream) { let expr = parseExprAtom(stream) for (;;) { if (stream.eat("+")) expr = {type: "plus", expr} else if (stream.eat("*")) expr = {type: "star", expr} else if (stream.eat("?")) expr = {type: "opt", expr} else if (stream.eat("{")) expr = parseExprRange(stream, expr) else break } return expr } function parseNum(stream) { if (/\D/.test(stream.next)) stream.err("Expected number, got '" + stream.next + "'") let result = Number(stream.next) stream.pos++ return result } function parseExprRange(stream, expr) { let min = parseNum(stream), max = min if (stream.eat(",")) { if (stream.next != "}") max = parseNum(stream) else max = -1 } if (!stream.eat("}")) stream.err("Unclosed braced range") return {type: "range", min, max, expr} } function resolveName(stream, name) { let types = stream.nodeTypes, type = types[name] if (type) return [type] let result = [] for (let typeName in types) { let type = types[typeName] if (type.groups.indexOf(name) > -1) result.push(type) } if (result.length == 0) stream.err("No node type or group '" + name + "' found") return result } function parseExprAtom(stream) { if (stream.eat("(")) { let expr = parseExpr(stream) if (!stream.eat(")")) stream.err("Missing closing paren") return expr } else if (!/\W/.test(stream.next)) { let exprs = resolveName(stream, stream.next).map(type => { if (stream.inline == null) stream.inline = type.isInline else if (stream.inline != type.isInline) stream.err("Mixing inline and block content") return {type: "name", value: type} }) stream.pos++ return exprs.length == 1 ? exprs[0] : {type: "choice", exprs} } else { stream.err("Unexpected token '" + stream.next + "'") } } // The code below helps compile a regular-expression-like language // into a deterministic finite automaton. For a good introduction to // these concepts, see https://swtch.com/~rsc/regexp/regexp1.html // : (Object) → [[{term: ?any, to: number}]] // Construct an NFA from an expression as returned by the parser. The // NFA is represented as an array of states, which are themselves // arrays of edges, which are `{term, to}` objects. The first state is // the entry state and the last node is the success state. // // Note that unlike typical NFAs, the edge ordering in this one is // significant, in that it is used to contruct filler content when // necessary. function nfa(expr) { let nfa = [[]] connect(compile(expr, 0), node()) return nfa function node() { return nfa.push([]) - 1 } function edge(from, to, term) { let edge = {term, to} nfa[from].push(edge) return edge } function connect(edges, to) { edges.forEach(edge => edge.to = to) } function compile(expr, from) { if (expr.type == "choice") { return expr.exprs.reduce((out, expr) => out.concat(compile(expr, from)), []) } else if (expr.type == "seq") { for (let i = 0;; i++) { let next = compile(expr.exprs[i], from) if (i == expr.exprs.length - 1) return next connect(next, from = node()) } } else if (expr.type == "star") { let loop = node() edge(from, loop) connect(compile(expr.expr, loop), loop) return [edge(loop)] } else if (expr.type == "plus") { let loop = node() connect(compile(expr.expr, from), loop) connect(compile(expr.expr, loop), loop) return [edge(loop)] } else if (expr.type == "opt") { return [edge(from)].concat(compile(expr.expr, from)) } else if (expr.type == "range") { let cur = from for (let i = 0; i < expr.min; i++) { let next = node() connect(compile(expr.expr, cur), next) cur = next } if (expr.max == -1) { connect(compile(expr.expr, cur), cur) } else { for (let i = expr.min; i < expr.max; i++) { let next = node() edge(cur, next) connect(compile(expr.expr, cur), next) cur = next } } return [edge(cur)] } else if (expr.type == "name") { return [edge(from, null, expr.value)] } } } function cmp(a, b) { return b - a } // Get the set of nodes reachable by null edges from `node`. Omit // nodes with only a single null-out-edge, since they may lead to // needless duplicated nodes. function nullFrom(nfa, node) { let result = [] scan(node) return result.sort(cmp) function scan(node) { let edges = nfa[node] if (edges.length == 1 && !edges[0].term) return scan(edges[0].to) result.push(node) for (let i = 0; i < edges.length; i++) { let {term, to} = edges[i] if (!term && result.indexOf(to) == -1) scan(to) } } } // : ([[{term: ?any, to: number}]]) → ContentMatch // Compiles an NFA as produced by `nfa` into a DFA, modeled as a set // of state objects (`ContentMatch` instances) with transitions // between them. function dfa(nfa) { let labeled = Object.create(null) return explore(nullFrom(nfa, 0)) function explore(states) { let out = [] states.forEach(node => { nfa[node].forEach(({term, to}) => { if (!term) return let known = out.indexOf(term), set = known > -1 && out[known + 1] nullFrom(nfa, to).forEach(node => { if (!set) out.push(term, set = []) if (set.indexOf(node) == -1) set.push(node) }) }) }) let state = labeled[states.join(",")] = new ContentMatch(states.indexOf(nfa.length - 1) > -1) for (let i = 0; i < out.length; i += 2) { let states = out[i + 1].sort(cmp) state.next.push(out[i], labeled[states.join(",")] || explore(states)) } return state } } function checkForDeadEnds(match, stream) { for (let i = 0, work = [match]; i < work.length; i++) { let state = work[i], dead = !state.validEnd, nodes = [] for (let j = 0; j < state.next.length; j += 2) { let node = state.next[j], next = state.next[j + 1] nodes.push(node.name) if (dead && !(node.isText || node.hasRequiredAttrs())) dead = false if (work.indexOf(next) == -1) work.push(next) } if (dead) stream.err("Only non-generatable nodes (" + nodes.join(", ") + ") in a required position (see https://prosemirror.net/docs/guide/#generatable)") } } prosemirror-model-1.15.0/src/diff.js000066400000000000000000000031501413544732700173250ustar00rootroot00000000000000export function findDiffStart(a, b, pos) { for (let i = 0;; i++) { if (i == a.childCount || i == b.childCount) return a.childCount == b.childCount ? null : pos let childA = a.child(i), childB = b.child(i) if (childA == childB) { pos += childA.nodeSize; continue } if (!childA.sameMarkup(childB)) return pos if (childA.isText && childA.text != childB.text) { for (let j = 0; childA.text[j] == childB.text[j]; j++) pos++ return pos } if (childA.content.size || childB.content.size) { let inner = findDiffStart(childA.content, childB.content, pos + 1) if (inner != null) return inner } pos += childA.nodeSize } } export function findDiffEnd(a, b, posA, posB) { for (let iA = a.childCount, iB = b.childCount;;) { if (iA == 0 || iB == 0) return iA == iB ? null : {a: posA, b: posB} let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize if (childA == childB) { posA -= size; posB -= size continue } if (!childA.sameMarkup(childB)) return {a: posA, b: posB} if (childA.isText && childA.text != childB.text) { let same = 0, minSize = Math.min(childA.text.length, childB.text.length) while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) { same++; posA--; posB-- } return {a: posA, b: posB} } if (childA.content.size || childB.content.size) { let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1) if (inner) return inner } posA -= size; posB -= size } } prosemirror-model-1.15.0/src/fragment.js000066400000000000000000000237271413544732700202340ustar00rootroot00000000000000import {findDiffStart, findDiffEnd} from "./diff" // ::- A fragment represents a node's collection of child nodes. // // Like nodes, fragments are persistent data structures, and you // should not mutate them or their content. Rather, you create new // instances whenever needed. The API tries to make this easy. export class Fragment { constructor(content, size) { this.content = content // :: number // The size of the fragment, which is the total of the size of its // content nodes. this.size = size || 0 if (size == null) for (let i = 0; i < content.length; i++) this.size += content[i].nodeSize } // :: (number, number, (node: Node, start: number, parent: Node, index: number) → ?bool, ?number) // Invoke a callback for all descendant nodes between the given two // positions (relative to start of this fragment). Doesn't descend // into a node when the callback returns `false`. nodesBetween(from, to, f, nodeStart = 0, parent) { for (let i = 0, pos = 0; pos < to; i++) { let child = this.content[i], end = pos + child.nodeSize if (end > from && f(child, nodeStart + pos, parent, i) !== false && child.content.size) { let start = pos + 1 child.nodesBetween(Math.max(0, from - start), Math.min(child.content.size, to - start), f, nodeStart + start) } pos = end } } // :: ((node: Node, pos: number, parent: Node) → ?bool) // Call the given callback for every descendant node. The callback // may return `false` to prevent traversal of a given node's children. descendants(f) { this.nodesBetween(0, this.size, f) } // :: (number, number, ?string, ?string | ?(leafNode: Node) -> string) → string // Extract the text between `from` and `to`. See the same method on // [`Node`](#model.Node.textBetween). textBetween(from, to, blockSeparator, leafText) { let text = "", separated = true this.nodesBetween(from, to, (node, pos) => { if (node.isText) { text += node.text.slice(Math.max(from, pos) - pos, to - pos) separated = !blockSeparator } else if (node.isLeaf && leafText) { text += typeof leafText === 'function' ? leafText(node): leafText separated = !blockSeparator } else if (!separated && node.isBlock) { text += blockSeparator separated = true } }, 0) return text } // :: (Fragment) → Fragment // Create a new fragment containing the combined content of this // fragment and the other. append(other) { if (!other.size) return this if (!this.size) return other let last = this.lastChild, first = other.firstChild, content = this.content.slice(), i = 0 if (last.isText && last.sameMarkup(first)) { content[content.length - 1] = last.withText(last.text + first.text) i = 1 } for (; i < other.content.length; i++) content.push(other.content[i]) return new Fragment(content, this.size + other.size) } // :: (number, ?number) → Fragment // Cut out the sub-fragment between the two given positions. cut(from, to) { if (to == null) to = this.size if (from == 0 && to == this.size) return this let result = [], size = 0 if (to > from) for (let i = 0, pos = 0; pos < to; i++) { let child = this.content[i], end = pos + child.nodeSize if (end > from) { if (pos < from || end > to) { if (child.isText) child = child.cut(Math.max(0, from - pos), Math.min(child.text.length, to - pos)) else child = child.cut(Math.max(0, from - pos - 1), Math.min(child.content.size, to - pos - 1)) } result.push(child) size += child.nodeSize } pos = end } return new Fragment(result, size) } cutByIndex(from, to) { if (from == to) return Fragment.empty if (from == 0 && to == this.content.length) return this return new Fragment(this.content.slice(from, to)) } // :: (number, Node) → Fragment // Create a new fragment in which the node at the given index is // replaced by the given node. replaceChild(index, node) { let current = this.content[index] if (current == node) return this let copy = this.content.slice() let size = this.size + node.nodeSize - current.nodeSize copy[index] = node return new Fragment(copy, size) } // : (Node) → Fragment // Create a new fragment by prepending the given node to this // fragment. addToStart(node) { return new Fragment([node].concat(this.content), this.size + node.nodeSize) } // : (Node) → Fragment // Create a new fragment by appending the given node to this // fragment. addToEnd(node) { return new Fragment(this.content.concat(node), this.size + node.nodeSize) } // :: (Fragment) → bool // Compare this fragment to another one. eq(other) { if (this.content.length != other.content.length) return false for (let i = 0; i < this.content.length; i++) if (!this.content[i].eq(other.content[i])) return false return true } // :: ?Node // The first child of the fragment, or `null` if it is empty. get firstChild() { return this.content.length ? this.content[0] : null } // :: ?Node // The last child of the fragment, or `null` if it is empty. get lastChild() { return this.content.length ? this.content[this.content.length - 1] : null } // :: number // The number of child nodes in this fragment. get childCount() { return this.content.length } // :: (number) → Node // Get the child node at the given index. Raise an error when the // index is out of range. child(index) { let found = this.content[index] if (!found) throw new RangeError("Index " + index + " out of range for " + this) return found } // :: (number) → ?Node // Get the child node at the given index, if it exists. maybeChild(index) { return this.content[index] } // :: ((node: Node, offset: number, index: number)) // Call `f` for every child node, passing the node, its offset // into this parent node, and its index. forEach(f) { for (let i = 0, p = 0; i < this.content.length; i++) { let child = this.content[i] f(child, p, i) p += child.nodeSize } } // :: (Fragment) → ?number // Find the first position at which this fragment and another // fragment differ, or `null` if they are the same. findDiffStart(other, pos = 0) { return findDiffStart(this, other, pos) } // :: (Fragment) → ?{a: number, b: number} // Find the first position, searching from the end, at which this // fragment and the given fragment differ, or `null` if they are the // same. Since this position will not be the same in both nodes, an // object with two separate positions is returned. findDiffEnd(other, pos = this.size, otherPos = other.size) { return findDiffEnd(this, other, pos, otherPos) } // : (number, ?number) → {index: number, offset: number} // Find the index and inner offset corresponding to a given relative // position in this fragment. The result object will be reused // (overwritten) the next time the function is called. (Not public.) findIndex(pos, round = -1) { if (pos == 0) return retIndex(0, pos) if (pos == this.size) return retIndex(this.content.length, pos) if (pos > this.size || pos < 0) throw new RangeError(`Position ${pos} outside of fragment (${this})`) for (let i = 0, curPos = 0;; i++) { let cur = this.child(i), end = curPos + cur.nodeSize if (end >= pos) { if (end == pos || round > 0) return retIndex(i + 1, end) return retIndex(i, curPos) } curPos = end } } // :: () → string // Return a debugging string that describes this fragment. toString() { return "<" + this.toStringInner() + ">" } toStringInner() { return this.content.join(", ") } // :: () → ?Object // Create a JSON-serializeable representation of this fragment. toJSON() { return this.content.length ? this.content.map(n => n.toJSON()) : null } // :: (Schema, ?Object) → Fragment // Deserialize a fragment from its JSON representation. static fromJSON(schema, value) { if (!value) return Fragment.empty if (!Array.isArray(value)) throw new RangeError("Invalid input for Fragment.fromJSON") return new Fragment(value.map(schema.nodeFromJSON)) } // :: ([Node]) → Fragment // Build a fragment from an array of nodes. Ensures that adjacent // text nodes with the same marks are joined together. static fromArray(array) { if (!array.length) return Fragment.empty let joined, size = 0 for (let i = 0; i < array.length; i++) { let node = array[i] size += node.nodeSize if (i && node.isText && array[i - 1].sameMarkup(node)) { if (!joined) joined = array.slice(0, i) joined[joined.length - 1] = node.withText(joined[joined.length - 1].text + node.text) } else if (joined) { joined.push(node) } } return new Fragment(joined || array, size) } // :: (?union) → Fragment // Create a fragment from something that can be interpreted as a set // of nodes. For `null`, it returns the empty fragment. For a // fragment, the fragment itself. For a node or array of nodes, a // fragment containing those nodes. static from(nodes) { if (!nodes) return Fragment.empty if (nodes instanceof Fragment) return nodes if (Array.isArray(nodes)) return this.fromArray(nodes) if (nodes.attrs) return new Fragment([nodes], nodes.nodeSize) throw new RangeError("Can not convert " + nodes + " to a Fragment" + (nodes.nodesBetween ? " (looks like multiple versions of prosemirror-model were loaded)" : "")) } } const found = {index: 0, offset: 0} function retIndex(index, offset) { found.index = index found.offset = offset return found } // :: Fragment // An empty fragment. Intended to be reused whenever a node doesn't // contain anything (rather than allocating a new empty fragment for // each leaf node). Fragment.empty = new Fragment([], 0) prosemirror-model-1.15.0/src/from_dom.js000066400000000000000000000737321413544732700202340ustar00rootroot00000000000000import {Fragment} from "./fragment" import {Slice} from "./replace" import {Mark} from "./mark" // ParseOptions:: interface // These are the options recognized by the // [`parse`](#model.DOMParser.parse) and // [`parseSlice`](#model.DOMParser.parseSlice) methods. // // preserveWhitespace:: ?union // By default, whitespace is collapsed as per HTML's rules. Pass // `true` to preserve whitespace, but normalize newlines to // spaces, and `"full"` to preserve whitespace entirely. // // findPositions:: ?[{node: dom.Node, offset: number}] // When given, the parser will, beside parsing the content, // record the document positions of the given DOM positions. It // will do so by writing to the objects, adding a `pos` property // that holds the document position. DOM positions that are not // in the parsed content will not be written to. // // from:: ?number // The child node index to start parsing from. // // to:: ?number // The child node index to stop parsing at. // // topNode:: ?Node // By default, the content is parsed into the schema's default // [top node type](#model.Schema.topNodeType). You can pass this // option to use the type and attributes from a different node // as the top container. // // topMatch:: ?ContentMatch // Provide the starting content match that content parsed into the // top node is matched against. // // context:: ?ResolvedPos // A set of additional nodes to count as // [context](#model.ParseRule.context) when parsing, above the // given [top node](#model.ParseOptions.topNode). // ParseRule:: interface // A value that describes how to parse a given DOM node or inline // style as a ProseMirror node or mark. // // tag:: ?string // A CSS selector describing the kind of DOM elements to match. A // single rule should have _either_ a `tag` or a `style` property. // // namespace:: ?string // The namespace to match. This should be used with `tag`. // Nodes are only matched when the namespace matches or this property // is null. // // style:: ?string // A CSS property name to match. When given, this rule matches // inline styles that list that property. May also have the form // `"property=value"`, in which case the rule only matches if the // property's value exactly matches the given value. (For more // complicated filters, use [`getAttrs`](#model.ParseRule.getAttrs) // and return false to indicate that the match failed.) Rules // matching styles may only produce [marks](#model.ParseRule.mark), // not nodes. // // priority:: ?number // Can be used to change the order in which the parse rules in a // schema are tried. Those with higher priority come first. Rules // without a priority are counted as having priority 50. This // property is only meaningful in a schema—when directly // constructing a parser, the order of the rule array is used. // // consuming:: ?boolean // By default, when a rule matches an element or style, no further // rules get a chance to match it. By setting this to `false`, you // indicate that even when this rule matches, other rules that come // after it should also run. // // context:: ?string // When given, restricts this rule to only match when the current // context—the parent nodes into which the content is being // parsed—matches this expression. Should contain one or more node // names or node group names followed by single or double slashes. // For example `"paragraph/"` means the rule only matches when the // parent node is a paragraph, `"blockquote/paragraph/"` restricts // it to be in a paragraph that is inside a blockquote, and // `"section//"` matches any position inside a section—a double // slash matches any sequence of ancestor nodes. To allow multiple // different contexts, they can be separated by a pipe (`|`) // character, as in `"blockquote/|list_item/"`. // // node:: ?string // The name of the node type to create when this rule matches. Only // valid for rules with a `tag` property, not for style rules. Each // rule should have one of a `node`, `mark`, or `ignore` property // (except when it appears in a [node](#model.NodeSpec.parseDOM) or // [mark spec](#model.MarkSpec.parseDOM), in which case the `node` // or `mark` property will be derived from its position). // // mark:: ?string // The name of the mark type to wrap the matched content in. // // ignore:: ?bool // When true, ignore content that matches this rule. // // closeParent:: ?bool // When true, finding an element that matches this rule will close // the current node. // // skip:: ?bool // When true, ignore the node that matches this rule, but do parse // its content. // // attrs:: ?Object // Attributes for the node or mark created by this rule. When // `getAttrs` is provided, it takes precedence. // // getAttrs:: ?(union) → ?union // A function used to compute the attributes for the node or mark // created by this rule. Can also be used to describe further // conditions the DOM element or style must match. When it returns // `false`, the rule won't match. When it returns null or undefined, // that is interpreted as an empty/default set of attributes. // // Called with a DOM Element for `tag` rules, and with a string (the // style's value) for `style` rules. // // contentElement:: ?union // For `tag` rules that produce non-leaf nodes or marks, by default // the content of the DOM element is parsed as content of the mark // or node. If the child nodes are in a descendent node, this may be // a CSS selector string that the parser must use to find the actual // content element, or a function that returns the actual content // element to the parser. // // getContent:: ?(dom.Node, schema: Schema) → Fragment // Can be used to override the content of a matched node. When // present, instead of parsing the node's child nodes, the result of // this function is used. // // preserveWhitespace:: ?union // Controls whether whitespace should be preserved when parsing the // content inside the matched element. `false` means whitespace may // be collapsed, `true` means that whitespace should be preserved // but newlines normalized to spaces, and `"full"` means that // newlines should also be preserved. // ::- A DOM parser represents a strategy for parsing DOM content into // a ProseMirror document conforming to a given schema. Its behavior // is defined by an array of [rules](#model.ParseRule). export class DOMParser { // :: (Schema, [ParseRule]) // Create a parser that targets the given schema, using the given // parsing rules. constructor(schema, rules) { // :: Schema // The schema into which the parser parses. this.schema = schema // :: [ParseRule] // The set of [parse rules](#model.ParseRule) that the parser // uses, in order of precedence. this.rules = rules this.tags = [] this.styles = [] rules.forEach(rule => { if (rule.tag) this.tags.push(rule) else if (rule.style) this.styles.push(rule) }) // Only normalize list elements when lists in the schema can't directly contain themselves this.normalizeLists = !this.tags.some(r => { if (!/^(ul|ol)\b/.test(r.tag) || !r.node) return false let node = schema.nodes[r.node] return node.contentMatch.matchType(node) }) } // :: (dom.Node, ?ParseOptions) → Node // Parse a document from the content of a DOM node. parse(dom, options = {}) { let context = new ParseContext(this, options, false) context.addAll(dom, null, options.from, options.to) return context.finish() } // :: (dom.Node, ?ParseOptions) → Slice // Parses the content of the given DOM node, like // [`parse`](#model.DOMParser.parse), and takes the same set of // options. But unlike that method, which produces a whole node, // this one returns a slice that is open at the sides, meaning that // the schema constraints aren't applied to the start of nodes to // the left of the input and the end of nodes at the end. parseSlice(dom, options = {}) { let context = new ParseContext(this, options, true) context.addAll(dom, null, options.from, options.to) return Slice.maxOpen(context.finish()) } matchTag(dom, context, after) { for (let i = after ? this.tags.indexOf(after) + 1 : 0; i < this.tags.length; i++) { let rule = this.tags[i] if (matches(dom, rule.tag) && (rule.namespace === undefined || dom.namespaceURI == rule.namespace) && (!rule.context || context.matchesContext(rule.context))) { if (rule.getAttrs) { let result = rule.getAttrs(dom) if (result === false) continue rule.attrs = result } return rule } } } matchStyle(prop, value, context, after) { for (let i = after ? this.styles.indexOf(after) + 1 : 0; i < this.styles.length; i++) { let rule = this.styles[i] if (rule.style.indexOf(prop) != 0 || rule.context && !context.matchesContext(rule.context) || // Test that the style string either precisely matches the prop, // or has an '=' sign after the prop, followed by the given // value. rule.style.length > prop.length && (rule.style.charCodeAt(prop.length) != 61 || rule.style.slice(prop.length + 1) != value)) continue if (rule.getAttrs) { let result = rule.getAttrs(value) if (result === false) continue rule.attrs = result } return rule } } // : (Schema) → [ParseRule] static schemaRules(schema) { let result = [] function insert(rule) { let priority = rule.priority == null ? 50 : rule.priority, i = 0 for (; i < result.length; i++) { let next = result[i], nextPriority = next.priority == null ? 50 : next.priority if (nextPriority < priority) break } result.splice(i, 0, rule) } for (let name in schema.marks) { let rules = schema.marks[name].spec.parseDOM if (rules) rules.forEach(rule => { insert(rule = copy(rule)) rule.mark = name }) } for (let name in schema.nodes) { let rules = schema.nodes[name].spec.parseDOM if (rules) rules.forEach(rule => { insert(rule = copy(rule)) rule.node = name }) } return result } // :: (Schema) → DOMParser // Construct a DOM parser using the parsing rules listed in a // schema's [node specs](#model.NodeSpec.parseDOM), reordered by // [priority](#model.ParseRule.priority). static fromSchema(schema) { return schema.cached.domParser || (schema.cached.domParser = new DOMParser(schema, DOMParser.schemaRules(schema))) } } // : Object The block-level tags in HTML5 const blockTags = { address: true, article: true, aside: true, blockquote: true, canvas: true, dd: true, div: true, dl: true, fieldset: true, figcaption: true, figure: true, footer: true, form: true, h1: true, h2: true, h3: true, h4: true, h5: true, h6: true, header: true, hgroup: true, hr: true, li: true, noscript: true, ol: true, output: true, p: true, pre: true, section: true, table: true, tfoot: true, ul: true } // : Object The tags that we normally ignore. const ignoreTags = { head: true, noscript: true, object: true, script: true, style: true, title: true } // : Object List tags. const listTags = {ol: true, ul: true} // Using a bitfield for node context options const OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4 function wsOptionsFor(preserveWhitespace) { return (preserveWhitespace ? OPT_PRESERVE_WS : 0) | (preserveWhitespace === "full" ? OPT_PRESERVE_WS_FULL : 0) } class NodeContext { constructor(type, attrs, marks, pendingMarks, solid, match, options) { this.type = type this.attrs = attrs this.solid = solid this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch) this.options = options this.content = [] // Marks applied to this node itself this.marks = marks // Marks applied to its children this.activeMarks = Mark.none // Marks that can't apply here, but will be used in children if possible this.pendingMarks = pendingMarks // Nested Marks with same type this.stashMarks = [] } findWrapping(node) { if (!this.match) { if (!this.type) return [] let fill = this.type.contentMatch.fillBefore(Fragment.from(node)) if (fill) { this.match = this.type.contentMatch.matchFragment(fill) } else { let start = this.type.contentMatch, wrap if (wrap = start.findWrapping(node.type)) { this.match = start return wrap } else { return null } } } return this.match.findWrapping(node.type) } finish(openEnd) { if (!(this.options & OPT_PRESERVE_WS)) { // Strip trailing whitespace let last = this.content[this.content.length - 1], m if (last && last.isText && (m = /[ \t\r\n\u000c]+$/.exec(last.text))) { if (last.text.length == m[0].length) this.content.pop() else this.content[this.content.length - 1] = last.withText(last.text.slice(0, last.text.length - m[0].length)) } } let content = Fragment.from(this.content) if (!openEnd && this.match) content = content.append(this.match.fillBefore(Fragment.empty, true)) return this.type ? this.type.create(this.attrs, content, this.marks) : content } popFromStashMark(mark) { for (let i = this.stashMarks.length - 1; i >= 0; i--) if (mark.eq(this.stashMarks[i])) return this.stashMarks.splice(i, 1)[0] } applyPending(nextType) { for (let i = 0, pending = this.pendingMarks; i < pending.length; i++) { let mark = pending[i] if ((this.type ? this.type.allowsMarkType(mark.type) : markMayApply(mark.type, nextType)) && !mark.isInSet(this.activeMarks)) { this.activeMarks = mark.addToSet(this.activeMarks) this.pendingMarks = mark.removeFromSet(this.pendingMarks) } } } inlineContext(node) { if (this.type) return this.type.inlineContent if (this.content.length) return this.content[0].isInline return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase()) } } class ParseContext { // : (DOMParser, Object) constructor(parser, options, open) { // : DOMParser The parser we are using. this.parser = parser // : Object The options passed to this parse. this.options = options this.isOpen = open let topNode = options.topNode, topContext let topOptions = wsOptionsFor(options.preserveWhitespace) | (open ? OPT_OPEN_LEFT : 0) if (topNode) topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, Mark.none, true, options.topMatch || topNode.type.contentMatch, topOptions) else if (open) topContext = new NodeContext(null, null, Mark.none, Mark.none, true, null, topOptions) else topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, Mark.none, true, null, topOptions) this.nodes = [topContext] // : [Mark] The current set of marks this.open = 0 this.find = options.findPositions this.needsBlock = false } get top() { return this.nodes[this.open] } // : (dom.Node) // Add a DOM node to the content. Text is inserted as text node, // otherwise, the node is passed to `addElement` or, if it has a // `style` attribute, `addElementWithStyles`. addDOM(dom) { if (dom.nodeType == 3) { this.addTextNode(dom) } else if (dom.nodeType == 1) { let style = dom.getAttribute("style") let marks = style ? this.readStyles(parseStyles(style)) : null, top = this.top if (marks != null) for (let i = 0; i < marks.length; i++) this.addPendingMark(marks[i]) this.addElement(dom) if (marks != null) for (let i = 0; i < marks.length; i++) this.removePendingMark(marks[i], top) } } addTextNode(dom) { let value = dom.nodeValue let top = this.top if (top.options & OPT_PRESERVE_WS_FULL || top.inlineContext(dom) || /[^ \t\r\n\u000c]/.test(value)) { if (!(top.options & OPT_PRESERVE_WS)) { value = value.replace(/[ \t\r\n\u000c]+/g, " ") // If this starts with whitespace, and there is no node before it, or // a hard break, or a text node that ends with whitespace, strip the // leading space. if (/^[ \t\r\n\u000c]/.test(value) && this.open == this.nodes.length - 1) { let nodeBefore = top.content[top.content.length - 1] let domNodeBefore = dom.previousSibling if (!nodeBefore || (domNodeBefore && domNodeBefore.nodeName == 'BR') || (nodeBefore.isText && /[ \t\r\n\u000c]$/.test(nodeBefore.text))) value = value.slice(1) } } else if (!(top.options & OPT_PRESERVE_WS_FULL)) { value = value.replace(/\r?\n|\r/g, " ") } else { value = value.replace(/\r\n?/g, "\n") } if (value) this.insertNode(this.parser.schema.text(value)) this.findInText(dom) } else { this.findInside(dom) } } // : (dom.Element, ?ParseRule) // Try to find a handler for the given tag and use that to parse. If // none is found, the element's content nodes are added directly. addElement(dom, matchAfter) { let name = dom.nodeName.toLowerCase(), ruleID if (listTags.hasOwnProperty(name) && this.parser.normalizeLists) normalizeList(dom) let rule = (this.options.ruleFromNode && this.options.ruleFromNode(dom)) || (ruleID = this.parser.matchTag(dom, this, matchAfter)) if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) { this.findInside(dom) this.ignoreFallback(dom) } else if (!rule || rule.skip || rule.closeParent) { if (rule && rule.closeParent) this.open = Math.max(0, this.open - 1) else if (rule && rule.skip.nodeType) dom = rule.skip let sync, top = this.top, oldNeedsBlock = this.needsBlock if (blockTags.hasOwnProperty(name)) { sync = true if (!top.type) this.needsBlock = true } else if (!dom.firstChild) { this.leafFallback(dom) return } this.addAll(dom) if (sync) this.sync(top) this.needsBlock = oldNeedsBlock } else { this.addElementByRule(dom, rule, rule.consuming === false ? ruleID : null) } } // Called for leaf DOM nodes that would otherwise be ignored leafFallback(dom) { if (dom.nodeName == "BR" && this.top.type && this.top.type.inlineContent) this.addTextNode(dom.ownerDocument.createTextNode("\n")) } // Called for ignored nodes ignoreFallback(dom) { // Ignored BR nodes should at least create an inline context if (dom.nodeName == "BR" && (!this.top.type || !this.top.type.inlineContent)) this.findPlace(this.parser.schema.text("-")) } // Run any style parser associated with the node's styles. Either // return an array of marks, or null to indicate some of the styles // had a rule with `ignore` set. readStyles(styles) { let marks = Mark.none style: for (let i = 0; i < styles.length; i += 2) { for (let after = null;;) { let rule = this.parser.matchStyle(styles[i], styles[i + 1], this, after) if (!rule) continue style if (rule.ignore) return null marks = this.parser.schema.marks[rule.mark].create(rule.attrs).addToSet(marks) if (rule.consuming === false) after = rule else break } } return marks } // : (dom.Element, ParseRule) → bool // Look up a handler for the given node. If none are found, return // false. Otherwise, apply it, use its return value to drive the way // the node's content is wrapped, and return true. addElementByRule(dom, rule, continueAfter) { let sync, nodeType, markType, mark if (rule.node) { nodeType = this.parser.schema.nodes[rule.node] if (!nodeType.isLeaf) { sync = this.enter(nodeType, rule.attrs, rule.preserveWhitespace) } else if (!this.insertNode(nodeType.create(rule.attrs))) { this.leafFallback(dom) } } else { markType = this.parser.schema.marks[rule.mark] mark = markType.create(rule.attrs) this.addPendingMark(mark) } let startIn = this.top if (nodeType && nodeType.isLeaf) { this.findInside(dom) } else if (continueAfter) { this.addElement(dom, continueAfter) } else if (rule.getContent) { this.findInside(dom) rule.getContent(dom, this.parser.schema).forEach(node => this.insertNode(node)) } else { let contentDOM = rule.contentElement if (typeof contentDOM == "string") contentDOM = dom.querySelector(contentDOM) else if (typeof contentDOM == "function") contentDOM = contentDOM(dom) if (!contentDOM) contentDOM = dom this.findAround(dom, contentDOM, true) this.addAll(contentDOM, sync) } if (sync) { this.sync(startIn); this.open-- } if (mark) this.removePendingMark(mark, startIn) } // : (dom.Node, ?NodeBuilder, ?number, ?number) // Add all child nodes between `startIndex` and `endIndex` (or the // whole node, if not given). If `sync` is passed, use it to // synchronize after every block element. addAll(parent, sync, startIndex, endIndex) { let index = startIndex || 0 for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) { this.findAtPoint(parent, index) this.addDOM(dom) if (sync && blockTags.hasOwnProperty(dom.nodeName.toLowerCase())) this.sync(sync) } this.findAtPoint(parent, index) } // Try to find a way to fit the given node type into the current // context. May add intermediate wrappers and/or leave non-solid // nodes that we're in. findPlace(node) { let route, sync for (let depth = this.open; depth >= 0; depth--) { let cx = this.nodes[depth] let found = cx.findWrapping(node) if (found && (!route || route.length > found.length)) { route = found sync = cx if (!found.length) break } if (cx.solid) break } if (!route) return false this.sync(sync) for (let i = 0; i < route.length; i++) this.enterInner(route[i], null, false) return true } // : (Node) → ?Node // Try to insert the given node, adjusting the context when needed. insertNode(node) { if (node.isInline && this.needsBlock && !this.top.type) { let block = this.textblockFromContext() if (block) this.enterInner(block) } if (this.findPlace(node)) { this.closeExtra() let top = this.top top.applyPending(node.type) if (top.match) top.match = top.match.matchType(node.type) let marks = top.activeMarks for (let i = 0; i < node.marks.length; i++) if (!top.type || top.type.allowsMarkType(node.marks[i].type)) marks = node.marks[i].addToSet(marks) top.content.push(node.mark(marks)) return true } return false } // : (NodeType, ?Object) → bool // Try to start a node of the given type, adjusting the context when // necessary. enter(type, attrs, preserveWS) { let ok = this.findPlace(type.create(attrs)) if (ok) this.enterInner(type, attrs, true, preserveWS) return ok } // Open a node of the given type enterInner(type, attrs, solid, preserveWS) { this.closeExtra() let top = this.top top.applyPending(type) top.match = top.match && top.match.matchType(type, attrs) let options = preserveWS == null ? top.options & ~OPT_OPEN_LEFT : wsOptionsFor(preserveWS) if ((top.options & OPT_OPEN_LEFT) && top.content.length == 0) options |= OPT_OPEN_LEFT this.nodes.push(new NodeContext(type, attrs, top.activeMarks, top.pendingMarks, solid, null, options)) this.open++ } // Make sure all nodes above this.open are finished and added to // their parents closeExtra(openEnd) { let i = this.nodes.length - 1 if (i > this.open) { for (; i > this.open; i--) this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd)) this.nodes.length = this.open + 1 } } finish() { this.open = 0 this.closeExtra(this.isOpen) return this.nodes[0].finish(this.isOpen || this.options.topOpen) } sync(to) { for (let i = this.open; i >= 0; i--) if (this.nodes[i] == to) { this.open = i return } } get currentPos() { this.closeExtra() let pos = 0 for (let i = this.open; i >= 0; i--) { let content = this.nodes[i].content for (let j = content.length - 1; j >= 0; j--) pos += content[j].nodeSize if (i) pos++ } return pos } findAtPoint(parent, offset) { if (this.find) for (let i = 0; i < this.find.length; i++) { if (this.find[i].node == parent && this.find[i].offset == offset) this.find[i].pos = this.currentPos } } findInside(parent) { if (this.find) for (let i = 0; i < this.find.length; i++) { if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) this.find[i].pos = this.currentPos } } findAround(parent, content, before) { if (parent != content && this.find) for (let i = 0; i < this.find.length; i++) { if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) { let pos = content.compareDocumentPosition(this.find[i].node) if (pos & (before ? 2 : 4)) this.find[i].pos = this.currentPos } } } findInText(textNode) { if (this.find) for (let i = 0; i < this.find.length; i++) { if (this.find[i].node == textNode) this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset) } } // : (string) → bool // Determines whether the given [context // string](#ParseRule.context) matches this context. matchesContext(context) { if (context.indexOf("|") > -1) return context.split(/\s*\|\s*/).some(this.matchesContext, this) let parts = context.split("/") let option = this.options.context let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type) let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1) let match = (i, depth) => { for (; i >= 0; i--) { let part = parts[i] if (part == "") { if (i == parts.length - 1 || i == 0) continue for (; depth >= minDepth; depth--) if (match(i - 1, depth)) return true return false } else { let next = depth > 0 || (depth == 0 && useRoot) ? this.nodes[depth].type : option && depth >= minDepth ? option.node(depth - minDepth).type : null if (!next || (next.name != part && next.groups.indexOf(part) == -1)) return false depth-- } } return true } return match(parts.length - 1, this.open) } textblockFromContext() { let $context = this.options.context if ($context) for (let d = $context.depth; d >= 0; d--) { let deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType if (deflt && deflt.isTextblock && deflt.defaultAttrs) return deflt } for (let name in this.parser.schema.nodes) { let type = this.parser.schema.nodes[name] if (type.isTextblock && type.defaultAttrs) return type } } addPendingMark(mark) { let found = findSameMarkInSet(mark, this.top.pendingMarks) if (found) this.top.stashMarks.push(found) this.top.pendingMarks = mark.addToSet(this.top.pendingMarks) } removePendingMark(mark, upto) { for (let depth = this.open; depth >= 0; depth--) { let level = this.nodes[depth] let found = level.pendingMarks.lastIndexOf(mark) if (found > -1) { level.pendingMarks = mark.removeFromSet(level.pendingMarks) } else { level.activeMarks = mark.removeFromSet(level.activeMarks) let stashMark = level.popFromStashMark(mark) if (stashMark && level.type && level.type.allowsMarkType(stashMark.type)) level.activeMarks = stashMark.addToSet(level.activeMarks) } if (level == upto) break } } } // Kludge to work around directly nested list nodes produced by some // tools and allowed by browsers to mean that the nested list is // actually part of the list item above it. function normalizeList(dom) { for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) { let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null if (name && listTags.hasOwnProperty(name) && prevItem) { prevItem.appendChild(child) child = prevItem } else if (name == "li") { prevItem = child } else if (name) { prevItem = null } } } // Apply a CSS selector. function matches(dom, selector) { return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector) } // : (string) → [string] // Tokenize a style attribute into property/value pairs. function parseStyles(style) { let re = /\s*([\w-]+)\s*:\s*([^;]+)/g, m, result = [] while (m = re.exec(style)) result.push(m[1], m[2].trim()) return result } function copy(obj) { let copy = {} for (let prop in obj) copy[prop] = obj[prop] return copy } // Used when finding a mark at the top level of a fragment parse. // Checks whether it would be reasonable to apply a given mark type to // a given node, by looking at the way the mark occurs in the schema. function markMayApply(markType, nodeType) { let nodes = nodeType.schema.nodes for (let name in nodes) { let parent = nodes[name] if (!parent.allowsMarkType(markType)) continue let seen = [], scan = match => { seen.push(match) for (let i = 0; i < match.edgeCount; i++) { let {type, next} = match.edge(i) if (type == nodeType) return true if (seen.indexOf(next) < 0 && scan(next)) return true } } if (scan(parent.contentMatch)) return true } } function findSameMarkInSet(mark, set) { for (let i = 0; i < set.length; i++) { if (mark.eq(set[i])) return set[i] } } prosemirror-model-1.15.0/src/index.js000066400000000000000000000005501413544732700175250ustar00rootroot00000000000000export {Node} from "./node" export {ResolvedPos, NodeRange} from "./resolvedpos" export {Fragment} from "./fragment" export {Slice, ReplaceError} from "./replace" export {Mark} from "./mark" export {Schema, NodeType, MarkType} from "./schema" export {ContentMatch} from "./content" export {DOMParser} from "./from_dom" export {DOMSerializer} from "./to_dom" prosemirror-model-1.15.0/src/mark.js000066400000000000000000000067721413544732700173640ustar00rootroot00000000000000import {compareDeep} from "./comparedeep" // ::- A mark is a piece of information that can be attached to a node, // such as it being emphasized, in code font, or a link. It has a type // and optionally a set of attributes that provide further information // (such as the target of the link). Marks are created through a // `Schema`, which controls which types exist and which // attributes they have. export class Mark { constructor(type, attrs) { // :: MarkType // The type of this mark. this.type = type // :: Object // The attributes associated with this mark. this.attrs = attrs } // :: ([Mark]) → [Mark] // Given a set of marks, create a new set which contains this one as // well, in the right position. If this mark is already in the set, // the set itself is returned. If any marks that are set to be // [exclusive](#model.MarkSpec.excludes) with this mark are present, // those are replaced by this one. addToSet(set) { let copy, placed = false for (let i = 0; i < set.length; i++) { let other = set[i] if (this.eq(other)) return set if (this.type.excludes(other.type)) { if (!copy) copy = set.slice(0, i) } else if (other.type.excludes(this.type)) { return set } else { if (!placed && other.type.rank > this.type.rank) { if (!copy) copy = set.slice(0, i) copy.push(this) placed = true } if (copy) copy.push(other) } } if (!copy) copy = set.slice() if (!placed) copy.push(this) return copy } // :: ([Mark]) → [Mark] // Remove this mark from the given set, returning a new set. If this // mark is not in the set, the set itself is returned. removeFromSet(set) { for (let i = 0; i < set.length; i++) if (this.eq(set[i])) return set.slice(0, i).concat(set.slice(i + 1)) return set } // :: ([Mark]) → bool // Test whether this mark is in the given set of marks. isInSet(set) { for (let i = 0; i < set.length; i++) if (this.eq(set[i])) return true return false } // :: (Mark) → bool // Test whether this mark has the same type and attributes as // another mark. eq(other) { return this == other || (this.type == other.type && compareDeep(this.attrs, other.attrs)) } // :: () → Object // Convert this mark to a JSON-serializeable representation. toJSON() { let obj = {type: this.type.name} for (let _ in this.attrs) { obj.attrs = this.attrs break } return obj } // :: (Schema, Object) → Mark static fromJSON(schema, json) { if (!json) throw new RangeError("Invalid input for Mark.fromJSON") let type = schema.marks[json.type] if (!type) throw new RangeError(`There is no mark type ${json.type} in this schema`) return type.create(json.attrs) } // :: ([Mark], [Mark]) → bool // Test whether two sets of marks are identical. static sameSet(a, b) { if (a == b) return true if (a.length != b.length) return false for (let i = 0; i < a.length; i++) if (!a[i].eq(b[i])) return false return true } // :: (?union) → [Mark] // Create a properly sorted mark set from null, a single mark, or an // unsorted array of marks. static setFrom(marks) { if (!marks || marks.length == 0) return Mark.none if (marks instanceof Mark) return [marks] let copy = marks.slice() copy.sort((a, b) => a.type.rank - b.type.rank) return copy } } // :: [Mark] The empty set of marks. Mark.none = [] prosemirror-model-1.15.0/src/node.js000066400000000000000000000361621413544732700173530ustar00rootroot00000000000000import {Fragment} from "./fragment" import {Mark} from "./mark" import {Slice, replace} from "./replace" import {ResolvedPos} from "./resolvedpos" import {compareDeep} from "./comparedeep" const emptyAttrs = Object.create(null) // ::- This class represents a node in the tree that makes up a // ProseMirror document. So a document is an instance of `Node`, with // children that are also instances of `Node`. // // Nodes are persistent data structures. Instead of changing them, you // create new ones with the content you want. Old ones keep pointing // at the old document shape. This is made cheaper by sharing // structure between the old and new data as much as possible, which a // tree shape like this (without back pointers) makes easy. // // **Do not** directly mutate the properties of a `Node` object. See // [the guide](/docs/guide/#doc) for more information. export class Node { constructor(type, attrs, content, marks) { // :: NodeType // The type of node that this is. this.type = type // :: Object // An object mapping attribute names to values. The kind of // attributes allowed and required are // [determined](#model.NodeSpec.attrs) by the node type. this.attrs = attrs // :: Fragment // A container holding the node's children. this.content = content || Fragment.empty // :: [Mark] // The marks (things like whether it is emphasized or part of a // link) applied to this node. this.marks = marks || Mark.none } // text:: ?string // For text nodes, this contains the node's text content. // :: number // The size of this node, as defined by the integer-based [indexing // scheme](/docs/guide/#doc.indexing). For text nodes, this is the // amount of characters. For other leaf nodes, it is one. For // non-leaf nodes, it is the size of the content plus two (the start // and end token). get nodeSize() { return this.isLeaf ? 1 : 2 + this.content.size } // :: number // The number of children that the node has. get childCount() { return this.content.childCount } // :: (number) → Node // Get the child node at the given index. Raises an error when the // index is out of range. child(index) { return this.content.child(index) } // :: (number) → ?Node // Get the child node at the given index, if it exists. maybeChild(index) { return this.content.maybeChild(index) } // :: ((node: Node, offset: number, index: number)) // Call `f` for every child node, passing the node, its offset // into this parent node, and its index. forEach(f) { this.content.forEach(f) } // :: (number, number, (node: Node, pos: number, parent: Node, index: number) → ?bool, ?number) // Invoke a callback for all descendant nodes recursively between // the given two positions that are relative to start of this node's // content. The callback is invoked with the node, its // parent-relative position, its parent node, and its child index. // When the callback returns false for a given node, that node's // children will not be recursed over. The last parameter can be // used to specify a starting position to count from. nodesBetween(from, to, f, startPos = 0) { this.content.nodesBetween(from, to, f, startPos, this) } // :: ((node: Node, pos: number, parent: Node) → ?bool) // Call the given callback for every descendant node. Doesn't // descend into a node when the callback returns `false`. descendants(f) { this.nodesBetween(0, this.content.size, f) } // :: string // Concatenates all the text nodes found in this fragment and its // children. get textContent() { return this.textBetween(0, this.content.size, "") } // :: (number, number, ?string, ?string | ?(leafNode: Node) -> string) → string // Get all text between positions `from` and `to`. When // `blockSeparator` is given, it will be inserted whenever a new // block node is started. When `leafText` is given, it'll be // inserted for every non-text leaf node encountered. textBetween(from, to, blockSeparator, leafText) { return this.content.textBetween(from, to, blockSeparator, leafText) } // :: ?Node // Returns this node's first child, or `null` if there are no // children. get firstChild() { return this.content.firstChild } // :: ?Node // Returns this node's last child, or `null` if there are no // children. get lastChild() { return this.content.lastChild } // :: (Node) → bool // Test whether two nodes represent the same piece of document. eq(other) { return this == other || (this.sameMarkup(other) && this.content.eq(other.content)) } // :: (Node) → bool // Compare the markup (type, attributes, and marks) of this node to // those of another. Returns `true` if both have the same markup. sameMarkup(other) { return this.hasMarkup(other.type, other.attrs, other.marks) } // :: (NodeType, ?Object, ?[Mark]) → bool // Check whether this node's markup correspond to the given type, // attributes, and marks. hasMarkup(type, attrs, marks) { return this.type == type && compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) && Mark.sameSet(this.marks, marks || Mark.none) } // :: (?Fragment) → Node // Create a new node with the same markup as this node, containing // the given content (or empty, if no content is given). copy(content = null) { if (content == this.content) return this return new this.constructor(this.type, this.attrs, content, this.marks) } // :: ([Mark]) → Node // Create a copy of this node, with the given set of marks instead // of the node's own marks. mark(marks) { return marks == this.marks ? this : new this.constructor(this.type, this.attrs, this.content, marks) } // :: (number, ?number) → Node // Create a copy of this node with only the content between the // given positions. If `to` is not given, it defaults to the end of // the node. cut(from, to) { if (from == 0 && to == this.content.size) return this return this.copy(this.content.cut(from, to)) } // :: (number, ?number) → Slice // Cut out the part of the document between the given positions, and // return it as a `Slice` object. slice(from, to = this.content.size, includeParents = false) { if (from == to) return Slice.empty let $from = this.resolve(from), $to = this.resolve(to) let depth = includeParents ? 0 : $from.sharedDepth(to) let start = $from.start(depth), node = $from.node(depth) let content = node.content.cut($from.pos - start, $to.pos - start) return new Slice(content, $from.depth - depth, $to.depth - depth) } // :: (number, number, Slice) → Node // Replace the part of the document between the given positions with // the given slice. The slice must 'fit', meaning its open sides // must be able to connect to the surrounding content, and its // content nodes must be valid children for the node they are placed // into. If any of this is violated, an error of type // [`ReplaceError`](#model.ReplaceError) is thrown. replace(from, to, slice) { return replace(this.resolve(from), this.resolve(to), slice) } // :: (number) → ?Node // Find the node directly after the given position. nodeAt(pos) { for (let node = this;;) { let {index, offset} = node.content.findIndex(pos) node = node.maybeChild(index) if (!node) return null if (offset == pos || node.isText) return node pos -= offset + 1 } } // :: (number) → {node: ?Node, index: number, offset: number} // Find the (direct) child node after the given offset, if any, // and return it along with its index and offset relative to this // node. childAfter(pos) { let {index, offset} = this.content.findIndex(pos) return {node: this.content.maybeChild(index), index, offset} } // :: (number) → {node: ?Node, index: number, offset: number} // Find the (direct) child node before the given offset, if any, // and return it along with its index and offset relative to this // node. childBefore(pos) { if (pos == 0) return {node: null, index: 0, offset: 0} let {index, offset} = this.content.findIndex(pos) if (offset < pos) return {node: this.content.child(index), index, offset} let node = this.content.child(index - 1) return {node, index: index - 1, offset: offset - node.nodeSize} } // :: (number) → ResolvedPos // Resolve the given position in the document, returning an // [object](#model.ResolvedPos) with information about its context. resolve(pos) { return ResolvedPos.resolveCached(this, pos) } resolveNoCache(pos) { return ResolvedPos.resolve(this, pos) } // :: (number, number, union) → bool // Test whether a given mark or mark type occurs in this document // between the two given positions. rangeHasMark(from, to, type) { let found = false if (to > from) this.nodesBetween(from, to, node => { if (type.isInSet(node.marks)) found = true return !found }) return found } // :: bool // True when this is a block (non-inline node) get isBlock() { return this.type.isBlock } // :: bool // True when this is a textblock node, a block node with inline // content. get isTextblock() { return this.type.isTextblock } // :: bool // True when this node allows inline content. get inlineContent() { return this.type.inlineContent } // :: bool // True when this is an inline node (a text node or a node that can // appear among text). get isInline() { return this.type.isInline } // :: bool // True when this is a text node. get isText() { return this.type.isText } // :: bool // True when this is a leaf node. get isLeaf() { return this.type.isLeaf } // :: bool // True when this is an atom, i.e. when it does not have directly // editable content. This is usually the same as `isLeaf`, but can // be configured with the [`atom` property](#model.NodeSpec.atom) on // a node's spec (typically used when the node is displayed as an // uneditable [node view](#view.NodeView)). get isAtom() { return this.type.isAtom } // :: () → string // Return a string representation of this node for debugging // purposes. toString() { if (this.type.spec.toDebugString) return this.type.spec.toDebugString(this) let name = this.type.name if (this.content.size) name += "(" + this.content.toStringInner() + ")" return wrapMarks(this.marks, name) } // :: (number) → ContentMatch // Get the content match in this node at the given index. contentMatchAt(index) { let match = this.type.contentMatch.matchFragment(this.content, 0, index) if (!match) throw new Error("Called contentMatchAt on a node with invalid content") return match } // :: (number, number, ?Fragment, ?number, ?number) → bool // Test whether replacing the range between `from` and `to` (by // child index) with the given replacement fragment (which defaults // to the empty fragment) would leave the node's content valid. You // can optionally pass `start` and `end` indices into the // replacement fragment. canReplace(from, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) { let one = this.contentMatchAt(from).matchFragment(replacement, start, end) let two = one && one.matchFragment(this.content, to) if (!two || !two.validEnd) return false for (let i = start; i < end; i++) if (!this.type.allowsMarks(replacement.child(i).marks)) return false return true } // :: (number, number, NodeType, ?[Mark]) → bool // Test whether replacing the range `from` to `to` (by index) with a // node of the given type would leave the node's content valid. canReplaceWith(from, to, type, marks) { if (marks && !this.type.allowsMarks(marks)) return false let start = this.contentMatchAt(from).matchType(type) let end = start && start.matchFragment(this.content, to) return end ? end.validEnd : false } // :: (Node) → bool // Test whether the given node's content could be appended to this // node. If that node is empty, this will only return true if there // is at least one node type that can appear in both nodes (to avoid // merging completely incompatible nodes). canAppend(other) { if (other.content.size) return this.canReplace(this.childCount, this.childCount, other.content) else return this.type.compatibleContent(other.type) } // :: () // Check whether this node and its descendants conform to the // schema, and raise error when they do not. check() { if (!this.type.validContent(this.content)) throw new RangeError(`Invalid content for node ${this.type.name}: ${this.content.toString().slice(0, 50)}`) let copy = Mark.none for (let i = 0; i < this.marks.length; i++) copy = this.marks[i].addToSet(copy) if (!Mark.sameSet(copy, this.marks)) throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(m => m.type.name)}`) this.content.forEach(node => node.check()) } // :: () → Object // Return a JSON-serializeable representation of this node. toJSON() { let obj = {type: this.type.name} for (let _ in this.attrs) { obj.attrs = this.attrs break } if (this.content.size) obj.content = this.content.toJSON() if (this.marks.length) obj.marks = this.marks.map(n => n.toJSON()) return obj } // :: (Schema, Object) → Node // Deserialize a node from its JSON representation. static fromJSON(schema, json) { if (!json) throw new RangeError("Invalid input for Node.fromJSON") let marks = null if (json.marks) { if (!Array.isArray(json.marks)) throw new RangeError("Invalid mark data for Node.fromJSON") marks = json.marks.map(schema.markFromJSON) } if (json.type == "text") { if (typeof json.text != "string") throw new RangeError("Invalid text node in JSON") return schema.text(json.text, marks) } let content = Fragment.fromJSON(schema, json.content) return schema.nodeType(json.type).create(json.attrs, content, marks) } } export class TextNode extends Node { constructor(type, attrs, content, marks) { super(type, attrs, null, marks) if (!content) throw new RangeError("Empty text nodes are not allowed") this.text = content } toString() { if (this.type.spec.toDebugString) return this.type.spec.toDebugString(this) return wrapMarks(this.marks, JSON.stringify(this.text)) } get textContent() { return this.text } textBetween(from, to) { return this.text.slice(from, to) } get nodeSize() { return this.text.length } mark(marks) { return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks) } withText(text) { if (text == this.text) return this return new TextNode(this.type, this.attrs, text, this.marks) } cut(from = 0, to = this.text.length) { if (from == 0 && to == this.text.length) return this return this.withText(this.text.slice(from, to)) } eq(other) { return this.sameMarkup(other) && this.text == other.text } toJSON() { let base = super.toJSON() base.text = this.text return base } } function wrapMarks(marks, str) { for (let i = marks.length - 1; i >= 0; i--) str = marks[i].type.name + "(" + str + ")" return str } prosemirror-model-1.15.0/src/replace.js000066400000000000000000000207061413544732700200360ustar00rootroot00000000000000import {Fragment} from "./fragment" // ReplaceError:: class extends Error // Error type raised by [`Node.replace`](#model.Node.replace) when // given an invalid replacement. export function ReplaceError(message) { let err = Error.call(this, message) err.__proto__ = ReplaceError.prototype return err } ReplaceError.prototype = Object.create(Error.prototype) ReplaceError.prototype.constructor = ReplaceError ReplaceError.prototype.name = "ReplaceError" // ::- A slice represents a piece cut out of a larger document. It // stores not only a fragment, but also the depth up to which nodes on // both side are ‘open’ (cut through). export class Slice { // :: (Fragment, number, number) // Create a slice. When specifying a non-zero open depth, you must // make sure that there are nodes of at least that depth at the // appropriate side of the fragment—i.e. if the fragment is an empty // paragraph node, `openStart` and `openEnd` can't be greater than 1. // // It is not necessary for the content of open nodes to conform to // the schema's content constraints, though it should be a valid // start/end/middle for such a node, depending on which sides are // open. constructor(content, openStart, openEnd) { // :: Fragment The slice's content. this.content = content // :: number The open depth at the start. this.openStart = openStart // :: number The open depth at the end. this.openEnd = openEnd } // :: number // The size this slice would add when inserted into a document. get size() { return this.content.size - this.openStart - this.openEnd } insertAt(pos, fragment) { let content = insertInto(this.content, pos + this.openStart, fragment, null) return content && new Slice(content, this.openStart, this.openEnd) } removeBetween(from, to) { return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd) } // :: (Slice) → bool // Tests whether this slice is equal to another slice. eq(other) { return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd } toString() { return this.content + "(" + this.openStart + "," + this.openEnd + ")" } // :: () → ?Object // Convert a slice to a JSON-serializable representation. toJSON() { if (!this.content.size) return null let json = {content: this.content.toJSON()} if (this.openStart > 0) json.openStart = this.openStart if (this.openEnd > 0) json.openEnd = this.openEnd return json } // :: (Schema, ?Object) → Slice // Deserialize a slice from its JSON representation. static fromJSON(schema, json) { if (!json) return Slice.empty let openStart = json.openStart || 0, openEnd = json.openEnd || 0 if (typeof openStart != "number" || typeof openEnd != "number") throw new RangeError("Invalid input for Slice.fromJSON") return new Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd) } // :: (Fragment, ?bool) → Slice // Create a slice from a fragment by taking the maximum possible // open value on both side of the fragment. static maxOpen(fragment, openIsolating=true) { let openStart = 0, openEnd = 0 for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild) openStart++ for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild) openEnd++ return new Slice(fragment, openStart, openEnd) } } function removeRange(content, from, to) { let {index, offset} = content.findIndex(from), child = content.maybeChild(index) let {index: indexTo, offset: offsetTo} = content.findIndex(to) if (offset == from || child.isText) { if (offsetTo != to && !content.child(indexTo).isText) throw new RangeError("Removing non-flat range") return content.cut(0, from).append(content.cut(to)) } if (index != indexTo) throw new RangeError("Removing non-flat range") return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1))) } function insertInto(content, dist, insert, parent) { let {index, offset} = content.findIndex(dist), child = content.maybeChild(index) if (offset == dist || child.isText) { if (parent && !parent.canReplace(index, index, insert)) return null return content.cut(0, dist).append(insert).append(content.cut(dist)) } let inner = insertInto(child.content, dist - offset - 1, insert) return inner && content.replaceChild(index, child.copy(inner)) } // :: Slice // The empty slice. Slice.empty = new Slice(Fragment.empty, 0, 0) export function replace($from, $to, slice) { if (slice.openStart > $from.depth) throw new ReplaceError("Inserted content deeper than insertion position") if ($from.depth - slice.openStart != $to.depth - slice.openEnd) throw new ReplaceError("Inconsistent open depths") return replaceOuter($from, $to, slice, 0) } function replaceOuter($from, $to, slice, depth) { let index = $from.index(depth), node = $from.node(depth) if (index == $to.index(depth) && depth < $from.depth - slice.openStart) { let inner = replaceOuter($from, $to, slice, depth + 1) return node.copy(node.content.replaceChild(index, inner)) } else if (!slice.content.size) { return close(node, replaceTwoWay($from, $to, depth)) } else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) { // Simple, flat case let parent = $from.parent, content = parent.content return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset))) } else { let {start, end} = prepareSliceForReplace(slice, $from) return close(node, replaceThreeWay($from, start, end, $to, depth)) } } function checkJoin(main, sub) { if (!sub.type.compatibleContent(main.type)) throw new ReplaceError("Cannot join " + sub.type.name + " onto " + main.type.name) } function joinable($before, $after, depth) { let node = $before.node(depth) checkJoin(node, $after.node(depth)) return node } function addNode(child, target) { let last = target.length - 1 if (last >= 0 && child.isText && child.sameMarkup(target[last])) target[last] = child.withText(target[last].text + child.text) else target.push(child) } function addRange($start, $end, depth, target) { let node = ($end || $start).node(depth) let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount if ($start) { startIndex = $start.index(depth) if ($start.depth > depth) { startIndex++ } else if ($start.textOffset) { addNode($start.nodeAfter, target) startIndex++ } } for (let i = startIndex; i < endIndex; i++) addNode(node.child(i), target) if ($end && $end.depth == depth && $end.textOffset) addNode($end.nodeBefore, target) } function close(node, content) { if (!node.type.validContent(content)) throw new ReplaceError("Invalid content for node " + node.type.name) return node.copy(content) } function replaceThreeWay($from, $start, $end, $to, depth) { let openStart = $from.depth > depth && joinable($from, $start, depth + 1) let openEnd = $to.depth > depth && joinable($end, $to, depth + 1) let content = [] addRange(null, $from, depth, content) if (openStart && openEnd && $start.index(depth) == $end.index(depth)) { checkJoin(openStart, openEnd) addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content) } else { if (openStart) addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content) addRange($start, $end, depth, content) if (openEnd) addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content) } addRange($to, null, depth, content) return new Fragment(content) } function replaceTwoWay($from, $to, depth) { let content = [] addRange(null, $from, depth, content) if ($from.depth > depth) { let type = joinable($from, $to, depth + 1) addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content) } addRange($to, null, depth, content) return new Fragment(content) } function prepareSliceForReplace(slice, $along) { let extra = $along.depth - slice.openStart, parent = $along.node(extra) let node = parent.copy(slice.content) for (let i = extra - 1; i >= 0; i--) node = $along.node(i).copy(Fragment.from(node)) return {start: node.resolveNoCache(slice.openStart + extra), end: node.resolveNoCache(node.content.size - slice.openEnd - extra)} } prosemirror-model-1.15.0/src/resolvedpos.js000066400000000000000000000262531413544732700207730ustar00rootroot00000000000000import {Mark} from "./mark" // ::- You can [_resolve_](#model.Node.resolve) a position to get more // information about it. Objects of this class represent such a // resolved position, providing various pieces of context information, // and some helper methods. // // Throughout this interface, methods that take an optional `depth` // parameter will interpret undefined as `this.depth` and negative // numbers as `this.depth + value`. export class ResolvedPos { constructor(pos, path, parentOffset) { // :: number The position that was resolved. this.pos = pos this.path = path // :: number // The number of levels the parent node is from the root. If this // position points directly into the root node, it is 0. If it // points into a top-level paragraph, 1, and so on. this.depth = path.length / 3 - 1 // :: number The offset this position has into its parent node. this.parentOffset = parentOffset } resolveDepth(val) { if (val == null) return this.depth if (val < 0) return this.depth + val return val } // :: Node // The parent node that the position points into. Note that even if // a position points into a text node, that node is not considered // the parent—text nodes are ‘flat’ in this model, and have no content. get parent() { return this.node(this.depth) } // :: Node // The root node in which the position was resolved. get doc() { return this.node(0) } // :: (?number) → Node // The ancestor node at the given level. `p.node(p.depth)` is the // same as `p.parent`. node(depth) { return this.path[this.resolveDepth(depth) * 3] } // :: (?number) → number // The index into the ancestor at the given level. If this points at // the 3rd node in the 2nd paragraph on the top level, for example, // `p.index(0)` is 1 and `p.index(1)` is 2. index(depth) { return this.path[this.resolveDepth(depth) * 3 + 1] } // :: (?number) → number // The index pointing after this position into the ancestor at the // given level. indexAfter(depth) { depth = this.resolveDepth(depth) return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1) } // :: (?number) → number // The (absolute) position at the start of the node at the given // level. start(depth) { depth = this.resolveDepth(depth) return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1 } // :: (?number) → number // The (absolute) position at the end of the node at the given // level. end(depth) { depth = this.resolveDepth(depth) return this.start(depth) + this.node(depth).content.size } // :: (?number) → number // The (absolute) position directly before the wrapping node at the // given level, or, when `depth` is `this.depth + 1`, the original // position. before(depth) { depth = this.resolveDepth(depth) if (!depth) throw new RangeError("There is no position before the top-level node") return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] } // :: (?number) → number // The (absolute) position directly after the wrapping node at the // given level, or the original position when `depth` is `this.depth + 1`. after(depth) { depth = this.resolveDepth(depth) if (!depth) throw new RangeError("There is no position after the top-level node") return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize } // :: number // When this position points into a text node, this returns the // distance between the position and the start of the text node. // Will be zero for positions that point between nodes. get textOffset() { return this.pos - this.path[this.path.length - 1] } // :: ?Node // Get the node directly after the position, if any. If the position // points into a text node, only the part of that node after the // position is returned. get nodeAfter() { let parent = this.parent, index = this.index(this.depth) if (index == parent.childCount) return null let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index) return dOff ? parent.child(index).cut(dOff) : child } // :: ?Node // Get the node directly before the position, if any. If the // position points into a text node, only the part of that node // before the position is returned. get nodeBefore() { let index = this.index(this.depth) let dOff = this.pos - this.path[this.path.length - 1] if (dOff) return this.parent.child(index).cut(0, dOff) return index == 0 ? null : this.parent.child(index - 1) } // :: (number, ?number) → number // Get the position at the given index in the parent node at the // given depth (which defaults to `this.depth`). posAtIndex(index, depth) { depth = this.resolveDepth(depth) let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1 for (let i = 0; i < index; i++) pos += node.child(i).nodeSize return pos } // :: () → [Mark] // Get the marks at this position, factoring in the surrounding // marks' [`inclusive`](#model.MarkSpec.inclusive) property. If the // position is at the start of a non-empty node, the marks of the // node after it (if any) are returned. marks() { let parent = this.parent, index = this.index() // In an empty parent, return the empty array if (parent.content.size == 0) return Mark.none // When inside a text node, just return the text node's marks if (this.textOffset) return parent.child(index).marks let main = parent.maybeChild(index - 1), other = parent.maybeChild(index) // If the `after` flag is true of there is no node before, make // the node after this position the main reference. if (!main) { let tmp = main; main = other; other = tmp } // Use all marks in the main node, except those that have // `inclusive` set to false and are not present in the other node. let marks = main.marks for (var i = 0; i < marks.length; i++) if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks))) marks = marks[i--].removeFromSet(marks) return marks } // :: (ResolvedPos) → ?[Mark] // Get the marks after the current position, if any, except those // that are non-inclusive and not present at position `$end`. This // is mostly useful for getting the set of marks to preserve after a // deletion. Will return `null` if this position is at the end of // its parent node or its parent node isn't a textblock (in which // case no marks should be preserved). marksAcross($end) { let after = this.parent.maybeChild(this.index()) if (!after || !after.isInline) return null let marks = after.marks, next = $end.parent.maybeChild($end.index()) for (var i = 0; i < marks.length; i++) if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks))) marks = marks[i--].removeFromSet(marks) return marks } // :: (number) → number // The depth up to which this position and the given (non-resolved) // position share the same parent nodes. sharedDepth(pos) { for (let depth = this.depth; depth > 0; depth--) if (this.start(depth) <= pos && this.end(depth) >= pos) return depth return 0 } // :: (?ResolvedPos, ?(Node) → bool) → ?NodeRange // Returns a range based on the place where this position and the // given position diverge around block content. If both point into // the same textblock, for example, a range around that textblock // will be returned. If they point into different blocks, the range // around those blocks in their shared ancestor is returned. You can // pass in an optional predicate that will be called with a parent // node to see if a range into that parent is acceptable. blockRange(other = this, pred) { if (other.pos < this.pos) return other.blockRange(this) for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--) if (other.pos <= this.end(d) && (!pred || pred(this.node(d)))) return new NodeRange(this, other, d) } // :: (ResolvedPos) → bool // Query whether the given position shares the same parent node. sameParent(other) { return this.pos - this.parentOffset == other.pos - other.parentOffset } // :: (ResolvedPos) → ResolvedPos // Return the greater of this and the given position. max(other) { return other.pos > this.pos ? other : this } // :: (ResolvedPos) → ResolvedPos // Return the smaller of this and the given position. min(other) { return other.pos < this.pos ? other : this } toString() { let str = "" for (let i = 1; i <= this.depth; i++) str += (str ? "/" : "") + this.node(i).type.name + "_" + this.index(i - 1) return str + ":" + this.parentOffset } static resolve(doc, pos) { if (!(pos >= 0 && pos <= doc.content.size)) throw new RangeError("Position " + pos + " out of range") let path = [] let start = 0, parentOffset = pos for (let node = doc;;) { let {index, offset} = node.content.findIndex(parentOffset) let rem = parentOffset - offset path.push(node, index, start + offset) if (!rem) break node = node.child(index) if (node.isText) break parentOffset = rem - 1 start += offset + 1 } return new ResolvedPos(pos, path, parentOffset) } static resolveCached(doc, pos) { for (let i = 0; i < resolveCache.length; i++) { let cached = resolveCache[i] if (cached.pos == pos && cached.doc == doc) return cached } let result = resolveCache[resolveCachePos] = ResolvedPos.resolve(doc, pos) resolveCachePos = (resolveCachePos + 1) % resolveCacheSize return result } } let resolveCache = [], resolveCachePos = 0, resolveCacheSize = 12 // ::- Represents a flat range of content, i.e. one that starts and // ends in the same node. export class NodeRange { // :: (ResolvedPos, ResolvedPos, number) // Construct a node range. `$from` and `$to` should point into the // same node until at least the given `depth`, since a node range // denotes an adjacent set of nodes in a single parent node. constructor($from, $to, depth) { // :: ResolvedPos A resolved position along the start of the // content. May have a `depth` greater than this object's `depth` // property, since these are the positions that were used to // compute the range, not re-resolved positions directly at its // boundaries. this.$from = $from // :: ResolvedPos A position along the end of the content. See // caveat for [`$from`](#model.NodeRange.$from). this.$to = $to // :: number The depth of the node that this range points into. this.depth = depth } // :: number The position at the start of the range. get start() { return this.$from.before(this.depth + 1) } // :: number The position at the end of the range. get end() { return this.$to.after(this.depth + 1) } // :: Node The parent node that the range points into. get parent() { return this.$from.node(this.depth) } // :: number The start index of the range in the parent node. get startIndex() { return this.$from.index(this.depth) } // :: number The end index of the range in the parent node. get endIndex() { return this.$to.indexAfter(this.depth) } } prosemirror-model-1.15.0/src/schema.js000066400000000000000000000512531413544732700176640ustar00rootroot00000000000000import OrderedMap from "orderedmap" import {Node, TextNode} from "./node" import {Fragment} from "./fragment" import {Mark} from "./mark" import {ContentMatch} from "./content" // For node types where all attrs have a default value (or which don't // have any attributes), build up a single reusable default attribute // object, and use it for all nodes that don't specify specific // attributes. function defaultAttrs(attrs) { let defaults = Object.create(null) for (let attrName in attrs) { let attr = attrs[attrName] if (!attr.hasDefault) return null defaults[attrName] = attr.default } return defaults } function computeAttrs(attrs, value) { let built = Object.create(null) for (let name in attrs) { let given = value && value[name] if (given === undefined) { let attr = attrs[name] if (attr.hasDefault) given = attr.default else throw new RangeError("No value supplied for attribute " + name) } built[name] = given } return built } function initAttrs(attrs) { let result = Object.create(null) if (attrs) for (let name in attrs) result[name] = new Attribute(attrs[name]) return result } // ::- Node types are objects allocated once per `Schema` and used to // [tag](#model.Node.type) `Node` instances. They contain information // about the node type, such as its name and what kind of node it // represents. export class NodeType { constructor(name, schema, spec) { // :: string // The name the node type has in this schema. this.name = name // :: Schema // A link back to the `Schema` the node type belongs to. this.schema = schema // :: NodeSpec // The spec that this type is based on this.spec = spec this.groups = spec.group ? spec.group.split(" ") : [] this.attrs = initAttrs(spec.attrs) this.defaultAttrs = defaultAttrs(this.attrs) // :: ContentMatch // The starting match of the node type's content expression. this.contentMatch = null // : ?[MarkType] // The set of marks allowed in this node. `null` means all marks // are allowed. this.markSet = null // :: bool // True if this node type has inline content. this.inlineContent = null // :: bool // True if this is a block type this.isBlock = !(spec.inline || name == "text") // :: bool // True if this is the text node type. this.isText = name == "text" } // :: bool // True if this is an inline type. get isInline() { return !this.isBlock } // :: bool // True if this is a textblock type, a block that contains inline // content. get isTextblock() { return this.isBlock && this.inlineContent } // :: bool // True for node types that allow no content. get isLeaf() { return this.contentMatch == ContentMatch.empty } // :: bool // True when this node is an atom, i.e. when it does not have // directly editable content. get isAtom() { return this.isLeaf || this.spec.atom } // :: () → bool // Tells you whether this node type has any required attributes. hasRequiredAttrs() { for (let n in this.attrs) if (this.attrs[n].isRequired) return true return false } compatibleContent(other) { return this == other || this.contentMatch.compatible(other.contentMatch) } computeAttrs(attrs) { if (!attrs && this.defaultAttrs) return this.defaultAttrs else return computeAttrs(this.attrs, attrs) } // :: (?Object, ?union, ?[Mark]) → Node // Create a `Node` of this type. The given attributes are // checked and defaulted (you can pass `null` to use the type's // defaults entirely, if no required attributes exist). `content` // may be a `Fragment`, a node, an array of nodes, or // `null`. Similarly `marks` may be `null` to default to the empty // set of marks. create(attrs, content, marks) { if (this.isText) throw new Error("NodeType.create can't construct text nodes") return new Node(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks)) } // :: (?Object, ?union, ?[Mark]) → Node // Like [`create`](#model.NodeType.create), but check the given content // against the node type's content restrictions, and throw an error // if it doesn't match. createChecked(attrs, content, marks) { content = Fragment.from(content) if (!this.validContent(content)) throw new RangeError("Invalid content for node " + this.name) return new Node(this, this.computeAttrs(attrs), content, Mark.setFrom(marks)) } // :: (?Object, ?union, ?[Mark]) → ?Node // Like [`create`](#model.NodeType.create), but see if it is necessary to // add nodes to the start or end of the given fragment to make it // fit the node. If no fitting wrapping can be found, return null. // Note that, due to the fact that required nodes can always be // created, this will always succeed if you pass null or // `Fragment.empty` as content. createAndFill(attrs, content, marks) { attrs = this.computeAttrs(attrs) content = Fragment.from(content) if (content.size) { let before = this.contentMatch.fillBefore(content) if (!before) return null content = before.append(content) } let after = this.contentMatch.matchFragment(content).fillBefore(Fragment.empty, true) if (!after) return null return new Node(this, attrs, content.append(after), Mark.setFrom(marks)) } // :: (Fragment) → bool // Returns true if the given fragment is valid content for this node // type with the given attributes. validContent(content) { let result = this.contentMatch.matchFragment(content) if (!result || !result.validEnd) return false for (let i = 0; i < content.childCount; i++) if (!this.allowsMarks(content.child(i).marks)) return false return true } // :: (MarkType) → bool // Check whether the given mark type is allowed in this node. allowsMarkType(markType) { return this.markSet == null || this.markSet.indexOf(markType) > -1 } // :: ([Mark]) → bool // Test whether the given set of marks are allowed in this node. allowsMarks(marks) { if (this.markSet == null) return true for (let i = 0; i < marks.length; i++) if (!this.allowsMarkType(marks[i].type)) return false return true } // :: ([Mark]) → [Mark] // Removes the marks that are not allowed in this node from the given set. allowedMarks(marks) { if (this.markSet == null) return marks let copy for (let i = 0; i < marks.length; i++) { if (!this.allowsMarkType(marks[i].type)) { if (!copy) copy = marks.slice(0, i) } else if (copy) { copy.push(marks[i]) } } return !copy ? marks : copy.length ? copy : Mark.empty } static compile(nodes, schema) { let result = Object.create(null) nodes.forEach((name, spec) => result[name] = new NodeType(name, schema, spec)) let topType = schema.spec.topNode || "doc" if (!result[topType]) throw new RangeError("Schema is missing its top node type ('" + topType + "')") if (!result.text) throw new RangeError("Every schema needs a 'text' type") for (let _ in result.text.attrs) throw new RangeError("The text node type should not have attributes") return result } } // Attribute descriptors class Attribute { constructor(options) { this.hasDefault = Object.prototype.hasOwnProperty.call(options, "default") this.default = options.default } get isRequired() { return !this.hasDefault } } // Marks // ::- Like nodes, marks (which are associated with nodes to signify // things like emphasis or being part of a link) are // [tagged](#model.Mark.type) with type objects, which are // instantiated once per `Schema`. export class MarkType { constructor(name, rank, schema, spec) { // :: string // The name of the mark type. this.name = name // :: Schema // The schema that this mark type instance is part of. this.schema = schema // :: MarkSpec // The spec on which the type is based. this.spec = spec this.attrs = initAttrs(spec.attrs) this.rank = rank this.excluded = null let defaults = defaultAttrs(this.attrs) this.instance = defaults && new Mark(this, defaults) } // :: (?Object) → Mark // Create a mark of this type. `attrs` may be `null` or an object // containing only some of the mark's attributes. The others, if // they have defaults, will be added. create(attrs) { if (!attrs && this.instance) return this.instance return new Mark(this, computeAttrs(this.attrs, attrs)) } static compile(marks, schema) { let result = Object.create(null), rank = 0 marks.forEach((name, spec) => result[name] = new MarkType(name, rank++, schema, spec)) return result } // :: ([Mark]) → [Mark] // When there is a mark of this type in the given set, a new set // without it is returned. Otherwise, the input set is returned. removeFromSet(set) { for (var i = 0; i < set.length; i++) if (set[i].type == this) { set = set.slice(0, i).concat(set.slice(i + 1)) i-- } return set } // :: ([Mark]) → ?Mark // Tests whether there is a mark of this type in the given set. isInSet(set) { for (let i = 0; i < set.length; i++) if (set[i].type == this) return set[i] } // :: (MarkType) → bool // Queries whether a given mark type is // [excluded](#model.MarkSpec.excludes) by this one. excludes(other) { return this.excluded.indexOf(other) > -1 } } // SchemaSpec:: interface // An object describing a schema, as passed to the [`Schema`](#model.Schema) // constructor. // // nodes:: union, OrderedMap> // The node types in this schema. Maps names to // [`NodeSpec`](#model.NodeSpec) objects that describe the node type // associated with that name. Their order is significant—it // determines which [parse rules](#model.NodeSpec.parseDOM) take // precedence by default, and which nodes come first in a given // [group](#model.NodeSpec.group). // // marks:: ?union, OrderedMap> // The mark types that exist in this schema. The order in which they // are provided determines the order in which [mark // sets](#model.Mark.addToSet) are sorted and in which [parse // rules](#model.MarkSpec.parseDOM) are tried. // // topNode:: ?string // The name of the default top-level node for the schema. Defaults // to `"doc"`. // NodeSpec:: interface // // content:: ?string // The content expression for this node, as described in the [schema // guide](/docs/guide/#schema.content_expressions). When not given, // the node does not allow any content. // // marks:: ?string // The marks that are allowed inside of this node. May be a // space-separated string referring to mark names or groups, `"_"` // to explicitly allow all marks, or `""` to disallow marks. When // not given, nodes with inline content default to allowing all // marks, other nodes default to not allowing marks. // // group:: ?string // The group or space-separated groups to which this node belongs, // which can be referred to in the content expressions for the // schema. // // inline:: ?bool // Should be set to true for inline nodes. (Implied for text nodes.) // // atom:: ?bool // Can be set to true to indicate that, though this isn't a [leaf // node](#model.NodeType.isLeaf), it doesn't have directly editable // content and should be treated as a single unit in the view. // // attrs:: ?Object // The attributes that nodes of this type get. // // selectable:: ?bool // Controls whether nodes of this type can be selected as a [node // selection](#state.NodeSelection). Defaults to true for non-text // nodes. // // draggable:: ?bool // Determines whether nodes of this type can be dragged without // being selected. Defaults to false. // // code:: ?bool // Can be used to indicate that this node contains code, which // causes some commands to behave differently. // // defining:: ?bool // Determines whether this node is considered an important parent // node during replace operations (such as paste). Non-defining (the // default) nodes get dropped when their entire content is replaced, // whereas defining nodes persist and wrap the inserted content. // Likewise, in _inserted_ content the defining parents of the // content are preserved when possible. Typically, // non-default-paragraph textblock types, and possibly list items, // are marked as defining. // // isolating:: ?bool // When enabled (default is false), the sides of nodes of this type // count as boundaries that regular editing operations, like // backspacing or lifting, won't cross. An example of a node that // should probably have this enabled is a table cell. // // toDOM:: ?(node: Node) → DOMOutputSpec // Defines the default way a node of this type should be serialized // to DOM/HTML (as used by // [`DOMSerializer.fromSchema`](#model.DOMSerializer^fromSchema)). // Should return a DOM node or an [array // structure](#model.DOMOutputSpec) that describes one, with an // optional number zero (“hole”) in it to indicate where the node's // content should be inserted. // // For text nodes, the default is to create a text DOM node. Though // it is possible to create a serializer where text is rendered // differently, this is not supported inside the editor, so you // shouldn't override that in your text node spec. // // parseDOM:: ?[ParseRule] // Associates DOM parser information with this node, which can be // used by [`DOMParser.fromSchema`](#model.DOMParser^fromSchema) to // automatically derive a parser. The `node` field in the rules is // implied (the name of this node will be filled in automatically). // If you supply your own parser, you do not need to also specify // parsing rules in your schema. // // toDebugString:: ?(node: Node) -> string // Defines the default way a node of this type should be serialized // to a string representation for debugging (e.g. in error messages). // MarkSpec:: interface // // attrs:: ?Object // The attributes that marks of this type get. // // inclusive:: ?bool // Whether this mark should be active when the cursor is positioned // at its end (or at its start when that is also the start of the // parent node). Defaults to true. // // excludes:: ?string // Determines which other marks this mark can coexist with. Should // be a space-separated strings naming other marks or groups of marks. // When a mark is [added](#model.Mark.addToSet) to a set, all marks // that it excludes are removed in the process. If the set contains // any mark that excludes the new mark but is not, itself, excluded // by the new mark, the mark can not be added an the set. You can // use the value `"_"` to indicate that the mark excludes all // marks in the schema. // // Defaults to only being exclusive with marks of the same type. You // can set it to an empty string (or any string not containing the // mark's own name) to allow multiple marks of a given type to // coexist (as long as they have different attributes). // // group:: ?string // The group or space-separated groups to which this mark belongs. // // spanning:: ?bool // Determines whether marks of this type can span multiple adjacent // nodes when serialized to DOM/HTML. Defaults to true. // // toDOM:: ?(mark: Mark, inline: bool) → DOMOutputSpec // Defines the default way marks of this type should be serialized // to DOM/HTML. When the resulting spec contains a hole, that is // where the marked content is placed. Otherwise, it is appended to // the top node. // // parseDOM:: ?[ParseRule] // Associates DOM parser information with this mark (see the // corresponding [node spec field](#model.NodeSpec.parseDOM)). The // `mark` field in the rules is implied. // AttributeSpec:: interface // // Used to [define](#model.NodeSpec.attrs) attributes on nodes or // marks. // // default:: ?any // The default value for this attribute, to use when no explicit // value is provided. Attributes that have no default must be // provided whenever a node or mark of a type that has them is // created. // ::- A document schema. Holds [node](#model.NodeType) and [mark // type](#model.MarkType) objects for the nodes and marks that may // occur in conforming documents, and provides functionality for // creating and deserializing such documents. export class Schema { // :: (SchemaSpec) // Construct a schema from a schema [specification](#model.SchemaSpec). constructor(spec) { // :: SchemaSpec // The [spec](#model.SchemaSpec) on which the schema is based, // with the added guarantee that its `nodes` and `marks` // properties are // [`OrderedMap`](https://github.com/marijnh/orderedmap) instances // (not raw objects). this.spec = {} for (let prop in spec) this.spec[prop] = spec[prop] this.spec.nodes = OrderedMap.from(spec.nodes) this.spec.marks = OrderedMap.from(spec.marks) // :: Object // An object mapping the schema's node names to node type objects. this.nodes = NodeType.compile(this.spec.nodes, this) // :: Object // A map from mark names to mark type objects. this.marks = MarkType.compile(this.spec.marks, this) let contentExprCache = Object.create(null) for (let prop in this.nodes) { if (prop in this.marks) throw new RangeError(prop + " can not be both a node and a mark") let type = this.nodes[prop], contentExpr = type.spec.content || "", markExpr = type.spec.marks type.contentMatch = contentExprCache[contentExpr] || (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes)) type.inlineContent = type.contentMatch.inlineContent type.markSet = markExpr == "_" ? null : markExpr ? gatherMarks(this, markExpr.split(" ")) : markExpr == "" || !type.inlineContent ? [] : null } for (let prop in this.marks) { let type = this.marks[prop], excl = type.spec.excludes type.excluded = excl == null ? [type] : excl == "" ? [] : gatherMarks(this, excl.split(" ")) } this.nodeFromJSON = this.nodeFromJSON.bind(this) this.markFromJSON = this.markFromJSON.bind(this) // :: NodeType // The type of the [default top node](#model.SchemaSpec.topNode) // for this schema. this.topNodeType = this.nodes[this.spec.topNode || "doc"] // :: Object // An object for storing whatever values modules may want to // compute and cache per schema. (If you want to store something // in it, try to use property names unlikely to clash.) this.cached = Object.create(null) this.cached.wrappings = Object.create(null) } // :: (union, ?Object, ?union, ?[Mark]) → Node // Create a node in this schema. The `type` may be a string or a // `NodeType` instance. Attributes will be extended // with defaults, `content` may be a `Fragment`, // `null`, a `Node`, or an array of nodes. node(type, attrs, content, marks) { if (typeof type == "string") type = this.nodeType(type) else if (!(type instanceof NodeType)) throw new RangeError("Invalid node type: " + type) else if (type.schema != this) throw new RangeError("Node type from different schema used (" + type.name + ")") return type.createChecked(attrs, content, marks) } // :: (string, ?[Mark]) → Node // Create a text node in the schema. Empty text nodes are not // allowed. text(text, marks) { let type = this.nodes.text return new TextNode(type, type.defaultAttrs, text, Mark.setFrom(marks)) } // :: (union, ?Object) → Mark // Create a mark with the given type and attributes. mark(type, attrs) { if (typeof type == "string") type = this.marks[type] return type.create(attrs) } // :: (Object) → Node // Deserialize a node from its JSON representation. This method is // bound. nodeFromJSON(json) { return Node.fromJSON(this, json) } // :: (Object) → Mark // Deserialize a mark from its JSON representation. This method is // bound. markFromJSON(json) { return Mark.fromJSON(this, json) } nodeType(name) { let found = this.nodes[name] if (!found) throw new RangeError("Unknown node type: " + name) return found } } function gatherMarks(schema, marks) { let found = [] for (let i = 0; i < marks.length; i++) { let name = marks[i], mark = schema.marks[name], ok = mark if (mark) { found.push(mark) } else { for (let prop in schema.marks) { let mark = schema.marks[prop] if (name == "_" || (mark.spec.group && mark.spec.group.split(" ").indexOf(name) > -1)) found.push(ok = mark) } } if (!ok) throw new SyntaxError("Unknown mark type: '" + marks[i] + "'") } return found } prosemirror-model-1.15.0/src/to_dom.js000066400000000000000000000167161413544732700177120ustar00rootroot00000000000000// DOMOutputSpec:: interface // A description of a DOM structure. Can be either a string, which is // interpreted as a text node, a DOM node, which is interpreted as // itself, a `{dom: Node, contentDOM: ?Node}` object, or an array. // // An array describes a DOM element. The first value in the array // should be a string—the name of the DOM element, optionally prefixed // by a namespace URL and a space. If the second element is plain // object, it is interpreted as a set of attributes for the element. // Any elements after that (including the 2nd if it's not an attribute // object) are interpreted as children of the DOM elements, and must // either be valid `DOMOutputSpec` values, or the number zero. // // The number zero (pronounced “hole”) is used to indicate the place // where a node's child nodes should be inserted. If it occurs in an // output spec, it should be the only child element in its parent // node. // ::- A DOM serializer knows how to convert ProseMirror nodes and // marks of various types to DOM nodes. export class DOMSerializer { // :: (Object<(node: Node) → DOMOutputSpec>, Object) // Create a serializer. `nodes` should map node names to functions // that take a node and return a description of the corresponding // DOM. `marks` does the same for mark names, but also gets an // argument that tells it whether the mark's content is block or // inline content (for typical use, it'll always be inline). A mark // serializer may be `null` to indicate that marks of that type // should not be serialized. constructor(nodes, marks) { // :: Object<(node: Node) → DOMOutputSpec> // The node serialization functions. this.nodes = nodes || {} // :: Object // The mark serialization functions. this.marks = marks || {} } // :: (Fragment, ?Object) → dom.DocumentFragment // Serialize the content of this fragment to a DOM fragment. When // not in the browser, the `document` option, containing a DOM // document, should be passed so that the serializer can create // nodes. serializeFragment(fragment, options = {}, target) { if (!target) target = doc(options).createDocumentFragment() let top = target, active = null fragment.forEach(node => { if (active || node.marks.length) { if (!active) active = [] let keep = 0, rendered = 0 while (keep < active.length && rendered < node.marks.length) { let next = node.marks[rendered] if (!this.marks[next.type.name]) { rendered++; continue } if (!next.eq(active[keep]) || next.type.spec.spanning === false) break keep += 2; rendered++ } while (keep < active.length) { top = active.pop() active.pop() } while (rendered < node.marks.length) { let add = node.marks[rendered++] let markDOM = this.serializeMark(add, node.isInline, options) if (markDOM) { active.push(add, top) top.appendChild(markDOM.dom) top = markDOM.contentDOM || markDOM.dom } } } top.appendChild(this.serializeNodeInner(node, options)) }) return target } serializeNodeInner(node, options = {}) { let {dom, contentDOM} = DOMSerializer.renderSpec(doc(options), this.nodes[node.type.name](node)) if (contentDOM) { if (node.isLeaf) throw new RangeError("Content hole not allowed in a leaf node spec") if (options.onContent) options.onContent(node, contentDOM, options) else this.serializeFragment(node.content, options, contentDOM) } return dom } // :: (Node, ?Object) → dom.Node // Serialize this node to a DOM node. This can be useful when you // need to serialize a part of a document, as opposed to the whole // document. To serialize a whole document, use // [`serializeFragment`](#model.DOMSerializer.serializeFragment) on // its [content](#model.Node.content). serializeNode(node, options = {}) { let dom = this.serializeNodeInner(node, options) for (let i = node.marks.length - 1; i >= 0; i--) { let wrap = this.serializeMark(node.marks[i], node.isInline, options) if (wrap) { ;(wrap.contentDOM || wrap.dom).appendChild(dom) dom = wrap.dom } } return dom } serializeMark(mark, inline, options = {}) { let toDOM = this.marks[mark.type.name] return toDOM && DOMSerializer.renderSpec(doc(options), toDOM(mark, inline)) } // :: (dom.Document, DOMOutputSpec) → {dom: dom.Node, contentDOM: ?dom.Node} // Render an [output spec](#model.DOMOutputSpec) to a DOM node. If // the spec has a hole (zero) in it, `contentDOM` will point at the // node with the hole. static renderSpec(doc, structure, xmlNS = null) { if (typeof structure == "string") return {dom: doc.createTextNode(structure)} if (structure.nodeType != null) return {dom: structure} if (structure.dom && structure.dom.nodeType != null) return structure let tagName = structure[0], space = tagName.indexOf(" ") if (space > 0) { xmlNS = tagName.slice(0, space) tagName = tagName.slice(space + 1) } let contentDOM = null, dom = xmlNS ? doc.createElementNS(xmlNS, tagName) : doc.createElement(tagName) let attrs = structure[1], start = 1 if (attrs && typeof attrs == "object" && attrs.nodeType == null && !Array.isArray(attrs)) { start = 2 for (let name in attrs) if (attrs[name] != null) { let space = name.indexOf(" ") if (space > 0) dom.setAttributeNS(name.slice(0, space), name.slice(space + 1), attrs[name]) else dom.setAttribute(name, attrs[name]) } } for (let i = start; i < structure.length; i++) { let child = structure[i] if (child === 0) { if (i < structure.length - 1 || i > start) throw new RangeError("Content hole must be the only child of its parent node") return {dom, contentDOM: dom} } else { let {dom: inner, contentDOM: innerContent} = DOMSerializer.renderSpec(doc, child, xmlNS) dom.appendChild(inner) if (innerContent) { if (contentDOM) throw new RangeError("Multiple content holes") contentDOM = innerContent } } } return {dom, contentDOM} } // :: (Schema) → DOMSerializer // Build a serializer using the [`toDOM`](#model.NodeSpec.toDOM) // properties in a schema's node and mark specs. static fromSchema(schema) { return schema.cached.domSerializer || (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema))) } // : (Schema) → Object<(node: Node) → DOMOutputSpec> // Gather the serializers in a schema's node specs into an object. // This can be useful as a base to build a custom serializer from. static nodesFromSchema(schema) { let result = gatherToDOM(schema.nodes) if (!result.text) result.text = node => node.text return result } // : (Schema) → Object<(mark: Mark) → DOMOutputSpec> // Gather the serializers in a schema's mark specs into an object. static marksFromSchema(schema) { return gatherToDOM(schema.marks) } } function gatherToDOM(obj) { let result = {} for (let name in obj) { let toDOM = obj[name].spec.toDOM if (toDOM) result[name] = toDOM } return result } function doc(options) { // declare global: window return options.document || window.document } prosemirror-model-1.15.0/test/000077500000000000000000000000001413544732700162505ustar00rootroot00000000000000prosemirror-model-1.15.0/test/test-content.js000066400000000000000000000177411413544732700212470ustar00rootroot00000000000000const {ContentMatch} = require("..") const {schema, eq, doc, p, pre, img, br, h1, hr} = require("prosemirror-test-builder") const ist = require("ist") function get(expr) { return ContentMatch.parse(expr, schema.nodes) } function match(expr, types) { let m = get(expr), ts = types ? types.split(" ").map(t => schema.nodes[t]) : [] for (let i = 0; m && i < ts.length; i++) m = m.matchType(ts[i]) return m && m.validEnd } function valid(expr, types) { ist(match(expr, types)) } function invalid(expr, types) { ist(!match(expr, types)) } function fill(expr, before, after, result) { let filled = get(expr).matchFragment(before.content).fillBefore(after.content, true) if (result) ist(filled, result.content, eq) else ist(!filled) } function fill3(expr, before, mid, after, left, right) { let content = get(expr) let a = content.matchFragment(before.content).fillBefore(mid.content) let b = a && content.matchFragment(before.content.append(a).append(mid.content)).fillBefore(after.content, true) if (left) { ist(a, left.content, eq) ist(b, right.content, eq) } else { ist(!b) } } describe("ContentMatch", () => { describe("matchType", () => { it("accepts empty content for the empty expr", () => valid("", "")) it("doesn't accept content in the empty expr", () => invalid("", "image")) it("matches nothing to an asterisk", () => valid("image*", "")) it("matches one element to an asterisk", () => valid("image*", "image")) it("matches multiple elements to an asterisk", () => valid("image*", "image image image image")) it("only matches appropriate elements to an asterisk", () => invalid("image*", "image text")) it("matches group members to a group", () => valid("inline*", "image text")) it("doesn't match non-members to a group", () => invalid("inline*", "paragraph")) it("matches an element to a choice expression", () => valid("(paragraph | heading)", "paragraph")) it("doesn't match unmentioned elements to a choice expr", () => invalid("(paragraph | heading)", "image")) it("matches a simple sequence", () => valid("paragraph horizontal_rule paragraph", "paragraph horizontal_rule paragraph")) it("fails when a sequence is too long", () => invalid("paragraph horizontal_rule", "paragraph horizontal_rule paragraph")) it("fails when a sequence is too short", () => invalid("paragraph horizontal_rule paragraph", "paragraph horizontal_rule")) it("fails when a sequence starts incorrectly", () => invalid("paragraph horizontal_rule", "horizontal_rule paragraph horizontal_rule")) it("accepts a sequence asterisk matching zero elements", () => valid("heading paragraph*", "heading")) it("accepts a sequence asterisk matching multiple elts", () => valid("heading paragraph*", "heading paragraph paragraph")) it("accepts a sequence plus matching one element", () => valid("heading paragraph+", "heading paragraph")) it("accepts a sequence plus matching multiple elts", () => valid("heading paragraph+", "heading paragraph paragraph")) it("fails when a sequence plus has no elements", () => invalid("heading paragraph+", "heading")) it("fails when a sequence plus misses its start", () => invalid("heading paragraph+", "paragraph paragraph")) it("accepts an optional element being present", () => valid("image?", "image")) it("accepts an optional element being missing", () => valid("image?", "")) it("fails when an optional element is present twice", () => invalid("image?", "image image")) it("accepts a nested repeat", () => valid("(heading paragraph+)+", "heading paragraph heading paragraph paragraph")) it("fails on extra input after a nested repeat", () => invalid("(heading paragraph+)+", "heading paragraph heading paragraph paragraph horizontal_rule")) it("accepts a matching count", () => valid("hard_break{2}", "hard_break hard_break")) it("rejects a count that comes up short", () => invalid("hard_break{2}", "hard_break")) it("rejects a count that has too many elements", () => invalid("hard_break{2}", "hard_break hard_break hard_break")) it("accepts a count on the lower bound", () => valid("hard_break{2, 4}", "hard_break hard_break")) it("accepts a count on the upper bound", () => valid("hard_break{2, 4}", "hard_break hard_break hard_break hard_break")) it("accepts a count between the bounds", () => valid("hard_break{2, 4}", "hard_break hard_break hard_break")) it("rejects a sequence with too few elements", () => invalid("hard_break{2, 4}", "hard_break")) it("rejects a sequence with too many elements", () => invalid("hard_break{2, 4}", "hard_break hard_break hard_break hard_break hard_break")) it("rejects a sequence with a bad element after it", () => invalid("hard_break{2, 4} text*", "hard_break hard_break image")) it("accepts a sequence with a matching element after it", () => valid("hard_break{2, 4} image?", "hard_break hard_break image")) it("accepts an open range", () => valid("hard_break{2,}", "hard_break hard_break")) it("accepts an open range matching many", () => valid("hard_break{2,}", "hard_break hard_break hard_break hard_break")) it("rejects an open range with too few elements", () => invalid("hard_break{2,}", "hard_break")) }) describe("fillBefore", () => { it("returns the empty fragment when things match", () => fill("paragraph horizontal_rule paragraph", doc(p(), hr), doc(p()), doc())) it("adds a node when necessary", () => fill("paragraph horizontal_rule paragraph", doc(p()), doc(p()), doc(hr))) it("accepts an asterisk across the bound", () => fill("hard_break*", p(br), p(br), p())) it("accepts an asterisk only on the left", () => fill("hard_break*", p(br), p(), p())) it("accepts an asterisk only on the right", () => fill("hard_break*", p(), p(br), p())) it("accepts an asterisk with no elements", () => fill("hard_break*", p(), p(), p())) it("accepts a plus across the bound", () => fill("hard_break+", p(br), p(br), p())) it("adds an element for a content-less plus", () => fill("hard_break+", p(), p(), p(br))) it("fails for a mismatched plus", () => fill("hard_break+", p(), p(img), null)) it("accepts asterisk with content on both sides", () => fill("heading* paragraph*", doc(h1()), doc(p()), doc())) it("accepts asterisk with no content after", () => fill("heading* paragraph*", doc(h1()), doc(), doc())) it("accepts plus with content on both sides", () => fill("heading+ paragraph+", doc(h1()), doc(p()), doc())) it("accepts plus with no content after", () => fill("heading+ paragraph+", doc(h1()), doc(), doc(p()))) it("adds elements to match a count", () => fill("hard_break{3}", p(br), p(br), p(br))) it("fails when there are too many elements", () => fill("hard_break{3}", p(br, br), p(br, br), null)) it("adds elements for two counted groups", () => fill("code_block{2} paragraph{2}", doc(pre()), doc(p()), doc(pre(), p()))) it("doesn't include optional elements", () => fill("heading paragraph? horizontal_rule", doc(h1()), doc(), doc(hr))) it("completes a sequence", () => fill3("paragraph horizontal_rule paragraph horizontal_rule paragraph", doc(p()), doc(p()), doc(p()), doc(hr), doc(hr))) it("accepts plus across two bounds", () => fill3("code_block+ paragraph+", doc(pre()), doc(pre()), doc(p()), doc(), doc())) it("fills a plus from empty input", () => fill3("code_block+ paragraph+", doc(), doc(), doc(), doc(), doc(pre(), p()))) it("completes a count", () => fill3("code_block{3} paragraph{3}", doc(pre()), doc(p()), doc(), doc(pre(), pre()), doc(p(), p()))) it("fails on non-matching elements", () => fill3("paragraph*", doc(p()), doc(pre()), doc(p()), null)) it("completes a plus across two bounds", () => fill3("paragraph{4}", doc(p()), doc(p()), doc(p()), doc(), doc(p()))) it("refuses to complete an overflown count across two bounds", () => fill3("paragraph{2}", doc(p()), doc(p()), doc(p()), null)) }) }) prosemirror-model-1.15.0/test/test-diff.js000066400000000000000000000057601413544732700205030ustar00rootroot00000000000000const {doc, blockquote, h1, h2, p, em, strong} = require("prosemirror-test-builder") const ist = require("ist") describe("Fragment", () => { describe("findDiffStart", () => { function start(a, b) { ist(a.content.findDiffStart(b.content), a.tag.a) } it("returns null for identical nodes", () => start(doc(p("a", em("b")), p("hello"), blockquote(h1("bye"))), doc(p("a", em("b")), p("hello"), blockquote(h1("bye"))))) it("notices when one node is longer", () => start(doc(p("a", em("b")), p("hello"), blockquote(h1("bye")), ""), doc(p("a", em("b")), p("hello"), blockquote(h1("bye")), p("oops")))) it("notices when one node is shorter", () => start(doc(p("a", em("b")), p("hello"), blockquote(h1("bye")), "", p("oops")), doc(p("a", em("b")), p("hello"), blockquote(h1("bye"))))) it("notices differing marks", () => start(doc(p("a", em("b"))), doc(p("a", strong("b"))))) it("stops at longer text", () => start(doc(p("foobar", em("b"))), doc(p("foo", em("b"))))) it("stops at a different character", () => start(doc(p("foobar")), doc(p("foocar")))) it("stops at a different node type", () => start(doc(p("a"), "", p("b")), doc(p("a"), h1("b")))) it("works when the difference is at the start", () => start(doc("", p("b")), doc(h1("b")))) it("notices a different attribute", () => start(doc(p("a"), "", h1("foo")), doc(p("a"), h2("foo")))) }) describe("findDiffEnd", () => { function end(a, b) { let found = a.content.findDiffEnd(b.content) ist(found && found.a, a.tag.a) } it("returns null when there is no difference", () => end(doc(p("a", em("b")), p("hello"), blockquote(h1("bye"))), doc(p("a", em("b")), p("hello"), blockquote(h1("bye"))))) it("notices when the second doc is longer", () => end(doc("", p("a", em("b")), p("hello"), blockquote(h1("bye"))), doc(p("oops"), p("a", em("b")), p("hello"), blockquote(h1("bye"))))) it("notices when the second doc is shorter", () => end(doc(p("oops"), "", p("a", em("b")), p("hello"), blockquote(h1("bye"))), doc(p("a", em("b")), p("hello"), blockquote(h1("bye"))))) it("notices different styles", () => end(doc(p("a", em("b"), "c")), doc(p("a", strong("b"), "c")))) it("spots longer text", () => end(doc(p("barfoo", em("b"))), doc(p("foo", em("b"))))) it("spots different text", () => end(doc(p("foobar")), doc(p("foocar")))) it("notices different nodes", () => end(doc(p("a"), "", p("b")), doc(h1("a"), p("b")))) it("notices a difference at the end", () => end(doc(p("b"), ""), doc(h1("b")))) it("handles a similar start", () => end(doc("", p("hello")), doc(p("hey"), p("hello")))) }) }) prosemirror-model-1.15.0/test/test-dom.js000066400000000000000000000602651413544732700203530ustar00rootroot00000000000000const {schema, eq, doc, blockquote, pre, h1, h2, p, li, ol, ul, em, strong, code, a, br, img, hr, builders} = require("prosemirror-test-builder") const ist = require("ist") const {DOMParser, DOMSerializer, Slice, Fragment, Schema} = require("..") // declare global: window let document = typeof window == "undefined" ? (new (require("jsdom").JSDOM)).window.document : window.document const xmlDocument = typeof window == "undefined" ? (new (require("jsdom").JSDOM)("", {contentType: "application/xml"})).window.document : window.document const parser = DOMParser.fromSchema(schema) const serializer = DOMSerializer.fromSchema(schema) describe("DOMParser", () => { describe("parse", () => { function domFrom(html, document_ = document) { let dom = document_.createElement("div") dom.innerHTML = html return dom } function test(doc, html, document_ = document) { return () => { let derivedDOM = document_.createElement("div"), schema = doc.type.schema derivedDOM.appendChild(DOMSerializer.fromSchema(schema).serializeFragment(doc.content, {document: document_})) let declaredDOM = domFrom(html, document_) ist(derivedDOM.innerHTML, declaredDOM.innerHTML) ist(DOMParser.fromSchema(schema).parse(derivedDOM), doc, eq) } } it("can represent simple node", test(doc(p("hello")), "

hello

")) it("can represent a line break", test(doc(p("hi", br, "there")), "

hi
there

")) it("can represent an image", test(doc(p("hi", img({alt: "x"}), "there")), '

hixthere

')) it("joins styles", test(doc(p("one", strong("two", em("three")), em("four"), "five")), "

onetwothreefourfive

")) it("can represent links", test(doc(p("a ", a({href: "foo"}, "big ", a({href: "bar"}, "nested"), " link"))), "

a big nested link

")) it("can represent and unordered list", test(doc(ul(li(p("one")), li(p("two")), li(p("three", strong("!")))), p("after")), "
  • one

  • two

  • three!

after

")) it("can represent an ordered list", test(doc(ol(li(p("one")), li(p("two")), li(p("three", strong("!")))), p("after")), "
  1. one

  2. two

  3. three!

after

")) it("can represent a blockquote", test(doc(blockquote(p("hello"), p("bye"))), "

hello

bye

")) it("can represent a nested blockquote", test(doc(blockquote(blockquote(blockquote(p("he said"))), p("i said"))), "

he said

i said

")) it("can represent headings", test(doc(h1("one"), h2("two"), p("text")), "

one

two

text

")) it("can represent inline code", test(doc(p("text and ", code("code that is ", em("emphasized"), "..."))), "

text and code that is emphasized...

")) it("can represent a code block", test(doc(blockquote(pre("some code")), p("and")), "
some code

and

")) it("supports leaf nodes in marks", test(doc(p(em("hi", br, "x"))), "

hi
x

")) it("doesn't collapse non-breaking spaces", test(doc(p("\u00a0 \u00a0hello\u00a0")), "

\u00a0 \u00a0hello\u00a0

")) it("can parse marks on block nodes", () => { let commentSchema = new Schema({ nodes: schema.spec.nodes.update("doc", Object.assign({marks: "comment"}, schema.spec.nodes.get("doc"))), marks: schema.spec.marks.update("comment", { parseDOM: [{tag: "div.comment"}], toDOM() { return ["div", {class: "comment"}, 0] } }) }) let b = builders(commentSchema) test(b.doc(b.paragraph("one"), b.comment(b.paragraph("two"), b.paragraph(b.strong("three"))), b.paragraph("four")), "

one

two

three

four

")() }) it("parses unique, non-exclusive, same-typed marks", () => { let commentSchema = new Schema({ nodes: schema.spec.nodes, marks: schema.spec.marks.update("comment", { attrs: { id: { default: null }}, parseDOM: [{ tag: "span.comment", getAttrs(dom) { return { id: parseInt(dom.getAttribute('data-id'), 10) } } }], excludes: '', toDOM(mark) { return ["span", {class: "comment", "data-id": mark.attrs.id }, 0] } }) }) let b = builders(commentSchema) test(b.schema.nodes.doc.createAndFill(undefined, [ b.schema.nodes.paragraph.createAndFill(undefined, [ b.schema.text('double comment', [ b.schema.marks.comment.create({ id: 1 }), b.schema.marks.comment.create({ id: 2 }) ]) ]) ]), "

double comment

")() }) it("serializes non-spanning marks correctly", () => { let markSchema = new Schema({ nodes: schema.spec.nodes, marks: schema.spec.marks.update("test", { parseDOM: [{tag: "test"}], toDOM() { return ["test", 0] }, spanning: false }) }) let b = builders(markSchema) test(b.doc(b.paragraph(b.test("a", b.image({src: "x"}), "b"))), "

ab

")() }) it("serializes an element and an attribute with XML namespace", () => { let xmlnsSchema = new Schema({ nodes: { doc: { content: "svg*" }, text: {}, "svg": { parseDOM: [{tag: "svg", namespace: 'http://www.w3.org/2000/svg'}], group: 'block', toDOM() { return ["http://www.w3.org/2000/svg svg", ["use", { "http://www.w3.org/1999/xlink href": "#svg-id" }]] }, }, }, }) let b = builders(xmlnsSchema) let d = b.doc(b.svg()) test(d, "", xmlDocument)() let dom = xmlDocument.createElement('div') dom.appendChild(DOMSerializer.fromSchema(xmlnsSchema).serializeFragment(d.content, {document: xmlDocument})) ist(dom.querySelector('svg').namespaceURI, 'http://www.w3.org/2000/svg') ist(dom.querySelector('use').namespaceURI, 'http://www.w3.org/2000/svg') ist(dom.querySelector('use').attributes[0].namespaceURI, 'http://www.w3.org/1999/xlink') }) function recover(html, doc, options) { return () => { let dom = document.createElement("div") dom.innerHTML = html ist(parser.parse(dom, options), doc, eq) } } it("can recover a list item", recover("

    Oh no

", doc(ol(li(p("Oh no")))))) it("wraps a list item in a list", recover("
  • hey
  • ", doc(ol(li(p("hey")))))) it("can turn divs into paragraphs", recover("
    hi
    bye
    ", doc(p("hi"), p("bye")))) it("interprets and as emphasis and strong", recover("

    hello there

    ", doc(p(em("hello ", strong("there")))))) it("wraps stray text in a paragraph", recover("hi", doc(p("hi")))) it("ignores an extra wrapping
    ", recover("

    one

    two

    ", doc(p("one"), p("two")))) it("ignores meaningless whitespace", recover("

    woo \n hooo

    ", doc(blockquote(p("woo ", em("hooo")))))) it("removes whitespace after a hard break", recover("

    hello
    \n world

    ", doc(p("hello", br, "world")))) it("converts br nodes to newlines when they would otherwise be ignored", recover("
    foo
    bar
    ", doc(pre("foo\nbar")))) it("finds a valid place for invalid content", recover("
    • hi
    • whoah

    • again
    ", doc(ul(li(p("hi")), li(p("whoah")), li(p("again")))))) it("moves nodes up when they don't fit the current context", recover("
    hello
    bye
    ", doc(p("hello"), hr, p("bye")))) it("doesn't ignore whitespace-only text nodes", recover("

    one two

    ", doc(p(em("one"), " ", strong("two"))))) it("can handle stray tab characters", recover("

    ", doc(p()))) it("normalizes random spaces", recover("

    1

    ", doc(p(strong("1"))))) it("can parse an empty code block", recover("
    ",
                   doc(pre())))
    
        it("preserves trailing space in a code block",
           recover("
    foo\n
    ", doc(pre("foo\n")))) it("normalizes newlines when preserving whitespace", recover("

    foo bar\nbaz

    ", doc(p("foo bar baz")), {preserveWhitespace: true})) it("ignores !

    ", doc(p("hello!")))) it("can handle a head/body input structure", recover("Thi", doc(p("hi")))) it("only applies a mark once", recover("

    A big strong monster.

    ", doc(p("A ", strong("big strong monster"), ".")))) it("interprets font-style: italic as em", recover("

    Hello!

    ", doc(p(em("Hello"), "!")))) it("interprets font-weight: bold as strong", recover("

    Hello

    ", doc(p(strong("Hello"))))) it("ignores unknown inline tags", recover("

    abc

    ", doc(p("abc")))) it("can add marks specified before their parent node is opened", recover("hi you", doc(p(em("hi"), " you")))) it("keeps applying a mark for the all of the node's content", recover("

    xxbar

    ", doc(p(strong("xxbar"))))) it("doesn't ignore whitespace-only nodes in preserveWhitespace full mode", recover(" x", doc(p(" x")), {preserveWhitespace: "full"})) function parse(html, options, doc) { return () => { let dom = document.createElement("div") dom.innerHTML = html let result = parser.parse(dom, options) ist(result, doc, eq) } } it("accepts the topNode option", parse("
  • wow
  • such
  • ", {topNode: schema.nodes.bullet_list.createAndFill()}, ul(li(p("wow")), li(p("such"))))) let item = schema.nodes.list_item.createAndFill() it("accepts the topMatch option", parse("
    • x
    ", {topNode: item, topMatch: item.contentMatchAt(1)}, li(ul(li(p("x")))))) it("accepts from and to options", parse("

    foo

    bar

    ", {from: 1, to: 3}, doc(p("foo"), p("bar")))) it("accepts the preserveWhitespace option", parse("foo bar", {preserveWhitespace: true}, doc(p("foo bar")))) function open(html, nodes, openStart, openEnd, options) { return () => { let dom = document.createElement("div") dom.innerHTML = html let result = parser.parseSlice(dom, options) ist(result, new Slice(Fragment.from(nodes.map(n => typeof n == "string" ? schema.text(n) : n)), openStart, openEnd), eq) } } it("can parse an open slice", open("foo", ["foo"], 0, 0)) it("will accept weird siblings", open("foo

    bar

    ", ["foo", p("bar")], 0, 1)) it("will open all the way to the inner nodes", open("
    • foo
    • bar
    ", [ul(li(p("foo")), li(p("bar", br)))], 3, 3)) it("accepts content open to the left", open("
    • a
  • ", [li(ul(li(p("a"))))], 4, 4)) it("accepts content open to the right", open("
  • foo
  • ", [li(p("foo")), li()], 2, 1)) it("will create textblocks for block nodes", open("
    foo
    bar
    ", [p("foo"), p("bar")], 1, 1)) it("can parse marks at the start of defaulted textblocks", open("
    foo
    bar
    ", [p("foo"), p(em("bar"))], 1, 1)) it("will not apply invalid marks to nodes", open("
    • foo
    ", [ul(li(p(strong("foo"))))], 3, 3)) it("will apply pending marks from parents to all children", open("
    • foo
    • bar
    ", [ul(li(p(strong("foo"))), li(p(strong("bar"))))], 3, 3)) it("can parse nested mark with same type", open("

    foobarbaz

    ", [p(strong("foobarbaz"))], 1, 1)) it("drops block-level whitespace", open("
    ", [], 0, 0, {preserveWhitespace: true})) it("keeps whitespace in inline elements", open(" ", [p(strong(" ")).child(0)], 0, 0, {preserveWhitespace: true})) it("can parse nested mark with same type but different attrs", () => { let markSchema = new Schema({ nodes: schema.spec.nodes, marks: schema.spec.marks.update("s", { attrs: { 'data-s': { default: 'tag' } }, excludes: '', parseDOM: [{ tag: "s", }, { style: "text-decoration", getAttrs() { return { 'data-s': 'style' } } }] }) }) let b = builders(markSchema) let dom = document.createElement("div") dom.innerHTML = "

    ooo

    " let result = DOMParser.fromSchema(markSchema).parseSlice(dom) ist(result, new Slice(Fragment.from( b.schema.nodes.paragraph.create( undefined, [ b.schema.text('o', [b.schema.marks.s.create({ 'data-s': 'style' })]), b.schema.text('o', [b.schema.marks.s.create({ 'data-s': 'style' }), b.schema.marks.s.create({ 'data-s': 'tag' })]), b.schema.text('o', [b.schema.marks.s.create({ 'data-s': 'style' })]) ] ) ), 1, 1), eq) dom.innerHTML = "

    ooo

    " result = DOMParser.fromSchema(markSchema).parseSlice(dom) ist(result, new Slice(Fragment.from( b.schema.nodes.paragraph.create( undefined, [ b.schema.text('o', [b.schema.marks.s.create({ 'data-s': 'style' }), b.schema.marks.s.create({ 'data-s': 'tag' })]), b.schema.text('o', [b.schema.marks.s.create({ 'data-s': 'style' })]), b.schema.text('o') ] ) ), 1, 1), eq) }) function find(html, doc) { return () => { let dom = document.createElement("div") dom.innerHTML = html let tag = dom.querySelector("var"), prev = tag.previousSibling, next = tag.nextSibling, pos if (prev && next && prev.nodeType == 3 && next.nodeType == 3) { pos = {node: prev, offset: prev.nodeValue.length} prev.nodeValue += next.nodeValue next.parentNode.removeChild(next) } else { pos = {node: tag.parentNode, offset: Array.prototype.indexOf.call(tag.parentNode.childNodes, tag)} } tag.parentNode.removeChild(tag) let result = parser.parse(dom, { findPositions: [pos] }) ist(result, doc, eq) ist(pos.pos, doc.tag.a) } } it("can find a position at the start of a paragraph", find("

    hello

    ", doc(p("hello")))) it("can find a position at the end of a paragraph", find("

    hello

    ", doc(p("hello
    ")))) it("can find a position inside text", find("

    hello

    ", doc(p("hel
    lo")))) it("can find a position inside an ignored node", find("

    hi

    foo

    ok

    ", doc(p("hi"), "
    ", p("ok")))) it("can find a position between nodes", find("
    • foo
    • bar
    ", doc(ul(li(p("foo")), "
    ", li(p("bar")))))) it("can find a position at the start of the document", find("

    hi

    ", doc("
    ", p("hi")))) it("can find a position at the end of the document", find("

    hi

    ", doc(p("hi"), "
    "))) let quoteSchema = new Schema({nodes: schema.spec.nodes, marks: schema.spec.marks, topNode: "blockquote"}) it("uses a custom top node when parsing", test(quoteSchema.node("blockquote", null, quoteSchema.node("paragraph", null, quoteSchema.text("hello"))), "

    hello

    ")) function contextParser(context) { return new DOMParser(schema, [{tag: "foo", node: "horizontal_rule", context}].concat(DOMParser.schemaRules(schema))) } it("recognizes context restrictions", () => { ist(contextParser("blockquote/").parse(domFrom("

    ")), doc(blockquote(hr, p())), eq) }) it("accepts group names in contexts", () => { ist(contextParser("block/").parse(domFrom("

    ")), doc(blockquote(hr, p())), eq) }) it("understands nested context restrictions", () => { ist(contextParser("blockquote/ordered_list//") .parse(domFrom("
    1. a

    ")), doc(blockquote(ol(li(p("a"), hr)))), eq) }) it("understands double slashes in context restrictions", () => { ist(contextParser("blockquote//list_item/") .parse(domFrom("
    1. a

    ")), doc(blockquote(ol(li(p("a"), hr)))), eq) }) it("understands pipes in context restrictions", () => { ist(contextParser("list_item/|blockquote/") .parse(domFrom("

    1. a

    ")), doc(blockquote(p(), hr), ol(li(p("a"), hr))), eq) }) it("uses the passed context", () => { let cxDoc = doc(blockquote("
    ", hr)) ist(contextParser("doc//blockquote/").parse(domFrom("
    "), { topNode: blockquote(), context: cxDoc.resolve(cxDoc.tag.a) }), blockquote(blockquote(hr)), eq) }) it("uses the passed context when parsing a slice", () => { let cxDoc = doc(blockquote("
    ", hr)) ist(contextParser("doc//blockquote/").parseSlice(domFrom(""), { context: cxDoc.resolve(cxDoc.tag.a) }), new Slice(blockquote(hr).content, 0, 0), eq) }) it("can close parent nodes from a rule", () => { let closeParser = new DOMParser(schema, [{tag: "br", closeParent: true}].concat(DOMParser.schemaRules(schema))) ist(closeParser.parse(domFrom("

    one
    two

    ")), doc(p("one"), p("two")), eq) }) it("supports non-consuming node rules", () => { let parser = new DOMParser(schema, [{tag: "ol", consuming: false, node: "blockquote"}] .concat(DOMParser.schemaRules(schema))) ist(parser.parse(domFrom("

      one

    ")), doc(blockquote(ol(li(p("one"))))), eq) }) it("supports non-consuming style rules", () => { let parser = new DOMParser(schema, [{style: "font-weight", consuming: false, mark: "em"}] .concat(DOMParser.schemaRules(schema))) ist(parser.parse(domFrom("

    one

    ")), doc(p(em(strong("one")))), eq) }) it("doesn't get confused by nested mark tags", recover("
    AB
    C", doc(p(strong("A"), "B"), p("C")))) }) describe("schemaRules", () => { it("defaults to schema order", () => { let schema = new Schema({ marks: {em: {parseDOM: [{tag: "i"}, {tag: "em"}]}}, nodes: {doc: {content: "inline*"}, text: {group: "inline"}, foo: {group: "inline", inline: true, parseDOM: [{tag: "foo"}]}, bar: {group: "inline", inline: true, parseDOM: [{tag: "bar"}]}} }) ist(DOMParser.schemaRules(schema).map(r => r.tag).join(" "), "i em foo bar") }) it("understands priority", () => { let schema = new Schema({ marks: {em: {parseDOM: [{tag: "i", priority: 40}, {tag: "em", priority: 70}]}}, nodes: {doc: {content: "inline*"}, text: {group: "inline"}, foo: {group: "inline", inline: true, parseDOM: [{tag: "foo"}]}, bar: {group: "inline", inline: true, parseDOM: [{tag: "bar", priority: 60}]}} }) ist(DOMParser.schemaRules(schema).map(r => r.tag).join(" "), "em bar foo i") }) function nsParse(doc, namespace) { let schema = new Schema({ nodes: {doc: {content: "h*"}, text: {}, h: {parseDOM: [{tag: "h", namespace}]}} }) return DOMParser.fromSchema(schema).parse(doc) } it("includes nodes when namespace is correct", () => { let doc = xmlDocument.createElement("doc") let h = xmlDocument.createElementNS("urn:ns", "h") doc.appendChild(h) ist(nsParse(doc, "urn:ns").childCount, 1) }) it("excludes nodes when namespace is wrong", () => { let doc = xmlDocument.createElement("doc") let h = xmlDocument.createElementNS("urn:nt", "h") doc.appendChild(h) ist(nsParse(doc, "urn:ns").childCount, 0) }) it("excludes nodes when namespace is absent", () => { let doc = xmlDocument.createElement("doc") // in HTML documents, createElement gives namespace // 'http://www.w3.org/1999/xhtml' so use createElementNS let h = xmlDocument.createElementNS(null, "h") doc.appendChild(h) ist(nsParse(doc, "urn:ns").childCount, 0) }) it("excludes nodes when namespace is wrong and xhtml", () => { let doc = xmlDocument.createElement("doc") let h = xmlDocument.createElementNS("urn:nt", "h") doc.appendChild(h) ist(nsParse(doc, "http://www.w3.org/1999/xhtml").childCount, 0) }) it("excludes nodes when namespace is wrong and empty", () => { let doc = xmlDocument.createElement("doc") let h = xmlDocument.createElementNS("urn:nt", "h") doc.appendChild(h) ist(nsParse(doc, "").childCount, 0) }) it("includes nodes when namespace is correct and empty", () => { let doc = xmlDocument.createElement("doc") let h = xmlDocument.createElementNS(null, "h") doc.appendChild(h) ist(nsParse(doc, null).childCount, 1) }) }) }) describe("DOMSerializer", () => { let noEm = new DOMSerializer(serializer.nodes, Object.assign({}, serializer.marks, {em: null})) it("can omit a mark", () => { ist(noEm.serializeNode(p("foo", em("bar"), strong("baz")), {document}).innerHTML, "foobarbaz") }) it("doesn't split other marks for omitted marks", () => { ist(noEm.serializeNode(p("foo", code("bar"), em(code("baz"), "quux"), "xyz"), {document}).innerHTML, "foobarbazquuxxyz") }) it("can render marks with complex structure", () => { let deepEm = new DOMSerializer(serializer.nodes, Object.assign({}, serializer.marks, { em() { return ["em", ["i", {"data-emphasis": true}, 0]] } })) ist(deepEm.serializeNode(p(strong("foo", code("bar"), em(code("baz"))), em("quux"), "xyz"), {document}).innerHTML, "foobarbazquuxxyz") }) }) prosemirror-model-1.15.0/test/test-mark.js000066400000000000000000000154411413544732700205220ustar00rootroot00000000000000const {Mark, Schema} = require("..") const {schema, doc, p, em, a} = require("prosemirror-test-builder") const ist = require("ist") let em_ = schema.mark("em") let strong = schema.mark("strong") let link = (href, title) => schema.mark("link", {href, title}) let code = schema.mark("code") let customSchema = new Schema({ nodes: {doc: {content: "paragraph+"}, paragraph: {content: "text*"}, text: {}}, marks: { remark: {attrs: {id: {}}, excludes: "", inclusive: false}, user: {attrs: {id: {}}, excludes: "_"}, strong: {excludes: "em-group"}, em: {group: "em-group"} } }), custom = customSchema.marks let remark1 = custom.remark.create({id: 1}), remark2 = custom.remark.create({id: 2}), user1 = custom.user.create({id: 1}), user2 = custom.user.create({id: 2}), customEm = custom.em.create(), customStrong = custom.strong.create() describe("Mark", () => { describe("sameSet", () => { it("returns true for two empty sets", () => ist(Mark.sameSet([], []))) it("returns true for simple identical sets", () => ist(Mark.sameSet([em_, strong], [em_, strong]))) it("returns false for different sets", () => ist(!Mark.sameSet([em_, strong], [em_, code]))) it("returns false when set size differs", () => ist(!Mark.sameSet([em_, strong], [em_, strong, code]))) it("recognizes identical links in set", () => ist(Mark.sameSet([link("http://foo"), code], [link("http://foo"), code]))) it("recognizes different links in set", () => ist(!Mark.sameSet([link("http://foo"), code], [link("http://bar"), code]))) }) describe("eq", () => { it("considers identical links to be the same", () => ist(link("http://foo").eq(link("http://foo")))) it("considers different links to differ", () => ist(!link("http://foo").eq(link("http://bar")))) it("considers links with different titles to differ", () => ist(!link("http://foo", "A").eq(link("http://foo", "B")))) }) describe("addToSet", () => { it("can add to the empty set", () => ist(em_.addToSet([]), [em_], Mark.sameSet)) it("is a no-op when the added thing is in set", () => ist(em_.addToSet([em_]), [em_], Mark.sameSet)) it("adds marks with lower rank before others", () => ist(em_.addToSet([strong]), [em_, strong], Mark.sameSet)) it("adds marks with higher rank after others", () => ist(strong.addToSet([em_]), [em_, strong], Mark.sameSet)) it("replaces different marks with new attributes", () => ist(link("http://bar").addToSet([link("http://foo"), em_]), [link("http://bar"), em_], Mark.sameSet)) it("does nothing when adding an existing link", () => ist(link("http://foo").addToSet([em_, link("http://foo")]), [em_, link("http://foo")], Mark.sameSet)) it("puts code marks at the end", () => ist(code.addToSet([em_, strong, link("http://foo")]), [em_, strong, link("http://foo"), code], Mark.sameSet)) it("puts marks with middle rank in the middle", () => ist(strong.addToSet([em_, code]), [em_, strong, code], Mark.sameSet)) it("allows nonexclusive instances of marks with the same type", () => ist(remark2.addToSet([remark1]), [remark1, remark2], Mark.sameSet)) it("doesn't duplicate identical instances of nonexclusive marks", () => ist(remark1.addToSet([remark1]), [remark1], Mark.sameSet)) it("clears all others when adding a globally-excluding mark", () => ist(user1.addToSet([remark1, customEm]), [user1], Mark.sameSet)) it("does not allow adding another mark to a globally-excluding mark", () => ist(customEm.addToSet([user1]), [user1], Mark.sameSet)) it("does overwrite a globally-excluding mark when adding another instance", () => ist(user2.addToSet([user1]), [user2], Mark.sameSet)) it("doesn't add anything when another mark excludes the added mark", () => ist(customEm.addToSet([remark1, customStrong]), [remark1, customStrong], Mark.sameSet)) it("remove excluded marks when adding a mark", () => ist(customStrong.addToSet([remark1, customEm]), [remark1, customStrong], Mark.sameSet)) }) describe("removeFromSet", () => { it("is a no-op for the empty set", () => ist(Mark.sameSet(em_.removeFromSet([]), []))) it("can remove the last mark from a set", () => ist(Mark.sameSet(em_.removeFromSet([em_]), []))) it("is a no-op when the mark isn't in the set", () => ist(Mark.sameSet(strong.removeFromSet([em_]), [em_]))) it("can remove a mark with attributes", () => ist(Mark.sameSet(link("http://foo").removeFromSet([link("http://foo")]), []))) it("doesn't remove a mark when its attrs differ", () => ist(Mark.sameSet(link("http://foo", "title").removeFromSet([link("http://foo")]), [link("http://foo")]))) }) describe("ResolvedPos.marks", () => { function isAt(doc, mark, result) { ist(mark.isInSet(doc.resolve(doc.tag.a).marks()), result) } it("recognizes a mark exists inside marked text", () => isAt(doc(p(em("fo
    o"))), em_, true)) it("recognizes a mark doesn't exist in non-marked text", () => isAt(doc(p(em("foo"))), strong, false)) it("considers a mark active after the mark", () => isAt(doc(p(em("hi"), " there")), em_, true)) it("considers a mark inactive before the mark", () => isAt(doc(p("one ", em("two"))), em_, false)) it("considers a mark active at the start of the textblock", () => isAt(doc(p(em("one"))), em_, true)) it("notices that attributes differ", () => isAt(doc(p(a("link"))), link("http://baz"), false)) let customDoc = customSchema.node("doc", null, [ customSchema.node("paragraph", null, [ // pos 1 customSchema.text("one", [remark1, customStrong]), customSchema.text("two") ]), customSchema.node("paragraph", null, [ // pos 9 customSchema.text("one"), customSchema.text("two", [remark1]), customSchema.text("three", [remark1]) ]), // pos 22 customSchema.node("paragraph", null, [ customSchema.text("one", [remark2]), customSchema.text("two", [remark1]) ]) ]) it("omits non-inclusive marks at end of mark", () => ist(Mark.sameSet(customDoc.resolve(4).marks(), [customStrong]))) it("includes non-inclusive marks inside a text node", () => ist(Mark.sameSet(customDoc.resolve(3).marks(), [remark1, customStrong]))) it("omits non-inclusive marks at the end of a line", () => ist(Mark.sameSet(customDoc.resolve(20).marks(), []))) it("includes non-inclusive marks between two marked nodes", () => ist(Mark.sameSet(customDoc.resolve(15).marks(), [remark1]))) it("excludes non-inclusive marks at a point where mark attrs change", () => ist(Mark.sameSet(customDoc.resolve(25).marks(), []))) }) }) prosemirror-model-1.15.0/test/test-node.js000066400000000000000000000133071413544732700205140ustar00rootroot00000000000000const ist = require("ist") const {Fragment, Schema} = require("..") const {schema, eq, doc, blockquote, p, li, ul, em, strong, code, a, br, hr, img} = require("prosemirror-test-builder") let customSchema = new Schema({ nodes: { doc: {content: "paragraph+"}, paragraph: {content: "text*"}, text: { toDebugString() { return 'custom_text' } }, hard_break: { toDebugString() { return 'custom_hard_break' } } }, }) describe("Node", () => { describe("toString", () => { it("nests", () => { ist(doc(ul(li(p("hey"), p()), li(p("foo")))).toString(), 'doc(bullet_list(list_item(paragraph("hey"), paragraph), list_item(paragraph("foo"))))') }) it("shows inline children", () => { ist(doc(p("foo", img, br, "bar")).toString(), 'doc(paragraph("foo", image, hard_break, "bar"))') }) it("shows marks", () => { ist(doc(p("foo", em("bar", strong("quux")), code("baz"))).toString(), 'doc(paragraph("foo", em("bar"), em(strong("quux")), code("baz")))') }) }) describe("cut", () => { function cut(doc, cut) { ist(doc.cut(doc.tag.a || 0, doc.tag.b), cut, eq) } it("extracts a full block", () => cut(doc(p("foo"), "", p("bar"), "", p("baz")), doc(p("bar")))) it("cuts text", () => cut(doc(p("0"), p("foobarbaz"), p("2")), doc(p("bar")))) it("cuts deeply", () => cut(doc(blockquote(ul(li(p("a"), p("bc")), li(p("d")), "", li(p("e"))), p("3"))), doc(blockquote(ul(li(p("c")), li(p("d"))))))) it("works from the left", () => cut(doc(blockquote(p("foobar"))), doc(blockquote(p("foo"))))) it("works to the right", () => cut(doc(blockquote(p("foobar"))), doc(blockquote(p("bar"))))) it("preserves marks", () => cut(doc(p("foo", em("bar", img, strong("baz"), br), "quux", code("xyz"))), doc(p(em("r", img, strong("baz"), br), "qu")))) }) describe("between", () => { function between(doc, ...nodes) { let i = 0 doc.nodesBetween(doc.tag.a, doc.tag.b, (node, pos) => { if (i == nodes.length) throw new Error("More nodes iterated than listed (" + node.type.name + ")") let compare = node.isText ? node.text : node.type.name if (compare != nodes[i++]) throw new Error("Expected " + JSON.stringify(nodes[i - 1]) + ", got " + JSON.stringify(compare)) if (!node.isText && doc.nodeAt(pos) != node) throw new Error("Pos " + pos + " does not point at node " + node + " " + doc.nodeAt(pos)) }) } it("iterates over text", () => between(doc(p("foobarbaz")), "paragraph", "foobarbaz")) it("descends multiple levels", () => between(doc(blockquote(ul(li(p("foo")), p("b"), ""), p("c"))), "blockquote", "bullet_list", "list_item", "paragraph", "foo", "paragraph", "b")) it("iterates over inline nodes", () => between(doc(p(em("x"), "foo", em("bar", img, strong("baz"), br), "quux", code("xyz"))), "paragraph", "foo", "bar", "image", "baz", "hard_break", "quux", "xyz")) }) describe("textBetween", () => { it("works when passing a custom function as leafText", () => { const d = doc(p("foo", img, br)) ist(d.textBetween(0, d.content.size, '', (node) => { if (node.type.name === 'image') { return '' } if (node.type.name === 'hard_break') { return '' } }), 'foo') }) }) describe("textContent", () => { it("works on a whole doc", () => { ist(doc(p("foo")).textContent, "foo") }) it("works on a text node", () => { ist(schema.text("foo").textContent, "foo") }) it("works on a nested element", () => { ist(doc(ul(li(p("hi")), li(p(em("a"), "b")))).textContent, "hiab") }) }) describe("from", () => { function from(arg, expect) { ist(expect.copy(Fragment.from(arg)), expect, eq) } it("wraps a single node", () => from(schema.node("paragraph"), doc(p()))) it("wraps an array", () => from([schema.node("hard_break"), schema.text("foo")], p(br, "foo"))) it("preserves a fragment", () => from(doc(p("foo")).content, doc(p("foo")))) it("accepts null", () => from(null, p())) it("joins adjacent text", () => from([schema.text("a"), schema.text("b")], p("ab"))) }) describe("toJSON", () => { function roundTrip(doc) { ist(schema.nodeFromJSON(doc.toJSON()), doc, eq) } it("can serialize a simple node", () => roundTrip(doc(p("foo")))) it("can serialize marks", () => roundTrip(doc(p("foo", em("bar", strong("baz")), " ", a("x"))))) it("can serialize inline leaf nodes", () => roundTrip(doc(p("foo", em(img, "bar"))))) it("can serialize block leaf nodes", () => roundTrip(doc(p("a"), hr, p("b"), p()))) it("can serialize nested nodes", () => roundTrip(doc(blockquote(ul(li(p("a"), p("b")), li(p(img))), p("c")), p("d")))) }) describe("toString", () => { it("should have the default toString method [text]", () => ist(schema.text("hello").toString(), "\"hello\"")) it("should have the default toString method [br]", () => ist(br().toString(), "hard_break")) it("should be able to redefine it from NodeSpec by specifying toDebugString method", () => ist(customSchema.text("hello").toString(), "custom_text")) it("should be respected by Fragment", () => ist( Fragment.fromArray( [customSchema.text("hello"), customSchema.nodes.hard_break.createChecked(), customSchema.text("world")] ), "" ) ) }) }) prosemirror-model-1.15.0/test/test-replace.js000066400000000000000000000106311413544732700211770ustar00rootroot00000000000000const {Slice} = require("..") const {eq, doc, blockquote, h1, p, ul, li} = require("prosemirror-test-builder") const ist = require("ist") describe("Node", () => { describe("replace", () => { function rpl(doc, insert, expected) { let slice = insert ? insert.slice(insert.tag.a, insert.tag.b) : Slice.empty ist(doc.replace(doc.tag.a, doc.tag.b, slice), expected, eq) } it("joins on delete", () => rpl(doc(p("one"), p("two")), null, doc(p("onwo")))) it("merges matching blocks", () => rpl(doc(p("one"), p("two")), doc(p("xxxx"), p("yyyy")), doc(p("onxx"), p("yywo")))) it("merges when adding text", () => rpl(doc(p("one"), p("two")), doc(p("H")), doc(p("onHwo")))) it("can insert text", () => rpl(doc(p("before"), p("one"), p("after")), doc(p("H")), doc(p("before"), p("onHe"), p("after")))) it("doesn't merge non-matching blocks", () => rpl(doc(p("one"), p("two")), doc(h1("H")), doc(p("onHwo")))) it("can merge a nested node", () => rpl(doc(blockquote(blockquote(p("one"), p("two")))), doc(p("H")), doc(blockquote(blockquote(p("onHwo")))))) it("can replace within a block", () => rpl(doc(blockquote(p("abcd"))), doc(p("xyz")), doc(blockquote(p("ayd"))))) it("can insert a lopsided slice", () => rpl(doc(blockquote(blockquote(p("one"), p("two"), "", p("three")))), doc(blockquote(p("aaaa"), p("bb"), p("cc"), "", p("dd"))), doc(blockquote(blockquote(p("onaa"), p("bb"), p("cc"), p("three")))))) it("can insert a deep, lopsided slice", () => rpl(doc(blockquote(blockquote(p("one"), p("two"), p("three")), "", p("x"))), doc(blockquote(p("aaaa"), p("bb"), p("cc")), "", p("dd")), doc(blockquote(blockquote(p("onaa"), p("bb"), p("cc")), p("x"))))) it("can merge multiple levels", () => rpl(doc(blockquote(blockquote(p("hello"))), blockquote(blockquote(p("a")))), null, doc(blockquote(blockquote(p("hella")))))) it("can merge multiple levels while inserting", () => rpl(doc(blockquote(blockquote(p("hello"))), blockquote(blockquote(p("a")))), doc(p("i")), doc(blockquote(blockquote(p("hellia")))))) it("can insert a split", () => rpl(doc(p("foobar")), doc(p("x"), p("y")), doc(p("foox"), p("ybar")))) it("can insert a deep split", () => rpl(doc(blockquote(p("fooxbar"))), doc(blockquote(p("x")), blockquote(p("y"))), doc(blockquote(p("foox")), blockquote(p("ybar"))))) it("can add a split one level up", () => rpl(doc(blockquote(p("foou"), p("vbar"))), doc(blockquote(p("x")), blockquote(p("y"))), doc(blockquote(p("foox")), blockquote(p("ybar"))))) it("keeps the node type of the left node", () => rpl(doc(h1("foobar"), ""), doc(p("foobaz"), ""), doc(h1("foobaz")))) it("keeps the node type even when empty", () => rpl(doc(h1("bar"), ""), doc(p("foobaz"), ""), doc(h1("baz")))) function bad(doc, insert, pattern) { let slice = insert ? insert.slice(insert.tag.a, insert.tag.b) : Slice.empty ist.throws(() => doc.replace(doc.tag.a, doc.tag.b, slice), new RegExp(pattern, "i")) } it("doesn't allow the left side to be too deep", () => bad(doc(p("")), doc(blockquote(p("")), ""), "deeper")) it("doesn't allow a depth mismatch", () => bad(doc(p("")), doc("", p("")), "inconsistent")) it("rejects a bad fit", () => bad(doc(""), doc(p("foo")), "invalid content")) it("rejects unjoinable content", () => bad(doc(ul(li(p("a")), ""), ""), doc(p("foo", ""), ""), "cannot join")) it("rejects an unjoinable delete", () => bad(doc(blockquote(p("a"), ""), ul("", li(p("b")))), null, "cannot join")) it("check content validity", () => bad(doc(blockquote("", p("hi")), ""), doc(blockquote("hi", ""), ""), "invalid content")) }) }) prosemirror-model-1.15.0/test/test-resolve.js000066400000000000000000000047331413544732700212510ustar00rootroot00000000000000const {doc, p, em, blockquote} = require("prosemirror-test-builder") const ist = require("ist") const testDoc = doc(p("ab"), blockquote(p(em("cd"), "ef"))) const _doc = {node: testDoc, start: 0, end: 12} const _p1 = {node: testDoc.child(0), start: 1, end: 3} const _blk = {node: testDoc.child(1), start: 5, end: 11} const _p2 = {node: _blk.node.child(0), start: 6, end: 10} describe("Node", () => { describe("resolve", () => { it("should reflect the document structure", () => { let expected = { 0: [_doc, 0, null, _p1.node], 1: [_doc, _p1, 0, null, "ab"], 2: [_doc, _p1, 1, "a", "b"], 3: [_doc, _p1, 2, "ab", null], 4: [_doc, 4, _p1.node, _blk.node], 5: [_doc, _blk, 0, null, _p2.node], 6: [_doc, _blk, _p2, 0, null, "cd"], 7: [_doc, _blk, _p2, 1, "c", "d"], 8: [_doc, _blk, _p2, 2, "cd", "ef"], 9: [_doc, _blk, _p2, 3, "e", "f"], 10: [_doc, _blk, _p2, 4, "ef", null], 11: [_doc, _blk, 6, _p2.node, null], 12: [_doc, 12, _blk.node, null] } for (let pos = 0; pos <= testDoc.content.size; pos++) { let $pos = testDoc.resolve(pos), exp = expected[pos] ist($pos.depth, exp.length - 4) for (let i = 0; i < exp.length - 3; i++) { ist($pos.node(i).eq(exp[i].node)) ist($pos.start(i), exp[i].start) ist($pos.end(i), exp[i].end) if (i) { ist($pos.before(i), exp[i].start - 1) ist($pos.after(i), exp[i].end + 1) } } ist($pos.parentOffset, exp[exp.length - 3]) let before = $pos.nodeBefore, eBefore = exp[exp.length - 2] ist(typeof eBefore == "string" ? before.textContent : before, eBefore) let after = $pos.nodeAfter, eAfter = exp[exp.length - 1] ist(typeof eAfter == "string" ? after.textContent : after, eAfter) } }) it("has a working posAtIndex method", () => { let d = doc(blockquote(p("one"), blockquote(p("two ", em("three")), p("four")))) let pThree = d.resolve(12) // Start of em("three") ist(pThree.posAtIndex(0), 8) ist(pThree.posAtIndex(1), 12) ist(pThree.posAtIndex(2), 17) ist(pThree.posAtIndex(0, 2), 7) ist(pThree.posAtIndex(1, 2), 18) ist(pThree.posAtIndex(2, 2), 24) ist(pThree.posAtIndex(0, 1), 1) ist(pThree.posAtIndex(1, 1), 6) ist(pThree.posAtIndex(2, 1), 25) ist(pThree.posAtIndex(0, 0), 0) ist(pThree.posAtIndex(1, 0), 26) }) }) }) prosemirror-model-1.15.0/test/test-slice.js000066400000000000000000000061151413544732700206650ustar00rootroot00000000000000const {doc, p, li, ul, em, a, blockquote} = require("prosemirror-test-builder") const ist = require("ist") describe("Node", () => { describe("slice", () => { function t(doc, expect, openStart, openEnd) { let slice = doc.slice(doc.tag.a || 0, doc.tag.b) ist(slice.content.eq(expect.content)) ist(slice.openStart, openStart) ist(slice.openEnd, openEnd) } it("can cut half a paragraph", () => t(doc(p("hello world")), doc(p("hello")), 0, 1)) it("can cut to the end of a pragraph", () => t(doc(p("hello")), doc(p("hello")), 0, 1)) it("leaves off extra content", () => t(doc(p("hello world"), p("rest")), doc(p("hello")), 0, 1)) it("preserves styles", () => t(doc(p("hello ", em("WORLD"))), doc(p("hello ", em("WOR"))), 0, 1)) it("can cut multiple blocks", () => t(doc(p("a"), p("b")), doc(p("a"), p("b")), 0, 1)) it("can cut to a top-level position", () => t(doc(p("a"), "", p("b")), doc(p("a")), 0, 0)) it("can cut to a deep position", () => t(doc(blockquote(ul(li(p("a")), li(p("b"))))), doc(blockquote(ul(li(p("a")), li(p("b"))))), 0, 4)) it("can cut everything after a position", () => t(doc(p("hello world")), doc(p(" world")), 1, 0)) it("can cut from the start of a textblock", () => t(doc(p("hello")), doc(p("hello")), 1, 0)) it("leaves off extra content before", () => t(doc(p("foo"), p("barbaz")), doc(p("baz")), 1, 0)) it("preserves styles after cut", () => t(doc(p("a sentence with an ", em("emphasized ", a("link")), " in it")), doc(p(em(a("nk")), " in it")), 1, 0)) it("preserves styles started after cut", () => t(doc(p("a ", em("sentence"), " with ", em("text"), " in it")), doc(p("th ", em("text"), " in it")), 1, 0)) it("can cut from a top-level position", () => t(doc(p("a"), "", p("b")), doc(p("b")), 0, 0)) it("can cut from a deep position", () => t(doc(blockquote(ul(li(p("a")), li(p("b"))))), doc(blockquote(ul(li(p("b"))))), 4, 0)) it("can cut part of a text node", () => t(doc(p("hello world")), p("o wo"), 0, 0)) it("can cut across paragraphs", () => t(doc(p("one"), p("two")), doc(p("e"), p("t")), 1, 1)) it("can cut part of marked text", () => t(doc(p("here's nothing and ", em("here's em"))), p("ing and ", em("here's e")), 0, 0)) it("can cut across different depths", () => t(doc(ul(li(p("hello")), li(p("world")), li(p("x"))), p(em("boo"))), doc(ul(li(p("rld")), li(p("x"))), p(em("bo"))), 3, 1)) it("can cut between deeply nested nodes", () => t(doc(blockquote(p("foobar"), ul(li(p("a")), li(p("b"), "", p("c"))), p("d"))), blockquote(p("bar"), ul(li(p("a")), li(p("b")))), 1, 2)) it("can include parents", () => { let d = doc(blockquote(p("foo"), p("bar"))) let slice = d.slice(d.tag.a, d.tag.b, true) ist(slice.toString(), '(2,2)') }) }) })