nokodown 0.1.0 → 0.1.1

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/nokodown/dom.rb CHANGED
@@ -14,6 +14,11 @@ module Nokodown
14
14
 
15
15
  # Elements that stop Readability from treating a div as a paragraph.
16
16
  PARAGRAPH_BREAKERS = Set.new(%w[blockquote dl div img ol p pre table ul]).freeze
17
+ PARAGRAPH_BREAKER_SELECTOR = PARAGRAPH_BREAKERS.to_a.join(", ").freeze
18
+
19
+ # The elements the HTML parser reopens after a block cuts them.
20
+ FORMATTING = Set.new(%w[a b big code em font i nobr s small strike strong tt u]).freeze
21
+ FORMATTING_XPATH = FORMATTING.map { |name| ".//#{name}" }.join("|").freeze
17
22
 
18
23
  CODE = %w[pre code].freeze
19
24
 
@@ -23,33 +28,122 @@ module Nokodown
23
28
  # Every character [[:space:]] matches. tr/squeeze is several times faster
24
29
  # than a regex gsub on large subtrees.
25
30
  UNICODE_SPACES = "\t\n\v\f\r\u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000"
31
+ ASCII_SPACES = "\t\n\v\f\r"
32
+ # The other characters of UNICODE_SPACES, as UTF-8 bytes.
33
+ NON_ASCII_SPACE_BYTES = Regexp.new(
34
+ "\xC2[\x85\xA0]|\xE1\x9A\x80|\xE2\x80[\x80-\x8A\xA8\xA9\xAF]|\xE2\x81\x9F|\xE3\x80\x80".b, Regexp::NOENCODING
35
+ )
36
+ # The first bytes of those sequences, the share of a text's bytes past
37
+ # which they are replaced faster as characters, and the length below
38
+ # which counting them costs more than it saves.
39
+ SPACE_LEADS = ["\xC2".b, "\xE1".b, "\xE2".b, "\xE3".b].map(&:freeze).freeze
40
+ DENSE_LEADS = 20
41
+ DENSE_MIN = 16
42
+ # What squish can drop: spaces, and a NUL that strip takes off the end.
43
+ ASCII_BLANKS = "#{ASCII_SPACES} \0"
44
+ # Bytes that start no more characters than there are blanks among them:
45
+ # the ASCII blanks, and every first byte of a non-ASCII space.
46
+ BLANK_BYTES = [*ASCII_BLANKS.chars, *SPACE_LEADS].map { |byte| byte.b.freeze }.freeze
47
+ # What squish changes in ASCII text: a space other than a blank, two
48
+ # blanks in a row, or a blank or NUL at either end.
49
+ UNSQUISHED = /[\t\n\v\f\r]| |\A[ \0]|[ \0]\z/.freeze
50
+ SHORT_TEXT = 96
51
+ SAMPLE_LIMITS = 8
26
52
 
27
53
  # Nokolexbor returns a new Ruby object every time a node is read, so nodes
28
54
  # cannot be hash keys. Elements get a numbered attribute to key on instead.
29
55
  KEY = "data-nokodown-key"
30
56
 
31
57
  UUID = /\h{8}-\h{4}-\h{4}-\h{4}-\h{12}/.freeze
58
+ # A shorter name cannot hold one, so it is not searched.
59
+ UUID_LENGTH = 36
60
+ # One level of brackets may nest ("[&>[data-slot=icon]]"). Possessive, so
61
+ # a run of unclosed "[" is not rescanned from each one.
62
+ ARBITRARY_VALUE = /\[(?:[^\s\[\]]|\[[^\s\[\]]*+\])*+\]/.freeze
32
63
  CSS_MODULE_HASH = /__(?=[\w-]{0,4}[A-Z\d])[\w-]{5}(?![\w-])/.freeze
64
+ CAMEL_CASE = /(?<=[a-z\d])(?=[A-Z])/.freeze
65
+ SIGNATURES = :nokodown_signatures
66
+ SECONDARY = :nokodown_secondary
67
+ WEIGHTS = :nokodown_weights
33
68
 
34
69
  # On a forum, the replies sit in containers named like a comment section.
