Module: Ruby2JS::Filter::React

Extended by:
SEXP
Includes:
SEXP
Defined in:
lib/ruby2js/filter/react.rb

Constant Summary collapse

REACT_IMPORTS =
{
  React: s(:import, ['React'], s(:attr, nil, :React)),
  ReactDOM: s(:import, ['ReactDOM'], s(:attr, nil, :ReactDOM))
}
ReactAttrs =

list of react attributes that require special processing

%w(acceptCharset accessKey allowFullScreen
allowTransparency autoCapitalize autoComplete autoCorrect autoFocus
autoPlay autoSave cellPadding cellSpacing charSet classID className
clipPath colSpan contentEditable contextMenu crossOrigin
dangerouslySetInnerHTML dateTime encType fillOpacity fontFamily fontSize
formAction formEncType formMethod formNoValidate formTarget frameBorder
gradientTransform gradientUnits hrefLang htmlFor httpEquiv inputMode
itemID itemProp itemRef itemScope itemType keyParams keyType
marginHeight marginWidth markerEnd markerMid markerStart maxLength
mediaGroup noValidate patternContentUnits patternUnits
preserveAspectRatio radioGroup readOnly rowSpan spellCheck spreadMethod
srcDoc srcSet stopColor stopOpacity strokeDasharray strokeLinecap
strokeOpacity strokeWidth tabIndex textAnchor useMap viewBox
xlinkActuate xlinkArcrole xlinkHref xlinkRole xlinkShow xlinkTitle
xlinkType xmlBase xmlLang xmlSpace)
ReactLifecycle =
%w(render componentDidMount shouldComponentUpdate
getShapshotBeforeUpdate componentDidUpdate componentWillUnmount
componentDidCatch)
ReactAttrMap =
ReactFragment =
:'_React.Fragment'

Class Method Summary collapse

Instance Method Summary collapse

Methods included from SEXP

S, s

Class Method Details

.genAttrsObject

the following command can be used to generate ReactAttrs:

ruby -r ruby2js/filter/react -e "Ruby2JS::Filter::React.genAttrs"


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/ruby2js/filter/react.rb', line 37

def self.genAttrs
  unless RUBY_ENGINE == 'opal'
    require 'nokogumbo'
    page = 'https://facebook.github.io/react/docs/tags-and-attributes.html'
    doc = Nokogiri::HTML5.get(page)

    # delete contents of page prior to the list of supported attributes
    attrs = doc.at('a[name=supported-attributes]')
    attrs = attrs.parent while attrs and not attrs.name.start_with? 'h'
    attrs.previous_sibling.remove while attrs and attrs.previous_sibling

    # extract attribute names with uppercase chars from code and format
    attrs = doc.search('code').map(&:text).join(' ')
    attrs = attrs.split(/\s+/).grep(/[A-Z]/).sort.uniq.join(' ')
    puts "ReactAttrs = %w(#{attrs})".gsub(/(.{1,72})(\s+|\Z)/, "\\1\n")
  end
end

Instance Method Details

#initialize(*args) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/ruby2js/filter/react.rb', line 80

def initialize(*args)
  @react = nil
  @reactApply = nil
  @reactBlock = nil
  @reactClass = nil
  @react_props = []
  @react_methods = []
  @react_filter_functions = false
  @react_imports = false
  @jsx = false
  super
end

#on_and_asgn(node) ⇒ Object

convert instance variables to state: “@x &&= y”



1074
1075
1076
1077
1078
# File 'lib/ruby2js/filter/react.rb', line 1074

def on_and_asgn(node)
  return super unless @react
  return super unless node.children.first.type == :ivasgn
  on_op_asgn(node)
end

#on_begin(node) ⇒ Object

collapse consecutive setState calls into a single call



1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
# File 'lib/ruby2js/filter/react.rb', line 1232

def on_begin(node)
  node = super
  (node.children.length-2).downto(0) do |i|
    if \
      node.children[i].type == :send and
      node.children[i].children[0] and
      node.children[i].children[0].type == :self and
      node.children[i].children[1] == :setState and
      node.children[i].children[2].type == :hash and
      node.children[i+1].type == :send and
      node.children[i+1].children[0] and
      node.children[i+1].children[0].type == :self and
      node.children[i+1].children[1] == :setState and
      node.children[i+1].children[2].type == :hash and
      @comments[node.children[i+1]].empty?
    then
      pairs = node.children[i].children[2].children +
             node.children[i+1].children[2].children
      children = node.children.dup
      children.delete_at(i)
      children[i] = children[i].updated(nil, [
        *children[i].children[0..1],
        children[i].children[2].updated(nil, pairs)])
      node = node.updated(nil, children)
    end
  end
  node
end

#on_block(node) ⇒ Object

convert blocks to proc arguments



898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
# File 'lib/ruby2js/filter/react.rb', line 898

