boto-rb-web 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +21 -0
  3. data/README.md +17 -0
  4. data/assets/boto-web/boot.js +16 -0
  5. data/assets/boto-web/boto-web.css +32 -0
  6. data/assets/boto-web/dom/animate.js +49 -0
  7. data/assets/boto-web/dom/flip.js +41 -0
  8. data/assets/boto-web/dom/keyed.js +15 -0
  9. data/assets/boto-web/dom/morph.js +112 -0
  10. data/assets/boto-web/dom/navigation.js +72 -0
  11. data/assets/boto-web/dom/sync.js +42 -0
  12. data/assets/boto-web/net/base.js +5 -0
  13. data/assets/boto-web/net/protocol.js +46 -0
  14. data/assets/boto-web/net/sse.js +45 -0
  15. data/assets/boto-web/net/sse_stream.js +84 -0
  16. data/assets/boto-web/net/token.js +9 -0
  17. data/assets/boto-web/net/transport.js +99 -0
  18. data/assets/boto-web/runtime/component.js +138 -0
  19. data/assets/boto-web/runtime/events.js +54 -0
  20. data/assets/boto-web/runtime/hooks.js +82 -0
  21. data/assets/boto-web/runtime/live.js +12 -0
  22. data/assets/boto-web/runtime/on.js +36 -0
  23. data/assets/boto-web/runtime/runtime.js +100 -0
  24. data/assets/boto-web/runtime/scope.js +112 -0
  25. data/assets/boto-web/runtime/signals.js +123 -0
  26. data/assets/boto-web/template/decimal.js +93 -0
  27. data/assets/boto-web/template/helpers.js +31 -0
  28. data/assets/boto-web/template/html.js +61 -0
  29. data/assets/boto-web/template/hydrate.js +25 -0
  30. data/assets/boto-web/template/ruby/core.js +72 -0
  31. data/assets/boto-web/template/ruby/lists.js +63 -0
  32. data/assets/boto-web/template/ruby.js +5 -0
  33. data/lib/boto/component/arguments.rb +58 -0
  34. data/lib/boto/component/definition.rb +114 -0
  35. data/lib/boto/component.rb +107 -0
  36. data/lib/boto/helper.rb +14 -0
  37. data/lib/boto/view.rb +63 -0
  38. data/lib/boto/web/app_extension.rb +78 -0
  39. data/lib/boto/web/assets.rb +59 -0
  40. data/lib/boto/web/child_path.rb +38 -0
  41. data/lib/boto/web/code_class.rb +16 -0
  42. data/lib/boto/web/compiler/analysis/deps.rb +46 -0
  43. data/lib/boto/web/compiler/analysis/handlers.rb +47 -0
  44. data/lib/boto/web/compiler/analysis/walker.rb +174 -0
  45. data/lib/boto/web/compiler/analysis.rb +44 -0
  46. data/lib/boto/web/compiler/client_helper.rb +34 -0
  47. data/lib/boto/web/compiler/computed_body.rb +40 -0
  48. data/lib/boto/web/compiler/directives.rb +86 -0
  49. data/lib/boto/web/compiler/expression/calls.rb +149 -0
  50. data/lib/boto/web/compiler/expression/collections.rb +116 -0
  51. data/lib/boto/web/compiler/expression/literals.rb +75 -0
  52. data/lib/boto/web/compiler/expression/logic.rb +53 -0
  53. data/lib/boto/web/compiler/expression/operators.rb +85 -0
  54. data/lib/boto/web/compiler/expression/strings.rb +31 -0
  55. data/lib/boto/web/compiler/expression.rb +93 -0
  56. data/lib/boto/web/compiler/module_writer/handlers_js.rb +75 -0
  57. data/lib/boto/web/compiler/module_writer/js.rb +24 -0
  58. data/lib/boto/web/compiler/module_writer/tag_js.rb +132 -0
  59. data/lib/boto/web/compiler/module_writer/template_js.rb +89 -0
  60. data/lib/boto/web/compiler/module_writer/type_shape.rb +28 -0
  61. data/lib/boto/web/compiler/module_writer.rb +79 -0
  62. data/lib/boto/web/compiler/template.rb +136 -0
  63. data/lib/boto/web/compiler/type_map.rb +43 -0
  64. data/lib/boto/web/compiler/type_scope.rb +68 -0
  65. data/lib/boto/web/compiler.rb +9 -0
  66. data/lib/boto/web/dispatcher.rb +113 -0
  67. data/lib/boto/web/events_endpoint.rb +43 -0
  68. data/lib/boto/web/failure.rb +30 -0
  69. data/lib/boto/web/head.rb +24 -0
  70. data/lib/boto/web/helpers.rb +40 -0
  71. data/lib/boto/web/hooks.rb +39 -0
  72. data/lib/boto/web/html.rb +65 -0
  73. data/lib/boto/web/layouts/context.rb +22 -0
  74. data/lib/boto/web/layouts/template.rb +31 -0
  75. data/lib/boto/web/layouts.rb +69 -0
  76. data/lib/boto/web/modules.rb +37 -0
  77. data/lib/boto/web/page_endpoint.rb +65 -0
  78. data/lib/boto/web/project_helpers.rb +54 -0
  79. data/lib/boto/web/protocol.rb +85 -0
  80. data/lib/boto/web/registry.rb +86 -0
  81. data/lib/boto/web/registry_error.rb +8 -0
  82. data/lib/boto/web/renderer/erb_source.rb +199 -0
  83. data/lib/boto/web/renderer/render_context.rb +37 -0
  84. data/lib/boto/web/renderer.rb +94 -0
  85. data/lib/boto/web/runtime.rb +45 -0
  86. data/lib/boto/web/scoped_css.rb +113 -0
  87. data/lib/boto/web/secret_key.rb +8 -0
  88. data/lib/boto/web/settings.rb +27 -0
  89. data/lib/boto/web/snapshot/changes.rb +26 -0
  90. data/lib/boto/web/snapshot/inputs.rb +50 -0
  91. data/lib/boto/web/snapshot/token.rb +42 -0
  92. data/lib/boto/web/snapshot.rb +111 -0
  93. data/lib/boto/web/static_file.rb +35 -0
  94. data/lib/boto/web/stylesheet.rb +53 -0
  95. data/lib/boto/web/tailwind.rb +69 -0
  96. data/lib/boto/web/template_preview.rb +31 -0
  97. data/lib/boto/web/transports/http.rb +36 -0
  98. data/lib/boto/web/transports/sse.rb +45 -0
  99. data/lib/boto/web/transports.rb +21 -0
  100. data/lib/boto/web/version.rb +7 -0
  101. data/lib/boto/web/view_loader.rb +21 -0
  102. data/lib/boto/web.rb +17 -0
  103. metadata +172 -0
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Web
5
+ module Compiler
6
+ # What a component's template needs at render time: the tree with its tags annotated, the handlers
7
+ # (h1, h2...) and the server blocks (b1, b2...), numbered in document order.
8
+ class Analysis
9
+ # pieces: Strings (HTML) and Directives::Tag, in order.
10
+ Markup = Data.define(:pieces)
11
+ # kind is :action or :assign; locals are the block locals the handler reads; scope types them for the writer.
12
+ Handler = Data.define(:kind, :source, :locals, :scope)
13
+ # node is the If/Each node (or the array of nodes, for the root block).
14
+ Block = Data.define(:id, :deps, :node)
15
+ # A read the browser cannot run: line is in the template, source is the Ruby expression.
16
+ ServerRead = Data.define(:line, :source)
17
+ # blocks is keyed by the node's seq: 0 is the root. deps are all the states, inputs and computeds read.
18
+ # scope is the attribute every tag gets when the component has a .css (nil otherwise), given by the caller.
19
+ # server_reads are the reads outside the browser subset, in document order.
20
+ Result = Data.define(:tree, :handlers, :blocks, :deps, :scope, :server_reads)
21
+
22
+ # registry finds the child components by their selector; path is the component's template;
23
+ # helpers are the names of the project's client helpers, which an expression may call in the browser.
24
+ def initialize(component_class, registry: Registry.new, path: Template.path_for(component_class), scope: nil,
25
+ helpers: [])
26
+ @component = component_class
27
+ @registry = registry
28
+ @path = path
29
+ @scope = scope
30
+ @helpers = helpers
31
+ end
32
+
33
+ def call
34
+ # The template is UTF-8 whatever the locale says: a US-ASCII read fails on any accented text.
35
+ tree = Template.parse(File.read(@path, encoding: "UTF-8"), path: @path)
36
+ walker = Walker.new(@component, registry: @registry, path: @path, helpers: @helpers)
37
+ nodes = walker.call(tree)
38
+ Result.new(tree: nodes, handlers: walker.handlers, blocks: walker.blocks, deps: walker.deps, scope: @scope,
39
+ server_reads: walker.server_reads)
40
+ end
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Web
5
+ module Compiler
6
+ # A client helper (`client def`) as the JavaScript arrow of the browser module. Its positional params are
7
+ # locals of unknown type, and its body must be one expression of the subset: otherwise the boot refuses it.
8
+ module ClientHelper
9
+ module_function
10
+
11
+ def compile(helper_module, name, helper_names)
12
+ label = "#{helper_module.name || helper_module.inspect}##{name}"
13
+ raise Error, "#{label} is not defined" unless helper_module.method_defined?(name)
14
+
15
+ params = positional_params(helper_module, name, label)
16
+ node = ComputedBody.of(helper_module, name) or raise Error, "#{label} must have one expression as its body"
17
+ result = Expression.compile_node(node, scope(params, helper_names))
18
+ raise Error, "#{label} runs on the server, so it has no browser code" if result.equal?(Expression::SERVER)
19
+
20
+ "(#{params.join(", ")}) => #{result.js}"
21
+ end
22
+
23
+ def positional_params(helper_module, name, label)
24
+ parameters = helper_module.instance_method(name).parameters
25
+ return parameters.map(&:last) if parameters.all? { _1.first == :req }
26
+
27
+ raise Error, "#{label} takes only positional arguments in the browser"
28
+ end
29
+
30
+ def scope(params, helper_names) = TypeScope.new(nil, locals: params.to_h { [_1, :any] }, helpers: helper_names)
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "prism"
4
+
5
+ module Boto
6
+ module Web
7
+ module Compiler
8
+ # The single expression of a computed method, found in its source file by line, or nil.
9
+ # A body with more statements stays on the server: the earlier ones would be lost in JS.
10
+ module ComputedBody
11
+ module_function
12
+
13
+ def of(component_class, name)
14
+ return unless component_class.method_defined?(name)
15
+
16
+ path, line = component_class.instance_method(name).source_location
17
+ return unless path
18
+
19
+ definition = find_def(Prism.parse_file(path).value, name, line)
20
+ last_expression(definition)
21
+ end
22
+
23
+ def find_def(node, name, line)
24
+ return node if node.is_a?(Prism::DefNode) && node.name == name && node.location.start_line == line
25
+
26
+ node.compact_child_nodes.each do |child|
27
+ found = find_def(child, name, line)
28
+ return found if found
29
+ end
30
+ nil
31
+ end
32
+
33
+ def last_expression(definition)
34
+ body = definition&.body
35
+ body.is_a?(Prism::StatementsNode) && body.body.size == 1 ? body.body.first : nil
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Web
5
+ module Compiler
6
+ # Splits a text into HTML pieces and opening tags, and reads each tag's attributes into
7
+ # static ones and directives. Attribute values keep their source text.
8
+ module Directives
9
+ Static = Data.define(:name, :value)
10
+ # kind: :event, :property, :attribute, :class, :class_map, :style, :model or :track.
11
+ # handler is set by the analysis for events (the id of the handler).
12
+ Directive = Data.define(:kind, :name, :modifiers, :source, :handler)
13
+ # child is the component class when the tag is a component's selector, else nil.
14
+ # slot is the tag's index among the tags of its selector, in document order (set by the analysis).
15
+ Tag = Data.define(:name, :attributes, :line, :child, :slot)
16
+
17
+ TAG = %r{<([a-zA-Z][\w-]*)((?:\s+[^\s"'<>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>=`]+))?)*)\s*/?>}
18
+ ATTR = %r{([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'<>=`]+)))?}
19
+ EVENT = /\A\((\w+)((?:\.\w+)*)\)\z/
20
+ MODEL = /\A\[\(model\)\]\z/
21
+ BINDING = /\A\[(class|style|attr)\.([\w-]+)\]\z/
22
+ PROPERTY = /\A\[([\w-]+)\]\z/
23
+ BINDING_KINDS = { "class" => :class, "style" => :style, "attr" => :attribute }.freeze
24
+ PROPERTY_KINDS = { "class" => :class_map, "track" => :track }.freeze
25
+ STATIC_NAMES = { "hook" => "data-hook", "animate.enter" => "data-enter", "animate.leave" => "data-leave" }.freeze
26
+
27
+ module_function
28
+
29
+ def split(html, path:, line:)
30
+ pieces = []
31
+ pos = 0
32
+ html.scan(TAG) do
33
+ match = Regexp.last_match
34
+ start = match.begin(0)
35
+ pieces << html[pos...start] << tag(match, path:, line: line + html[0, start].count("\n"))
36
+ pos = match.end(0)
37
+ end
38
+ pieces << html[pos..]
39
+ pieces.reject { _1.is_a?(String) && _1.empty? }
40
+ end
41
+
42
+ def tag(match, path:, line:)
43
+ attributes = []
44
+ match[2].scan(ATTR) { attributes << attribute(Regexp.last_match, path:, line:) }
45
+ Tag.new(name: match[1], attributes:, line:, child: nil, slot: nil)
46
+ end
47
+
48
+ def attribute(match, path:, line:)
49
+ name = match[1]
50
+ value = match[2] || match[3] || match[4]
51
+ if (found = EVENT.match(name)) then event(found, value, path:, line:)
52
+ elsif MODEL.match?(name) then dynamic(:model, nil, value, path:, line:)
53
+ elsif (found = BINDING.match(name)) then dynamic(BINDING_KINDS.fetch(found[1]), found[2], value, path:, line:)
54
+ elsif (found = PROPERTY.match(name)) then property(found[1], value, path:, line:)
55
+ else static(name, value)
56
+ end
57
+ end
58
+
59
+ def static(name, value)
60
+ Static.new(name: STATIC_NAMES.fetch(name, name), value: value ? value.gsub('"', "&quot;") : true)
61
+ end
62
+
63
+ def event(found, value, path:, line:)
64
+ raise error(path, line, "(#{found[1]}) needs a command") if value.nil? || value.strip.empty?
65
+ raise error(path, line, "(#{found[1]}) takes one command, without ';'") if value.include?(";")
66
+
67
+ Directive.new(kind: :event, name: found[1], modifiers: found[2].split(".").reject(&:empty?),
68
+ source: value, handler: nil)
69
+ end
70
+
71
+ def property(name, value, path:, line:)
72
+ kind = PROPERTY_KINDS.fetch(name, :property)
73
+ dynamic(kind, kind == :property ? name : nil, value, path:, line:)
74
+ end
75
+
76
+ def dynamic(kind, name, value, path:, line:)
77
+ raise error(path, line, "#{kind} needs an expression") if value.nil? || value.strip.empty?
78
+
79
+ Directive.new(kind:, name:, modifiers: [], source: value, handler: nil)
80
+ end
81
+
82
+ def error(path, line, message) = Error.new("#{path}:#{line}: #{message}")
83
+ end
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,149 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Web
5
+ module Compiler
6
+ class Expression
7
+ # Method calls: bare names, `pending?` and the client helpers, and calls on a value (fields, operators, ...).
8
+ module Calls
9
+ HELPERS = Boto::Web::Helpers::NAMES
10
+ IDENTIFIER = /\A[a-z_][a-z0-9_]*\z/
11
+
12
+ private
13
+
14
+ def call(node)
15
+ return bare_call(node) unless node.receiver
16
+ return negation(node) if node.name == :!
17
+
18
+ base = visit(node.receiver)
19
+ return SERVER if base.equal?(SERVER)
20
+ return event_field(base, node) if event_base?(node.receiver, base)
21
+
22
+ member_call(base, node.name, arguments_of(node), node.block)
23
+ end
24
+
25
+ def bare_call(node)
26
+ return plain_name(node.name) if plain?(node)
27
+ return SERVER if node.block || node.arguments.nil?
28
+
29
+ args = node.arguments.arguments
30
+ return pending(args) if node.name == :pending?
31
+ return helper(node.name, args) if HELPERS.include?(node.name) || @scope.client_helper?(node.name)
32
+
33
+ SERVER
34
+ end
35
+
36
+ # A name is a local or a component name first; without either, a client helper with no argument.
37
+ def plain_name(name)
38
+ return client_helper(name, []) if !@scope.lookup(name) && @scope.client_helper?(name)
39
+
40
+ read_name(name)
41
+ end
42
+
43
+ def pending(args)
44
+ return SERVER unless args.size == 1 && (args.first.is_a?(Prism::SymbolNode) || args.first.is_a?(Prism::StringNode))
45
+
46
+ result("$.$pending(#{JSON.generate(args.first.unescaped)})", :boolean)
47
+ end
48
+
49
+ def helper(name, args)
50
+ return client_helper(name, args) unless HELPERS.include?(name)
51
+
52
+ values = visit_all(args)
53
+ return SERVER unless values
54
+
55
+ result("H.#{name}(#{values.map(&:js).join(", ")})", :string, deps_of(*values))
56
+ end
57
+
58
+ # The browser's copy takes positional arguments only, and its type is unknown, so nothing is operated on it.
59
+ def client_helper(name, args)
60
+ return SERVER if args.any?(Prism::KeywordHashNode)
61
+
62
+ values = visit_all(args)
63
+ return SERVER unless values
64
+
65
+ result("P.#{name}(#{values.map(&:js).join(", ")})", :any, deps_of(*values))
66
+ end
67
+
68
+ def plain?(node) = node.arguments.nil? && node.block.nil?
69
+
70
+ def arguments_of(node) = node.arguments ? node.arguments.arguments : []
71
+
72
+ # `event` is a local of type :any, so `event.value` reads the DOM event's field as it is.
73
+ def event_base?(receiver, base)
74
+ base.type == :any && bare_name(receiver) == :event
75
+ end
76
+
77
+ def bare_name(node)
78
+ case node
79
+ when Prism::LocalVariableReadNode then node.name
80
+ when Prism::CallNode then node.name if node.receiver.nil? && plain?(node)
81
+ end
82
+ end
83
+
84
+ def event_field(base, node)
85
+ return SERVER unless plain?(node) && IDENTIFIER.match?(node.name.to_s)
86
+
87
+ result("#{base.js}.#{node.name}", :any, base.deps)
88
+ end
89
+
90
+ def member_call(base, name, args, block)
91
+ return SERVER unless TypeMap.operable?(base.type)
92
+ return list_block(base, name, args, block) if block
93
+ return nullary(base, name) if args.empty?
94
+
95
+ with_args(base, name, args)
96
+ end
97
+
98
+ def nullary(base, name)
99
+ case name
100
+ when :nil? then result("(#{base.js} == null)", :boolean, base.deps)
101
+ when :to_s then to_text(base)
102
+ else typed_nullary(base, name)
103
+ end
104
+ end
105
+
106
+ def to_text(base)
107
+ return SERVER unless TypeMap.scalar?(base.type)
108
+
109
+ result("R.str(#{base.js})", :string, base.deps)
110
+ end
111
+
112
+ def typed_nullary(base, name)
113
+ return field(base, name) if TypeMap.schema_type?(base.type)
114
+ return list_nullary(base, name) if TypeMap.list_type?(base.type)
115
+ return string_nullary(base, name) if base.type == :string
116
+
117
+ SERVER
118
+ end
119
+
120
+ # A name that is not a field of the schema is an error, found at boot instead of in the browser.
121
+ def field(base, name)
122
+ return SERVER unless IDENTIFIER.match?(name.to_s)
123
+
124
+ schema = base.type[1]
125
+ found = schema.fields.find { |candidate| candidate.name == name }
126
+ raise Error, "#{name} is not a field of #{schema.name}" unless found
127
+
128
+ result("#{base.js}.#{name}", TypeMap.of(found.declared_type), base.deps)
129
+ end
130
+
131
+ def with_args(base, name, args)
132
+ values = visit_all(args)
133
+ return SERVER unless values && values.size == 1
134
+
135
+ one_arg(base, name, values.first)
136
+ end
137
+
138
+ def one_arg(base, name, arg)
139
+ return operator(base, name, arg) if Operators::NAMES.include?(name)
140
+ return list_include(base, arg) if name == :include? && TypeMap.list_type?(base.type)
141
+ return string_affix(base, name, arg) if base.type == :string
142
+
143
+ SERVER
144
+ end
145
+ end
146
+ end
147
+ end
148
+ end
149
+ end
@@ -0,0 +1,116 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Web
5
+ module Compiler
6
+ class Expression
7
+ # Lists: size and emptiness, first and last, and the block methods that run as arrows on the client.
8
+ module Collections
9
+ LIST_SIZES = %i[size length count].freeze
10
+ FILTERS = { select: "R.select", filter: "R.select", reject: "R.reject" }.freeze
11
+ SORTABLE = %i[integer float string].freeze
12
+
13
+ private
14
+
15
+ def list_nullary(base, name)
16
+ element = TypeMap.element(base.type)
17
+ case name
18
+ when *LIST_SIZES then result("#{base.js}.length", :integer, base.deps)
19
+ when :empty?, :none? then result("(#{base.js}.length === 0)", :boolean, base.deps)
20
+ when :any? then result("(#{base.js}.length > 0)", :boolean, base.deps)
21
+ when :first, :last then result("R.#{name}(#{base.js})", element, base.deps)
22
+ when :sum then sum_of(base.js, element, base.deps)
23
+ else SERVER
24
+ end
25
+ end
26
+
27
+ def list_include(base, arg)
28
+ result("R.include(#{base.js}, #{arg.js})", :boolean, deps_of(base, arg))
29
+ end
30
+
31
+ def list_block(base, name, args, block)
32
+ return SERVER unless TypeMap.list_type?(base.type) && args.empty?
33
+
34
+ element = TypeMap.element(base.type)
35
+ fn = arrow(block, element)
36
+ return SERVER if fn.equal?(SERVER)
37
+
38
+ block_call(base, name, fn, element)
39
+ end
40
+
41
+ def block_call(base, name, fn, element)
42
+ deps = deps_of(base, fn)
43
+ case name
44
+ when :map then result("R.map(#{base.js}, #{fn.js})", [:list, fn.type], deps)
45
+ when *FILTERS.keys then result("#{FILTERS[name]}(#{base.js}, #{fn.js})", base.type, deps)
46
+ when :find then result("R.find(#{base.js}, #{fn.js})", element, deps)
47
+ when :count then result("R.count(#{base.js}, #{fn.js})", :integer, deps)
48
+ when :any?, :all?, :none? then result("R.#{name.to_s.chomp("?")}(#{base.js}, #{fn.js})", :boolean, deps)
49
+ when :sum then sum_of("R.map(#{base.js}, #{fn.js})", fn.type, deps)
50
+ when :sort_by then sort_by(base, fn, deps)
51
+ else SERVER
52
+ end
53
+ end
54
+
55
+ # Decimals sum in the runtime; integers and floats sum as numbers.
56
+ def sum_of(list_js, value_type, deps)
57
+ case value_type
58
+ when :decimal then result("D.sum(#{list_js})", :decimal, deps)
59
+ when :integer, :float then result("R.sum(#{list_js})", value_type, deps)
60
+ else SERVER
61
+ end
62
+ end
63
+
64
+ def sort_by(base, fn, deps)
65
+ return SERVER unless SORTABLE.include?(fn.type)
66
+
67
+ result("R.sortBy(#{base.js}, #{fn.js})", base.type, deps)
68
+ end
69
+
70
+ # The Ruby block as a JavaScript arrow, with its body's type; SERVER when the body is not in the subset.
71
+ def arrow(block, element)
72
+ return symbol_arrow(block, element) if block.is_a?(Prism::BlockArgumentNode)
73
+
74
+ param = block_param(block)
75
+ return SERVER if param.nil? || JS_RESERVED.include?(param.to_s)
76
+
77
+ body = Expression.new(@scope.with_local(param, element)).visit(block.body)
78
+ return SERVER if body.equal?(SERVER)
79
+
80
+ lambda_result(param.to_s, body)
81
+ end
82
+
83
+ # `&:price` is the same as `{ |x| x.price }`.
84
+ def symbol_arrow(block, element)
85
+ return SERVER unless block.expression.is_a?(Prism::SymbolNode)
86
+
87
+ body = member_call(result("x", element), block.expression.unescaped.to_sym, [], nil)
88
+ return SERVER if body.equal?(SERVER)
89
+
90
+ lambda_result("x", body)
91
+ end
92
+
93
+ def lambda_result(param, body)
94
+ js = body.js.start_with?("{") ? "(#{body.js})" : body.js
95
+ result("(#{param}) => #{js}", body.type, body.deps)
96
+ end
97
+
98
+ def block_param(block)
99
+ case block.parameters
100
+ when nil, Prism::ItParametersNode then :it
101
+ when Prism::NumberedParametersNode then block.parameters.maximum == 1 ? :_1 : nil
102
+ when Prism::BlockParametersNode then single_required(block.parameters)
103
+ end
104
+ end
105
+
106
+ def single_required(block_params)
107
+ requireds = block_params.parameters ? block_params.parameters.requireds : []
108
+ return unless requireds.size == 1 && requireds.first.is_a?(Prism::RequiredParameterNode)
109
+
110
+ requireds.first.name
111
+ end
112
+ end
113
+ end
114
+ end
115
+ end
116
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Web
5
+ module Compiler
6
+ class Expression
7
+ # Literals: numbers, strings (with interpolation), symbols, arrays and hashes.
8
+ module Literals
9
+ private
10
+
11
+ def number(node)
12
+ result(node.value.to_s, node.is_a?(Prism::IntegerNode) ? :integer : :float)
13
+ end
14
+
15
+ # A symbol is a string on the client, like the names of pending? and the keys of a hash.
16
+ def text(node)
17
+ result(JSON.generate(node.unescaped), :string)
18
+ end
19
+
20
+ def interpolated(node)
21
+ parts = node.parts.map { |part| template_part(part) }
22
+ return SERVER if parts.any? { |part| part.equal?(SERVER) }
23
+
24
+ result("`#{parts.map(&:js).join}`", :string, deps_of(*parts))
25
+ end
26
+
27
+ def template_part(part)
28
+ case part
29
+ when Prism::StringNode then result(escape_template(part.unescaped), :string)
30
+ when Prism::EmbeddedStatementsNode then embedded(part)
31
+ else SERVER
32
+ end
33
+ end
34
+
35
+ def embedded(part)
36
+ value = visit(part.statements)
37
+ return SERVER if value.equal?(SERVER)
38
+
39
+ result("${R.str(#{value.js})}", :string, value.deps)
40
+ end
41
+
42
+ def escape_template(text)
43
+ text.gsub(/[\\`]|\$\{/) { |match| "\\#{match}" }
44
+ end
45
+
46
+ def array_literal(elements)
47
+ values = visit_all(elements)
48
+ return SERVER unless values
49
+
50
+ types = values.map(&:type).uniq
51
+ item = types.size == 1 ? types.first : :any
52
+ result("[#{values.map(&:js).join(", ")}]", [:list, item], deps_of(*values))
53
+ end
54
+
55
+ # Keys are strings or symbols; the JavaScript key is always the quoted name.
56
+ def object_literal(elements)
57
+ keys = elements.map { |pair| literal_key(pair) }
58
+ return SERVER if keys.include?(nil)
59
+
60
+ values = visit_all(elements.map(&:value))
61
+ return SERVER unless values
62
+
63
+ fields = keys.zip(values).map { |key, value| "#{JSON.generate(key)}: #{value.js}" }
64
+ result("{#{fields.join(", ")}}", :hash, deps_of(*values))
65
+ end
66
+
67
+ def literal_key(pair)
68
+ key = pair.key if pair.is_a?(Prism::AssocNode)
69
+ key.unescaped if key.is_a?(Prism::StringNode) || key.is_a?(Prism::SymbolNode)
70
+ end
71
+ end
72
+ end
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Web
5
+ module Compiler
6
+ class Expression
7
+ # Ruby truthiness (only nil and false are falsy), and/or, ternary, `!` and writes to states.
8
+ module Logic
9
+ private
10
+
11
+ def logical(node, helper)
12
+ parts = visit_all([node.left, node.right])
13
+ return SERVER unless parts
14
+
15
+ left, right = parts
16
+ result("#{helper}(#{left.js}, () => #{right.js})", union_type(left.type, right.type), deps_of(*parts))
17
+ end
18
+
19
+ def ternary(node)
20
+ return SERVER unless node.if_keyword_loc.nil? && node.subsequent.is_a?(Prism::ElseNode)
21
+
22
+ parts = visit_all([node.predicate, node.statements, node.subsequent.statements])
23
+ return SERVER unless parts
24
+
25
+ condition, yes, no = parts
26
+ result("(R.t(#{condition.js}) ? #{yes.js} : #{no.js})", union_type(yes.type, no.type), deps_of(*parts))
27
+ end
28
+
29
+ def negation(node)
30
+ operand = visit(node.receiver)
31
+ return SERVER if operand.equal?(SERVER)
32
+
33
+ result("!R.t(#{operand.js})", :boolean, operand.deps)
34
+ end
35
+
36
+ # Only a state can be written, and only where the caller allows it (events, not render).
37
+ def assignment(node)
38
+ return SERVER unless @assignment && state?(node.name)
39
+
40
+ value = Expression.compile_node(node.value, @scope)
41
+ return SERVER if value.equal?(SERVER)
42
+
43
+ result("$.#{node.name} = #{value.js}", value.type, value.deps)
44
+ end
45
+
46
+ def state?(name) = @scope.lookup(name)&.fetch(:kind) == :state
47
+
48
+ def union_type(left, right) = left == right ? left : :any
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Boto
4
+ module Web
5
+ module Compiler
6
+ class Expression
7
+ # Binary operators. Decimals go through the runtime (D.*) and never through floats.
8
+ module Operators
9
+ NAMES = %i[== != < > <= >= + - *].freeze
10
+ EQUALITY = %i[== !=].freeze
11
+ ORDERING_JS = { :< => "<", :> => ">", :<= => "<=", :>= => ">=" }.freeze
12
+ ORDERING_DECIMAL = { :< => "D.lt", :> => "D.gt", :<= => "D.lte", :>= => "D.gte" }.freeze
13
+ ARITHMETIC_DECIMAL = { :+ => "D.add", :- => "D.sub", :* => "D.mul" }.freeze
14
+ NUMERIC = %i[integer float].freeze
15
+ DECIMAL_OPERAND = %i[decimal integer].freeze
16
+
17
+ private
18
+
19
+ def operator(left, name, right)
20
+ return SERVER unless TypeMap.operable?(right.type)
21
+ return equality(name, left, right) if EQUALITY.include?(name)
22
+ return ordering(name, left, right) if ORDERING_JS.key?(name)
23
+
24
+ arithmetic(name, left, right)
25
+ end
26
+
27
+ def equality(name, left, right)
28
+ js = equal_js(left, right)
29
+ return SERVER unless js
30
+
31
+ result(name == :!= ? "!#{js}" : js, :boolean, deps_of(left, right))
32
+ end
33
+
34
+ def equal_js(left, right)
35
+ return "D.eq(#{decimal_arg(left)}, #{decimal_arg(right)})" if decimal_operands?(left, right)
36
+ return if decimal_involved?(left, right)
37
+
38
+ "R.eq(#{left.js}, #{right.js})"
39
+ end
40
+
41
+ def ordering(name, left, right)
42
+ js = ordering_js(name, left, right)
43
+ return SERVER unless js
44
+
45
+ result(js, :boolean, deps_of(left, right))
46
+ end
47
+
48
+ def ordering_js(name, left, right)
49
+ return "#{ORDERING_DECIMAL[name]}(#{decimal_arg(left)}, #{decimal_arg(right)})" if decimal_operands?(left, right)
50
+ return "(#{left.js} #{ORDERING_JS[name]} #{right.js})" if numeric?(left) && numeric?(right)
51
+
52
+ nil
53
+ end
54
+
55
+ def arithmetic(name, left, right)
56
+ deps = deps_of(left, right)
57
+ if decimal_operands?(left, right)
58
+ result("#{ARITHMETIC_DECIMAL[name]}(#{decimal_arg(left)}, #{decimal_arg(right)})", :decimal, deps)
59
+ elsif name == :+ && left.type == :string && right.type == :string
60
+ result("(#{left.js} + #{right.js})", :string, deps)
61
+ elsif numeric?(left) && numeric?(right)
62
+ result("(#{left.js} #{name} #{right.js})", numeric_type(left, right), deps)
63
+ else
64
+ SERVER
65
+ end
66
+ end
67
+
68
+ def decimal_operands?(left, right)
69
+ types = [left.type, right.type]
70
+ types.include?(:decimal) && types.all? { |type| DECIMAL_OPERAND.include?(type) }
71
+ end
72
+
73
+ def decimal_involved?(left, right) = [left.type, right.type].include?(:decimal)
74
+
75
+ # An integer becomes a decimal with scale 0; the runtime takes the rest as it is.
76
+ def decimal_arg(value) = value.type == :integer ? "D.from(#{value.js})" : value.js
77
+
78
+ def numeric?(value) = NUMERIC.include?(value.type)
79
+
80
+ def numeric_type(left, right) = left.type == :integer && right.type == :integer ? :integer : :float
81
+ end
82
+ end
83
+ end
84
+ end
85
+ end