lib/phlex/sgml.rb

Lines

94%

235 of 250 covered

Branches

85%

92 of 107 covered

Methods

94%

47 of 50 covered

Not run
229234237241324-325332-334414418-419421451-452
Never called
1# frozen_string_literal: true
2
3# **Standard Generalized Markup Language** for behaviour common to {HTML} and {SVG}.
41class Phlex::SGML
51 include Phlex::Helpers
6
71 class << self
8 # Render the view to a String. Arguments are delegated to {.new}.
91 def call(...)
101338 new(...).call
11 end
12
13 # Create a new instance of the component.
14 # @note The block will not be delegated to {#initialize}. Instead, it will be sent to {#view_template} when rendering.
151 def new(*, **, &block)
162553 object = allocate
172553 object.__send__(:initialize, *, **)
182541 object.instance_variable_set(:@_content_block, block) if block
192540 object
20 end
21 end
22
231 def view_template
24403 if block_given?
25393 yield
26 else
2710 plain "Phlex Warning: Your `#{self.class.name}` class doesn't define a `view_template` method. If you are upgrading to Phlex 2.x make sure to rename your `template` method to `view_template`. See: https://beta.phlex.fun/guides/v2-upgrade.html"
28 end
29 end
30
311 def to_proc
322 proc { |c| c.render(self) }
33 end
34
35 # Components can only be rendered once, because Phlex can't reset their instance variables. Pass `rerenderable: true` to allow the component to be rendered again.
361 def call(buffer = +"", context: {}, fragments: nil, rerenderable: false, &)
372443 state = Phlex::SGML::State.new(
38 user_context: context,
39 output_buffer: buffer,
40 fragments: fragments&.to_set(&:to_s),
41 )
42
432443 internal_call(parent: nil, state:, &)
44
452293 state.output_buffer << state.buffer
46 ensure
472443 @_state = nil if rerenderable && @_state.equal?(state)
48 end
49
501 def internal_call(parent: nil, state: nil, &block)
512538 if @_state
525 raise Phlex::DoubleRenderError.new(
53 "You can't render a #{self.class.name} more than once. To render a component more than once, pass `rerenderable: true` to `call` each time you render it."
54 )
55 end
56
572533 @_state = state
58
592533 return "" unless render?
60
612530 block ||= @_content_block
62
63 begin
642530 previous_phlex_component = Thread.current[:__phlex_component__]
652530 Thread.current[:__phlex_component__] = self
66
672530 state.around_render(self) do
682530 before_template(&block)
69
702530 around_template do
712530 if block
72889 view_template do |*args|
73800 if args.length > 0
74385 __yield_content_with_args__(*args, &block)
75 else
76415 __yield_content__(&block)
77 end
78 end
79 else
801641 view_template
81 end
82 end
83
842339 after_template(&block)
85 end
86 ensure
872530 Thread.current[:__phlex_component__] = previous_phlex_component
88 end
89 end
90
911 def context
926 if rendering?
935 @_state.user_context
94 else
951 raise Phlex::ArgumentError.new(<<~MESSAGE)
96 You can’t access the context before the component has started rendering.
97 MESSAGE
98 end
99 end
100
101 # Returns `false` before rendering and `true` once the component has started rendering.
102 # It will not reset back to false after rendering, unless the component was rendered with `rerenderable: true`.
1031 def rendering?
1047 !!@_state
105 end
106
107 # Output plain text.
1081 def plain(content)
109275 raise Phlex::ArgumentError.new("plain does not accept a block.") if block_given?
110
111273 unless __text__(content)
1121 raise Phlex::ArgumentError.new("You've passed an object to plain that is not handled by format_object. See https://rubydoc.info/gems/phlex/Phlex/SGML#format_object-instance_method for more information")
113 end
114
115272 nil
116 end
117
118 # Output a single space character. If a block is given, a space will be output before and after the block.
1191 def whitespace(&)
12026 state = @_state
121
12226 unless state.should_render?
1239 yield(self) if block_given?
1248 return nil
125 end
126
12717 buffer = state.buffer
128
12917 buffer << " "
130
13117 if block_given?
13216 __yield_content__(&)
13316 buffer << " "
134 end
135
13617 nil
137 end
138
139 # Wrap the output in an HTML comment.
140 #
141 # [MDN Docs](https://developer.mozilla.org/en-US/docs/Web/HTML/Comments)
1421 def comment(&)
14341 state = @_state
144
14541 unless state.should_render?
14615 yield(self) if block_given?
14714 return nil
148 end
149
15026 buffer = state.buffer
151
15226 buffer << "<!-- "
15326 __yield_content__(&)
15426 buffer << " -->"
155
15626 nil
157 end
158
159 # Output the given safe object as-is. You may need to use `safe` to mark a string as a safe object.
1601 def raw(content)
1611069 case content
162 when Phlex::SGML::SafeObject
1631066 state = @_state
1641066 return unless state.should_render?then never taken
165
1661066 state.append(content.to_s)
167 when nil, "" # do nothing
168 else
1691 raise Phlex::ArgumentError.new("You passed an unsafe object to `raw`.")
170 end
171
1721068 nil
173 end
174
175 # Capture the output of the block and returns it as a string.
1761 def capture(*args, &block)
1771141 return "" unless blockthen never taken
178
1791141 if args.length > 0
1802 @_state.capture { __yield_content_with_args__(*args, &block) }
181 else
1822280 @_state.capture { __yield_content__(&block) }
183 end
184 end
185
186 # Define a named fragment that can be selectively rendered.
1871 def fragment(name)
1881301 name = name.to_s
1891301 state = @_state
1901301 state.begin_fragment(name)
1911301 completed = false
192 begin
1931301 yield
1941295 completed = true
195 ensure
1961301 state.end_fragment(name, halt: completed)
197 end
1981263 nil
199 end
200
201 # Mark the given string as safe for HTML output.
2021 def safe(value)
2031126 case value
204 when String
2051125 Phlex::SGML::SafeValue.new(value)
206 else
2071 raise Phlex::ArgumentError.new("Expected a String.")
208 end
209 end
210
2111 alias_method :🦺, :safe
212
213 # Flush the current state to the output buffer.
2141 def flush
21540 @_state.flush
216 end
217
2181 def render(renderable = nil, &)
219100 case renderable
220 when Phlex::SGML
22195 renderable.internal_call(state: @_state, parent: self, &)
222 when Class
2232 if renderable < Phlex::SGML
2241 render(renderable.new, &)
225 else
2261 raise Phlex::ArgumentError.new("You can't render a #{renderable.inspect}.")
227 end
228 when Enumerable
2290 renderable.each { |r| render(r, &) }when never taken
230 when Proc, Method
2312 if renderable.arity == 0
2322 __yield_content_with_no_yield_args__(&renderable)
233 else
2340 __yield_content__(&renderable)else never taken
235 end
236 when String
2370 plain(renderable)when never taken
238 when nil
2391 __yield_content__(&) if block_given?else never taken
240 else
2410 raise Phlex::ArgumentError.new("You can't render a #{renderable.inspect}.")else never taken
242 end
243
24484 nil
245 end
246
247 # Cache a block of content.
248 #
249 # ```ruby
250 # @products.each do |product|
251 # cache product do
252 # h1 { product.name }
253 # end
254 # end
255 # ```
2561 def cache(*cache_key, **, &content)
25739 location = caller_locations(1, 1)[0]
258
259 full_key = [
26039 app_version_key, # invalidates the key when deploying new code in case of changes
261 self.class.name, # prevents collisions between classes
26239 (self.class.object_id if enable_cache_reloading?), # enables reloadingthen never taken
263 location.base_label, # prevents collisions between different methods
264 Phlex.__source_line__(location), # prevents collisions between different lines, compiled or not
265 cache_key, # allows for custom cache keys
266 ].freeze
267
26839 low_level_cache(full_key, **, &content)
269
27039 nil
271 end
272
273 # Cache a block of content where you control the entire cache key.
274 # If you really know what you’re doing and want to take full control
275 # and responsibility for the cache key, use this method.
276 #
277 # ```ruby
278 # low_level_cache([Commonmarker::VERSION, Digest::MD5.hexdigest(@content)]) do
279 # markdown(@content)
280 # end
281 # ```
282 #
283 # Note: To allow you more control, this method does not take a splat of cache keys.
284 # If you need to pass multiple cache keys, you should pass an array.
2851 def low_level_cache(cache_key, **options, &content)
286223 state = @_state
287
288333 cached_buffer, fragment_map = cache_store.fetch(cache_key, **options) { state.caching(&content) }
289
290221 if state.should_render?
291103 fragment_map.each do |fragment_name, (offset, length, nested_fragments)|
2921170 state.record_fragment(fragment_name, offset, length, nested_fragments)
293 end
294103 state.buffer << cached_buffer
295 else
296118 fragment_map.each do |fragment_name, (offset, length, nested_fragments)|
2972263 if state.fragments.include?(fragment_name)
298110 state.fragments.delete(fragment_name)
299110 state.fragments.subtract(nested_fragments)
300110 state.buffer << cached_buffer.byteslice(offset, length)
301 end
302 end
303 end
304
305221 nil
306 end
307
3081 def json_escape(string)
3092 string.gsub(/[&<>\u2028\u2029]/, {
310 "&" => '\u0026',
311 "<" => '\u003c',
312 ">" => '\u003e',
313 "\u2028" => '\u2028',
314 "\u2029" => '\u2029',
315 })
316 end
317
318 # Override this method to use a different deployment key.
3191 private def app_version_key
32039 Phlex::DEPLOYED_AT
321 end
322
323 # Override this method to use a different cache store.
3240 private def cache_store
3250 raise "Cache store not implemented."
326 end
327
3281 private def enable_cache_reloading?
32939 false
330 end
331
3320 private def vanish(...)
3330 capture(...)
3340 nil
335 end
336
3371 private def render?
3382528 true
339 end
340
3411 private def format_object(object)
3421093 case object
343 when Float, Integer
3441058 object.to_s
345 end
346 end
347
3481 private def around_template
3492530 yield
3502339 nil
351 end
352
3531 private def before_template(&)
3542529 nil
355 end
356
3571 private def after_template(&)
3582338 nil
359 end
360
361 # The class or module that registered the element `tag` renders for `name`.
3621 private def __element_registrar__(name)
363128 return unless Phlex::SGML::Elements.registered_name?(name)
364
365206 self.class.ancestors.find { |ancestor| Phlex::SGML::Elements === ancestor && ancestor.__element_registered__?(name) }
366 end
367
3681 private def __yield_content__
3691999 return unless block_given?then never taken
370
3711999 state = @_state
372
3731999 original_length = state.output_bytesize
3741999 content = yield(self)
3751846 __implicit_output__(content) if original_length == state.output_bytesize
376
3771846 nil
378 end
379
3801 private def __yield_content_with_no_yield_args__
3812 return unless block_given?then never taken
382
3832 state = @_state
384
3852 original_length = state.output_bytesize
3862 content = yield # <-- doesn’t yield self 😉
3872 __implicit_output__(content) if original_length == state.output_bytesize
388
3892 nil
390 end
391
3921 private def __yield_content_with_args__(*a)
393386 return unless block_given?then never taken
394
395386 state = @_state
396
397386 original_length = state.output_bytesize
398386 content = yield(*a)
399386 __implicit_output__(content) if original_length == state.output_bytesize
400
401386 nil
402 end
403
4041 private def __implicit_output__(content)
405425 state = @_state
406425 return true unless state.should_render?
407
408411 case content
409 when Phlex::SGML::SafeObject
41016 state.append(content.to_s)
411 when String
412391 state.buffer << Phlex::Escape.html_escape(content)
413 when Symbol
4140 state.buffer << Phlex::Escape.html_escape(content.name)when never taken
415 when nil
416 nil
417 else
4180 if (formatted_object = format_object(content))else never taken
4190 state.buffer << Phlex::Escape.html_escape(formatted_object)
420 else
4210 return false
422 end
423 end
424
425411 true
426 end
427
428 # same as __implicit_output__ but escapes even `safe` objects
4291 private def __text__(content)
430273 state = @_state
431273 return true unless state.should_render?
432
433270 case content
434 when String
435265 state.buffer << Phlex::Escape.html_escape(content)
436 when Symbol
4371 state.buffer << Phlex::Escape.html_escape(content.name)
438 when nil
439 nil
440 else
4413 if (formatted_object = format_object(content))
4422 state.buffer << Phlex::Escape.html_escape(formatted_object)
443 else
4441 return false
445 end
446 end
447
448269 true
449 end
450
4510 private def __attributes__(attributes)
4520 @_state.attribute_cache.fetch(attributes) { Phlex::SGML::Attributes.generate_attributes(attributes) }
453 end
454
4551 private_class_method def self.method_added(method_name)
456978 if method_name == :view_template
457813 location = instance_method(method_name).source_location[0]
458
459813 if location[0] in "/" | "."
460731 Phlex.__expand_attribute_cache__(location)
461 end
462 end
463
464978 __inlining_changed__(self, [method_name])
465976 super
466 end
467
4681 private_class_method def self.method_removed(method_name)
4693 __inlining_changed__(self, [method_name])
4703 super
471 end
472
4731 private_class_method def self.method_undefined(method_name)
4741 __inlining_changed__(self, [method_name])
4751 super
476 end
477
4781 def self.include(*modules)
47929 super
48059 __inlining_changed__(self, modules.flat_map { |mod| mod.instance_methods + mod.private_instance_methods })
48128 self
482 end
483
4841 def self.prepend(*modules)
4853 super
4866 __inlining_changed__(self, modules.flat_map { |mod| mod.instance_methods + mod.private_instance_methods })
4872 self
488 end
489
490 # A frozen class can't be recompiled when an element or helper it inlined
491 # changes, so its original definitions are put back first.
4921 def self.freeze
4933 Phlex::Compiler.decompile(self) if !Phlex.__compiled_source_maps__.empty? && Phlex::Compiler.compiled?(self) && !frozen?
494
4953 super
496 end
497
498 # Compiled methods inline elements and helpers as they were at compile
499 # time, so a change to one has to be seen. Nothing to do until something
500 # has been compiled.
5011 private_class_method def self.__inlining_changed__(target, names)
5021033 if names.include?(:__phlex_equal__?) && !Phlex::SGML.equal?(target)
5036 raise Phlex::NameError, "__phlex_equal__? is reserved for compiled blocks, so it can't be defined on #{target.inspect}."
504 end
505
5061027 Phlex::Compiler.inlining_changed(target, names) unless Phlex.__compiled_source_maps__.empty?
507 end
508
509 # Inlined svg blocks rely on the class methods that build a Phlex::SVG.
510 # Defined before the hooks below, which call it when it's defined.
5111 private_class_method def self.__svg_class_changed__(method_name)
51233 __inlining_changed__(self, [method_name]) if (method_name in :new | :allocate | :===) && Phlex::SVG <= self
513 end
514
5151 private_class_method def self.singleton_method_added(method_name)
51625 __svg_class_changed__(method_name)
51725 super
518 end
519
5201 private_class_method def self.singleton_method_removed(method_name)
5217 __svg_class_changed__(method_name)
5227 super
523 end
524
5251 private_class_method def self.singleton_method_undefined(method_name)
5261 __svg_class_changed__(method_name)
5271 super
528 end
529
5301 private def singleton_method_added(method_name)
5318 self.class.__send__(:__inlining_changed__, singleton_class, [method_name])
5325 super
533 end
534
5351 def extend(*modules)
5363 super
5376 self.class.__send__(:__inlining_changed__, singleton_class, modules.flat_map { |mod| mod.instance_methods + mod.private_instance_methods })
5381 self
539 end
540
541 # BasicObject#equal? under a name a component can't override. A compiled
542 # block runs its compiled body only when the component says the block's
543 # receiver is itself, rather than asking the receiver, which could be
544 # anything.
5451 define_method(:__phlex_equal__?, BasicObject.instance_method(:equal?))
546end