def on_block(node)
  if not @react
    # enable React filtering within React class method calls or
    # React component calls
    if \
      node.children.first == s(:const, nil, :React)
    then
      begin
        react, @react = @react, true
        return on_block(node)
      ensure
        @react = react
      end
    end
  end

  return super unless @react

  # block calls to createElement
  #
  # collect block and apply.  Intermediate representation
  # will look something like the following:
  #
  #   React.createElement(*proc {
  #     var $_ = ['tag', hash]
  #     $_.push(React.createElement(...))
  #     return $_
  #   }())
  #
  # Base Ruby2JS processing will convert the 'splat' to 'apply'
  child = node.children.first
  if \
    child.children[1] == :createElement and
    child.children[0] == s(:const, nil, :React)
  then
    begin
      reactApply, @reactApply = @reactApply, true
      params = [s(:splat, s(:send, s(:block, s(:send, nil, :proc),
        s(:args, s(:shadowarg, :$_)), s(:begin,
        s(:lvasgn, :$_, s(:array, *child.children[2..-1])),
        process(node.children[2]),
        s(:return, s(:lvar, :$_)))), :[]))]
    ensure
      @reactApply = reactApply
    end

    if reactApply
      return child.updated(:send, [s(:gvar, :$_), :push, 
        s(:send, *child.children[0..1], *params)])
    else
      return child.updated(:send, [*child.children[0..1], *params])
    end
  end

  # traverse through potential "css proxy" style method calls
  test = child.children.first
  while test and test.type == :send and not test.is_method?
    child, test = test, test.children.first
  end

  # wunderbar style calls
  if child.children[0] == nil and child.children[1] == :_ and \
    node.children[1].children.empty? and !@jsx

    block = s(:block, s(:send, nil, :proc), s(:args),
      *node.children[2..-1])
    return on_send node.children.first.updated(:send,
      [nil, ReactFragment, block])

  elsif !@jsx and child.children[0] == nil and child.children[1] =~ /^_\w/
    if node.children[1].children.empty?
      # append block as a standalone proc
      block = s(:block, s(:send, nil, :proc), s(:args),
        *node.children[2..-1])
      return on_send node.children.first.updated(:send,
        [*node.children.first.children, block])
    else
      # iterate over Enumerable arguments if there are args present
      send = node.children.first.children
      return super if send.length < 3
      if node.children.length == 3 and
        node.children.last.respond_to? :type and
        node.children.last.type == :send

        return process s(:send, *send[0..1], *send[3..-1],
          s(:splat, s(:block, s(:send, send[2], :map),
          node.children[1], s(:return, node.children[2]))))
      else
        return process s(:block, s(:send, *send[0..1], *send[3..-1]),
          s(:args), s(:block, s(:send, send[2], :forEach),
          *node.children[1..-1]))
      end
    end
  end

  begin
    reactBlock, @reactBlock = @reactBlock, true
    super
  ensure
    @reactBlock = reactBlock
  end
end

#on_class(node) ⇒ Object

Example conversion

before:
  (class (const nil :Foo) (const nil :React) nil)
after:
  (casgn nil :foo, (send :React :createClass (hash (sym :displayName)
     (:str, "Foo"))))


128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
# File 'lib/ruby2js/filter/react.rb', line 128