35
70
  # ContentLocator marks them and everything inside them, so the mark
36
71
  # survives the copy that article cleaning works on.
37
72
  THREAD = "data-nokodown-thread"
38
73
 
74
+ ELEMENTS_XPATH = "descendant::*"
75
+
76
+ # Set by HeadingAnchors on elements whose id is made from their heading.
77
+ ANCHOR = "data-nokodown-anchor"
78
+
39
79
  module_function
40
80
 
41
- def assign_keys(root)
81
+ # Numbers the elements in the order elements(root) lists them.
82
+ def assign_keys(root, elements = elements(root))
42
83
  root[KEY] = "0"
43
- root.css("*").each_with_index { |node, index| node[KEY] = (index + 1).to_s }
84
+ elements.each_with_index { |node, index| node[KEY] = (index + 1).to_s }
44
85
  end
45
86
 
46
87
  def key(node)
47
88
  node[KEY]
48
89
  end
49
90
 
91
+ # The elements under root in document order, as css("*") lists them.
92
+ # Lexbor's selector engine takes several times longer, and a walk from
93
+ # Ruby twice as long. The axis is spelled out: ".//*" is evaluated as a
94
+ # stream that stops 10,000 levels down.
95
+ def elements(root)
96
+ root.xpath(ELEMENTS_XPATH).to_a
97
+ end
98
+
99
+ # A node's children, text included, as an Array. Nokolexbor builds a
100
+ # NodeSet and wraps every node again when it is read by index;
101
+ # following the sibling pointers reads each node once.
102
+ def children(node)
103
+ found = []
104
+ child = node.child
105
+ while child
106
+ found << child
107
+ child = child.next_sibling
108
+ end
109
+ found
110
+ end
111
+
112
+ # A node's element children as an Array, read through the element
113
+ # pointers like children above.
114
+ def element_children(node)
115
+ found = []
116
+ child = node.first_element_child
117
+ while child
118
+ found << child
119
+ child = child.next_element
120
+ end
121
+ found
122
+ end
123
+
124
+ # Root and the elements under it, children before their parent, in the
125
+ # order Node#traverse yields them. Walking the element pointers skips
126
+ # the text nodes and the NodeSet traverse builds for every element.
127
+ def elements_bottom_up(root)
128
+ found = []
129
+ stack = [[root, root.first_element_child]]
130
+ until stack.empty?
131
+ entry = stack.last
132
+ child = entry[1]
133
+ if child
134
+ entry[1] = child.next_element
135
+ stack << [child, child.first_element_child]
136
+ else
137
+ stack.pop
138
+ found << entry[0]
139
+ end
140
+ end
141
+ found
142
+ end
143
+
50
144
  def mark_as_thread(node)
51
145
  node[THREAD] = "1"
52
- node.css("*").each { |descendant| descendant[THREAD] = "1" }
146
+ elements(node).each { |descendant| descendant[THREAD] = "1" }
53
147
  end
54
148
 
55
149
  def thread?(node)
@@ -57,28 +151,68 @@ module Nokodown
57
151
  end
58
152
 
59
153
  def thread_post?(node)
60
- thread?(node) && signature(node).match?(Patterns::SECONDARY)
154
+ thread?(node) && secondary?(node)
61
155
  end
62
156
 
63
157
  # Keys of the <p>s and of the divs Readability would rewrite into <p>
64
- # (no block-level descendants), found in one bottom-up pass.
158
+ # (no block-level descendants). Breakers are rare, so marking their
159
+ # ancestors, up to one already marked, is much faster than visiting every
160
+ # node. But Lexbor copies a formatting element that a block cuts
161
+ # (<a><div>…</a>) into elements sharing one attribute list, and so one
162
+ # key, and then which copy holds the block decides. A root with such
163
+ # copies keeps the bottom-up pass, which content selection and cleaning
164
+ # were tuned with: there the copy visited last decides. The lists are
165
+ # found with CSS rather than a faster XPath union: a CSS selector list
166
+ # numbers the document's nodes to sort its results, copies inherit those
167
+ # numbers, and later selector lists on a copy of the article return their
168
+ # results in the order those numbers give.
65
169
  def paragraph_keys(root)
