summaryrefslogtreecommitdiff
path: root/luigi-template.js
blob: 8bf35ef70d6c2b4dcbe15d4a6d12955b8d15eeea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
LuigiTemplate = (function() {
  "use strict";

  var VERSION = '0.3.0';

  // list of built-in filters
  var FILTERS = {
    hash: function(v, args) {
      return 'hash(' + v + ')';
    },

    uc: function(v) {
      return v.toUpperCase();
    },

    lc: function(v) {
      return v.toLowerCase();
    },

    pluralize: function(v) {
      return v + 's';
    },

    length: function(v) {
      return v.length;
    },

    trim: function(v) {
      return (v || '').replace(/^\s+|\s+$/mg, '');
    },

    h: (function() {
      var LUT = {
        '"': '"',
        "'": ''',
        '>': '>',
        '<': '&lt;',
        '&': '&amp;'
      };
      
      return function(v) {
        if (v === undefined || v === null)
          return '';

        return (v || '').replace(/(['"<>&])/g, function(s) {
          return LUT[s];
        });
      };
    })()
  };

  var RES = {
    run:    /%\{\s*(\w+)((\s*\|\s*\w+\s*(\([\w\s,-]+\))?)*)\}/g,
    filter: /(\w+)\s*(\(([\w\s,-]+)\))?/,
    trim:   /^\s+|\s+$/
  };

  function init(s, o) {
    this.s = s;
    this.o = o;
    this.filters = (o && 'filters' in o) ? o.filters : {};
  };

  function safe_trim(s) {
    return ((s !== undefined) ? s : '').replace(RES.trim, '');
  }

  // given a filter string, return a list of filters
  function make_filter_list(s) {
    var i, l, a, md, r = [], fs = s.split(/\s*\|\s*/);

    if (s.length > 0 && fs.length > 0) {
      for (i = 1, l = fs.length; i < l; i++) {
        if (md = fs[i].match(RES.filter)) {
          r.push({
            k: md[1],
            a: safe_trim(md[3]).split(/\s*,\s*/)
          });
        } else {
          throw new Error("invalid filter string: " + fs[i]);
        }
      }
    }

    return r;
  }

  function get_filter(k, me) {
    var r = me.filters[k] || FILTERS[k];

    if (!r)
      throw new Error("unknown filter: " + k);

    return r;
  }

  function run(o) {
    var i, l, f, fs, me = this;

    // TODO: add compiled support here

    return this.s.replace(RES.run, function(m, k, filters) {
      var r = o[k];

      // build filter list
      fs = make_filter_list(filters);

      // iterate over and apply each filter
      for (i = 0, l = fs.length; i < l; i++) {
        // get/check filter
        f = get_filter(fs[i].k, me);

        // apply filter
        r = f(r, fs[i].a, o, this);
      }

      // return result
      return r;
    });
  }

  function get_inline_template(key) {
    // get script element
    var e = document.getElementById(key);
    if (!e)
      throw new Error('unknown inline template key: ' + key);

    // return result
    return e.innerText || '';
  }

  // declare constructor
  var T = init;

  // declare run method
  T.prototype.run = run;

  // declare cache constructor
  T.Cache = function(templates, try_dom) {
    this.templates = templates;
    this.try_dom = !!try_dom;
    this.cache = {};
  };

  // cache run method
  T.Cache.prototype.run = function(key, args) {
    if (!(key in this.cache)) {
      var s = null;

      if (key in this.templates) {
        // get template from constructor templates
        s = this.templates[key].join('');
      } else if (this.try_dom) {
        // get source from inline script tag
        s = get_inline_template(key);
      } else {
        throw new Error('unknown key: ' + key);
      }

      // cache template
      this.cache[key] = new T(s);
    }

    // run template
    return this.cache[key].run(args);
  };

  // declare domcache constructor
  T.DOMCache = function() {
    this.cache = {};
  };
  
  // domcache run method
  T.DOMCache.prototype.run = function(key, args) {
    if (!(key in this.cache))
      this.cache[key] = new T(get_inline_template(key));

    // run template
    return this.cache[key].run(args);
  };

  // create DOMCache singleton
  T.dom = new T.DOMCache();

  // expose filters and version
  T.FILTERS = FILTERS;
  T.VERSION = VERSION;

  // add singleton run
  T.run = function(s, o) {
    return new T(s).run(o);
  }

  // expose interface
  return T;
}());