def on_class(node)
  cname, inheritance, *body = node.children
  return super unless cname.children.first == nil
  return super unless inheritance == s(:const, nil, :React) or
    inheritance == s(:const, nil, :Vue) or
    inheritance == s(:const, s(:const, nil, :React), :Component) or
    inheritance == s(:send, s(:const, nil, :React), :Component)

  prepend_list << REACT_IMPORTS[:React] if @react_imports

  # traverse down to actual list of class statements
  if body.length == 1
    if not body.first
      body = []
    elsif body.first.type == :begin
      body = body.first.children
    end
  end

  # abort conversion unless all body statements are method definitions
  return super unless body.all? do |child|
    child.type == :def or
    (child.type == :defs and child.children.first == s(:self))
  end

  begin
    react, @react = @react, true
    reactClass, @reactClass = @reactClass, true

    pairs = []

    unless es2015
      # automatically capture the displayName for the class
      pairs << s(:pair, s(:sym, :displayName),
        s(:str, cname.children.last.to_s))
    end

    # collect static properties/functions
    statics = []
    body.select {|child| child.type == :defs}.each do |child|
      _parent, mname, args, *block = child.children
      if es2015
        block = [s(:autoreturn, *block)] unless child.is_method?
        pairs << s(:defs, s(:self), mname, args, *block)
      elsif child.is_method?
        statics << s(:pair, s(:sym, mname), process(child.updated(:block,
          [s(:send, nil, :proc), args, s(:autoreturn, *block)])))
      elsif \
        block.length == 1 and
        Converter::EXPRESSIONS.include? block.first.type
      then
        statics << s(:pair, s(:sym, mname), *block)
      else
        statics << s(:pair, s(:prop, mname), {get: child.updated(
          :block, [s(:send, nil, :proc), args, s(:autoreturn, *block)])})
      end
    end

    # collect instance methods (including getters and setters)
    @react_props = []
    @react_methods = []
    body.each do |statement|
      if statement.type == :def
        method = statement.children.first
        unless method == :initialize
          if method.to_s.end_with? '='
            method = method.to_s[0..-2].to_sym
            @react_props << method unless @react_props.include? method
          elsif statement.is_method?
            @react_methods << method unless @react_methods.include? method
          else
            @react_props << method unless @react_props.include? method
          end
        end
      end
    end

    # determine which instance methods need binding
    needs_binding = []
    scan_events = lambda do |list|
      list.each do |node|
        next unless Parser::AST::Node === node
        node = process node if node.type == :xstr
        if node.type == :hash
          node.children.each do |pair|
            value = pair.children.last
            if value.type == :send and \
              @react_methods.include? value.children[1] and \
              [nil, s(:self), s(:send, nil, :this)].include? value.children[0]

              needs_binding << value.children[1]
            end
          end
        end
        scan_events[node.children]
      end
    end
    scan_events[body]

    # append statics (if any)
    unless statics.empty?
      pairs << s(:pair, s(:sym, :statics), s(:hash, *statics))
    end

    # create a default getInitialState method if there is no such method
    # and there are either references to instance variables or there are
    # methods that need to be bound.
    if \
      not body.any? do |child|
        child.type == :def and
        [:getInitialState, :initialize].include? child.children.first
      end
    then
      @reactIvars = {pre: [], post: [], asgn: [], ref: [], cond: []}
      react_walk(node)
      if not es2015 and not @reactIvars.values.flatten.empty?
        body = [s(:def, :getInitialState, s(:args),
          s(:return, s(:hash))), *body]
      elsif not needs_binding.empty? or not @reactIvars.values.flatten.empty?
        body = [s(:def, :initialize, s(:args)), *body]
      end
    end

    # add a proc/function for each method
    body.select {|child| child.type == :def}.each do |child|
      mname, args, *block = child.children
      @reactMethod = mname
      @reactProps = child.updated(:attr, [s(:self), :props])

      # analyze ivar usage
      @reactIvars = {pre: [], post: [], asgn: [], ref: [], cond: []}
      react_walk(child) unless mname == :initialize
      @reactIvars[:capture] =
        (@reactIvars[:pre] + @reactIvars[:post]).uniq

      if mname == :initialize
        mname = es2015 ? :initialize : :getInitialState

        # extract real list of statements
        if block.length == 1
          if not block.first
            block = []
          elsif block.first.type == :begin
            block = block.first.children
          end
        end

        # add props argument if there is a reference to a prop
        if args.children.length == 0
          has_cvar = lambda {|list|
            list.any? {|node|
              next unless Parser::AST::Node === node
              return true if node.type == :cvar
              has_cvar.call(node.children)
            }
          }
          args = s(:args, s(:arg, 'prop$')) if has_cvar[block]
        end

        # peel off the initial set of instance variable assignment stmts
        assigns = []
        block = block.dup
        block.shift if block.first == s(:zsuper)
        while not block.empty? and block.first.type == :ivasgn
          node = block.shift
          vars = [node.children.first]
          while node.children[1].type == :ivasgn
            node = node.children[1]
            vars << node.children.first
          end
          vars.each do |var|
            assigns << s(:ivasgn, var, node.children.last)
          end
        end

        # build a hash for state
        state = s(:hash, *assigns.map {|anode| s(:pair, s(:str,
          anode.children.first.to_s[1..-1]), anode.children.last)})

        # bind methods as needed
        needs_binding.each do |method|
          block.push(s(:send, s(:self), "#{method}=",
            s(:send, s(:attr, s(:self), method), :bind, s(:self))))
        end

        # modify block to build and/or return state
        if mname == :initialize
          block.unshift(s(:zsuper), s(:send, s(:self), :state=, state))
        elsif block.empty?
          block = [s(:return, state)]
        else
          block.unshift(s(:send, s(:self), :state=, state))
          block.push(s(:return, s(:attr, s(:self), :state)))
        end

      elsif mname == :render and not react_wunderbar_free(block, true)
        if \
           block.length != 1 or not block.last or
          not [:send, :block].include? block.last.type
        then
          if @jsx
            while block.length == 1 and block.first.type == :begin
              block = block.first.children.dup
            end

            # gather non-element emitting statements in the front
            prolog = []
            while not block.empty? and 
              react_wunderbar_free([block.first]) do
              prolog << process(block.shift)
            end

            # wrap multi-line blocks with an empty element
            block = [*prolog, s(:return,
              s(:xnode, '', *process_all(block)))]
          else
            # wrap multi-line blocks with a React Fragment
            block = [s(:return,
              s(:block, s(:send, nil, ReactFragment), s(:args), *block))]
          end
        end

      elsif mname == :componentWillReceiveProps
        if args.children.length == 0
          args = s(:args, s(:arg, :"$$props"))
          comments = @comments[child]
          child = child.updated(:def, [mname, args, *block])
          @comments[child] = comments unless comments.empty?
          @reactProps = s(:lvar, :"$$props")
        else
          @reactProps = s(:lvar, args.children.first.children.last)
        end
      end

      # capture and update ivars as required
      block = react_process_ivars(block)

      # add method to class
      type = (child.is_method? ? :begin : :autoreturn)
      type = :begin if mname == :initialize
      if block.length == 1 and Parser::AST::Node === block.first
        type = :begin if block.first.type == :return
      end

      if es2015
        pairs << child.updated(
          ReactLifecycle.include?(mname.to_s) ? :defm : :def, 
          [mname, args, process(s(type, *block))]
        )
      else
        pairs << s(:pair, s(:sym, mname), child.updated(:block,
          [s(:send, nil, :proc), args, process(s(type, *block))]))
      end

      # retain comment
      unless @comments[child].empty?
        @comments[pairs.last] = @comments[child]
      end
    end
  ensure
    @react = react
    @reactClass = reactClass
    @reactMethod = nil
  end

  if es2015
    # emit a class that extends React.Component
    node.updated(:class, [s(:const, nil, cname.children.last),
      s(:attr, s(:const, nil, :React), :Component), *pairs]) 
  else
    # emit a createClass statement
    node.updated(:casgn, [nil, cname.children.last,
      s(:send, s(:const, nil, :React), :createClass, s(:hash, *pairs))])
  end
