Module: Ruby2JS::Filter::React
- Includes:
- SEXP
- Defined in:
- lib/ruby2js/filter/react.rb
Constant Summary collapse
- 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)
- ReactAttrMap =
Hash[ReactAttrs.map {|name| [name.downcase, name]
Class Method Summary collapse
-
.genAttrs ⇒ Object
the following command can be used to generate ReactAttrs:.
Instance Method Summary collapse
- #initialize(*args) ⇒ Object
-
#on_and_asgn(node) ⇒ Object
convert instance variables to state: “@x &&= y”.
-
#on_begin(node) ⇒ Object
collapse consecutive setState calls into a single call.
-
#on_block(node) ⇒ Object
convert blocks to proc arguments.
-
#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”)))).
-
#on_cvar(node) ⇒ Object
convert class variables to props.
-
#on_cvasgn(node) ⇒ Object
prevent attempts to assign to React properties.
- #on_defs(node) ⇒ Object
-
#on_gvar(node) ⇒ Object
convert global variables to refs.
-
#on_ivar(node) ⇒ Object
convert instance variables to state.
-
#on_ivasgn(node) ⇒ Object
convert instance variable assignments to setState calls.
-
#on_op_asgn(node) ⇒ Object
convert instance variables to state: “@x += y”.
-
#on_or_asgn(node) ⇒ Object
convert instance variables to state: “@x ||= y”.
-
#on_pair(node) ⇒ Object
Convert hash values of type ‘lambda’ to ‘proc’.
- #on_send(node) ⇒ Object
- #options=(options) ⇒ Object
-
#react_element?(node) ⇒ Boolean
is this a “wunderbar” style call or createElement?.
-
#react_process_ivars(block) ⇒ Object
common logic for inserting code to manage state (ivars).
-
#react_walk(node) ⇒ Object
analyze ivar usage.
-
#react_wunderbar_free(nodes) ⇒ Object
ensure that there are no “wunderbar” or “createElement” calls in a set of statements.
Methods included from SEXP
Class Method Details
.genAttrs ⇒ Object
the following command can be used to generate ReactAttrs:
ruby -r ruby2js/filter/react -e "Ruby2JS::Filter::React.genAttrs"
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/ruby2js/filter/react.rb', line 30 def self.genAttrs 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 |
Instance Method Details
#initialize(*args) ⇒ Object
66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/ruby2js/filter/react.rb', line 66 def initialize(*args) @react = nil @reactApply = nil @reactBlock = nil @reactClass = nil @react_props = [] @react_methods = [] @react_filter_functions = false @jsx = false super end |
#on_and_asgn(node) ⇒ Object
convert instance variables to state: “@x &&= y”
954 955 956 957 958 |
# File 'lib/ruby2js/filter/react.rb', line 954 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
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 |
# File 'lib/ruby2js/filter/react.rb', line 1109 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
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 |
# File 'lib/ruby2js/filter/react.rb', line 802 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 !@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 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 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"))))
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 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 |
# File 'lib/ruby2js/filter/react.rb', line 104 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(:send, s(:const, nil, :React), :Component) # 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 # 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 references to instance variables. if \ not es2015 and 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) unless @reactIvars.values.flatten.empty? body = [s(:def, :getInitialState, s(:args), s(:return, s(:hash))), *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 # peel off the initial set of instance variable assignment stmts assigns = [] block = block.dup 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)}) # modify block to build and/or return state if mname == :initialize block.unshift(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 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 ([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 'span' element block = [s(:return, s(:block, s(:send, nil, :_span), 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 << s(: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
990 991 992 993 |
# File 'lib/ruby2js/filter/react.rb', line 990 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
941 942 943 944 |
# File 'lib/ruby2js/filter/react.rb', line 941 def on_cvasgn(node) return super unless @reactMethod raise Error.new("setting a React property", node) end |
#on_defs(node) ⇒ Object
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 |
# File 'lib/ruby2js/filter/react.rb', line 1138 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
889 890 891 892 |
# File 'lib/ruby2js/filter/react.rb', line 889 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
895 896 897 898 899 900 901 902 903 |
# File 'lib/ruby2js/filter/react.rb', line 895 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
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 |
# File 'lib/ruby2js/filter/react.rb', line 906 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_op_asgn(node) ⇒ Object
convert instance variables to state: “@x += y”
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 |
# File 'lib/ruby2js/filter/react.rb', line 961 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”
947 948 949 950 951 |
# File 'lib/ruby2js/filter/react.rb', line 947 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.
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 |
# File 'lib/ruby2js/filter/react.rb', line 1095 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
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 403 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 |
# File 'lib/ruby2js/filter/react.rb', line 331 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) then 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 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) # 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 params += args.map {|arg| process(arg)} 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 |
#options=(options) ⇒ Object
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
# File 'lib/ruby2js/filter/react.rb', line 78 def () super @react = true if [:react] filters = [:filters] || Filter::DEFAULTS if \ defined? Ruby2JS::Filter::Functions and filters.include? Ruby2JS::Filter::Functions then @react_filter_functions = true end if \ defined? Ruby2JS::Filter::Wunderbar and filters.include? Ruby2JS::Filter::Wunderbar then @jsx = true end end |
#react_element?(node) ⇒ Boolean
is this a “wunderbar” style call or createElement?
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 |
# File 'lib/ruby2js/filter/react.rb', line 996 def react_element?(node) 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) # 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) # 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)
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 |
# File 'lib/ruby2js/filter/react.rb', line 1155 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
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 |
# File 'lib/ruby2js/filter/react.rb', line 1039 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) ⇒ Object
ensure that there are no “wunderbar” or “createElement” calls in a set of statements.
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 |
# File 'lib/ruby2js/filter/react.rb', line 1024 def (nodes) nodes.each do |node| if Parser::AST::Node === node return false if react_element?(node) # recurse return false unless (node.children) end end # no problems found return true end |