yrby 0.9.0-aarch64-linux → 0.10.0-aarch64-linux

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 8c1d9b86b8778b8120f728232c70de38d9a0dfc09ff99973f7ac7ad772c6bcd8
4
- data.tar.gz: 32e33a4f2cab0777d3e15953aca69085fcedd4189de11a57756fadda5d760553
3
+ metadata.gz: e2ac2583690a26000f902571fe801b09262079f4540cb24e7519fcdc74e73a8a
4
+ data.tar.gz: f4285f7ebddd652fa8b4e396b4d6a32f2915c28a646965531baac0c6b849859c
5
5
  SHA512:
6
- metadata.gz: 6bb73b454506e9e766fc7ff22074363a517ac5624075185b79f2c19d0c0cd754997c1b48d6a1341c4a7a0ccfa442f8f6d501d23d38a94100183083417da94107
7
- data.tar.gz: 45fcbb30ba7e37a59803b6f7ba2d4ac051bf3c59d342eb1dbdef8724e4461661ca3ce64c0fd5a9218d5d44173dc10b0e78baa7b430355976c8ee2e0a084c1c79
6
+ metadata.gz: fb6c94b69a2a326a1d47ca490c62ff67a1b290612b505e1a397b6ab1f12b25f13d58f9b4b0148b0b692e8fe86836a98f63eb61604852106658c5c3388c2c32d3
7
+ data.tar.gz: cc7eade6987f11c4a292cf159444df6829083217e72a32d30ecc49b1710aff8fab5d3b753a0dcb0b12cc8cf3d5c3b2b94db88cb035772012887bfcb3024536d7
data/CHANGELOG.md CHANGED
@@ -6,6 +6,52 @@ to follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.10.0] - 2026-11-26
10
+
11
+ ### Added
12
+
13
+ - `Y::Doc#read_text_delta(name)` reads a `Y.Text` root with its formatting:
14
+ the runs of text with their attributes, and the embeds, as a JSON array
15
+ string. It is what `ytext.toDelta()` returns in JavaScript. `read_text`
16
+ gives the characters alone, which is not enough for an editor that keeps
17
+ rich text in a plain `Y.Text` (Quill, or Trix through y-trix).
18
+
19
+ - `Y::Trix` renders a Trix document shared with the
20
+ [y-trix](https://github.com/jpcamara/y-trix) binding to the HTML Trix
21
+ saves: `Y::Trix.new(doc).to_html`. Blocks and how they nest, text
22
+ attributes, links, line breaks, Trix's handling of spaces, right to left
23
+ text and attachments come out as Trix writes them, checked against
24
+ documents captured from real editors. Content from the document is
25
+ escaped and filtered, and the HTML of a content attachment is left out
26
+ unless `content:` says how to make it safe.
27
+
28
+ ## [0.9.1] - 2026-11-08
29
+
30
+ ### Changed
31
+
32
+ - yrby builds against yrs 0.28.1. An insert into a text no longer recounts
33
+ the UTF-16 length of each string before it, so appending to a long text
34
+ costs about the same at any length: 80k one-character appends took 2.5 s
35
+ and now take 48 ms.
36
+
37
+ ### Experimental
38
+
39
+ - `Y::Doc#edit` returns the document's own writes and never a peer's. The
40
+ document keeps the update of every local transaction until an edit returns
41
+ it, merged into one, so a write made outside an edit, from another thread
42
+ or fiber, or in a block that raised comes with the next edit. Before this,
43
+ the edit returned everything the document gained while the block ran, so
44
+ an update applied from a peer meanwhile was sent again as the edit's own,
45
+ and a caller had to lock the document to keep them apart. Each edit takes
46
+ everything unsent at once, so the updates edits return have no gaps
47
+ between them. A peer's update doesn't wait for an edit.
48
+
49
+ - `Y::Map#set_text(key, content = "")` stores a new `Y.Text` at a key and
50
+ returns its live `Y::Text`. `Y::Array#push_text(content = "")` and
51
+ `#insert_text(index, content = "")` do the same in a list. Before this,
52
+ Ruby could edit a nested `Y.Text` a browser made but couldn't make one,
53
+ so a server couldn't set up a form whose fields merge typing.
54
+
9
55
  ## yrby-client 0.7.1 - 2026-11-03
10
56
 
11
57
  ### Fixed
data/README.md CHANGED
@@ -76,15 +76,21 @@ doc = post.collaborative_document(:body).y_doc
76
76
  doc.read_text("content") # or Y::Lexxy.new(doc).to_html for rich text
77
77
  ```
78
78
 
79
- Install the gem and the npm package:
79
+ Install the gem and run its generator:
80
80
 
81
81
  ```
82
- gem install yrby-rails # depends on yrby
83
- npm install yrby-client yjs y-protocols @rails/actioncable
84
-
82
+ bundle add yrby-rails # depends on yrby
85
83
  bin/rails generate yrby:install && bin/rails db:migrate
86
84
  ```
87
85
 
86
+ In an app that uses import maps, the generator pins `yrby-client`, `yjs`, and
87
+ `@rails/actioncable` to JavaScript the gem ships. With a bundler, install the
88
+ npm packages instead:
89
+
90
+ ```
91
+ npm install yrby-client yjs y-protocols @rails/actioncable
92
+ ```
93
+
88
94
  ## Contents
89
95
 
90
96
  - [Scope](#scope)
@@ -101,7 +107,7 @@ bin/rails generate yrby:install && bin/rails db:migrate
101
107
  - [Rendering to HTML](#rendering-to-html)
102
108
  - [Protocol codec (module functions)](#protocol-codec-module-functions)
103
109
  - [ActionCable Integration](#actioncable-integration)
104
- - [Experimental: writing from Ruby](#experimental-writing-from-ruby)
110
+ - [Experimental: writing from Ruby, and collaborators](#experimental-writing-from-ruby-and-collaborators)
105
111
  - [Thread Safety](#thread-safety)
106
112
  - [Parallelism (GVL release)](#parallelism-gvl-release)
107
113
  - [Message Type Constants](#message-type-constants)
@@ -262,6 +268,7 @@ doc.read_text("prosemirror") # => plain text of a Y.Text root, or nil
262
268
  doc.read_xml("root") # => text of an XML root, one block per line
263
269
  doc.read_map("state") # => a Y.Map root as a JSON string; JSON.parse it
264
270
  doc.read_array("cards") # => a Y.Array root as a JSON string; JSON.parse it
271
+ doc.read_text_delta("body") # => a Y.Text root with its formatting, as a JSON string (Yjs's toDelta)
265
272
  ```
266
273
 
267
274
  ### Pending structs and gap-free state
@@ -359,6 +366,34 @@ types replaces the built-in one.
359
366
  In both renderers, an unknown node still renders its text and nested blocks as
360
367
  readable markup.
361
368
 
369
+ #### `Y::Trix`
370
+
371
+ ```ruby
372
+ Y::Trix.new(doc).to_html # the root named "trix"
373
+ Y::Trix.new(doc).to_html("body") # another root
374
+ ```
375
+
376
+ Renders a [Trix](https://trix-editor.org) document shared with the
377
+ [y-trix](https://github.com/jpcamara/y-trix) binding to the HTML Trix itself
378
+ saves, which is what Action Text stores. y-trix keeps the whole document in
379
+ one `Y.Text`: the text carries Trix's attributes (bold, italic, strike,
380
+ href), an attachment is an embed, and each block ends in a line break whose
381
+ attributes name the block (heading, quote, code, list item, and how they
382
+ nest). `Y::Trix` reads that with `Doc#read_text_delta` and is plain Ruby.
383
+
384
+ The output is checked against a few hundred documents captured from real
385
+ Trix editors, attachments and nested lists included
386
+ (`test/fixtures/trix.json`).
387
+
388
+ Nothing in the document is trusted. Text is escaped, only the attributes
389
+ Trix knows are read, and links and images keep only URLs a browser would not
390
+ run. A content attachment (a mention, an embed card) stores HTML of its own,
391
+ and that is left out unless you say how to make it safe:
392
+
393
+ ```ruby
394
+ Y::Trix.new(doc, content: ->(html) { sanitize(html) }).to_html
395
+ ```
396
+
362
397
  #### Custom nodes and marks
363
398
 
364
399
  The built-in schemas match what Tiptap and Lexxy ship. When your app adds its
@@ -664,6 +699,16 @@ the `authorize_document` block with the record and the attribute name, or to
664
699
  accept any valid grant when there's no block. A subclass can override
665
700
  `authorized?` directly and read the located record from `record`.
666
701
 
702
+ A page subscribes to the channel its document names, `Y::DocumentChannel`
703
+ unless the model says otherwise. Name a subclass where you declare the
704
+ attribute, and the tag, a Ruby client, and a collaborator all use it:
705
+
706
+ ```ruby
707
+ class Post < ApplicationRecord
708
+ has_collaborative_document :body, channel: "PostDocumentChannel"
709
+ end
710
+ ```
711
+
667
712
  ### Grant lifetime and refresh
668
713
 
669
714
  A grant lasts as long as GlobalID's signed-id default, which is one month under
@@ -1077,7 +1122,7 @@ The browser clients manage presence (cursors, selections). The server doesn't
1077
1122
  set or hold presence state, and it relays awareness frames without reading
1078
1123
  them. See `yrby-client` for the client-side awareness API.
1079
1124
 
1080
- ## Experimental: writing from Ruby
1125
+ ## Experimental: writing from Ruby, and collaborators
1081
1126
 
1082
1127
  These APIs are new. They may change in any minor release, and they aren't
1083
1128
  covered by yrby's usual compatibility promise.
@@ -1088,6 +1133,12 @@ covered by yrby's usual compatibility promise.
1088
1133
  - Anchors: a block's identity as a value
1089
1134
  - Streaming into a document with `Doc#edit`
1090
1135
  - Editing a record's document from Ruby
1136
+ - From the `yrby-agent` gem: joining a document from a Ruby process with
1137
+ `Y::ActionCable::Client`, collaborators with `Y::Collaborator`, and agents
1138
+ with `Y::Agent`
1139
+
1140
+ `require "y/action_cable/client"`, `require "y/collaborator"`, and
1141
+ `require "y/agent"` print a warning in Ruby's `:experimental` category. `Warning[:experimental] = false` turns it off.
1091
1142
 
1092
1143
  ## Thread Safety
1093
1144
 
@@ -9,6 +9,7 @@ module Yrby
9
9
  # migration. The models and Y::DocumentChannel ship in the gem, so that is
10
10
  # the only file it generates by default. Pass --channel to also generate
11
11
  # an application channel for custom authorization or room-keyed documents.
12
+ # In an import-map app it also pins the JavaScript the gem ships.
12
13
  class InstallGenerator < ::Rails::Generators::Base
13
14
  source_root File.expand_path("templates", __dir__)
14
15
  class_option :channel, type: :boolean, default: false, desc: "Generate a custom DocumentChannel"
@@ -21,6 +22,39 @@ module Yrby
21
22
  invoke "yrby:tables"
22
23
  end
23
24
 
25
+ # Each shared module has one pin, so the page loads one copy of it:
26
+ #
27
+ # - yrby-client and yrby-client/element point at one file, so the page
28
+ # has one session store and one <yrby-document> class.
29
+ # - yjs is one copy, because Yjs checks constructors with instanceof.
30
+ # The app's editor binding imports it through this pin too.
31
+ # - @rails/actioncable is Rails' own file. <yrby-document> loads it for
32
+ # its default consumer.
33
+ #
34
+ # A pin the app already has is left alone, so re-running the generator
35
+ # adds only what is missing.
36
+ IMPORTMAP_PINS = {
37
+ "yrby-client" => "yrby/yrby-client.js",
38
+ "yrby-client/element" => "yrby/yrby-client.js",
39
+ "yjs" => "yrby/yjs.js",
40
+ "@rails/actioncable" => "actioncable.esm.js"
41
+ }.freeze
42
+
43
+ def add_importmap_pins
44
+ importmap = File.join(destination_root, "config/importmap.rb")
45
+ return unless File.exist?(importmap)
46
+
47
+ existing = File.read(importmap)
48
+ missing = IMPORTMAP_PINS.reject { |name, _| existing.match?(/^\s*pin\s+["']#{Regexp.escape(name)}["']/) }
49
+ return if missing.empty?
50
+
51
+ append_to_file "config/importmap.rb", <<~RUBY
52
+
53
+ # yrby. One pin per shared module, so the page loads one copy of each.
54
+ #{missing.map { |name, path| %(pin "#{name}", to: "#{path}") }.join("\n")}
55
+ RUBY
56
+ end
57
+
24
58
  def show_next_steps
25
59
  say <<~NEXT
26
60
 
@@ -32,9 +66,11 @@ module Yrby
32
66
 
33
67
  <%= collaborative_document_tag @post, :body %>
34
68
 
35
- 3. Install the yrby-client npm package. The tag renders an
36
- element that connects automatically. Once it syncs, your code
37
- gets the document and can bind it to any Yjs editor:
69
+ 3. Load yrby-client. With import maps, the generator added pins.
70
+ With a bundler, install the yrby-client and yjs npm packages.
71
+ The tag renders an element that connects automatically. Once
72
+ it syncs, your code gets the document and can bind it to any
73
+ Yjs editor:
38
74
 
39
75
  import "yrby-client/element"
40
76
 
data/lib/y/3.4/yrby.so CHANGED
Binary file
data/lib/y/4.0/yrby.so CHANGED
Binary file
data/lib/y/array.rb ADDED
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Y
4
+ # Inside module Y, `Array` is this class.
5
+ class Array
6
+ # Insert a new Y.Text holding `content` at `index` and return a live
7
+ # Y::Text for it. Indexes work as in `insert`: -1 appends.
8
+ def insert_text(index, content = "")
9
+ native_insert_text(index, content)
10
+ end
11
+
12
+ # Append a new Y.Text holding `content` and return a live Y::Text for it.
13
+ def push_text(content = "")
14
+ insert_text(-1, content)
15
+ end
16
+ end
17
+ end
@@ -22,10 +22,10 @@ module Y
22
22
  # this to return before it acknowledges or broadcasts the change.
23
23
  def append(update) = document_row.append(update)
24
24
 
25
- # A signed grant for this document, what a page or a Ruby client
26
- # subscribes with. It's a signed GlobalID scoped to this attribute, and
27
- # Y::Collaborative.locate turns it back into the record. Pass
28
- # expires_in: to limit how long it lasts. Without it GlobalID's own
25
+ # A signed grant for this document, what a page, a Ruby client, or a
26
+ # Y::Collaborator subscribes with. It's a signed GlobalID scoped to this
27
+ # attribute, and Y::Collaborative.locate turns it back into the record.
28
+ # Pass expires_in: to limit how long it lasts. Without it GlobalID's own
29
29
  # default applies, which is one month under Rails. The option goes
30
30
  # through only when it's given, because an explicit nil would mean
31
31
  # "never expire".
@@ -35,15 +35,16 @@ module Y
35
35
  record.to_sgid(**options).to_s
36
36
  end
37
37
 
38
- # The channel that accepts this document's grant. A gem with its own
39
- # grants and channel, such as lexxy-realtime, returns its own document
40
- # with both.
41
- def channel = "Y::DocumentChannel"
38
+ # The channel that accepts this document's grant: the one the model
39
+ # declared with has_collaborative_document, or Y::DocumentChannel. A
40
+ # gem with its own grants and channel, such as lexxy-realtime, returns
41
+ # its own document with both.
42
+ def channel = record.class.collaborative_document_options.dig(name, :channel) || "Y::DocumentChannel"
42
43
 
43
44
  # Edits the document from Ruby the way a browser does: yields the
44
45
  # current document, records what the block changed, and broadcasts it so
45
46
  # open editors apply it. Returns the update, or nil when the block
46
- # changed nothing.
47
+ # wrote nothing.
47
48
  #
48
49
  # post.collaborative_document(:body).edit do |doc|
49
50
  # Y::Lexxy.append_paragraph(doc, "Reviewed by ops.")
@@ -18,10 +18,10 @@ module Y
18
18
  #
19
19
  # The grant and channel come from record.collaborative_document(name), so
20
20
  # the tag works for any gem that returns its own document, such as
21
- # lexxy-realtime. Pass channel: for an app's own Y::DocumentChannel
22
- # subclass. The grant is scoped to this record and attribute. Only render
23
- # the tag on pages where
24
- # the user may edit the record, because by default anyone holding the
21
+ # lexxy-realtime. An app's own Y::DocumentChannel subclass is named where
22
+ # the model declares the attribute, with has_collaborative_document's
23
+ # channel:. The grant is scoped to this record and attribute. Only render
24
+ # the tag on pages where the user may edit the record, because by default anyone holding the
25
25
  # grant can open the document. To also check the user's current
26
26
  # permissions when they subscribe, use Y::DocumentChannel.authorize_document.
27
27
  #
@@ -61,12 +61,13 @@ module Y
61
61
  end
62
62
 
63
63
  class_methods do
64
- # Declares how one attribute's document is stored. The shipped channel
65
- # and Ruby reads both follow it, and undeclared attributes use plain
66
- # Y::Document.
67
- def has_collaborative_document(name, encrypted: false) # rubocop:disable Naming/PredicatePrefix
64
+ # Declares how one attribute's document is stored, and the channel that
65
+ # serves it: an app's own Y::DocumentChannel subclass, by name. The
66
+ # shipped channel and Ruby reads both follow it. Undeclared attributes
67
+ # use plain Y::Document and Y::DocumentChannel.
68
+ def has_collaborative_document(name, encrypted: false, channel: nil) # rubocop:disable Naming/PredicatePrefix
68
69
  self.collaborative_document_options = collaborative_document_options.merge(
69
- name.to_s => { encrypted: encrypted }.freeze
70
+ name.to_s => { encrypted: encrypted, channel: channel&.to_s }.freeze
70
71
  ).freeze
71
72
  end
72
73
 
data/lib/y/doc.rb CHANGED
@@ -4,17 +4,43 @@ module Y
4
4
  # Ruby-side conveniences over the native document.
5
5
  class Doc
6
6
  # Runs the block, which edits this document through handles, and returns
7
- # the update its writes produced, or nil when the document didn't change.
8
- # The document has the edit either way. The update is what a process
9
- # saves and broadcasts, one call per chunk as it streams into a document.
7
+ # an update with every local write no edit has returned yet, or nil when
8
+ # there's nothing to send. The document has the writes either way. The
9
+ # update is what a process saves and broadcasts, one call per chunk as it
10
+ # streams into a document.
10
11
  #
11
- # The update holds everything the document gained while the block ran,
12
- # so a write another thread or peer made meanwhile is in it too. Applying
13
- # an update twice changes nothing, so that only adds bytes.
12
+ # The document keeps every local write until an edit returns it, so none
13
+ # is left out: a write made outside an edit, from another thread or
14
+ # fiber, or in a block that raised comes with the next edit's update. An
15
+ # update applied from a peer is never in it, and doesn't wait for the
16
+ # block. Each edit takes everything unsent at once, so the updates edits
17
+ # return have no gaps between them. An edit inside another, including one
18
+ # in a fiber or thread the outer block starts, returns what it took and
19
+ # leaves it for the outer edit to return again. Once the outer edit
20
+ # returns, a thread it started edits on its own.
21
+ #
22
+ # So send every update an edit returns. An edit in a thread the block
23
+ # didn't start, such as a pool thread, isn't nested: it takes the outer
24
+ # block's writes too, and they're sent only if its update is.
25
+ #
26
+ # An exception raised as `edit` returns, such as a Thread#raise or a
27
+ # signal trap, loses the update the edit took. A caller that must send
28
+ # every update masks interrupts around `edit` and doesn't raise from a
29
+ # trap.
14
30
  def edit
15
- before = native_snapshot
16
- yield self
17
- native_update_since(before)
31
+ # The edits running in this fiber, inherited by the fibers and threads
32
+ # their blocks start. Each is `[doc]` until it ends, then empty.
33
+ outer = (Fiber[:yrby_editing] || []).reject(&:empty?)
34
+ nested = outer.any? { |running| running.include?(self) }
35
+ running = [self]
36
+ Fiber[:yrby_editing] = [*outer, running]
37
+ begin
38
+ yield self
39
+ ensure
40
+ running.clear
41
+ Fiber[:yrby_editing] = outer
42
+ end
43
+ take_unsent(nested)
18
44
  end
19
45
 
20
46
  # The ordinal of the top-level block a position falls in, or nil at the
@@ -32,5 +58,22 @@ module Y
32
58
  def find(anchor)
33
59
  native_find(anchor.position, anchor.root)
34
60
  end
61
+
62
+ private
63
+
64
+ # An interrupt that arrives during the take is raised once the masked
65
+ # block ends, and the taken update goes back to the document first, for
66
+ # the next edit to return. A nested edit has already put it back.
67
+ def take_unsent(nested)
68
+ taken = nil
69
+ Thread.handle_interrupt(Object => :never) do
70
+ taken = native_take_unsent
71
+ native_keep_unsent(taken) if taken && nested
72
+ end
73
+ taken
74
+ rescue Exception # rubocop:disable Lint/RescueException -- an interrupt is any exception
75
+ native_keep_unsent(taken) if taken && !nested
76
+ raise
77
+ end
35
78
  end
36
79
  end
data/lib/y/map.rb ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Y
4
+ class Map
5
+ # Store a new Y.Text holding `content` at `key`, replacing what was
6
+ # there, and return a live Y::Text for it. `map[key] = "..."` stores a
7
+ # plain string instead, and the last write to it wins.
8
+ def set_text(key, content = "")
9
+ native_set_text(key, content)
10
+ end
11
+ end
12
+ end
data/lib/y/trix.rb ADDED
@@ -0,0 +1,393 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Y
6
+ # Renders a Trix document kept in a `Y.Text` (the y-trix binding's format)
7
+ # to the HTML Trix itself saves, with no browser.
8
+ #
9
+ # Y::Trix.new(doc).to_html # the root named "trix"
10
+ # Y::Trix.new(doc).to_html("body") # another root
11
+ #
12
+ # The format: text runs carry Trix's text attributes (bold, italic, strike,
13
+ # href); an attachment is an embed `{ "attachment" => {...} }`; and every
14
+ # block ends in a "\n" whose attributes say `blockBreak: true` and, under
15
+ # `block`, the block's attributes in order (["quote", "bulletList",
16
+ # "bullet"]). A "\n" without blockBreak is a line break inside a block.
17
+ #
18
+ # The document can come from anyone who can write to it, so nothing in it is
19
+ # trusted: text is escaped, only the attributes Trix knows are read, and
20
+ # links and images keep only URLs a browser would not run. The HTML of a
21
+ # content attachment is left out unless you pass `content:`, a callable
22
+ # that takes the stored HTML and returns HTML that is safe to show:
23
+ #
24
+ # Y::Trix.new(doc, content: ->(html) { sanitize(html) }).to_html
25
+ class Trix
26
+ DEFAULT_ROOT = "trix"
27
+
28
+ BLOCKS = {
29
+ "quote" => { tag: "blockquote" },
30
+ "heading1" => { tag: "h1", group: false },
31
+ "code" => { tag: "pre", html: ["language"], plaintext: true },
32
+ "bulletList" => { tag: "ul" },
33
+ "bullet" => { tag: "li", group: false },
34
+ "numberList" => { tag: "ol" },
35
+ "number" => { tag: "li", group: false },
36
+ "attachmentGallery" => { tag: "div", group: false }
37
+ }.freeze
38
+ LISTS = %w[bulletList numberList].freeze
39
+ MARKS = { "bold" => "strong", "italic" => "em", "strike" => "del" }.freeze
40
+ PREVIEWABLE = %r{\Aimage(/(gif|png|webp|jpe?g)|\z)}
41
+ SIZES = %w[Bytes KB MB GB TB PB].freeze
42
+ NBSP = "\u00A0"
43
+ BAD_EMBED = "\uFFFD"
44
+ PIECE_STRINGS = %w[caption presentation].freeze
45
+ URL_KEYS = %w[url href previewURL].freeze
46
+ STRING_KEYS = %w[content contentType filename alt].freeze
47
+ NUMBER_KEYS = %w[filesize width height].freeze
48
+ # What DOMPurify, which Trix uses, lets through as a link or a source.
49
+ SAFE_URL = /\A(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|\z))/i
50
+ URL_NOISE = /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/
51
+ RTL = /\p{Hebrew}|\p{Arabic}|\p{Syriac}|\p{Thaana}|\p{Nko}/
52
+ STRONG = /\p{L}/
53
+
54
+ Piece = Struct.new(:string, :attachment, :attrs)
55
+ Block = Struct.new(:pieces, :attributes, :html) do
56
+ def text = pieces.map { |piece| piece.attachment ? "\uFFFC" : piece.string }.join
57
+ def empty? = pieces.empty?
58
+
59
+ def direction
60
+ @direction ||= begin
61
+ first = text[STRONG]
62
+ first && RTL.match?(first) ? "rtl" : "ltr"
63
+ end
64
+ end
65
+ end
66
+ Group = Struct.new(:objects, :depth)
67
+
68
+ # `doc` is a Y::Doc. `content:` renders the HTML of content attachments
69
+ # (see the class comment); without it they keep their frame and caption
70
+ # and show nothing inside.
71
+ def initialize(doc, content: nil)
72
+ @doc = doc
73
+ @content = content
74
+ end
75
+
76
+ # The document's HTML, or nil when the doc has no such text root.
77
+ def to_html(root = DEFAULT_ROOT)
78
+ json = @doc.read_text_delta(root.to_s)
79
+ json && self.class.render(JSON.parse(json), content: @content)
80
+ end
81
+
82
+ # Renders a delta that is already parsed: an array of
83
+ # `{ "insert" => ..., "attributes" => {...} }`, as `read_text_delta` and
84
+ # Yjs's `toDelta()` give it.
85
+ def self.render(delta, content: nil)
86
+ new(nil, content: content).render(delta)
87
+ end
88
+
89
+ def render(delta)
90
+ blocks = blocks_of(delta)
91
+ return "" if blocks.empty? || (blocks.size == 1 && blocks[0].empty? && blocks[0].attributes.empty?)
92
+
93
+ group(blocks, 0).map { |object| render_object(object) }.join
94
+ end
95
+
96
+ private
97
+
98
+ # ---- the delta, as Trix's blocks of pieces ------------------------------
99
+
100
+ def blocks_of(delta)
101
+ blocks = []
102
+ pieces = []
103
+ Array(delta).each do |op|
104
+ next unless op.is_a?(Hash)
105
+
106
+ attrs = op["attributes"].is_a?(Hash) ? op["attributes"] : {}
107
+ insert = op["insert"]
108
+ if insert.is_a?(String) && attrs["blockBreak"] == true
109
+ # (one "\n" each: equal breaks in a row come as one run)
110
+ insert.each_char do |char|
111
+ next add_text(pieces, char, attrs) unless char == "\n"
112
+
113
+ blocks << Block.new(pieces, block_attributes(attrs["block"]), attrs["html"])
114
+ pieces = []
115
+ end
116
+ elsif insert.is_a?(String) then add_text(pieces, insert, attrs)
117
+ elsif !insert.nil? then add_embed(pieces, insert, attrs)
118
+ end
119
+ end
120
+ # (text after the last block break: Trix would end it with one)
121
+ blocks << Block.new(pieces, [], nil) unless pieces.empty?
122
+ blocks
123
+ end
124
+
125
+ def add_embed(pieces, embed, attrs)
126
+ attachment = clean_attachment(embed)
127
+ return add_text(pieces, BAD_EMBED, {}) unless attachment
128
+
129
+ pieces << Piece.new(nil, attachment, piece_attrs(attrs, attachment: true))
130
+ end
131
+
132
+ def add_text(pieces, string, attrs)
133
+ string = string.gsub("\r\n", "\n").tr("\r", "\n")
134
+ return if string.empty?
135
+
136
+ attrs = piece_attrs(attrs)
137
+ last = pieces.last
138
+ if last && last.attachment.nil? && last.attrs == attrs
139
+ last.string += string
140
+ else
141
+ pieces << Piece.new(+string, nil, attrs)
142
+ end
143
+ end
144
+
145
+ # The text attributes Trix knows, by name, as it nests them. (y-trix
146
+ # takes true, a string or a number as a format being on, so this does.)
147
+ def piece_attrs(attrs, attachment: false)
148
+ attrs.keys.sort.each_with_object({}) do |key, out|
149
+ value = piece_value(key, attrs[key], attachment)
150
+ out[key] = value unless value.nil?
151
+ end
152
+ end
153
+
154
+ def piece_value(key, value, attachment)
155
+ if MARKS.key?(key) then true if value == true || value.is_a?(String) || value.is_a?(Numeric)
156
+ elsif key == "href" then value if value.is_a?(String) && safe_url?(value)
157
+ elsif attachment && PIECE_STRINGS.include?(key) then value if value.is_a?(String)
158
+ end
159
+ end
160
+
161
+ def block_attributes(block)
162
+ return [] unless block.is_a?(::Array)
163
+
164
+ block.select { |name| name.is_a?(String) && BLOCKS.key?(name) }
165
+ end
166
+
167
+ def clean_attachment(embed)
168
+ return nil unless embed.is_a?(Hash) && embed["attachment"].is_a?(Hash)
169
+
170
+ embed["attachment"].keys.sort.each_with_object({}) do |key, out|
171
+ value = embed["attachment"][key]
172
+ out[key] = value if attachment_value?(key, value)
173
+ end
174
+ end
175
+
176
+ def attachment_value?(key, value)
177
+ if URL_KEYS.include?(key) then value.is_a?(String) && safe_url?(value)
178
+ elsif STRING_KEYS.include?(key) then value.is_a?(String)
179
+ elsif NUMBER_KEYS.include?(key) then value.is_a?(Numeric) && value.finite?
180
+ else value.is_a?(String) || value.is_a?(Numeric) || value == true || value == false
181
+ end
182
+ end
183
+
184
+ def safe_url?(url)
185
+ SAFE_URL.match?(url.gsub(URL_NOISE, ""))
186
+ end
187
+
188
+ # ---- blocks, grouped the way Trix groups them ---------------------------
189
+
190
+ def group(blocks, depth)
191
+ objects = []
192
+ current = nil
193
+ blocks.each do |block|
194
+ if current
195
+ if block.attributes[depth] && groups_with?(current.last, block, depth)
196
+ current << block
197
+ next
198
+ end
199
+ objects << Group.new(group(current, depth + 1), depth)
200
+ current = nil
201
+ end
202
+ if block.attributes[depth]
203
+ current = [block]
204
+ else
205
+ objects << block
206
+ end
207
+ end
208
+ objects << Group.new(group(current, depth + 1), depth) if current
209
+ objects
210
+ end
211
+
212
+ def groups_with?(block, other, depth)
213
+ attribute = block.attributes[depth]
214
+ return false unless attribute == other.attributes[depth]
215
+ return false if BLOCKS[attribute][:group] == false && !LISTS.include?(other.attributes[depth + 1])
216
+
217
+ block.direction == other.direction || other.empty?
218
+ end
219
+
220
+ def render_object(object)
221
+ return render_block(object) unless object.is_a?(Group)
222
+
223
+ first = object
224
+ first = first.objects.first while first.is_a?(Group)
225
+ open, close = container(first, object.depth)
226
+ "#{open}#{object.objects.map { |child| render_object(child) }.join}#{close}"
227
+ end
228
+
229
+ def container(block, depth)
230
+ name = block.attributes[depth]
231
+ config = BLOCKS[name]
232
+ attributes = +""
233
+ if name == "attachmentGallery"
234
+ attributes << %( class="attachment-gallery attachment-gallery--#{block.text.length}")
235
+ end
236
+ attributes << %( dir="rtl") if depth.zero? && block.direction == "rtl"
237
+ if block.html.is_a?(Hash)
238
+ block.html.keys.sort.each do |key|
239
+ value = block.html[key]
240
+ next unless Array(config[:html]).include?(key) && (value.is_a?(String) || value.is_a?(Numeric))
241
+
242
+ attributes << %( #{key}="#{escape_attribute(value.to_s)}")
243
+ end
244
+ end
245
+ ["<#{config[:tag]}#{attributes}>", "</#{config[:tag]}>"]
246
+ end
247
+
248
+ def render_block(block)
249
+ inner =
250
+ if block.empty?
251
+ "<br>"
252
+ else
253
+ plaintext = BLOCKS.dig(block.attributes.last, :plaintext) == true
254
+ html = render_text(block.pieces, plaintext)
255
+ html << "<br>" if block.text.end_with?("\n")
256
+ html
257
+ end
258
+ return inner unless block.attributes.empty?
259
+
260
+ block.direction == "rtl" ? %(<div dir="rtl">#{inner}</div>) : "<div>#{inner}</div>"
261
+ end
262
+
263
+ # ---- the text of a block --------------------------------------------------
264
+
265
+ # Pieces in a row with one href share one <a>, and what Trix decides by a
266
+ # piece's place in the text (see spaces) it decides by the link's place.
267
+ def render_text(pieces, plaintext)
268
+ runs = pieces.chunk_while { |a, b| a.attrs["href"] && a.attrs["href"] == b.attrs["href"] }.to_a
269
+ runs.each_with_index.map do |run, index|
270
+ context = { first: index.zero?, last: index == runs.size - 1,
271
+ follows_whitespace: index.positive? && ends_in_whitespace?(runs[index - 1]) }
272
+ inner = run.map { |piece| render_piece(piece, plaintext, context) }.join
273
+ href = run[0].attrs["href"]
274
+ href ? %(<a href="#{escape_attribute(href)}">#{inner}</a>) : inner
275
+ end.join
276
+ end
277
+
278
+ # (Trix asks a link, not its text, and a link or an attachment is no whitespace)
279
+ def ends_in_whitespace?(run)
280
+ piece = run[0]
281
+ run.size == 1 && piece.attrs["href"].nil? && piece.attachment.nil? && piece.string.match?(/\s\z/)
282
+ end
283
+
284
+ def render_piece(piece, plaintext, context)
285
+ inner = piece.attachment ? render_attachment(piece) : render_string(piece.string, plaintext, context)
286
+ tags = piece.attrs.keys.filter_map { |key| MARKS[key] }
287
+ "#{tags.map { |tag| "<#{tag}>" }.join}#{inner}#{tags.reverse.map { |tag| "</#{tag}>" }.join}"
288
+ end
289
+
290
+ def render_string(string, plaintext, context)
291
+ return escape_text(string) if plaintext
292
+
293
+ string.split("\n", -1).each_with_index.map do |line, index|
294
+ "#{"<br>" if index.positive?}#{escape_text(spaces(line, context)) unless line.empty?}"
295
+ end.join
296
+ end
297
+
298
+ # Runs of spaces would collapse in HTML, so Trix alternates them with
299
+ # no-break spaces, and keeps one at either end of the text.
300
+ def spaces(string, context)
301
+ string = string.sub(/ \z/, NBSP) if context[:last]
302
+ string = string.gsub(/(\S) {3}(\S)/, "\\1 #{NBSP} \\2").gsub(/ {2}/, "#{NBSP} ").gsub(/ {2}/, " #{NBSP}")
303
+ string = string.sub(/\A /, NBSP) if context[:first] || context[:follows_whitespace]
304
+ string
305
+ end
306
+
307
+ # ---- attachments -----------------------------------------------------------
308
+
309
+ def render_attachment(piece)
310
+ attachment = piece.attachment
311
+ content = attachment["content"]
312
+ type = attachment_type(attachment)
313
+ inner = +""
314
+ if content
315
+ inner << @content.call(content).to_s if @content
316
+ elsif type == "preview"
317
+ inner << image(attachment)
318
+ end
319
+ inner << caption(piece, type)
320
+ href = attachment["href"]
321
+ # (Trix leaves the link off when the content has one of its own)
322
+ inner = %(<a href="#{escape_attribute(href)}">#{inner}</a>) if href && !content.to_s.match?(/<a[\s>]/i)
323
+ "#{figure(piece, type)}#{inner}</figure>"
324
+ end
325
+
326
+ def figure(piece, type)
327
+ attachment = piece.attachment
328
+ classes = ["attachment", "attachment--#{type}"]
329
+ extension = attachment["filename"].to_s[/\.(\w+)\z/, 1]
330
+ classes << "attachment--#{extension.downcase}" if extension
331
+ data = { "data-trix-attachment" => JSON.generate(attachment),
332
+ "data-trix-content-type" => attachment.fetch("contentType", "undefined").to_s }
333
+ data["data-trix-attributes"] = JSON.generate(piece.attrs) unless piece.attrs.empty?
334
+ data["class"] = classes.join(" ")
335
+ "<figure#{data.map { |name, value| %( #{name}="#{escape_attribute(value)}") }.join}>"
336
+ end
337
+
338
+ def attachment_type(attachment)
339
+ return "content" if attachment.key?("content")
340
+
341
+ previewable =
342
+ if attachment.key?("previewable") then attachment["previewable"]
343
+ else PREVIEWABLE.match?(attachment["contentType"].to_s)
344
+ end
345
+ previewable ? "preview" : "file"
346
+ end
347
+
348
+ def image(attachment)
349
+ html = %(<img src="#{escape_attribute(attachment["url"].to_s)}")
350
+ %w[width height alt].each do |name|
351
+ html << %( #{name}="#{escape_attribute(attachment[name].to_s)}") unless attachment[name].nil?
352
+ end
353
+ html << ">"
354
+ end
355
+
356
+ def caption(piece, type)
357
+ edited = piece.attrs["caption"]
358
+ if edited && !edited.empty?
359
+ klass = "attachment__caption attachment__caption--edited"
360
+ return %(<figcaption class="#{klass}">#{escape_text(edited)}</figcaption>)
361
+ end
362
+
363
+ attachment = piece.attachment
364
+ name = attachment["filename"].to_s if %w[preview file].include?(type)
365
+ size = filesize(attachment["filesize"]) if %w[preview file].include?(type)
366
+ parts = []
367
+ parts << %(<span class="attachment__name">#{escape_text(name)}</span>) if name && !name.empty?
368
+ parts << %(<span class="attachment__size">#{escape_text(size)}</span>) if size && !size.empty?
369
+ %(<figcaption class="attachment__caption">#{parts.join(" ")}</figcaption>)
370
+ end
371
+
372
+ def filesize(number)
373
+ return "" unless number.is_a?(Numeric)
374
+ return "0 Bytes" if number.zero?
375
+ return "1 Byte" if number == 1
376
+
377
+ exponent = (Math.log(number) / Math.log(1024)).floor
378
+ exponent = exponent.clamp(0, SIZES.size - 1)
379
+ human = format("%.2f", number / (1024.0**exponent)).sub(/0*\z/, "").sub(/\.\z/, "")
380
+ "#{human} #{SIZES[exponent]}"
381
+ end
382
+
383
+ # ---- escaping, as a browser serializes -------------------------------------
384
+
385
+ def escape_text(string)
386
+ string.gsub("&", "&amp;").gsub("<", "&lt;").gsub(">", "&gt;").gsub(NBSP, "&nbsp;")
387
+ end
388
+
389
+ def escape_attribute(string)
390
+ string.gsub("&", "&amp;").gsub('"', "&quot;").gsub("<", "&lt;").gsub(">", "&gt;").gsub(NBSP, "&nbsp;")
391
+ end
392
+ end
393
+ end
data/lib/y/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Y
4
- VERSION = "0.9.0"
4
+ VERSION = "0.10.0"
5
5
  end
data/lib/y.rb CHANGED
@@ -19,8 +19,11 @@ require_relative "y/lexical_markdown"
19
19
  require_relative "y/anchor"
20
20
  require_relative "y/xml_text"
21
21
  require_relative "y/text"
22
+ require_relative "y/map"
23
+ require_relative "y/array"
22
24
  require_relative "y/doc"
23
25
  require_relative "y/tiptap"
26
+ require_relative "y/trix"
24
27
  require_relative "y/decoder"
25
28
 
26
29
  module Y
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: yrby
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.9.0
4
+ version: 0.10.0
5
5
  platform: aarch64-linux
6
6
  authors:
7
7
  - JP Camara
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-03 00:00:00.000000000 Z
11
+ date: 2026-11-26 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: minitest
@@ -73,6 +73,7 @@ files:
73
73
  - lib/y/3.4/yrby.so
74
74
  - lib/y/4.0/yrby.so
75
75
  - lib/y/anchor.rb
76
+ - lib/y/array.rb
76
77
  - lib/y/collaborative.rb
77
78
  - lib/y/collaborative/attribute.rb
78
79
  - lib/y/collaborative/helper.rb
@@ -81,9 +82,11 @@ files:
81
82
  - lib/y/lexical_markdown.rb
82
83
  - lib/y/lexical_writer.rb
83
84
  - lib/y/lexxy.rb
85
+ - lib/y/map.rb
84
86
  - lib/y/rendering.rb
85
87
  - lib/y/text.rb
86
88
  - lib/y/tiptap.rb
89
+ - lib/y/trix.rb
87
90
  - lib/y/version.rb
88
91
  - lib/y/xml_text.rb
89
92
  - lib/yrby.rb