end

#on_cvar(node) ⇒ Object

convert class variables to props



1110
1111
1112
1113
# File 'lib/ruby2js/filter/react.rb', line 1110

def on_cvar(node)
  return super unless @reactMethod
  s(:attr, @reactProps, node.children.first.to_s[2..-1])
end

#on_cvasgn(node) ⇒ Object

prevent attempts to assign to React properties

Raises:



1061
1062
1063
1064
# File 'lib/ruby2js/filter/react.rb', line 1061

def on_cvasgn(node)
  return super unless @reactMethod
  raise Error.new("setting a React property", node)
end

#on_defs(node) ⇒ Object



1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
# File 'lib/ruby2js/filter/react.rb', line 1261

def on_defs(node)
  return super unless @react

  begin
    reactIvars = @reactIvars
    @reactIvars = {pre: [], post: [], asgn: [], ref: [], cond: []}
    react_walk(node.children.last)
    @reactIvars[:capture] = (@reactIvars[:pre] + @reactIvars[:post]).uniq
    node = super
    block = react_process_ivars([node.children.last.dup])
    node.updated(nil, [*node.children[0..-2], s(:begin, *block)])
  ensure
    @reactIvars = reactIvars
  end
end

#on_gvar(node) ⇒ Object

convert global variables to refs



1009
1010
1011
1012
# File 'lib/ruby2js/filter/react.rb', line 1009

def on_gvar(node)
  return super unless @reactClass
  s(:attr, s(:attr, s(:self), :refs), node.children.first.to_s[1..-1])
end

#on_ivar(node) ⇒ Object

convert instance variables to state



1015
1016
1017
1018
1019
1020
1021
1022
1023
# File 'lib/ruby2js/filter/react.rb', line 1015

def on_ivar(node)
  return super unless @reactClass
  if @reactMethod and @reactIvars[:capture].include? node.children.first
    node.updated(:lvar, ["$#{node.children.first[1..-1]}"])
  else
    node.updated(:attr, [s(:attr, s(:self), :state),
      node.children.first.to_s[1..-1]])
  end
end

#on_ivasgn(node) ⇒ Object

convert instance variable assignments to setState calls



1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
# File 'lib/ruby2js/filter/react.rb', line 1026

def on_ivasgn(node)
  return super unless @react

  if @reactMethod and @reactIvars[:capture].include? node.children.first
    ivar = node.children.first.to_s
    if @reactBlock
      return s(:send, s(:self), :setState, s(:hash, s(:pair,
        s(:lvar, ivar[1..-1]), process(s(:lvasgn, "$#{ivar[1..-1]}",
        *node.children[1..-1])))))
    else
      return s(:lvasgn, "$#{ivar[1..-1]}",
        *process_all(node.children[1..-1]))
    end
  end

  vars = [node.children.first]

  while node.children.length > 1 and node.children[1].type == :ivasgn
    node = node.children[1]
    vars << node.children.first
  end

  if node.children.length == 2
    if @reactMethod == :initialize
      s(:begin, *vars.map {|var| s(:send, s(:attr, s(:self), :state),
        var.to_s[1..-1] + '=', process(node.children.last))})
    else
      s(:send, s(:self), :setState, s(:hash,
        *vars.map {|var| s(:pair, s(:str, var.to_s[1..-1]),
        process(node.children.last))}))
    end
  end
end

#on_lvasgn(node) ⇒ Object



1001
1002
1003
1004
1005
1006
# File 'lib/ruby2js/filter/react.rb', line 1001

def on_lvasgn(node)
  return super unless @reactClass
  return super unless @react_props.include? node.children.first
  node.updated(:send, [s(:self), "#{node.children.first}=",
    node.children.last])
end

#on_op_asgn(node) ⇒ Object

convert instance variables to state: “@x += y”



1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
# File 'lib/ruby2js/filter/react.rb', line 1081

def on_op_asgn(node)
  return super unless @react
  return super unless node.children.first.type == :ivasgn
  var = node.children.first.children.first
  if @reactMethod and @reactIvars[:capture].include? var
    if @reactBlock
      s(:send, s(:self), :setState, s(:hash, s(:pair,
        s(:lvar, var[1..-1]), process(s(node.type,
        s(:lvasgn, "$#{var[1..-1]}"), *node.children[1..-1])))))
    else
      process s(node.type, s(:lvasgn, "$#{var[1..-1]}"),
        *node.children[1..-1])
    end
  elsif @reactMethod == :initialize
    process s(node.type, s(:attr, s(:attr, s(:self), :state),
      var[1..-1]), *node.children[1..-1])
  elsif node.type == :or_asgn
    process s(:ivasgn, var, s(:or, s(:ivar, var),
      *node.children[1..-1]))
  elsif node.type == :and_asgn
    process s(:ivasgn, var, s(:and, s(:ivar, var),
      *node.children[1..-1]))
  else
    process s(:ivasgn, var, s(:send, s(:ivar, var),
      *node.children[1..-1]))
  end
end

#on_or_asgn(node) ⇒ Object

convert instance variables to state: “@x ||= y”



1067
1068
1069
1070
1071
# File 'lib/ruby2js/filter/react.rb', line 1067

def on_or_asgn(node)
  return super unless @react
  return super unless node.children.first.type == :ivasgn
  on_op_asgn(node)
end

#on_pair(node) ⇒ Object