170
+ return paragraph_keys_bottom_up(root) if shared_keys?(root)
171
+
172
+ broken = Set.new
173
+ root.css(PARAGRAPH_BREAKER_SELECTOR).to_a.each do |breaker|
174
+ ancestor = breaker.parent
175
+ ancestor = ancestor.parent while ancestor&.element? && broken.add?(key(ancestor))
176
+ end
177
+
178
+ candidates = root.css("p, div").to_a
179
+ candidates << root if root.name == "p" || root.name == "div"
180
+ candidates.each_with_object(Set.new) do |node, keys|
181
+ key = key(node)
182
+ keys << key if node.name == "p" || !broken.include?(key)
183
+ end
184
+ end
185
+
186
+ def paragraph_keys_bottom_up(root)
66
187
  keys = Set.new
67
188
  breaks = {}
68
- root.traverse do |node|
69
- next unless node.element?
70
-
189
+ elements_bottom_up(root).each do |node|
71
190
  key = key(node)
72
- breaks[key] = node.element_children.any? { |child| PARAGRAPH_BREAKERS.include?(child.name) || breaks[key(child)] }
191
+ breaks[key] = element_children(node).any? { |child| PARAGRAPH_BREAKERS.include?(child.name) || breaks[key(child)] }
73
192
  keys << key if node.name == "p" || (node.name == "div" && !breaks[key])
74
193
  end
75
194
  keys
76
195
  end
77
196
 
197
+ # XPath, because Lexbor's CSS engine takes several times longer to
198
+ # match a list of tag names.
199
+ def shared_keys?(root)
200
+ keys = root.xpath(FORMATTING_XPATH).to_a.map { |node| key(node) }
201
+ keys << key(root) if FORMATTING.include?(root.name)
202
+ keys.uniq.size != keys.size
203
+ end
204
+
78
205
  # Nokolexbor answers ancestors(selector) by running CSS matching per
79
- # ancestor, which dominated extraction time; compare tag names instead.
206
+ # ancestor, which dominated extraction time, and builds a NodeSet of
207
+ # every ancestor even without one; walk up and compare tag names instead.
80
208
  def ancestors_named(node, *names)
81
- node.ancestors.select { |ancestor| ancestor.element? && names.include?(ancestor.name) }
209
+ found = []
210
+ ancestor = node.parent
211
+ while ancestor
212
+ found << ancestor if ancestor.element? && names.include?(ancestor.name)
213
+ ancestor = ancestor.parent
214
+ end
215
+ found
82
216
  end
83
217
 
84
218
  # Syntax highlighters wrap tokens in spans whose class ("token comment",
@@ -103,23 +237,115 @@ module Nokodown
103
237
  squish(node.content)
104
238
  end
105
239
 
240
+ # Whether squish(string) is surely longer than limit. Squishing keeps
241
+ # every character other than a blank, so a start of the string with
242
+ # more than limit of those is enough. Reading no further than
243
+ # SAMPLE_LIMITS times the limit bounds what the check costs on long text
244
+ # that is mostly blanks, which then has to be squished anyway. In other
245
+ # UTF-8 a character counts as a blank when its first byte can start one,
246
+ # which overcounts blanks but counts bytes, not characters. Text squish
247
+ # would raise on is left to it.
248
+ def squishes_longer?(string, limit)
249
+ return false if string.bytesize <= limit
250
+
251
+ if string.ascii_only?
252
+ head = string.byteslice(0, SAMPLE_LIMITS * limit)
253
+ head.bytesize - head.count(ASCII_BLANKS) > limit
254
+ elsif string.encoding == Encoding::UTF_8 && string.valid_encoding?
255
+ head = string[0, SAMPLE_LIMITS * limit]
256
+ bytes = head.b
257
+ head.length - BLANK_BYTES.sum { |byte| bytes.count(byte) } > limit
258
+ else
259
+ false
260
+ end
261
+ end
262
+
263
+ # Most texts an extraction reads are a few words with single spaces
264
+ # between them, which squishing gives back unchanged; one search finds
265
+ # those. Past SHORT_TEXT bytes the search takes longer than squishing.
106
266
  def squish(string)
