yrby 0.9.0 → 0.10.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.
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,7 +1,7 @@
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: ruby
6
6
  authors:
7
7
  - JP Camara
@@ -103,6 +103,7 @@ files:
103
103
  - lib/generators/yrby/tables/templates/create_y_tables.rb
104
104
  - lib/y.rb
105
105
  - lib/y/anchor.rb
106
+ - lib/y/array.rb
106
107
  - lib/y/collaborative.rb
107
108
  - lib/y/collaborative/attribute.rb
108
109
  - lib/y/collaborative/helper.rb
@@ -111,9 +112,11 @@ files:
111
112
  - lib/y/lexical_markdown.rb
112
113
  - lib/y/lexical_writer.rb
113
114
  - lib/y/lexxy.rb
115
+ - lib/y/map.rb
114
116
  - lib/y/rendering.rb
115
117
  - lib/y/text.rb
116
118
  - lib/y/tiptap.rb
119
+ - lib/y/trix.rb
117
120
  - lib/y/version.rb
118
121
  - lib/y/xml_text.rb
119
122
  - lib/yrby.rb