prosemirror 0.7.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +26 -0
  3. data/COOKBOOK.md +70 -13
  4. data/README.md +97 -3
  5. data/TYPES.md +5 -3
  6. data/lib/prosemirror/checker.rb +1 -0
  7. data/lib/prosemirror/coerce.rb +4 -0
  8. data/lib/prosemirror/content_expression.rb +1 -0
  9. data/lib/prosemirror/content_match.rb +7 -0
  10. data/lib/prosemirror/document.rb +106 -7
  11. data/lib/prosemirror/extensions/text_align.rb +34 -0
  12. data/lib/prosemirror/html/builder.rb +30 -11
  13. data/lib/prosemirror/html/entities.rb +1 -0
  14. data/lib/prosemirror/html/selector.rb +1 -0
  15. data/lib/prosemirror/html/splitter.rb +17 -4
  16. data/lib/prosemirror/html_parser.rb +45 -15
  17. data/lib/prosemirror/html_renderer.rb +5 -2
  18. data/lib/prosemirror/json_parser.rb +6 -2
  19. data/lib/prosemirror/mark_type.rb +10 -0
  20. data/lib/prosemirror/markdown/builder.rb +4 -2
  21. data/lib/prosemirror/markdown_serializer.rb +10 -0
  22. data/lib/prosemirror/marks/link.rb +1 -0
  23. data/lib/prosemirror/marks/text_style.rb +51 -0
  24. data/lib/prosemirror/naming.rb +1 -0
  25. data/lib/prosemirror/node.rb +19 -4
  26. data/lib/prosemirror/node_type.rb +6 -2
  27. data/lib/prosemirror/nodes/bullet_list.rb +1 -0
  28. data/lib/prosemirror/nodes/code_block.rb +1 -0
  29. data/lib/prosemirror/nodes/heading.rb +1 -1
  30. data/lib/prosemirror/nodes/image.rb +1 -0
  31. data/lib/prosemirror/nodes/mention.rb +1 -0
  32. data/lib/prosemirror/nodes/ordered_list.rb +3 -0
  33. data/lib/prosemirror/nodes/table_cell.rb +2 -2
  34. data/lib/prosemirror/nodes/twitch.rb +7 -2
  35. data/lib/prosemirror/nodes/youtube.rb +6 -2
  36. data/lib/prosemirror/parse_rule.rb +1 -0
  37. data/lib/prosemirror/rendering.rb +7 -0
  38. data/lib/prosemirror/schema.rb +20 -6
  39. data/lib/prosemirror/text_serializer.rb +1 -0
  40. data/lib/prosemirror/transformer.rb +5 -2
  41. data/lib/prosemirror/type_definition.rb +14 -1
  42. data/lib/prosemirror/utf8.rb +1 -0
  43. data/lib/prosemirror/version.rb +1 -1
  44. data/lib/prosemirror.rb +7 -3
  45. metadata +10 -7
  46. data/ROADMAP.md +0 -224
  47. data/lib/prosemirror/text_align.rb +0 -31
  48. data/sig/prosemirror.rbs +0 -4
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 2ad2aa4d8468d9b854e0cd4214e965d9ccd66b0f704f7c93c3967083ebf4f2cc
4
- data.tar.gz: 748a27e4d904030581b4a7d9b05b347c5fd1c6e793561f3b296d54fa3122e84d
3
+ metadata.gz: 83299630ad74178efaf62c0e40968ef3e1a085ddba12d9b50684c05b1f27f057
4
+ data.tar.gz: fbb545591e530721443848ce7f2044aa62338437d2926d480f0baa0f5ef2ef3d
5
5
  SHA512:
6
- metadata.gz: 4d8d3c8840d8ef938a25ed3240aa7b779ace824c33b0ed968f17f0e808b37249b966a5884bd8eb122fb659ada2fe9fc9eaef4917cbae8dbf4f048d0182de1402
7
- data.tar.gz: 4abe5b6e30afc8ec7b98311dc0dddf773c737127d81ce1e47be592f21a4e892ea76193ad04c5a0f05ebf1de18a4b1a5a8494432641d108cb4a0edee7e7e09d52
6
+ metadata.gz: bdcd3ce77eed14f095685bd6d47d7d3d1d7ee0975f869845268487f4e91221dd22b721801ac91c7db3913222c638b1881e0396148bf266a3081155e905cfe011
7
+ data.tar.gz: af476e5844149a351f8fc4d6b3575cdc256ce23d4ca46c3e4c345ca10700c916f4a7dfd08b4769341e15ea19435c882a13e1bf1a6f50f3df4e7a1701ef478698
data/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [1.1.0] - 2026-10-26
4
+
5
+ - `Document#truncate(length, omission: "…")` gives a shorter document, for previews: about that many characters of text, cut at the end of a word, keeping the marks and blocks the text is in.
6
+ - `Document#headings` lists the headings, for a table of contents, with an id unique in the document, made from their text (with Rails' `parameterize` when ActiveSupport is loaded), and `to_html(heading_ids: true)` renders the same ids on them. A heading's own id is kept. The cookbook's heading anchors recipe becomes a table of contents recipe.
7
+ - Tiptap's TextStyle mark, `Prosemirror::Marks::TextStyle`, with the attributes of its TextStyleKit (`color`, `backgroundColor`, `fontFamily`, `fontSize`, `lineHeight`), rendered as a span's `style` and imported from it. As in Tiptap, it isn't in the default schema: add it with `Schema.tiptap.with(Prosemirror::Marks::TextStyle)`. Unsafe CSS values, like `url()`, are invalid.
8
+ - Mark types declare a `priority`, as in Tiptap: the schema orders marks by priority, then as listed, so a mark added with `with` takes its place among the others. Tiptap's link has 1000, and its TextStyle 101.
9
+ - `to_json` raised `JSON::NestingError` for documents nested more than about 50 levels deep, and HTML and Markdown import gave documents up to about 190 levels deep, more than `Prosemirror.parse` accepts. Import now flattens nodes from 90 levels deep, and `to_json` writes documents as deep as `parse` reads: 100 levels.
10
+ - Table cells render their `colwidth` as an attribute, as Tiptap does, so that HTML import gives it back: it was lost. An empty `colwidth` attribute imports as nil, as in Tiptap, rather than an empty array.
11
+ - Markdown import replaces U+0000 with U+FFFD, as the CommonMark spec requires. It was kept, and dropped once the document was rendered to HTML.
12
+ - HTML import reads Tiptap's YouTube and Twitch markup only around a YouTube or Twitch URL. With another URL, it gave an embed that rendered nothing.
13
+
14
+ ## [1.0.0] - 2026-10-25
15
+
16
+ ### Public API
17
+
18
+ The public API is defined for 1.0: what the README, TYPES.md and the cookbook document. The rest is marked `@api private`.
19
+
20
+ - **Breaking:** `Schema#parse_html`, `#parse_markdown` and `#parse_text` are renamed `#from_html`, `#from_markdown` and `#from_text`, as `Prosemirror.from_html`, `.from_markdown` and `.from_text`, which are unchanged.
21
+ - **Breaking:** `Prosemirror::TextAlign` moves to `Prosemirror::Extensions::TextAlign`, with its `Paragraph` and `Heading`.
22
+ - **Breaking:** a JSON string or Markdown nested too deeply raises `Prosemirror::TooDeep`, a subclass of `Prosemirror::Error`. JSON raised `InvalidDocument`, and Markdown `Error`.
23
+ - `Schema#with_options` is documented: a copy of the schema with other options.
24
+
25
+ ### Performance
26
+
27
+ - Faster HTML and Markdown import: about a quarter less time, with the same results. Imports allocate a third fewer objects, so they also spend less time in garbage collection.
28
+
3
29
  ## [0.7.1] - 2026-10-24
4
30
 
5
31
  - A URL that `resolve_url` or `resolve_urls` resolves to nil, like a link to a deleted record, is reported as `Prosemirror::UnresolvedURL`, a subclass of `InvalidDocument` with the `url`, so that error trackers group dead links apart from other problems.
data/COOKBOOK.md CHANGED
@@ -48,30 +48,67 @@ record.update!(content: document.to_h)
48
48
 
49
49
  Without `case: :camel`, `to_h` writes snake_case type names like `bullet_list`, which Tiptap doesn't read. `blank?` gets the schema so that it knows your custom types: an image block isn't blank. Children are transformed first, so the list sees its remaining items. Attributes the schema doesn't declare are kept. When something the schema requires is gone, like the only paragraph of a list item kept by another rule, `transform` adds it back and reports it with `on_invalid`.
50
50
 
51
- ## Heading anchors
51
+ ## Tight lists
52
52
 
53
- To link to a section, give each heading an `id` made from its text, unless the document already has one:
53
+ Editors wrap each list item's text in a paragraph, so lists render as `<li><p>text</p></li>`, with the paragraphs' margins. To render an item of a single paragraph as `<li>text</li>`, as Markdown does for tight lists:
54
54
 
55
55
  ```ruby
56
- class Heading < Prosemirror::Nodes::Heading
57
- prop :id, _String?
58
-
56
+ class ListItem < Prosemirror::Nodes::ListItem
59
57
  def view_template(&)
60
- tag(:"h#{@level}", id: @id || slug, &)
58
+ paragraph = node.content.first if node.content.size == 1
59
+ return super unless paragraph&.type == :paragraph && paragraph.content.any?
60
+
61
+ li { render_content(paragraph.content) }
61
62
  end
63
+ end
64
+ ```
65
+
66
+ Items with several paragraphs or a nested list, and items left empty, render as before.
62
67
 
63
- private
68
+ ## Table of contents
64
69
 
65
- # "Café & co" becomes "cafe-co". In Rails, `node.text_content.parameterize` does the same.
66
- def slug
67
- slug = node.text_content.unicode_normalize(:nfkd).gsub(/\p{Mn}/, "").downcase.gsub(/[^a-z0-9]+/, "-")
68
- slug = slug.delete_prefix("-").delete_suffix("-")
69
- slug unless slug.empty?
70
+ List the headings as links, and render the document with the same ids on its headings:
71
+
72
+ ```ruby
73
+ class TableOfContents < Phlex::HTML
74
+ def initialize(document)
75
+ @document = document
76
+ end
77
+
78
+ def view_template
79
+ nav do
80
+ ul do
81
+ @document.headings.each do |heading|
82
+ li(class: "level-#{heading[:level]}") { a(href: "##{heading[:id]}") { heading[:text] } }
83
+ end
84
+ end
85
+ end
70
86
  end
71
87
  end
88
+
89
+ render TableOfContents.new(doc)
90
+ render doc.to_phlex(heading_ids: true)
72
91
  ```
73
92
 
74
- A node doesn't see the rest of the document, so two headings with the same text get the same `id`.
93
+ Ids are unique in the document: two headings with the same text get `setup` and `setup-2`.
94
+
95
+ ## Quotes with their author
96
+
97
+ A node can render parts of its content in different places, with `node` and `render_content`. Here, a quote's last line, after a line break, is its author:
98
+
99
+ ```ruby
100
+ class Blockquote < Prosemirror::Nodes::Blockquote
101
+ def view_template
102
+ inline = node.content.flat_map(&:content)
103
+ split = inline.rindex { |child| child.type == :hard_break }
104
+
105
+ figure do
106
+ blockquote { render_content(split ? inline[...split] : inline) }
107
+ figcaption { render_content(inline[(split + 1)..]) } if split
108
+ end
109
+ end
110
+ end
111
+ ```
75
112
 
76
113
  ## Render your own components
77
114
 
@@ -135,3 +172,23 @@ Prosemirror::Schema.tiptap(
135
172
  end
136
173
  )
137
174
  ```
175
+
176
+ ## Word count
177
+
178
+ Count the words of a document from its text. A hyphenated word or an elision, like `well-known` or `l’été`, counts as one word, as in word processors:
179
+
180
+ ```ruby
181
+ WORD = /[[:alnum:]]+(?:[-'’][[:alnum:]]+)*/
182
+
183
+ def word_count(document)
184
+ document.to_text.scan(WORD).size
185
+ end
186
+ ```
187
+
188
+ To leave code blocks out of the count, remove them first:
189
+
190
+ ```ruby
191
+ word_count(document.transform { |node| (node.type == :code_block) ? nil : node })
192
+ ```
193
+
194
+ Languages written without spaces between words, like Chinese or Japanese, need a segmenter instead.
data/README.md CHANGED
@@ -7,7 +7,11 @@ Render [ProseMirror](https://prosemirror.net) and [Tiptap](https://tiptap.dev) d
7
7
  - Link and image URLs must use an allowed scheme.
8
8
  - No Rails dependency.
9
9
 
10
- This gem replaces [prosemirror_to_html](https://github.com/etaminstudio/prosemirror_to_html) and [html_to_prosemirror](https://github.com/etaminstudio/html_to_prosemirror): see [Migrating](MIGRATING.md). See the [roadmap](ROADMAP.md) for what comes next.
10
+ This gem replaces [prosemirror_to_html](https://github.com/etaminstudio/prosemirror_to_html) and [html_to_prosemirror](https://github.com/etaminstudio/html_to_prosemirror), now deprecated: see [Migrating](MIGRATING.md).
11
+
12
+ ## Why
13
+
14
+ ProseMirror editors store documents as JSON. Ruby apps need to render this JSON to HTML, extract its text, and import old HTML or Markdown content. This gem does all of it with one schema: a custom type is declared once, and renders, imports and exports the same way.
11
15
 
12
16
  ## Installation
13
17
 
@@ -49,6 +53,15 @@ doc.select { |node| node in { type: :heading, attrs: { level: 1 } } }
49
53
  doc.content.first.text_content
50
54
  ```
51
55
 
56
+ `headings` lists the headings, for a table of contents, with an id unique in the document. `to_html(heading_ids: true)`, or `to_phlex(heading_ids: true)`, renders the same ids on the headings, so the links work:
57
+
58
+ ```ruby
59
+ doc.headings # => [{level: 2, text: "Café & co", id: "cafe-co"}, {level: 3, text: "Setup", id: "setup"}]
60
+ doc.to_html(heading_ids: true) # => "<h2 id=\"cafe-co\">Café &amp; co</h2>…"
61
+ ```
62
+
63
+ Ids come from the heading's text, with a number when two are the same (`setup-2`). A heading's own id, an attribute its type declares or one the editor saved, like Tiptap's UniqueID extension, is kept.
64
+
52
65
  ## Transforming documents
53
66
 
54
67
  `transform` builds a new document from a block called with each node. The block returns the node to keep, another node, an array of nodes to put in its place, or nil to remove it:
@@ -75,6 +88,13 @@ end
75
88
  doc.check # raises "doc.content[0]: invalid content for blockquote: paragraph text"
76
89
  ```
77
90
 
91
+ `truncate` gives a shorter document, for previews and listings: about that many characters of text, cut at the end of a word, followed by `omission` (`"…"` by default). It keeps the marks and blocks the text is in, and leaves out what comes after the cut. Trailing punctuation is dropped before the omission, and a block isn't started for less than one of its words. A document short enough is returned as it is.
92
+
93
+ ```ruby
94
+ doc.truncate(200).to_html # => "<p>The first <strong>words</strong>…</p>"
95
+ doc.truncate(200, omission: " [more]").to_text
96
+ ```
97
+
78
98
  ## HTML import
79
99
 
80
100
  HTML import uses [Herb](https://herb-tools.dev)'s parser, which never raises on malformed HTML. Add it to your Gemfile:
@@ -116,7 +136,7 @@ It reads GitHub Flavored Markdown: tables, strikethrough, autolinks and task lis
116
136
 
117
137
  Raw HTML in Markdown goes through HTML import when the herb gem is installed, and stays as text otherwise.
118
138
 
119
- YAML front matter, between `---` lines at the start, is dropped. Footnotes aren't supported yet: `[^1]: Note` reads as a link definition, as in CommonMark. Markdown nested more than 1,000 levels deep raises `Prosemirror::Error`.
139
+ YAML front matter, between `---` lines at the start, is dropped. Footnotes aren't supported yet: `[^1]: Note` reads as a link definition, as in CommonMark. Markdown nested more than 1,000 levels deep raises `Prosemirror::TooDeep`.
120
140
 
121
141
  ## Markdown export
122
142
 
@@ -128,7 +148,7 @@ doc.to_markdown(html: true) # underline, highlight, subscript, superscript and
128
148
  ```
129
149
 
130
150
  - Text is escaped, so that it reads back as text: `*`, `_`, `[`, a `#` or `-` that would start a block, HTML-like `<b>`, and URLs that GitHub would turn into links.
131
- - Markdown has no syntax for underline, highlight, subscript, superscript, image sizes or mentions: by default, only their text or image is written, like `@Ada` for a mention. With `html: true`, they are written as HTML.
151
+ - Markdown has no syntax for underline, highlight, subscript, superscript, text styles, image sizes or mentions: by default, only their text or image is written, like `@Ada` for a mention. With `html: true`, they are written as HTML.
132
152
  - Emphasis that CommonMark can't write where it is, like bold on a comma between two letters, is dropped and its text kept.
133
153
  - Tables are written as GFM tables. A cell's paragraphs and line breaks are joined with `<br>`, and its other blocks, like lists, are written as HTML.
134
154
  - Details are written as `<details>` HTML, as on GitHub, with their content in Markdown.
@@ -165,12 +185,38 @@ Type names are written in snake_case (`bullet_list`). Use `case: :camel` to writ
165
185
  Prosemirror.schema = Prosemirror::Schema.tiptap(case: :camel)
166
186
  ```
167
187
 
188
+ `case:` doesn't change attribute names: editors only read the exact names they declare, and Tiptap mixes styles (`textAlign`, `colwidth`). The built-in types use Tiptap's exact names, and input accepts both cases.
189
+
190
+ The two schemas differ in more than names:
191
+
192
+ | | `Schema.tiptap` | `Schema.prosemirror` |
193
+ |---|---|---|
194
+ | Marks | `bold`, `italic`, `code`, `link`, `strike`, `underline`… | `strong`, `em`, `code`, `link` |
195
+ | Ordered list | `start` | `order` |
196
+ | Code block | `language` | no attributes |
197
+ | Image | block | inline |
198
+ | Link | `href`, `target`, `rel`, `class`, `title` | `href`, `title` |
199
+
200
+ Each accepts the other's names on input (`strong` for `bold`, `order` for `start`), and the types that are the same in both, like paragraphs, headings and lists, are the same classes.
201
+
202
+ Schemas are immutable. `with` returns a copy with more types (see [Custom nodes and marks](#custom-nodes-and-marks)), and `with_options` a copy with other options, like a stricter one for an import:
203
+
204
+ ```ruby
205
+ strict = Prosemirror.schema.with_options(strict: true)
206
+ ```
207
+
168
208
  `text_align: true` adds Tiptap's TextAlign extension, configured for headings and paragraphs: a `textAlign` attribute, `left`, `center`, `right` or `justify`, rendered as a `text-align` style. HTML import also reads the old `align` attribute. Markdown has no syntax for it: Markdown export leaves it out. Without the option, `textAlign` is kept in `to_h`, but not rendered.
169
209
 
170
210
  ```ruby
171
211
  Prosemirror::Schema.tiptap(text_align: true)
172
212
  ```
173
213
 
214
+ Tiptap's TextStyle mark isn't in its StarterKit, nor in `Schema.tiptap`: add `Prosemirror::Marks::TextStyle`, with the attributes of its TextStyleKit: `color`, `backgroundColor`, `fontFamily`, `fontSize` and `lineHeight`, rendered as a span's `style`. HTML import reads them from spans' styles, merging nested spans as Tiptap does. Unlike Tiptap, a span without any of them gets no mark, and values that could load or run something, like `url()`, are invalid.
215
+
216
+ ```ruby
217
+ Prosemirror::Schema.tiptap.with(Prosemirror::Marks::TextStyle)
218
+ ```
219
+
174
220
  YouTube and Twitch embeds store the video's URL in `src`, and render an iframe of its embed URL, built from the video's id: other URLs render nothing. HTML import reads Tiptap's markup, and also iframes of embed URLs without it. Twitch only plays embeds on the domain they name, so set it in a subclass, as Tiptap's `parent` option. YouTube's `nocookie` option is a subclass too:
175
221
 
176
222
  ```ruby
@@ -250,6 +296,8 @@ Prosemirror::Schema.tiptap(strict: true) # raises Prosemirror::InvalidDocument
250
296
 
251
297
  A URL that `resolve_url` or `resolve_urls` resolves to nil, like a link to a deleted record, is reported as `Prosemirror::UnresolvedURL`, a subclass of `InvalidDocument` with the `url`, so that error trackers group dead links apart from other problems.
252
298
 
299
+ A JSON string or Markdown nested too deeply to import raises `Prosemirror::TooDeep`, in any mode: JSON deeper than 100 levels, Markdown deeper than 1,000. A Hash nested too deeply is cut and reported instead.
300
+
253
301
  ## URLs
254
302
 
255
303
  Links and images allow `http`, `https`, `mailto`, `tel` and relative URLs. Change the list with `url_schemes:`, or rewrite URLs before they are checked with `resolve_url:`:
@@ -263,10 +311,56 @@ Prosemirror::Schema.tiptap(
263
311
 
264
312
  `resolve_urls:` gets all the URLs of a document at once, before rendering it, and returns a Hash from each URL to its rewritten URL, to look up records in one query (see the [cookbook](COOKBOOK.md#links-to-records-with-globalid)). A URL missing from the Hash, or mapped to nil, is removed and reported, as with `resolve_url`. The URLs are those of the attributes declared with `url: true`, like links' `href` and images' `src`, which `doc.urls` lists. URLs that types build while rendering, like YouTube's embed URLs, are resolved one at a time.
265
313
 
314
+ ## Design
315
+
316
+ - Nothing is cleaned up after rendering: Phlex escapes text and attribute values as it writes them, attributes are typed, attribute names never come from the document, and URLs must use an allowed scheme.
317
+ - Output is HTML5 only: no `<strike>`, `<font>` or `align=`. Import still reads them.
318
+ - Only `phlex` and `literal` are required. [`herb`](https://herb-tools.dev) and [`commonmarker`](https://github.com/gjtorikian/commonmarker) are loaded only by HTML and Markdown import.
319
+ - Schemas, content expressions, marks and parse rules work as in [ProseMirror's guide](https://prosemirror.net/docs/guide/#schema), with the same JSON. Methods keep ProseMirror's names in Ruby style (`text_content`, `descendants`, `check`).
320
+ - Nodes are immutable values with pattern matching, documents are `Enumerable`, and node types are classes. Each type declares its attributes, its content, its HTML and how to recognize it in HTML, so rendering and import use the same schema.
321
+
322
+ Out of scope: CSS framework themes (subclass node types instead), a Rails or ViewComponent dependency, editing features (positions, steps, commands, collaboration), and the editor itself.
323
+
324
+ ## Performance
325
+
326
+ On a page of 151 nodes (8 KB of JSON: headings, paragraphs with marks and links, lists, an image, a table…) and a long document of 50 such pages, with Ruby 4.0 and YJIT on an Apple M2:
327
+
328
+ | | Page | Long document |
329
+ |---|--:|--:|
330
+ | `parse` (JSON) | 0.3 ms | 15 ms |
331
+ | `to_html` | 0.2 ms | 8 ms |
332
+ | `to_text` | 0.06 ms | 3 ms |
333
+ | `to_markdown` | 0.6 ms | 29 ms |
334
+ | `to_h` | 0.2 ms | 10 ms |
335
+ | `from_html` | 1.2 ms | 68 ms |
336
+ | `from_markdown` | 1 ms | 46 ms |
337
+ | `transform`, `check` | 0.3 ms | 15 ms |
338
+
339
+ From a JSON string to HTML, a page takes 0.6 ms, about 5 times less than with prosemirror_to_html. HTML import takes about 1.5 times as long as html_to_prosemirror's, which does less: it drops text in nested marks, ignores styles, and doesn't follow the schema. See [`benchmark/run.rb`](benchmark/run.rb) to measure on your machine.
340
+
341
+ ## Versioning
342
+
343
+ The gem follows [semantic versioning](https://semver.org). Its public API is what this README, [Node and mark types](TYPES.md) and the [cookbook](COOKBOOK.md) document: it only changes in a major version. The rest, marked `@api private` in the code, like the parsers and the schema's internal methods, can change in any version.
344
+
266
345
  ## Development
267
346
 
268
347
  After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests, and `rake` to also run [Standard](https://github.com/standardrb/standard). You can also run `bin/console` for an interactive prompt that will allow you to experiment.
269
348
 
349
+ `benchmark/run.rb` measures each operation on a page and a long document, and compares with the gems this one replaces. It has its own Gemfile:
350
+
351
+ ```sh
352
+ BUNDLE_GEMFILE=benchmark/Gemfile bundle install
353
+ BUNDLE_GEMFILE=benchmark/Gemfile bundle exec ruby benchmark/run.rb
354
+ ```
355
+
356
+ `rake fuzz` imports random HTML and Markdown, made by mutating the test fixtures, for a minute. It reports inputs that raise, give an invalid document, or don't survive rendering and importing again, each shrunk to a small example to add as a fixture:
357
+
358
+ ```sh
359
+ SECONDS=600 bundle exec rake fuzz # longer
360
+ SEED=1234 bundle exec rake fuzz # repeat a run
361
+ STRICT=1 bundle exec rake fuzz # a round trip must give the same document
362
+ ```
363
+
270
364
  To install this gem onto your local machine, run `bundle exec rake install`.
271
365
 
272
366
  To release a new version, update the version number in `version.rb` and the changelog, and merge them into main. Then tag the version and push the tag:
data/TYPES.md CHANGED
@@ -60,8 +60,9 @@ Type names are snake_case Symbols in Ruby. On input, camelCase works too (`image
60
60
  | `excludes "_"` | marks of the same type | The marks this one can't be combined with: names or groups, `"_"` for all. A link excludes other links, and Tiptap's `code` excludes all marks. |
61
61
  | `spanning false` | true | Render one element per text node, instead of one for adjacent nodes with the same mark. |
62
62
  | `code` | false | The mark holds code, as ProseMirror's `code`. Not used by this gem yet. |
63
+ | `priority 101` | 100 | The mark's place in the schema, as Tiptap's `priority`: higher first. Tiptap's link has 1000, and its TextStyle 101. |
63
64
 
64
- The order of marks in the schema sorts the marks of a node, and nests their elements: the first mark is the outermost element.
65
+ The order of marks in the schema sorts the marks of a node, and nests their elements: the first mark is the outermost element. Marks are ordered by priority, then in the order they're listed and added with `with`, so a mark added with `with` takes the same place as in Tiptap when it declares Tiptap's priority.
65
66
 
66
67
  ## Content expressions
67
68
 
@@ -122,6 +123,7 @@ Without `view_template`, the content is rendered without a wrapping element. The
122
123
  | `render_content(nodes)` | Renders any list of nodes, with their marks, for example only some of the node's children. |
123
124
  | `safe_url(url)` | The URL after the schema's `resolve_url`, when its scheme is allowed, or nil. Use it for every URL from the document. |
124
125
  | `prosemirror_schema` | The schema of the document being rendered. |
126
+ | `heading_id` | In a heading type, its id from `Document#headings`, when the document is rendered with `heading_ids: true`, or nil. A subclass of the built-in heading renders it with `id: heading_id`. |
125
127
 
126
128
  Phlex escapes text and attribute values, but doesn't check URLs: pass them through `safe_url`.
127
129
 
@@ -261,11 +263,11 @@ Prosemirror.schema = Prosemirror::Schema.tiptap.with(Paragraph)
261
263
 
262
264
  A subclass that declares parse rules replaces the rules of its parent. See the [cookbook](COOKBOOK.md) for more examples.
263
265
 
264
- With `Schema.tiptap(text_align: true)`, paragraphs and headings are `Prosemirror::TextAlign::Paragraph` and `Prosemirror::TextAlign::Heading`: subclass these to keep the alignment. Other types get it by including `Prosemirror::TextAlign`, which declares the `text_align` attribute, and rendering `text_align_style`:
266
+ With `Schema.tiptap(text_align: true)`, paragraphs and headings are `Prosemirror::Extensions::TextAlign::Paragraph` and `Prosemirror::Extensions::TextAlign::Heading`: subclass these to keep the alignment. Other types get it by including `Prosemirror::Extensions::TextAlign`, which declares the `text_align` attribute, and rendering `text_align_style`:
265
267
 
266
268
  ```ruby
267
269
  class Callout < Prosemirror::NodeType
268
- include Prosemirror::TextAlign
270
+ include Prosemirror::Extensions::TextAlign
269
271
  group :block
270
272
  content "inline*"
271
273
 
@@ -6,6 +6,7 @@ module Prosemirror
6
6
  #
7
7
  # Rendering and JSON parsing don't need valid content: they render what they get. This checks what
8
8
  # they don't: node and mark types, attributes, content expressions, and the marks each node allows.
9
+ # @api private
9
10
  class Checker
10
11
  def initialize(schema)
11
12
  @schema = schema
@@ -9,14 +9,18 @@ module Prosemirror
9
9
  INTEGER = proc { |value| (value.is_a?(String) && value.match?(/\A\s*-?\d+\s*\z/)) ? value.to_i : value }
10
10
 
11
11
  # "bullet_list" becomes :bullet_list.
12
+ # @api private
12
13
  SYMBOL = proc { |value| value.is_a?(String) ? value.to_sym : value }
13
14
 
14
15
  # A frozen copy, unless the value is already frozen.
16
+ # @api private
15
17
  FROZEN = proc { |value| value.frozen? ? value : value.dup.freeze }
16
18
 
17
19
  # The coercions above, which don't use `self`.
20
+ # @api private
18
21
  PLAIN = [INTEGER, SYMBOL, FROZEN].freeze
19
22
 
23
+ # @api private
20
24
  def self.frozen(value)
21
25
  value.frozen? ? value : value.dup.freeze
22
26
  end
@@ -3,6 +3,7 @@
3
3
  module Prosemirror
4
4
  # A parsed content expression, such as `"paragraph block*"` or `"(table_cell | table_header){1,5}"`.
5
5
  # See https://prosemirror.net/docs/guide/#schema.content_expressions
6
+ # @api private
6
7
  class ContentExpression
7
8
  TOKEN = /\s*(\w+|[()|+*?]|\{\s*\d+\s*(?:,\s*\d*\s*)?\})/
8
9
 
@@ -6,6 +6,7 @@ module Prosemirror
6
6
  #
7
7
  # Edges go from one state to the next for a node type. Their order matters: the first generatable
8
8
  # type is used to fill required content.
9
+ # @api private
9
10
  class ContentMatch
10
11
  attr_reader :edges
11
12
 
@@ -34,6 +35,8 @@ module Prosemirror
34
35
 
35
36
  # The state after these node types, or nil when they don't match.
36
37
  def match_types(types)
38
+ return self if types.empty?
39
+
37
40
  types.reduce(self) { |match, type| match&.match_type(type) }
38
41
  end
39
42
 
@@ -49,6 +52,10 @@ module Prosemirror
49
52
  # The node types to insert before `types` so that they match, possibly none, or nil when no
50
53
  # insertion works. With `to_end`, the content must also be able to end after them.
51
54
  def fill_before(types, schema, to_end: false)
55
+ # Most content needs nothing: no search.
56
+ finished = match_types(types)
57
+ return Node::EMPTY_ARRAY if finished && (!to_end || finished.valid_end?)
58
+
52
59
  seen = [self]
53
60
  search = lambda do |match, filled|
54
61
  finished = match.match_types(types)
@@ -33,17 +33,38 @@ module Prosemirror
33
33
  end.to_a
34
34
  end
35
35
 
36
- # The document as HTML. The string is `html_safe` when ActiveSupport is loaded.
37
- def to_html
38
- html = to_phlex.call
36
+ # The headings, for a table of contents, with their level, their text, and an id unique in the document:
37
+ #
38
+ # doc.headings # => [{level: 2, text: "Café & co", id: "cafe-co"}, {level: 2, text: "Café & co", id: "cafe-co-2"}]
39
+ #
40
+ # A heading's own `id`, an attribute its type declares or one the editor added, like Tiptap's UniqueID
41
+ # extension, is its id. Others get one from their text. `to_html(heading_ids: true)` renders the same ids.
42
+ def headings
43
+ heading_ids.map { |node, id| {level: node.attrs[:level], text: node.text_content, id:} }
44
+ end
45
+
46
+ # The document as HTML, with `heading_ids: true` the ids of `headings` on the headings. The string is
47
+ # `html_safe` when ActiveSupport is loaded.
48
+ def to_html(heading_ids: false)
49
+ html = to_phlex(heading_ids:).call
39
50
  html.respond_to?(:html_safe) ? html.html_safe : html
40
51
  end
41
52
 
42
53
  # A Phlex component rendering the document, to render it inside another Phlex component:
43
54
  #
44
55
  # render doc.to_phlex
45
- def to_phlex
46
- HTMLRenderer.new(self)
56
+ def to_phlex(heading_ids: false)
57
+ HTMLRenderer.new(self, heading_ids:)
58
+ end
59
+
60
+ # The id of each heading node, in order. Keyed by identity: two headings with the same text are equal.
61
+ # @api private
62
+ def heading_ids
63
+ nodes = select { |node| schema.node_type(node.type)&.<=(Nodes::Heading) }
64
+ taken = nodes.filter_map { |node| own_id(node) }.to_set
65
+ nodes.each_with_object({}.compare_by_identity) do |node, ids|
66
+ ids[node] = own_id(node) || unique_id(slug(node.text_content), taken)
67
+ end
47
68
  end
48
69
 
49
70
  # Lets Rails render the document in ERB templates and ViewComponents: `<%= render doc %>`.
@@ -71,8 +92,9 @@ module Prosemirror
71
92
  to_h
72
93
  end
73
94
 
74
- def to_json(*)
75
- to_h.to_json(*)
95
+ # As deep as `Prosemirror.parse` accepts: the JSON gem's default limit allows about 50 nodes.
96
+ def to_json(*args)
97
+ args.empty? ? JSON.generate(to_h, max_nesting: JSONParser::MAX_NESTING) : to_h.to_json(*args)
76
98
  end
77
99
 
78
100
  def text_content
@@ -96,6 +118,31 @@ module Prosemirror
96
118
  Document.new(Transformer.new(schema, &).call(root), schema: schema)
97
119
  end
98
120
 
121
+ # A shorter document, for previews: about `length` characters of text, cut at the end of a word, with
122
+ # `omission` after it. It keeps its structure: the marks and blocks the text is in, and what comes before
123
+ # the cut. What comes after is left out. The document itself when its text is short enough.
124
+ #
125
+ # doc.truncate(200).to_html # => "<p>The first <strong>words</strong>…</p>"
126
+ def truncate(length, omission: "…")
127
+ cut_index, cut_text = cut(length)
128
+ return self unless cut_index
129
+
130
+ seen = 0
131
+ content = Transformer.new(schema, report: false) do |node|
132
+ if node.text?
133
+ seen += 1
134
+ if seen - 1 < cut_index then node
135
+ elsif seen - 1 == cut_index then node.with(text: cut_text + omission)
136
+ end
137
+ elsif seen > cut_index && (node.content.empty? || schema.node_type(node.type)&.leaf?)
138
+ nil
139
+ else
140
+ node
141
+ end
142
+ end.call(root)
143
+ Document.new(content, schema: schema)
144
+ end
145
+
99
146
  # Raises InvalidDocument for the first problem with the schema: an unknown node or mark type, invalid
100
147
  # attributes, content that doesn't match a content expression, or marks a node doesn't allow. Returns
101
148
  # the document.
@@ -122,6 +169,58 @@ module Prosemirror
122
169
 
123
170
  private
124
171
 
172
+ # Where to cut the text to keep about `length` characters, at the end of a word: the index of the last
173
+ # text node to keep, and its kept text, without trailing spaces and punctuation. Nil when the text is
174
+ # short enough. A first word longer than `length` is cut inside it.
175
+ def cut(length)
176
+ texts = select(&:text?)
177
+ remaining = length
178
+ texts.each_with_index do |node, index|
179
+ text = node.text
180
+ if text.length <= remaining
181
+ remaining -= text.length
182
+ next unless remaining.zero? && index < texts.size - 1
183
+
184
+ return [index, trim_end(text)]
185
+ end
186
+
187
+ word_end = text[0, remaining + 1].rindex(/\s/)
188
+ kept = word_end ? trim_end(text[0, word_end]) : ""
189
+ return [index, kept] unless kept.empty?
190
+ return [index, text[0, remaining]] if index.zero?
191
+
192
+ return [index - 1, trim_end(texts[index - 1].text)]
193
+ end
194
+ nil
195
+ end
196
+
197
+ def trim_end(text) = text.sub(/[[:space:][:punct:]]+\z/, "")
198
+
199
+ def own_id(node)
200
+ id = node.attrs[:id] || node.unknown_attrs["id"]
201
+ id if id.is_a?(String) && !id.empty?
202
+ end
203
+
204
+ # "Café & co" becomes "cafe-co", with Rails' `parameterize` when ActiveSupport is loaded, so that the
205
+ # app's I18n transliteration rules apply. Text without letters or digits becomes "section".
206
+ def slug(text)
207
+ slug = if defined?(ActiveSupport::Inflector.parameterize)
208
+ ActiveSupport::Inflector.parameterize(text)
209
+ else
210
+ text.unicode_normalize(:nfkd).gsub(/\p{Mn}/, "").downcase.gsub(/[^a-z0-9]+/, "-").delete_prefix("-").delete_suffix("-")
211
+ end
212
+ slug.empty? ? "section" : slug
213
+ end
214
+
215
+ # The slug, or with a number after it when it's taken: "setup", "setup-2".
216
+ def unique_id(slug, taken)
217
+ id = slug
218
+ number = 1
219
+ id = "#{slug}-#{number += 1}" while taken.include?(id)
220
+ taken << id
221
+ id
222
+ end
223
+
125
224
  def add_urls(urls, type, attrs)
126
225
  type&.url_attributes&.each do |name|
127
226
  value = attrs[name]
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Prosemirror
4
+ # Tiptap extensions that add attributes to existing types, rather than types of their own.
5
+ module Extensions
6
+ # Tiptap's TextAlign extension: a `textAlign` attribute, rendered as a `text-align` style. Included in the
7
+ # paragraphs and headings of `Schema.tiptap(text_align: true)`. A custom type includes it, and renders
8
+ # `style: text_align_style`.
9
+ module TextAlign
10
+ ALIGNMENTS = %w[left center right justify].freeze
11
+
12
+ def self.included(type)
13
+ # From the `text-align` style, or the old `align` attribute, which Tiptap doesn't read.
14
+ type.prop :text_align, type._Union?(*ALIGNMENTS), json: "textAlign", parse_html: lambda { |element|
15
+ (element.style["text-align"] || element["align"]).to_s.strip.downcase.then { |value| value if ALIGNMENTS.include?(value) }
16
+ }
17
+ end
18
+
19
+ def text_align_style = @text_align && "text-align: #{@text_align}"
20
+
21
+ class Paragraph < Nodes::Paragraph
22
+ include TextAlign
23
+
24
+ def view_template(&) = p(style: text_align_style, &)
25
+ end
26
+
27
+ class Heading < Nodes::Heading
28
+ include TextAlign
29
+
30
+ def view_template(&) = tag(:"h#{@level}", id: heading_id, style: text_align_style, &)
31
+ end
32
+ end
33
+ end
34
+ end