107
- string.tr(UNICODE_SPACES, " ").squeeze(" ").strip
267
+ return string if string.bytesize <= SHORT_TEXT && string.ascii_only? && !string.frozen? && !string.match?(UNSQUISHED)
268
+
269
+ spaces_to_blanks(string).squeeze(" ").strip
108
270
  end
109
271
 
272
+ # Most text is ASCII, where a shorter tr table is twice as fast. Other
273
+ # UTF-8 is changed in its bytes, which takes a third of the time tr
274
+ # takes to read it as characters. No byte of these sequences, nor an
275
+ # ASCII space, occurs inside another character's encoding. The search
276
+ # stops at every byte that starts one, so text full of those bytes
277
+ # (Japanese, or a space in every other word) goes through tr. Counting
278
+ # them costs more than it saves only in the shortest text.
279
+ def spaces_to_blanks(string)
280
+ return string.tr(ASCII_SPACES, " ") if string.ascii_only?
281
+ return string.tr(UNICODE_SPACES, " ") unless string.encoding == Encoding::UTF_8 && string.valid_encoding?
282
+
283
+ bytes = string.b
284
+ return string.tr(UNICODE_SPACES, " ") if bytes.bytesize > DENSE_MIN && SPACE_LEADS.sum { |lead| bytes.count(lead) } * DENSE_LEADS > bytes.bytesize
285
+
286
+ bytes.gsub!(NON_ASCII_SPACE_BYTES, " ")
287
+ bytes.tr!(ASCII_SPACES, " ")
288
+ bytes.force_encoding(Encoding::UTF_8)
289
+ end
290
+
291
+ # The cache is kept by class list, then by id, so a repeated element
292
+ # finds its signature without building the string it is made from. No
293
+ # rewrite of signature_of reaches across a space, so the class list is
294
+ # read once, and an id (most are unique) on its own.
110
295
  def signature(node)
111
296
  classes = node["class"]
112
- id = node["id"]
297
+ id = name_id(node)
113
298
  return "" if classes.nil? && id.nil?
114
299
 
115
- signature_of("#{classes} #{id}")
300
+ signatures = Thread.current[SIGNATURES]
301
+ return signature_of("#{classes} #{id}") unless signatures
302
+
303
+ by_id = signatures[classes] ||= {}
304
+ by_id.fetch(id) do
305
+ classes_signature = by_id.fetch(:classes) { by_id[:classes] = signature_of(classes.to_s) }
306
+ by_id[id] = "#{classes_signature} #{id && signature_of(id)}".freeze
307
+ end
308
+ end
309
+
310
+ # Every stage reads the signatures of the same elements again, and a
311
+ # page repeats its class lists, so an extraction computes each one once.
312
+ # The cache lives only as long as the block, so pages share nothing.
313
+ def caching_signatures
314
+ outer = Thread.current[SIGNATURES]
315
+ outer_secondary = Thread.current[SECONDARY]
316
+ outer_weights = Thread.current[WEIGHTS]
317
+ Thread.current[SIGNATURES] = outer || {}
318
+ Thread.current[SECONDARY] = outer_secondary || {}
319
+ Thread.current[WEIGHTS] = outer_weights || {}
320
+ yield
321
+ ensure
322
+ Thread.current[SIGNATURES] = outer
323
+ Thread.current[SECONDARY] = outer_secondary
324
+ Thread.current[WEIGHTS] = outer_weights
325
+ end
326
+
327
+ # Whether the element is named like a secondary region. The stages ask
328
+ # it of the same names again, so the answer is kept with the signatures.
329
+ def secondary?(node)
330
+ signature = signature(node)
331
+ answers = Thread.current[SECONDARY]
332
+ return Patterns.secondary?(signature) unless answers
333
+
334
+ answers.fetch(signature) { answers[signature] = Patterns.secondary?(signature) }
335
+ end
336
+
337
+ # The id as a name for the element; a heading anchor only repeats the heading.
338
+ def name_id(node)
339
+ node.key?(ANCHOR) ? nil : node["id"]
116
340
  end