Convert hash values of type ‘lambda’ to ‘proc’. This is because Ruby ‘desugars’ -> to lambda, and Ruby2JS presumes that lambdas return a value.



1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
# File 'lib/ruby2js/filter/react.rb', line 1218

def on_pair(node)
  if \
    node.children[1].type == :block and
    node.children[1].children[0] == s(:send, nil, :lambda)
  then
    process node.updated(nil, [node.children[0],
      node.children[1].updated(nil, [s(:send, nil, :proc),
        *node.children[1].children[1..-1]])])
  else
    super
  end
end

#on_send(node) ⇒ Object



404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
# File 'lib/ruby2js/filter/react.rb', line 404

def on_send(node)
  # convert Vue.utile.defineReactive to class fields or assignments
  if node.children.first == s(:send, s(:const, nil, :Vue), :util)
    if node.children[1] == :defineReactive
      if node.children[2].type == :cvar
        return process s(:cvasgn, node.children[2].children.first,
          node.children[3])
      elsif node.children[2].type == :send
        assign = node.children[2]
        return assign.updated(nil, [assign.children[0],
          assign.children[1].to_s + '=', node.children[3]])
      end
    end
  end

  # calls to methods (including getters) defined in this class
  if node.children[0]==nil and Symbol === node.children[1]
    if node.is_method?
      if @react_methods.include? node.children[1]
        # calls to methods defined in this class
        return node.updated nil, [s(:self), node.children[1],
          *process_all(node.children[2..-1])]
      end
    else
      if @react_props.include? node.children[1]
        # access to properties defined in this class
        return node.updated nil, [s(:self), node.children[1],
          *process_all(node.children[2..-1])]
      end
    end
  end

  if node.children.first == s(:const, nil, :Vue)
    node = node.updated(nil, [s(:const, nil, :React),
      *node.children[1..-1]])
  end

  if not @react
    # enable React filtering within React class method calls or
    # React component calls
    if \
      node.children.first == s(:const, nil, :React) or
      node.children.first == s(:const, nil, :ReactDOM)
    then
      if @react_imports
        prepend_list << REACT_IMPORTS[node.children.first.children.last]
      end

      begin
        react, @react = @react, true
        return on_send(node)
      ensure
        @react = react
      end
    end
  end

  return super unless @react

  if node.children[0] == nil and node.children[1] == :_
    # text nodes
    if @reactApply
      # if apply is set, emit code that pushes text
      s(:send, s(:gvar, :$_), :push, process(node.children[2]))
    else
      # simple/normal case: simply return the text
      process(node.children[2])
    end

  elsif \
    @reactApply and node.children[1] == :createElement and
    node.children[0] == s(:const, nil, :React)
  then
    # push results of explicit calls to React.createElement
    s(:send, s(:gvar, :$_), :push, s(:send, *node.children[0..1],
      *process_all(node.children[2..-1])))

  elsif !@jsx and node.children[0] == nil and node.children[1] =~ /^_\w/
    # map method calls starting with an underscore to React calls
    # to create an element.
    #
    # input:
    #   _a 'name', href: 'link'
    # output:
    #  React.createElement("a", {href: "link"}, "name")
    #
    tag = node.children[1].to_s[1..-1]
    pairs = []
    text = block = nil
    node.children[2..-1].each do |child|
      if child.type == :hash
        # convert _ to - in attribute names
        pairs += child.children.map do |pair|
          key, value = pair.children
          if key.type == :sym
            s(:pair, s(:str, key.children[0].to_s.gsub('_', '-')), value)
          else
            pair
          end
        end

      elsif child.type == :block
        # :block arguments are inserted by on_block logic below
        block = child

      elsif child.type == :splat
        # arrays need not be expanded
        text = child.children.first

      else
        # everything else added as text
        text = child
      end
    end

    # extract all class names
    classes = pairs.find_all do |pair|
      key = pair.children.first.children.first
      [:class, 'class', :className, 'className'].include? key
    end

    # combine all classes into a single value (or expression)
    if classes.length > 0
      expr = nil
      values = classes.map do |pair|
        if [:sym, :str].include? pair.children.last.type
          pair.children.last.children.first.to_s
        else
          expr = pair.children.last
          ''
        end
      end
      pairs -= classes
      if expr
        if values.length > 1
          while expr.type == :begin and expr.children.length == 1
            expr = expr.children.first
          end

          if \
            expr.type == :if and expr.children[1] and
            expr.children[1].type == :str
          then
            left = expr.children[1]
            right = expr.children[2] || s(:str, '')
            right = s(:or, right, s(:str, '')) unless right.type == :str
            expr = expr.updated(nil, [expr.children[0], left, right])
          elsif expr.type != :str
            expr = s(:or, expr, s(:str, ''))
          end

          value = s(:send, s(:str, values.join(' ')), :+, expr)
        else
          value = expr
        end
      else
        value = s(:str, values.join(' '))
      end
      pairs.unshift s(:pair, s(:sym, :className), value)
    end

    # support controlled form components
    if %w(input select textarea).include? tag
      # search for the presence of a 'value' attribute
      value = pairs.find_index do |pair|
        ['value', :value].include? pair.children.first.children.first
      end

      # search for the presence of a 'onChange' attribute
      onChange = pairs.find_index do |pair|
        ['onChange', :onChange].include? pair.children.first.children[0]
      end

      if value and pairs[value].children.last.type == :ivar and !onChange
        pairs << s(:pair, s(:sym, :onChange),
          s(:block, s(:send, nil, :proc), s(:args, s(:arg, :event)),
          s(:ivasgn, pairs[value].children.last.children.first,
          s(:attr, s(:attr, s(:lvar, :event), :target), :value))))
      end

      if not value and not onChange and tag == 'input'
        # search for the presence of a 'checked' attribute
        checked = pairs.find_index do |pair|
          ['checked', :checked].include? pair.children.first.children[0]
        end

        if checked and pairs[checked].children.last.type == :ivar
          pairs << s(:pair, s(:sym, :onChange),
            s(:block, s(:send, nil, :proc), s(:args),
            s(:ivasgn, pairs[checked].children.last.children.first,
            s(:send, pairs[checked].children.last, :!))))
        end
      end
    end

    # replace attribute names with case-sensitive javascript properties
    pairs.each_with_index do |pair, index|
      next if pair.type == :kwsplat
      name = pair.children.first.children.first.downcase
      if ReactAttrMap[name] and name.to_s != ReactAttrMap[name]
        pairs[index] = pairs[index].updated(nil, 
          [s(:str, ReactAttrMap[name]), pairs[index].children.last])
      end
    end

    # search for the presence of a 'style' attribute
    style = pairs.find_index do |pair|
      ['style', :style].include? pair.children.first.children.first
    end

    # converts style strings into style hashes
    if style and pairs[style].children[1].type == :str
      hash = []
      pairs[style].children[1].children[0].split(/;\s+/).each do |prop|
        prop.strip!
        next unless prop =~ /^([-a-z]+):\s*(.*)$/
        name, value = $1, $2
        name.gsub!(/-[a-z]/) {|str| str[1].upcase}
        if value =~ /^-?\d+$/
          hash << s(:pair, s(:str, name), s(:int, value.to_i))
        elsif value =~ /^-?\d+$\.\d*/
          hash << s(:pair, s(:str, name), s(:float, value.to_f))
        else
          hash << s(:pair, s(:str, name), s(:str, value))
        end
      end
      pairs[style] = s(:pair, pairs[style].children[0], s(:hash, *hash))
    end

    # construct hash (or nil) from pairs
    if pairs.length == 1 and pairs.first.type == :kwsplat
      hash = pairs.first.children.first
    else
      hash = (pairs.length > 0 ? process(s(:hash, *pairs)) : s(:nil))
    end

    # based on case of tag name, build a HTML tag or React component
    if tag =~ /^[A-Z]/
      params = [s(:const, nil, tag), hash]
    else
      params = [s(:str, tag), hash]
    end

    # handle nested elements
    if block
      # enable hashes to be passed as a variable on block calls
      params[-1] = text if text and params.last == s(:nil)

      # traverse down to actual list of nested statements
      args = block.children[2..-1]
      if args.length == 1
        if not args.first
          args = []
        elsif args.first.type == :begin
          args = args.first.children
        end
      end

      # check for normal case: only elements and text
      simple = args.all? do |arg|
        # explicit call to React.createElement
        next true if arg.children[1] == :createElement and
          arg.children[0] == s(:const, nil, :React)
        next true if arg.children[1] == :createElement and
          arg.children[0] == s(:const, nil, :Vue)

        # JSX
        next true if arg.type == :xstr

        # wunderbar style call
        arg = arg.children.first if arg.type == :block
        while arg.type == :send and arg.children.first != nil
          arg = arg.children.first
        end
        arg.type == :send and arg.children[1] =~ /^_/
      end

      begin
        if simple
          # in the normal case, process each argument
          reactApply, @reactApply = @reactApply, false
          args.each do |arg|
            arg = process(arg)
            if arg.type == :send and 
              arg.children[0] == s(:const, nil, :React) and
              arg.children[1] == :createElement and
              arg.children[2] == s(:const, nil, "React.Fragment") and
              arg.children[3] == s(:nil) 
            then
              params += arg.children[4..-1]
            else
              params << arg
            end
          end
        else
          reactApply, @reactApply = @reactApply, true

          # collect children and apply.  Intermediate representation
          # will look something like the following:
          #
          #   React.createElement(*proc {
          #     var $_ = ['tag', hash]
          #     $_.push(React.createElement(...))
          #     return $_
          #   }())
          #
          # Base Ruby2JS processing will convert the 'splat' to 'apply'
          params = [s(:splat, s(:send, s(:block, s(:send, nil, :proc),
            s(:args, s(:shadowarg, :$_)), s(:begin,
            s(:lvasgn, :$_, s(:array, *params)),
            *args.map {|arg| process arg},
            s(:return, s(:lvar, :$_)))), :[]))]
        end
      ensure
        @reactApply = reactApply
      end

    elsif text
      # add text
      params << process(text)
    end

    # trim trailing null if no text or children
    params.pop if params.last == s(:nil)

    # construct element using params
    element = node.updated(:send, [s(:const, nil, :React),
      :createElement, *params])

    if @reactApply
      # if apply is set, emit code that pushes result
      s(:send, s(:gvar, :$_), :push, element)
    else
      # simple/normal case: simply return the element
      element
    end

  elsif node.children[0]==s(:send, nil, :_) and node.children[1]==:[]
    if @reactApply
      # if apply is set, emit code that pushes results
      s(:send, s(:gvar, :$_), :push, *process_all(node.children[2..-1]))
    elsif node.children.length == 3
      process(node.children[2])
    else
      # simple/normal case: simply return the element
      s(:splat, s(:array, *process_all(node.children[2..-1])))
    end

  # map method calls involving i/g/c vars to straight calls
  #
  # input:
  #   @x.(a,b,c)
  # output:
  #   @x(a,b,c)
  elsif node.children[1] == :call
    if [:ivar, :gvar, :cvar].include? node.children.first.type
      return process(s(:send, node.children.first, nil,
        *node.children[2..-1]))
    else
      return super
    end

  elsif node.children[1] == :~
    # Locate a DOM Node
    #   map ~(expression) to document.querySelector(expression)
    #   map ~name to this.refs.name
    #   map ~"a b" to document.querySelector("a b")
    #   map ~"#a" to document.getElementById("a")
    #   map ~"a" to document.getElementsByTagName("a")[0]
    #   map ~".a.b" to document.getElementsByClassName("a b")[0]
    #   map ~~expression to ~~expression
    #   map ~~~expression to ~expression

    if node.children[0] and node.children[0].type == :op_asgn
      asgn = node.children[0]
      if asgn.children[0] and asgn.children[0].type == :send
        inner = asgn.children[0]
        return on_send s(:send, s(:send, inner.children[0],
          (inner.children[1].to_s+'=').to_sym,
          s(:send, s(:send, s(:send, inner.children[0], '~'),
          *inner.children[1..-1]), *asgn.children[1..-1])), '~')
      else
        return on_send asgn.updated nil, [s(:send, asgn.children[0], '~'),
          *asgn.children[1..-1]]
      end
    end

    rewrite_tilda = proc do |tnode|
      # Example conversion:
      #   before:
      #    (send (send nil :a) :text) :~)
      #   after:
      #    (send (gvar :$a))), :text)
      if tnode.type == :send and tnode.children[0]
        if tnode.children[1] == :~ and tnode.children[0].children[1] == :~
          # consecutive tildes
          if tnode.children[0].children[0].children[1] == :~
            result = tnode.children[0].children[0].children[0]
          else
            result = s(:attr, tnode.children[0].children[0], '~')
          end
          s(:attr, s(:attr, process(result), '~'), '~')
        else
          # possible getter/setter
          method = tnode.children[1]
          method = method.to_s.chomp('=') if method =~ /=$/
          rewrite = [rewrite_tilda[tnode.children[0]],
            method, *tnode.children[2..-1]]
          rewrite[1] = tnode.children[1]
          tnode.updated nil, rewrite
        end
      elsif tnode.children.first == nil and Symbol === tnode.children[1]
        # innermost expression is a scalar
        s(:gvar, "$#{tnode.children[1]}")
      elsif tnode.type == :lvar
        s(:gvar, "$#{tnode.children[0]}")
      elsif tnode.type == :str
        if tnode.children.first =~ /^#[-\w]+$/
          s(:send, s(:attr, nil, :document), :getElementById,
            s(:str, tnode.children.first[1..-1].gsub('_', '-')))
        elsif tnode.children.first =~ /^(\.[-\w]+)+$/
          s(:send, s(:send, s(:attr, nil, :document),
            :getElementsByClassName, s(:str,
            tnode.children.first[1..-1].gsub('.', ' ').gsub('_', '-'))),
            :[], s(:int, 0))
        elsif tnode.children.first =~ /^[-\w]+$/
          s(:send, s(:send, s(:attr, nil, :document),
            :getElementsByTagName, s(:str,
            tnode.children.first.gsub('_', '-'))), :[], s(:int, 0))
        else
          s(:send, s(:attr, nil, :document), :querySelector, tnode)
        end
      else
        s(:send, s(:attr, nil, :document), :querySelector, tnode)
      end
    end

    return process rewrite_tilda[node].children[0]

  elsif node.children[0] and node.children[0].type == :send
    # determine if markaby style class and id names are being used
    child = node
    test = child.children.first
    while test and test.type == :send and not test.is_method?
      child, test = test, test.children.first
    end

    if child.children[0] == nil and child.children[1] =~ /^_\w/
      # capture the arguments provided on the current node
      children = node.children[2..-1]

      # convert method calls to id and class values
      while node != child
        if node.children[1] !~ /!$/
          # convert method name to hash {className: name} pair
          pair = s(:pair, s(:sym, :className),
            s(:str, node.children[1].to_s.gsub('_','-')))
        else
          # convert method name to hash {id: name} pair
          pair = s(:pair, s(:sym, :id),
            s(:str, node.children[1].to_s[0..-2].gsub('_','-')))
        end

        # if a hash argument is already passed, merge in id value
        hash = children.find_index {|cnode| cnode.type == :hash}
        if hash
          children[hash] = s(:hash, pair, *children[hash].children)
        else
          children.unshift s(:hash, pair)
        end

        # advance to next node
        node = node.children.first
      end

      # collapse series of method calls into a single call
      return process(node.updated(nil, [*node.children[0..1], *children]))
    else
      super
    end

  elsif \
    node.children[0] and node.children[0].type == :self and
    node.children.length == 2 and
    node.children[1] == :componentWillReceiveProps
  then
    s(:send, *node.children, s(:attr, s(:self), :props))

  else
    super
  end
