Module: Interscript::Opal

Included in:
Interscript
Defined in:
lib/interscript/opal.rb

Instance Method Summary collapse

Instance Method Details

#aliasesObject



177
178
179
# File 'lib/interscript/opal.rb', line 177

def aliases
  @aliases ||= Hash.new(`Opal.global.InterscriptMapAliases`)
end

#external_processing(mapping, string) ⇒ Object



38
39
40
# File 'lib/interscript/opal.rb', line 38

def external_processing(mapping, string)
  string
end

#load_map_json(_, json) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/interscript/opal.rb', line 42

def load_map_json(_, json)
  json = Hash.new(json) if native? json
  json = JSON.load(json) if String === json
  json.each do |k,v|
    `Opal.global.InterscriptMaps[#{k}] = #{JSON.dump(v)}`
  end
end

#load_maps(opts, &block) ⇒ Object

Use #on_load_maps if possible. It will be available earlier. See lib/interscript/opal/entrypoint.rb



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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
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
# File 'lib/interscript/opal.rb', line 52

def load_maps(opts, &block)
  # Convert arg
  opts = Hash.new(opts) if native? opts

  defaults = {
    maps: [],
    path: nil,
    node_path: "./maps/",
    ajax_path: "maps/",
    loader: nil,
    processor: proc { |i| i },
  }

  opts = defaults.merge opts
  opts[:maps] = Array(opts[:maps])

  %x{
    var ajax_loader = function(map) {
      return new Promise(function(ok, fail) {
        var httpRequest = new XMLHttpRequest();
        httpRequest.onreadystatechange = function() {
          if (httpRequest.readyState === XMLHttpRequest.DONE) {
            if (httpRequest.responseText) {
              ok(JSON.parse(httpRequest.responseText));
            }
            else {
              if (is_local) {
                console.log(httpRequest.responseText);
                fail("Ajax failed load: "+map+". Status: "+httpRequest.statusText+". "+
                  "Are you running this locally? Try adding: "+
                  "--allow-file-access-from-files to your Chromium command line.")
              }
              else fail("Ajax failed load: "+map+". Status: "+httpRequest.statusText);
            }
          }
        };
        httpRequest.open('GET', #{opts[:path] || opts[:ajax_path]}+map+".json", true);
        httpRequest.send();
      });
    };

    var fetch_loader = function(map) {
      return fetch(#{opts[:path] || opts[:ajax_path]}+map+".json").then(function(response) {
        return response.json();
      });
    };

    var node_loader = function(map) {
      var resolve = null, error = null;
      var prom = new Promise(function(ok, fail) {
        resolve = ok;
        error = fail;
      });
      try {
        var node_require = eval("require");
        var data = node_require(#{opts[:path] || opts[:node_path]}+map+'.json');
        resolve(data);
      }
      catch(e) {
        error("Node failed load: "+map+". Error: "+e);
      }
      return prom;
    };

    var is_local = false;
    if (typeof document !== "undefined" &&
        typeof document.location !== "undefined" &&
        typeof document.location.protocol !== "undefined") {
          is_local = document.location.protocol == "file:";
        }

    var loader = function(map) {
      if (#{opts[:loader] != nil}) {
        return #{opts[:loader]}(#{opts[:path]}+map+'.json').then(#{opts[:processor]});
      }
      else if (typeof window !== "undefined") {
        return ajax_loader(map);
      }
      else if (typeof global !== "undefined") {
        return node_loader(map);
      }
      else if (!is_local && typeof fetch === "function") {
        return fetch_loader(map);
      }
      else {
        #{raise StandardError, "We couldn't find a good way to load a map"}
      }
    };
  }

  prom = `new Promise(function(ok, fail) {
    #{
      maps = opts[:maps]
      maps = maps.map { |i| map_resolve i }
      maps = maps.reject { |i| map_loaded? i }
      #p ["Loading:", maps]
      maps = maps.map do |i|
        `loader(#{i})`.JS.then do |map|
          load_map_json(nil, map)

          m = Native(map)
          inherits = []
          m.each do |mapname, mapvalue|
            inherits += Array(Native(mapvalue)[:map][:inherit])
            inherits += Array(Native(mapvalue)[:chain])
          end
          inherits = inherits.uniq
          inherits = inherits.reject { |i| map_loaded? i }

          load_maps(opts.merge({maps: inherits})) unless inherits.empty?
        end.JS.catch do |response|
          `fail(#{response})`
        end
      end
    }
    Promise.all(#{maps}).then(ok).catch(fail);
  })`

  if block_given?
    prom.JS.then(block)
  else
    prom
  end
end

#map_exist?(map) ⇒ Boolean

Returns:

  • (Boolean)


181
182
183
# File 'lib/interscript/opal.rb', line 181

def map_exist?(map)
  `typeof(Opal.global.InterscriptMaps[#{map}]) !== 'undefined'`
end

#map_loaded?(map) ⇒ Boolean

Returns:

  • (Boolean)


185
186
187
# File 'lib/interscript/opal.rb', line 185

def map_loaded?(map)
  `!!Opal.global.InterscriptMaps[#{map}]`
end

#mkregexp(regexpstring) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/interscript/opal.rb', line 10

def mkregexp(regexpstring)
  @cache ||= {}
  if s = @cache[regexpstring]
    s
  else
    # JS regexp is more performant than Onigmo. Let's use the JS
    # regexp wherever possible, but use Onigmo where we must.
    # Let's allow those characters to happen for the regexp to be
    # considered compatible: ()|.*+?{} ** BUT NOT (? **.
    if /[\\$^\[\]]|\(\?/.match?(regexpstring)
      # Ruby caches its regexps internally. We can't GC. We could
      # think about freeing them, but we really can't, because they
      # may be in use.

      # Uncomment those to keep track of Onigmo/JS regexp compilation.
      # print '#'
      @cache[regexpstring] = Onigmo::Regexp.new(regexpstring)
    else
      # print '.'
      @cache[regexpstring] = Regexp.new(regexpstring)
    end
  end
end

#sub_replace(string, pos, size, repl) ⇒ Object



34
35
36
# File 'lib/interscript/opal.rb', line 34

def sub_replace(string, pos, size, repl)
  string[0, pos] + repl + string[pos + size..-1]
end