117
341
 
118
342
  def signature_of(value)
343
+ # A Tailwind arbitrary value ("lg:h-[calc(100vh-var(--nav-height))]") is CSS, not a name.
344
+ value = value.gsub(ARBITRARY_VALUE, "") if value.include?("[")
119
345
  # Generated ids (Webflow "w-node-<uuid>") would otherwise read as words.
120
- value = value.gsub(UUID, " ") if value.match?(UUID)
346
+ value = value.gsub(UUID, " ") if value.length >= UUID_LENGTH && value.match?(UUID)
121
347
  value = value.gsub(CSS_MODULE_HASH, "") if value.include?("__")
122
- value = value.gsub(/([a-z\d])([A-Z])/, '\1-\2') if value.match?(/[a-z\d][A-Z]/)
348
+ value = value.gsub(CAMEL_CASE, "-") if value.match?(CAMEL_CASE)
123
349
  value.downcase
124
350
  end
125
351
 
@@ -3,20 +3,34 @@
3
3
  module Nokodown
4
4
  class Extractor
5
5
  TITLE_SIMILARITY = 0.75
6
+ OPENING_PROSE = 150
6
7
  MIN_ARTICLE_LENGTH = 500
7
8
  CONDITIONAL_SHARE = 0.5
8
9
  REMOVED_LINK_SHARE = 0.5
10
+ MIN_BUDGET = 1000
11
+ # A paragraph that long makes the excerpt when the page gives none.
12
+ EXCERPT_MIN = 80
9
13
 
10
- def initialize(html, url: nil, main_content: true, title: true, images: true, links: true)
14
+ def initialize(html, url: nil, main_content: true, title: true, images: true, links: true, max_length: nil)
11
15
  @html = html
12
16
  @url = url
13
17
  @main_content = main_content
14
18
  @title = title
15
19
  @images = images
16
20
  @links = links
21
+ @max_length = max_length
22
+ return if max_length.nil? || (max_length.is_a?(Integer) && !max_length.negative?)
23
+
24
+ raise ArgumentError, "max_length must be nil or a non-negative Integer, not #{max_length.inspect}"
17
25
  end
18
26
 
19
27
  def call
28
+ Dom.caching_signatures { extract }
29
+ end
30
+
31
+ private
32
+
33
+ def extract
20
34
  doc = Nokolexbor::HTML(Charset.utf8(@html.to_s))
21
35
  metadata = Metadata.new(doc).to_h
22
36
  urls = UrlResolver.new(@url, doc.at_css("base[href]")&.[]("href"))
@@ -24,19 +38,50 @@ module Nokodown
24
38
  return result([], metadata, :none) if body.nil?
25
39
 
26
40
  product_page = @main_content && ProductReviews.product_page?(doc, metadata[:page_type])
27
- Preprocessor.new(body).call
41
+ Preprocessor.new(body, full: !@main_content).call
28
42
  nodes, mode = select_content(body, metadata[:page_type], product_page)
29
- blocks = render(nodes, mode, urls)
30
- blocks = with_title(blocks, metadata[:title]) if @title
43
+ blocks = content(nodes, mode, urls, metadata)
31
44
  result(blocks, metadata, mode)
32
45
  end
33
46
 
34
- private
35
-
36
- def render(nodes, mode, urls)
47
+ # With max_length, rendering stops after about twice that much. When that
48
+ # settles the result it is kept; otherwise the whole content is rendered,
49
+ # so a page costs at most one short render and a whole one.
50
+ def content(nodes, mode, urls, metadata)
37
51
  redundant = redundant_images(nodes, mode, urls)