end

#on_xstr(node) ⇒ Object



1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
# File 'lib/ruby2js/filter/react.rb', line 1308

def on_xstr(node)
 loc = node.loc
 return super unless loc
 source = loc.begin.source_buffer.source
 source = source[loc.begin.end_pos...loc.end.begin_pos].strip
 return super unless @reactClass or source.start_with? '<'
 source = Ruby2JS.jsx2_rb(source)
 ast =  Ruby2JS.parse(source).first
 ast = s(:block, s(:send, nil, :_), s(:args), ast) if ast.type == :begin
 process ast
end

#options=(options) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/ruby2js/filter/react.rb', line 93

def options=(options)
  super
  @react = true if options[:react]
  filters = options[:filters] || Filter::DEFAULTS

  if \
    defined? Ruby2JS::Filter::Functions and
    filters.include? Ruby2JS::Filter::Functions
  then
    @react_filter_functions = true
  end

  if \
    (defined? Ruby2JS::Filter::ESM and
    filters.include? Ruby2JS::Filter::ESM) or
    (defined? Ruby2JS::Filter::CJS and
    filters.include? Ruby2JS::Filter::CJS)
  then
    @react_imports = true
  end

  if \
    defined? Ruby2JS::Filter::JSX and
    filters.include? Ruby2JS::Filter::JSX
  then
    @jsx = true
  end