38
- renderer = Markdown::Renderer.new(urls, images: @images, links: @links, redundant_images: redundant)
39
- Markdown::Cleanup.call(renderer.render(nodes), renderer.rendered_images)
52
+ budget = @max_length && [@max_length * 2, MIN_BUDGET].max
53
+ blocks, settled = render(nodes, mode, urls, redundant, metadata, budget)
54
+ settled ? blocks : render(nodes, mode, urls, redundant, metadata, nil).first
55
+ end
56
+
57
+ # The blocks, and whether they settle the result: either all of the
58
+ # content was rendered, or the whole content gives the same first
59
+ # max_length characters, title and excerpt. Cleanup keeps only blocks
60
+ # that start the whole content's when content was left out.
61
+ def render(nodes, mode, urls, redundant, metadata, budget)
62
+ renderer = Markdown::Renderer.new(urls, images: @images, links: @links, redundant_images: redundant, budget: budget)
63
+ rendered = renderer.render(nodes)
64
+ more = renderer.cut?
65
+ blocks = Markdown::Cleanup.call(rendered, renderer.rendered_images, full: mode == :full, more: more)
66
+ h1 = blocks.any? { |block| block.kind == :heading && block.level == 1 }
67
+ blocks = with_title(blocks, metadata[:title]) if @title
68
+ [blocks, !more || settled?(blocks, h1, renderer.rendered_images, nodes, metadata)]
69
+ end
70
+
71
+ # An image whose copies so far are all redundant can still have one that
72
+ # is not; a page title depends on the first H1, which must be among the
73
+ # blocks or nowhere; the excerpt, when the page gives none, on the first
74
+ # long paragraph.
75
+ def settled?(blocks, h1, images, nodes, metadata)
76
+ return false if images.each_value.any?(&:redundant)
77
+ return false if @title && !h1 && metadata[:title] && nodes.any? { |node| node.name == "h1" || node.at_css("h1") }
78
+ return false if metadata[:excerpt].nil? && blocks.none? { |block| long_paragraph?(block) }
79
+
80
+ blocks.sum { |block| block.text.length + 2 } - 2 >= @max_length
81
+ end
82
+
83
+ def long_paragraph?(block)
84
+ block.kind == :paragraph && Markdown::Text.plain(block.text).length >= EXCERPT_MIN
40
85
  end
41
86
 
42
87
  # Converting the whole page keeps every visible image.
@@ -49,15 +94,54 @@ module Nokodown
49
94
  def select_content(body, page_type, product_page)
50
95
  return [[body], :full] unless @main_content
51
96
 
52
- Boilerplate.new(body).call
53
- ProductReviews.new(body).call if product_page
54
- selection = ContentLocator.new(body, page_type: page_type).call
55
- return [cleaned_article(selection.nodes, page_type), :article] if selection.mode == :article
97
+ attribution = PostAttribution.new(body).call if ContentLocator::DISCUSSIONS.include?(page_type)
98
+ # ContentLocator reuses the counts Boilerplate kept, unless the page
99
+ # changed after it.
100
+ stats = Boilerplate.new(body).call.stats
101
+ if product_page
102
+ ProductReviews.new(body).call
103
+ stats = nil
104
+ end
105
+ selection = ContentLocator.new(body, page_type: page_type, stats: stats).call
106
+ attribution&.write(selection.nodes)
107
+ if selection.mode == :article
108
+ lead = @title ? title_lead(selection.nodes) : []
109
+ return [lead + cleaned_article(selection.nodes, page_type), :article]
110
+ end
56
111
 
57
112
  Pruner.new(selection.nodes, :page).call
58
113
  [selection.nodes, :page]
59
114
  end
60
115
 
116
+ # An article body chosen inside <main> can leave out the headline above
117
+ # it; the page's H1, when it comes before the body there, opens the
118
+ # content again, as the title would. A deck or subtitle below it stays
119
+ # out: the article references of the benchmarks leave it out too.
120
+ def title_lead(nodes)
121
+ first = nodes.first
122
+ return [] if first.nil? || nodes.any? { |node| node.name == "h1" || node.at_css("h1") }
123
+
124
+ path = [first, *first.ancestors.select(&:element?)]
125
+ main = path.drop(1).find { |node| node.name == "main" || node["role"] == "main" }
126
+ h1 = main&.at_css("h1")
127
+ return [] if h1.nil? || Dom.text(h1).empty?
128
+
129
+ before?(h1, main, path.map { |node| Dom.key(node) }.to_set) ? [h1] : []
130
+ end
131
+
132
+ # Whether the body follows the headline inside <main>.
133
+ def before?(h1, main, path_keys)
134
+ current = h1
135
+ until current == main
136
+ sibling = current
137
+ while (sibling = sibling.next_element)
138
+ return true if path_keys.include?(Dom.key(sibling))
139
+ end
140
+ current = current.parent
141
+ end
142
+ false
143
+ end
144
+
61
145
  # Like Readability, fall back to lighter cleaning when conditional cleaning
62
146
  # throws away most of what it sees; markup made of many small linky blocks
63
147
  # (React apps, card grids) trips it, and a short intro would otherwise pass
@@ -90,21 +174,33 @@ module Nokodown
90
174
  kept < MIN_ARTICLE_LENGTH && kept < nodes.sum { |node| Dom.text(node).length } * 0.25
91
175
  end
92
176
 
93
- # One H1 at the top: the page's own if the content has one, otherwise the
94
- # metadata title, replacing a near-duplicate heading right below it.
177
+ # One H1 at the top: the page's own if the content opens with one,
178
+ # otherwise the metadata title, replacing a near-duplicate heading right
179
+ # below it.
95
180
  # Nothing found stays empty, so a script-rendered shell or a bot wall does
96
181
  # not pass for a page; Result#title still has the title.
97
182
  def with_title(blocks, title)
98
183
  return blocks if blocks.empty?
99
184
 
100
185
  first_h1 = blocks.find { |block| block.kind == :heading && block.level == 1 }
101
- return demote_h1s(blocks, first_h1) if first_h1
186
+ return demote_h1s(blocks, first_h1) if first_h1 && (title.nil? || page_heading?(blocks, first_h1, title))
102
187
  return blocks if title.nil?
103
188
 
104
189
  duplicate = blocks.first(3).find do |block|
105
190
  block.kind == :heading && Dom.similarity(title, Markdown::Cleanup.heading_text(block)) > TITLE_SIMILARITY
106
191
  end
107
- [Markdown::Block.new(:heading, "# #{Markdown::Text.escape(title)}", 1)] + blocks.reject { |block| block.equal?(duplicate) }
192
+ rest = demote_h1s(blocks.reject { |block| block.equal?(duplicate) }, nil)
193
+ [Markdown::Block.new(:heading, "# #{Markdown::Text.escape(title)}", 1)] + rest
194
+ end
195
+
196
+ # When the page's title block is left out of the content, the first H1
197
+ # left can be a section heading below the body's opening paragraphs. A
198
+ # headline may follow a caption or a promo line, but not the body.
199
+ def page_heading?(blocks, h1, title)
200
+ return true if Dom.similarity(title, Markdown::Cleanup.heading_text(h1)) > TITLE_SIMILARITY
201
+
202
+ opening = blocks.take_while { |block| !block.equal?(h1) }.select { |block| block.kind == :paragraph }
203
+ opening.sum { |block| Markdown::Text.plain(block.text).length } < OPENING_PROSE
108
204
  end
109
205
 
110
206
  def demote_h1s(blocks, keep)
@@ -117,8 +213,9 @@ module Nokodown
117
213
  end
118
214
 
119
215
  def result(blocks, metadata, mode)
216
+ markdown = blocks.map(&:text).join("\n\n")
120
217
  Result.new(
121
- markdown: blocks.map(&:text).join("\n\n"),
218
+ markdown: @max_length ? markdown[0, @max_length] : markdown,
122
219
  title: metadata[:title],
123
220
  byline: metadata[:byline],
124
221
  excerpt: metadata[:excerpt] || first_paragraph(blocks),
@@ -131,7 +228,7 @@ module Nokodown
131
228
 
132
229
  def first_paragraph(blocks)
133
230
  paragraphs = blocks.select { |block| block.kind == :paragraph }.map { |block| Markdown::Text.plain(block.text) }
134
- paragraphs.find { |text| text.length >= 80 } || paragraphs.find { |text| !text.empty? }
231
+ paragraphs.find { |text| text.length >= EXCERPT_MIN } || paragraphs.find { |text| !text.empty? }
135
232
  end
136
233
  end
137
234
  end