end

#react_element?(node, wunderbar_only = false) ⇒ Boolean

is this a “wunderbar” style call or createElement?

Returns:

  • (Boolean)


1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
# File 'lib/ruby2js/filter/react.rb', line 1116

def react_element?(node, wunderbar_only=false)
  return false unless node

  forEach = [:forEach]
  forEach << :each if @react_filter_functions

  return true if node.type == :block and
    forEach.include? node.children.first.children.last and 
    react_element?(node.children.last, wunderbar_only)

  unless wunderbar_only
    # explicit call to React.createElement
    return true if node.children[1] == :createElement and
      node.children[0] == s(:const, nil, :React)

    # explicit call to Vue.createElement
    return true if node.children[1] == :createElement and
      node.children[0] == s(:const, nil, :Vue)
  end

  # wunderbar style call
  node = node.children.first if node.type == :block
  while node.type == :send and node.children.first != nil
    node = node.children.first
  end
  node.type == :send and node.children[1].to_s.start_with? '_'
end

#react_process_ivars(block) ⇒ Object

common logic for inserting code to manage state (ivars)



1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
# File 'lib/ruby2js/filter/react.rb', line 1278

def react_process_ivars(block)
  # drill down if necessary to find the block
  while block.length==1 and block.first and block.first.type==:begin
    block = block.first.children.dup
  end

  # capture ivars that are both set and referenced
  @reactIvars[:pre].uniq.sort.reverse.each do |ivar|
    block.unshift(s(:lvasgn, "$#{ivar.to_s[1..-1]}",
      s(:attr, s(:attr, s(:self), :state), ivar.to_s[1..-1])))
  end

  # update ivars that are set and later referenced
  unless @reactIvars[:post].empty?
    updates = @reactIvars[:post].uniq.sort.reverse.map do |ivar|
      s(:pair, s(:lvar, ivar.to_s[1..-1]),
        s(:lvar, "$#{ivar.to_s[1..-1]}"))
    end
    update = s(:send, s(:self), :setState, s(:hash, *updates))

    if block.last.type == :return
      block.insert(block.length-1, update)
    else
      block.push(update)
    end
  end

  block
end

#react_walk(node) ⇒ Object

analyze ivar usage



1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
# File 'lib/ruby2js/filter/react.rb', line 1162

def react_walk(node)
  # ignore hash values which are blocks (most typically, event handlers)
  # as these create their own scopes.
  return if node.type == :pair and node.children[0].type == :sym and
    node.children[1].type == :block
  return if node.type == :defs

  base = @reactIvars[:asgn].dup if [:if, :case].include? node.type

  node.children.each do |child|
    react_walk(child) if Parser::AST::Node === child
  end

  child = node.children.first

  case node.type
  when :if, :case
    @reactIvars[:cond] += @reactIvars[:asgn] - base

  when :ivar
    if @reactIvars[:cond].include? child
      @reactIvars[:post] << child
      @reactIvars[:pre] << child
    elsif @reactIvars[:asgn].include? child
      @reactIvars[:post] << child
      @reactIvars[:pre] << child if @reactIvars[:ref].include? child
    end
    @reactIvars[:ref] << child

  when :ivasgn
    @reactIvars[:asgn] << child

  when :op_asgn, :or_asgn, :and_asgn
    if child.type == :ivasgn
      gchild = child.children.first
      if (@reactIvars[:ref]+@reactIvars[:cond]).include? gchild
        @reactIvars[:pre] << gchild
        @reactIvars[:post] << gchild
      end
      @reactIvars[:ref] << gchild
      @reactIvars[:asgn] << gchild
    end

  when :send
    if \
      child and child.type == :self and node.children.length == 2 and
      node.children[1] == :componentWillReceiveProps
    then
      @reactIvars[:post] += @reactIvars[:asgn]
    end
  end
end

#react_wunderbar_free(nodes, wunderbar_only = false) ⇒ Object

ensure that there are no “wunderbar” or “createElement” calls in a set of statements.



1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
# File 'lib/ruby2js/filter/react.rb', line 1146

def react_wunderbar_free(nodes, wunderbar_only=false)
  nodes.each do |node|
    if Parser::AST::Node === node
      return false if node.type == :xstr
      return false if react_element?(node, wunderbar_only)

      # recurse
      return false unless react_wunderbar_free(node.children, wunderbar_only)
    end
  end

  # no problems found
  return true
end