function Tag$2(el, opts) { // get the tag properties from the class constructor var ref = this; var name = ref.name; var tmpl = ref.tmpl; var css = ref.css; var attrs = ref.attrs; var onCreate = ref.onCreate; // register a new tag and cache the class prototype if (!__TAG_IMPL[name]) { tag$1(name, tmpl, css, attrs, onCreate); // cache the class constructor __TAG_IMPL[name].class = this.constructor; } // mount the tag using the class instance mountTo(el, name, opts, this); // inject the component css if (css) { styleManager.inject(); } return this }
n/a
function compile(src, opts, url) { var parts = [], included, defaultParserptions = { template: {}, js: {}, style: {} } if (!opts) opts = {} opts.parserOptions = extend(defaultParserptions, opts.parserOptions || {}) included = opts.exclude ? function (s) { return opts.exclude.indexOf(s) < 0 } : function () { return 1 } if (!url) url = process.cwd() + '/.' var _bp = brackets.array(opts.brackets) if (opts.template) { src = compileTemplate(src, url, opts.template, opts.parserOptions.template) } src = cleanSource(src) .replace(CUST_TAG, function (_, indent, tagName, attribs, body, body2) { var jscode = '', styles = '', html = '', imports = '', pcex = [] pcex._bp = _bp tagName = tagName.toLowerCase() attribs = attribs && included('attribs') ? restoreExpr( parseAttribs( splitHtml(attribs, opts, pcex), pcex), pcex) : '' if ((body || (body = body2)) && /\S/.test(body)) { if (body2) { if (included('html')) html = _compileHTML(body2, opts, pcex) } else { body = body.replace(RegExp('^' + indent, 'gm'), '') body = body.replace(SCRIPTS, function (_m, _attrs, _script) { if (included('js')) { var code = getCode(_script, opts, _attrs, url) if (code === false) return _m.replace(DEFER_ATTR, '') if (code) jscode += (jscode ? '\n' : '') + code } return '' }) body = body.replace(STYLES, function (_m, _attrs, _style) { if (included('css')) { styles += (styles ? ' ' : '') + cssCode(_style, opts, _attrs, url, tagName) } return '' }) var blocks = splitBlocks(body.replace(TRIM_TRAIL, '')) if (included('html')) { html = _compileHTML(blocks[0], opts, pcex) } if (included('js')) { body = _compileJS(blocks[1], opts, null, null, url) if (body) jscode += (jscode ? '\n' : '') + body jscode = jscode.replace(IMPORT_STATEMENT, function (s) { imports += s.trim() + '\n' return '' }) } } } jscode = /\S/.test(jscode) ? jscode.replace(/\n{3,}/g, '\n\n') : '' if (opts.entities) { parts.push({ tagName: tagName, html: html, css: styles, attribs: attribs, js: jscode, imports: imports }) return '' } return mktag(tagName, html, styles, attribs, jscode, imports, opts) }) if (opts.entities) return parts if (opts.debug && url.slice(-2) !== '/.') { if (/^[\\/]/.test(url)) url = path.relative('.', url) src = '//src: ' + url.replace(/\\/g, '/') + '\n' + src } return src }
...
opts = extend({
source: url,
modules: false
}, opts);
return _r('buble').transform(js, opts).code
},
coffee: function (js, opts) {
return _r('CoffeeScript').compile(js, extend({ bare: true }, opts))
},
livescript: function (js, opts) {
return _r('livescript').compile(js, extend({ bare: true, header: false }, opts))
},
typescript: function (js, opts) {
return _r('typescript')(js, opts)
},
...
function mixin$1(name, mix, g) { // Unnamed global if (isObject(name)) { mixin$1(("__unnamed_" + (mixins_id++)), name, true); return } var store = g ? globals : mixins; // Getter if (!mix) { if (isUndefined(store[name])) { throw new Error('Unregistered mixin: ' + name) } return store[name] } // Setter store[name] = isFunction(mix) ? extend(mix.prototype, store[name] || {}) && mix : extend(store[name] || {}, mix); }
...
// add global mixins
var globalMixin = mixin$1(GLOBAL_MIXIN);
if (globalMixin && !skipAnonymous) {
for (var i in globalMixin) {
if (globalMixin.hasOwnProperty(i)) {
this$1.mixin(globalMixin[i]);
}
}
}
if (impl.fn) { impl.fn.call(this, opts); }
if (!skipAnonymous) { this.trigger('before-mount'); }
...
function mount$1(selector, tagName, opts) { var tags = []; function pushTagsTo(root) { if (root.tagName) { var riotTag = getAttr(root, IS_DIRECTIVE); // have tagName? force riot-tag to be the same if (tagName && riotTag !== tagName) { riotTag = tagName; setAttr(root, IS_DIRECTIVE, tagName); } var tag = mountTo(root, riotTag || root.tagName.toLowerCase(), opts); if (tag) { tags.push(tag); } } else if (root.length) { each(root, pushTagsTo); } // assume nodeList } // inject styles into DOM styleManager.inject(); if (isObject(tagName)) { opts = tagName; tagName = 0; } var elem; var allTags; // crawl the DOM to find the tag if (isString(selector)) { selector = selector === '*' ? // select all registered tags // & tags found with the riot-tag attribute set allTags = selectTags() : // or just the ones named like the selector selector + selectTags(selector.split(/, */)); // make sure to pass always a selector // to the querySelectorAll function elem = selector ? $$(selector) : []; } else // probably you have passed already a tag or a NodeList { elem = selector; } // select all the registered and mount them inside their root elements if (tagName === '*') { // get all custom tags tagName = allTags || selectTags(); // if the root els it's just a single tag if (elem.tagName) { elem = $$(tagName, elem); } else { // select all the children for all the different root elements var nodeList = []; each(elem, function (_el) { return nodeList.push($$(tagName, _el)); }); elem = nodeList; } // get rid of the tagName tagName = 0; } pushTagsTo(elem); return tags }
...
```
[Open this example on Plunker](http://riotjs.com/examples/plunker/?app=timer)
#### Mounting
``` javascript
riot.mount('timer', { start: 0 })
```
#### Nesting
Custom tags lets you build complex views with HTML.
``` html
...
observable = function (el) {
/**
* Extend the original object or create a new empty one
* @type { Object }
*/
el = el || {};
/**
* Private variables
*/
var callbacks = {},
slice = Array.prototype.slice;
/**
* Public Api
*/
// extend the el object adding the observable methods
Object.defineProperties(el, {
/**
* Listen to the given `event` ands
* execute the `callback` each time an event is triggered.
* @param { String } event - event id
* @param { Function } fn - callback function
* @returns { Object } el
*/
on: {
value: function(event, fn) {
if (typeof fn == 'function')
{ (callbacks[event] = callbacks[event] || []).push(fn); }
return el
},
enumerable: false,
writable: false,
configurable: false
},
/**
* Removes the given `event` listeners
* @param { String } event - event id
* @param { Function } fn - callback function
* @returns { Object } el
*/
off: {
value: function(event, fn) {
if (event == '*' && !fn) { callbacks = {}; }
else {
if (fn) {
var arr = callbacks[event];
for (var i = 0, cb; cb = arr && arr[i]; ++i) {
if (cb == fn) { arr.splice(i--, 1); }
}
} else { delete callbacks[event]; }
}
return el
},
enumerable: false,
writable: false,
configurable: false
},
/**
* Listen to the given `event` and
* execute the `callback` at most once
* @param { String } event - event id
* @param { Function } fn - callback function
* @returns { Object } el
*/
one: {
value: function(event, fn) {
function on() {
el.off(event, on);
fn.apply(el, arguments);
}
return el.on(event, on)
},
enumerable: false,
writable: false,
configurable: false
},
/**
* Execute all callback functions that listen to
* the given `event`
* @param { String } event - event id
* @returns { Object } el
*/
trigger: {
value: function(event) {
var arguments$1 = arguments;
// getting the arguments
var arglen = arguments.length - 1,
args = new Array(arglen),
fns,
fn,
i;
for (i = 0; i < arglen; i++) {
args[i] = arguments$1[i + 1]; // skip first argument
}
fns = slice.call(callbacks[event] || [], 0);
for (i = 0; fn = fns[i]; ++i) {
fn.apply(el, args);
}
if (callbacks['*'] && event != '*')
{ el.trigger.apply(el, ['*', event].concat(args)); }
return el
},
enumerable: false,
writable: false,
configurable: false
}
});
return el
}
n/a
function render(tagName, opts) { var tag = render.tag(tagName, opts), html = getTagHtml(tag) // unmount the tag avoiding memory leaks tag.unmount() return html }
...
function renderPug (compilerName, html, opts, url) {
opts = extend({
pretty: true,
filename: url,
doctype: 'html'
}, opts);
return _r(compilerName).render(html, opts)
}
_p.html = {
jade: function (html, opts, url) {
/* eslint-disable */
console.log('DEPRECATION WARNING: jade was renamed "pug" - The jade parser will be removed in riot@3.0.0!'
;);
/* eslint-enable */
...
function renderAsync(tagName, opts) { return Promise.race([ new Promise((resolve, reject) => { setTimeout(function() { reject(new Error(`Timeout error:: the tag "${ tagName }" didn\'t trigger the "ready" event during the rendering process`)) }, riot.settings.asyncRenderTimeout) }), new Promise(resolve => { var tag = render.tag(tagName, opts) tag.on('ready', function() { var html = getTagHtml(tag) tag.unmount() resolve(html) }) }) ]) }
n/a
function riotRequire(filename, opts) { var module = new Module() module.id = module.filename = filename loadAndCompile(filename, opts, module) return module.exports }
...
var riot = require('${ hasRiotPath ? riotPath : 'riot' }')
${ preTag }
module.exports = ${ tagDefinition }
`, filename)
}
/**
* Enable the loading of riot tags with options riot.require('some.tag', {
template: 'pug' })
* @param { String } filename - path to the file to load and compile
* @param { Object } opts - compiler options
* @returns { String } tag name
*/
function riotRequire(filename, opts) {
var module = new Module()
module.id = module.filename = filename
...
function tag$1(name, tmpl, css, attrs, fn) { if (isFunction(attrs)) { fn = attrs; if (/^[\w\-]+\s?=/.test(css)) { attrs = css; css = ''; } else { attrs = ''; } } if (css) { if (isFunction(css)) { fn = css; } else { styleManager.add(css); } } name = name.toLowerCase(); __TAG_IMPL[name] = { name: name, tmpl: tmpl, attrs: attrs, fn: fn }; return name }
...
/**
* Render riot tags returning a strings
* @param { String } tagName - tag identifier
* @param { Object } opts - options to pass to the tag
* @returns { String } tag resulting template
*/
function render(tagName, opts) {
var tag = render.tag(tagName, opts),
html = getTagHtml(tag)
// unmount the tag avoiding memory leaks
tag.unmount()
return html
}
/**
...
function tag2$1(name, tmpl, css, attrs, fn) { if (css) { styleManager.add(css, name); } __TAG_IMPL[name] = { name: name, tmpl: tmpl, attrs: attrs, fn: fn }; return name }
...
function mktag (name, html, css, attr, js, imports, opts) {
var
c = opts.debug ? ',\n ' : ', ',
s = '});';
if (js && js.slice(-1) !== '\n') { s = '\n' + s; }
return imports + 'riot.tag2(\'' + name + SQ +
c + _q(html, 1) +
c + _q(css) +
c + _q(attr) + ', function(opts) {\n' + js + s
}
function splitBlocks (str) {
if (/<[-\w]/.test(str)) {
...
function unregister$1(name) { delete __TAG_IMPL[name]; }
n/a
function update$1() { return each(__TAGS_CACHE, function (tag) { return tag.update(); }) }
...
<timer>
<p>Seconds Elapsed: { time }</p>
this.time = opts.start || 0
tick() {
this.update({ time: ++this.time })
}
var timer = setInterval(this.tick, 1000)
this.on('unmount', function() {
clearInterval(timer)
})
...
function _brackets(reOrIdx) { return reOrIdx instanceof RegExp ? _regex(reOrIdx) : _cache[reOrIdx] }
n/a
function _tmpl(str, data) { if (!str) { return str } return (_cache[str] || (_cache[str] = _create(str))).call(data, _logErr) }
n/a
function _req(name, req) { var err, mod, branch, parser = name.split('.') if (parser.length > 1) { branch = parser[0] parser = parser[1] } else { branch = NULL parser = name } // is the parser registered? branch = _find(branch, parser) if (!branch) { if (req) { err = 'Riot parser "' + name + '" is not registered.' throw new Error(err) } return NULL } // parser registered, needs load? if (_loaders[branch][parser]) { if (req) { mod = _load(branch, parser) } else { try { mod = _load(branch, parser) } catch (_) { // istanbul ignore next mod = NULL } } } else { mod = _parsers[branch][parser] } return mod }
...
}
}
function _compileJS (js, opts, type, parserOpts, url) {
if (!/\S/.test(js)) { return '' }
if (!type) { type = opts.type; }
var parser = opts.parser || type && parsers$1._req('js.' + type,
true) || riotjs;
return parser(js, parserOpts, url).replace(/\r\n?/g, '\n').replace(TRIM_TRAIL, '')
}
function compileJS (js, opts, type, userOpts) {
if (typeof opts === 'string') {
userOpts = type;
...
function _loadParser(p1, p2, p3, p4) { var fn = _load(branch, parser) return fn(p1, p2, p3, p4) }
n/a
function _loadParser(p1, p2, p3, p4) { var fn = _load(branch, parser) return fn(p1, p2, p3, p4) }
n/a
function _loadParser(p1, p2, p3, p4) { var fn = _load(branch, parser) return fn(p1, p2, p3, p4) }
n/a
function _loadParser(p1, p2, p3, p4) { var fn = _load(branch, parser) return fn(p1, p2, p3, p4) }
n/a
function _loadParser(p1, p2, p3, p4) { var fn = _load(branch, parser) return fn(p1, p2, p3, p4) }
n/a
function _loadParser(p1, p2, p3, p4) { var fn = _load(branch, parser) return fn(p1, p2, p3, p4) }
n/a
function _loadParser(p1, p2, p3, p4) { var fn = _load(branch, parser) return fn(p1, p2, p3, p4) }
n/a
function _loadParser(p1, p2, p3, p4) { var fn = _load(branch, parser) return fn(p1, p2, p3, p4) }
n/a
function _loadParser(p1, p2, p3, p4) { var fn = _load(branch, parser) return fn(p1, p2, p3, p4) }
n/a
function _loadParser(p1, p2, p3, p4) { var fn = _load(branch, parser) return fn(p1, p2, p3, p4) }
n/a
function _none(src) { return src }
n/a
function _loadParser(p1, p2, p3, p4) { var fn = _load(branch, parser) return fn(p1, p2, p3, p4) }
n/a
function _none(src) { return src }
n/a
function _loadParser(p1, p2, p3, p4) { var fn = _load(branch, parser) return fn(p1, p2, p3, p4) }
n/a
function render(tagName, opts) { var tag = render.tag(tagName, opts), html = getTagHtml(tag) // unmount the tag avoiding memory leaks tag.unmount() return html }
...
function renderPug (compilerName, html, opts, url) {
opts = extend({
pretty: true,
filename: url,
doctype: 'html'
}, opts);
return _r(compilerName).render(html, opts)
}
_p.html = {
jade: function (html, opts, url) {
/* eslint-disable */
console.log('DEPRECATION WARNING: jade was renamed "pug" - The jade parser will be removed in riot@3.0.0!'
;);
/* eslint-enable */
...
dom = function (tagName, opts) { return riot.render.tag(tagName, opts).root }
n/a
tag = function (tagName, opts) { var root = document.createElement(tagName), tag = riot.mount(root, opts)[0] return tag }
...
/**
* Render riot tags returning a strings
* @param { String } tagName - tag identifier
* @param { Object } opts - options to pass to the tag
* @returns { String } tag resulting template
*/
function render(tagName, opts) {
var tag = render.tag(tagName, opts),
html = getTagHtml(tag)
// unmount the tag avoiding memory leaks
tag.unmount()
return html
}
/**
...
function Tag$2(el, opts) { // get the tag properties from the class constructor var ref = this; var name = ref.name; var tmpl = ref.tmpl; var css = ref.css; var attrs = ref.attrs; var onCreate = ref.onCreate; // register a new tag and cache the class prototype if (!__TAG_IMPL[name]) { tag$1(name, tmpl, css, attrs, onCreate); // cache the class constructor __TAG_IMPL[name].class = this.constructor; } // mount the tag using the class instance mountTo(el, name, opts, this); // inject the component css if (css) { styleManager.inject(); } return this }
n/a
function compile(src, opts, url) { var parts = [], included, defaultParserptions = { template: {}, js: {}, style: {} } if (!opts) opts = {} opts.parserOptions = extend(defaultParserptions, opts.parserOptions || {}) included = opts.exclude ? function (s) { return opts.exclude.indexOf(s) < 0 } : function () { return 1 } if (!url) url = process.cwd() + '/.' var _bp = brackets.array(opts.brackets) if (opts.template) { src = compileTemplate(src, url, opts.template, opts.parserOptions.template) } src = cleanSource(src) .replace(CUST_TAG, function (_, indent, tagName, attribs, body, body2) { var jscode = '', styles = '', html = '', imports = '', pcex = [] pcex._bp = _bp tagName = tagName.toLowerCase() attribs = attribs && included('attribs') ? restoreExpr( parseAttribs( splitHtml(attribs, opts, pcex), pcex), pcex) : '' if ((body || (body = body2)) && /\S/.test(body)) { if (body2) { if (included('html')) html = _compileHTML(body2, opts, pcex) } else { body = body.replace(RegExp('^' + indent, 'gm'), '') body = body.replace(SCRIPTS, function (_m, _attrs, _script) { if (included('js')) { var code = getCode(_script, opts, _attrs, url) if (code === false) return _m.replace(DEFER_ATTR, '') if (code) jscode += (jscode ? '\n' : '') + code } return '' }) body = body.replace(STYLES, function (_m, _attrs, _style) { if (included('css')) { styles += (styles ? ' ' : '') + cssCode(_style, opts, _attrs, url, tagName) } return '' }) var blocks = splitBlocks(body.replace(TRIM_TRAIL, '')) if (included('html')) { html = _compileHTML(blocks[0], opts, pcex) } if (included('js')) { body = _compileJS(blocks[1], opts, null, null, url) if (body) jscode += (jscode ? '\n' : '') + body jscode = jscode.replace(IMPORT_STATEMENT, function (s) { imports += s.trim() + '\n' return '' }) } } } jscode = /\S/.test(jscode) ? jscode.replace(/\n{3,}/g, '\n\n') : '' if (opts.entities) { parts.push({ tagName: tagName, html: html, css: styles, attribs: attribs, js: jscode, imports: imports }) return '' } return mktag(tagName, html, styles, attribs, jscode, imports, opts) }) if (opts.entities) return parts if (opts.debug && url.slice(-2) !== '/.') { if (/^[\\/]/.test(url)) url = path.relative('.', url) src = '//src: ' + url.replace(/\\/g, '/') + '\n' + src } return src }
...
opts = extend({
source: url,
modules: false
}, opts);
return _r('buble').transform(js, opts).code
},
coffee: function (js, opts) {
return _r('CoffeeScript').compile(js, extend({ bare: true }, opts))
},
livescript: function (js, opts) {
return _r('livescript').compile(js, extend({ bare: true, header: false }, opts))
},
typescript: function (js, opts) {
return _r('typescript')(js, opts)
},
...
function mixin$1(name, mix, g) { // Unnamed global if (isObject(name)) { mixin$1(("__unnamed_" + (mixins_id++)), name, true); return } var store = g ? globals : mixins; // Getter if (!mix) { if (isUndefined(store[name])) { throw new Error('Unregistered mixin: ' + name) } return store[name] } // Setter store[name] = isFunction(mix) ? extend(mix.prototype, store[name] || {}) && mix : extend(store[name] || {}, mix); }
...
// add global mixins
var globalMixin = mixin$1(GLOBAL_MIXIN);
if (globalMixin && !skipAnonymous) {
for (var i in globalMixin) {
if (globalMixin.hasOwnProperty(i)) {
this$1.mixin(globalMixin[i]);
}
}
}
if (impl.fn) { impl.fn.call(this, opts); }
if (!skipAnonymous) { this.trigger('before-mount'); }
...
function mount$1(selector, tagName, opts) { var tags = []; function pushTagsTo(root) { if (root.tagName) { var riotTag = getAttr(root, IS_DIRECTIVE); // have tagName? force riot-tag to be the same if (tagName && riotTag !== tagName) { riotTag = tagName; setAttr(root, IS_DIRECTIVE, tagName); } var tag = mountTo(root, riotTag || root.tagName.toLowerCase(), opts); if (tag) { tags.push(tag); } } else if (root.length) { each(root, pushTagsTo); } // assume nodeList } // inject styles into DOM styleManager.inject(); if (isObject(tagName)) { opts = tagName; tagName = 0; } var elem; var allTags; // crawl the DOM to find the tag if (isString(selector)) { selector = selector === '*' ? // select all registered tags // & tags found with the riot-tag attribute set allTags = selectTags() : // or just the ones named like the selector selector + selectTags(selector.split(/, */)); // make sure to pass always a selector // to the querySelectorAll function elem = selector ? $$(selector) : []; } else // probably you have passed already a tag or a NodeList { elem = selector; } // select all the registered and mount them inside their root elements if (tagName === '*') { // get all custom tags tagName = allTags || selectTags(); // if the root els it's just a single tag if (elem.tagName) { elem = $$(tagName, elem); } else { // select all the children for all the different root elements var nodeList = []; each(elem, function (_el) { return nodeList.push($$(tagName, _el)); }); elem = nodeList; } // get rid of the tagName tagName = 0; } pushTagsTo(elem); return tags }
...
```
[Open this example on Plunker](http://riotjs.com/examples/plunker/?app=timer)
#### Mounting
``` javascript
riot.mount('timer', { start: 0 })
```
#### Nesting
Custom tags lets you build complex views with HTML.
``` html
...
observable = function (el) {
/**
* Extend the original object or create a new empty one
* @type { Object }
*/
el = el || {};
/**
* Private variables
*/
var callbacks = {},
slice = Array.prototype.slice;
/**
* Public Api
*/
// extend the el object adding the observable methods
Object.defineProperties(el, {
/**
* Listen to the given `event` ands
* execute the `callback` each time an event is triggered.
* @param { String } event - event id
* @param { Function } fn - callback function
* @returns { Object } el
*/
on: {
value: function(event, fn) {
if (typeof fn == 'function')
{ (callbacks[event] = callbacks[event] || []).push(fn); }
return el
},
enumerable: false,
writable: false,
configurable: false
},
/**
* Removes the given `event` listeners
* @param { String } event - event id
* @param { Function } fn - callback function
* @returns { Object } el
*/
off: {
value: function(event, fn) {
if (event == '*' && !fn) { callbacks = {}; }
else {
if (fn) {
var arr = callbacks[event];
for (var i = 0, cb; cb = arr && arr[i]; ++i) {
if (cb == fn) { arr.splice(i--, 1); }
}
} else { delete callbacks[event]; }
}
return el
},
enumerable: false,
writable: false,
configurable: false
},
/**
* Listen to the given `event` and
* execute the `callback` at most once
* @param { String } event - event id
* @param { Function } fn - callback function
* @returns { Object } el
*/
one: {
value: function(event, fn) {
function on() {
el.off(event, on);
fn.apply(el, arguments);
}
return el.on(event, on)
},
enumerable: false,
writable: false,
configurable: false
},
/**
* Execute all callback functions that listen to
* the given `event`
* @param { String } event - event id
* @returns { Object } el
*/
trigger: {
value: function(event) {
var arguments$1 = arguments;
// getting the arguments
var arglen = arguments.length - 1,
args = new Array(arglen),
fns,
fn,
i;
for (i = 0; i < arglen; i++) {
args[i] = arguments$1[i + 1]; // skip first argument
}
fns = slice.call(callbacks[event] || [], 0);
for (i = 0; fn = fns[i]; ++i) {
fn.apply(el, args);
}
if (callbacks['*'] && event != '*')
{ el.trigger.apply(el, ['*', event].concat(args)); }
return el
},
enumerable: false,
writable: false,
configurable: false
}
});
return el
}
n/a
function render(tagName, opts) { var tag = render.tag(tagName, opts), html = getTagHtml(tag) // unmount the tag avoiding memory leaks tag.unmount() return html }
...
function renderPug (compilerName, html, opts, url) {
opts = extend({
pretty: true,
filename: url,
doctype: 'html'
}, opts);
return _r(compilerName).render(html, opts)
}
_p.html = {
jade: function (html, opts, url) {
/* eslint-disable */
console.log('DEPRECATION WARNING: jade was renamed "pug" - The jade parser will be removed in riot@3.0.0!'
;);
/* eslint-enable */
...
function renderAsync(tagName, opts) { return Promise.race([ new Promise((resolve, reject) => { setTimeout(function() { reject(new Error(`Timeout error:: the tag "${ tagName }" didn\'t trigger the "ready" event during the rendering process`)) }, riot.settings.asyncRenderTimeout) }), new Promise(resolve => { var tag = render.tag(tagName, opts) tag.on('ready', function() { var html = getTagHtml(tag) tag.unmount() resolve(html) }) }) ]) }
n/a
function riotRequire(filename, opts) { var module = new Module() module.id = module.filename = filename loadAndCompile(filename, opts, module) return module.exports }
...
var riot = require('${ hasRiotPath ? riotPath : 'riot' }')
${ preTag }
module.exports = ${ tagDefinition }
`, filename)
}
/**
* Enable the loading of riot tags with options riot.require('some.tag', {
template: 'pug' })
* @param { String } filename - path to the file to load and compile
* @param { Object } opts - compiler options
* @returns { String } tag name
*/
function riotRequire(filename, opts) {
var module = new Module()
module.id = module.filename = filename
...
function tag$1(name, tmpl, css, attrs, fn) { if (isFunction(attrs)) { fn = attrs; if (/^[\w\-]+\s?=/.test(css)) { attrs = css; css = ''; } else { attrs = ''; } } if (css) { if (isFunction(css)) { fn = css; } else { styleManager.add(css); } } name = name.toLowerCase(); __TAG_IMPL[name] = { name: name, tmpl: tmpl, attrs: attrs, fn: fn }; return name }
...
/**
* Render riot tags returning a strings
* @param { String } tagName - tag identifier
* @param { Object } opts - options to pass to the tag
* @returns { String } tag resulting template
*/
function render(tagName, opts) {
var tag = render.tag(tagName, opts),
html = getTagHtml(tag)
// unmount the tag avoiding memory leaks
tag.unmount()
return html
}
/**
...
function tag2$1(name, tmpl, css, attrs, fn) { if (css) { styleManager.add(css, name); } __TAG_IMPL[name] = { name: name, tmpl: tmpl, attrs: attrs, fn: fn }; return name }
...
function mktag (name, html, css, attr, js, imports, opts) {
var
c = opts.debug ? ',\n ' : ', ',
s = '});';
if (js && js.slice(-1) !== '\n') { s = '\n' + s; }
return imports + 'riot.tag2(\'' + name + SQ +
c + _q(html, 1) +
c + _q(css) +
c + _q(attr) + ', function(opts) {\n' + js + s
}
function splitBlocks (str) {
if (/<[-\w]/.test(str)) {
...
function unregister$1(name) { delete __TAG_IMPL[name]; }
n/a
function update$1() { return each(__TAGS_CACHE, function (tag) { return tag.update(); }) }
...
<timer>
<p>Seconds Elapsed: { time }</p>
this.time = opts.start || 0
tick() {
this.update({ time: ++this.time })
}
var timer = setInterval(this.tick, 1000)
this.on('unmount', function() {
clearInterval(timer)
})
...
function Tag$2(el, opts) { // get the tag properties from the class constructor var ref = this; var name = ref.name; var tmpl = ref.tmpl; var css = ref.css; var attrs = ref.attrs; var onCreate = ref.onCreate; // register a new tag and cache the class prototype if (!__TAG_IMPL[name]) { tag$1(name, tmpl, css, attrs, onCreate); // cache the class constructor __TAG_IMPL[name].class = this.constructor; } // mount the tag using the class instance mountTo(el, name, opts, this); // inject the component css if (css) { styleManager.inject(); } return this }
n/a
compile = function (arg, fn, opts) { if (typeof arg === T_STRING) { // 2nd parameter is optional, but can be null if (isObject(fn)) { opts = fn; fn = false; } // `riot.compile(tag [, callback | true][, options])` if (/^\s*</m.test(arg)) { var js = compiler.compile(arg, opts); if (fn !== true) { globalEval(js); } if (isFunction(fn)) { fn(js, arg, opts); } return js } // `riot.compile(url [, callback][, options])` GET(arg, function (str, opts, url) { var js = compiler.compile(str, opts, url); globalEval(js, url); if (fn) { fn(js, str, opts); } }, opts); } else if (isArray(arg)) { var i = arg.length; // `riot.compile([urlsList] [, callback][, options])` arg.forEach(function(str) { GET(str, function (str, opts, url) { var js = compiler.compile(str, opts, url); globalEval(js, url); i --; if (!i && fn) { fn(js, str, opts); } }, opts); }); } else { // `riot.compile([callback][, options])` if (isFunction(arg)) { opts = fn; fn = arg; } else { opts = arg; fn = undefined; } if (ready) { return fn && fn() } if (promise) { if (fn) { promise.on('ready', fn); } } else { promise = observable$1(); compileScripts(fn, opts); } } }
...
opts = extend({
source: url,
modules: false
}, opts);
return _r('buble').transform(js, opts).code
},
coffee: function (js, opts) {
return _r('CoffeeScript').compile(js, extend({ bare: true }, opts))
},
livescript: function (js, opts) {
return _r('livescript').compile(js, extend({ bare: true, header: false }, opts))
},
typescript: function (js, opts) {
return _r('typescript')(js, opts)
},
...
function mixin$1(name, mix, g) { // Unnamed global if (isObject(name)) { mixin$1(("__unnamed_" + (mixins_id++)), name, true); return } var store = g ? globals : mixins; // Getter if (!mix) { if (isUndefined(store[name])) { throw new Error('Unregistered mixin: ' + name) } return store[name] } // Setter store[name] = isFunction(mix) ? extend(mix.prototype, store[name] || {}) && mix : extend(store[name] || {}, mix); }
...
// add global mixins
var globalMixin = mixin$1(GLOBAL_MIXIN);
if (globalMixin && !skipAnonymous) {
for (var i in globalMixin) {
if (globalMixin.hasOwnProperty(i)) {
this$1.mixin(globalMixin[i]);
}
}
}
if (impl.fn) { impl.fn.call(this, opts); }
if (!skipAnonymous) { this.trigger('before-mount'); }
...
function mount$$1() { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var ret; compile(function () { ret = mount$1.apply(riot$2, args); }); return ret }
...
```
[Open this example on Plunker](http://riotjs.com/examples/plunker/?app=timer)
#### Mounting
``` javascript
riot.mount('timer', { start: 0 })
```
#### Nesting
Custom tags lets you build complex views with HTML.
``` html
...
observable = function (el) {
/**
* Extend the original object or create a new empty one
* @type { Object }
*/
el = el || {};
/**
* Private variables
*/
var callbacks = {},
slice = Array.prototype.slice;
/**
* Public Api
*/
// extend the el object adding the observable methods
Object.defineProperties(el, {
/**
* Listen to the given `event` ands
* execute the `callback` each time an event is triggered.
* @param { String } event - event id
* @param { Function } fn - callback function
* @returns { Object } el
*/
on: {
value: function(event, fn) {
if (typeof fn == 'function')
{ (callbacks[event] = callbacks[event] || []).push(fn); }
return el
},
enumerable: false,
writable: false,
configurable: false
},
/**
* Removes the given `event` listeners
* @param { String } event - event id
* @param { Function } fn - callback function
* @returns { Object } el
*/
off: {
value: function(event, fn) {
if (event == '*' && !fn) { callbacks = {}; }
else {
if (fn) {
var arr = callbacks[event];
for (var i = 0, cb; cb = arr && arr[i]; ++i) {
if (cb == fn) { arr.splice(i--, 1); }
}
} else { delete callbacks[event]; }
}
return el
},
enumerable: false,
writable: false,
configurable: false
},
/**
* Listen to the given `event` and
* execute the `callback` at most once
* @param { String } event - event id
* @param { Function } fn - callback function
* @returns { Object } el
*/
one: {
value: function(event, fn) {
function on() {
el.off(event, on);
fn.apply(el, arguments);
}
return el.on(event, on)
},
enumerable: false,
writable: false,
configurable: false
},
/**
* Execute all callback functions that listen to
* the given `event`
* @param { String } event - event id
* @returns { Object } el
*/
trigger: {
value: function(event) {
var arguments$1 = arguments;
// getting the arguments
var arglen = arguments.length - 1,
args = new Array(arglen),
fns,
fn,
i;
for (i = 0; i < arglen; i++) {
args[i] = arguments$1[i + 1]; // skip first argument
}
fns = slice.call(callbacks[event] || [], 0);
for (i = 0; fn = fns[i]; ++i) {
fn.apply(el, args);
}
if (callbacks['*'] && event != '*')
{ el.trigger.apply(el, ['*', event].concat(args)); }
return el
},
enumerable: false,
writable: false,
configurable: false
}
});
return el
}
n/a
function tag$1(name, tmpl, css, attrs, fn) { if (isFunction(attrs)) { fn = attrs; if (/^[\w\-]+\s?=/.test(css)) { attrs = css; css = ''; } else { attrs = ''; } } if (css) { if (isFunction(css)) { fn = css; } else { styleManager.add(css); } } name = name.toLowerCase(); __TAG_IMPL[name] = { name: name, tmpl: tmpl, attrs: attrs, fn: fn }; return name }
...
/**
* Render riot tags returning a strings
* @param { String } tagName - tag identifier
* @param { Object } opts - options to pass to the tag
* @returns { String } tag resulting template
*/
function render(tagName, opts) {
var tag = render.tag(tagName, opts),
html = getTagHtml(tag)
// unmount the tag avoiding memory leaks
tag.unmount()
return html
}
/**
...
function tag2$1(name, tmpl, css, attrs, fn) { if (css) { styleManager.add(css, name); } __TAG_IMPL[name] = { name: name, tmpl: tmpl, attrs: attrs, fn: fn }; return name }
...
function mktag (name, html, css, attr, js, imports, opts) {
var
c = opts.debug ? ',\n ' : ', ',
s = '});';
if (js && js.slice(-1) !== '\n') { s = '\n' + s; }
return imports + 'riot.tag2(\'' + name + SQ +
c + _q(html, 1) +
c + _q(css) +
c + _q(attr) + ', function(opts) {\n' + js + s
}
function splitBlocks (str) {
if (/<[-\w]/.test(str)) {
...
function unregister$1(name) { delete __TAG_IMPL[name]; }
n/a
function update$1() { return each(__TAGS_CACHE, function (tag) { return tag.update(); }) }
...
<timer>
<p>Seconds Elapsed: { time }</p>
this.time = opts.start || 0
tick() {
this.update({ time: ++this.time })
}
var timer = setInterval(this.tick, 1000)
this.on('unmount', function() {
clearInterval(timer)
})
...
function Tag$2(el, opts) { // get the tag properties from the class constructor var ref = this; var name = ref.name; var tmpl = ref.tmpl; var css = ref.css; var attrs = ref.attrs; var onCreate = ref.onCreate; // register a new tag and cache the class prototype if (!__TAG_IMPL[name]) { tag$1(name, tmpl, css, attrs, onCreate); // cache the class constructor __TAG_IMPL[name].class = this.constructor; } // mount the tag using the class instance mountTo(el, name, opts, this); // inject the component css if (css) { styleManager.inject(); } return this }
n/a
function mixin$1(name, mix, g) { // Unnamed global if (isObject(name)) { mixin$1(("__unnamed_" + (mixins_id++)), name, true); return } var store = g ? globals : mixins; // Getter if (!mix) { if (isUndefined(store[name])) { throw new Error('Unregistered mixin: ' + name) } return store[name] } // Setter store[name] = isFunction(mix) ? extend(mix.prototype, store[name] || {}) && mix : extend(store[name] || {}, mix); }
...
// add global mixins
var globalMixin = mixin$1(GLOBAL_MIXIN);
if (globalMixin && !skipAnonymous) {
for (var i in globalMixin) {
if (globalMixin.hasOwnProperty(i)) {
this$1.mixin(globalMixin[i]);
}
}
}
if (impl.fn) { impl.fn.call(this, opts); }
if (!skipAnonymous) { this.trigger('before-mount'); }
...
function mount$1(selector, tagName, opts) { var tags = []; function pushTagsTo(root) { if (root.tagName) { var riotTag = getAttr(root, IS_DIRECTIVE); // have tagName? force riot-tag to be the same if (tagName && riotTag !== tagName) { riotTag = tagName; setAttr(root, IS_DIRECTIVE, tagName); } var tag = mountTo(root, riotTag || root.tagName.toLowerCase(), opts); if (tag) { tags.push(tag); } } else if (root.length) { each(root, pushTagsTo); } // assume nodeList } // inject styles into DOM styleManager.inject(); if (isObject(tagName)) { opts = tagName; tagName = 0; } var elem; var allTags; // crawl the DOM to find the tag if (isString(selector)) { selector = selector === '*' ? // select all registered tags // & tags found with the riot-tag attribute set allTags = selectTags() : // or just the ones named like the selector selector + selectTags(selector.split(/, */)); // make sure to pass always a selector // to the querySelectorAll function elem = selector ? $$(selector) : []; } else // probably you have passed already a tag or a NodeList { elem = selector; } // select all the registered and mount them inside their root elements if (tagName === '*') { // get all custom tags tagName = allTags || selectTags(); // if the root els it's just a single tag if (elem.tagName) { elem = $$(tagName, elem); } else { // select all the children for all the different root elements var nodeList = []; each(elem, function (_el) { return nodeList.push($$(tagName, _el)); }); elem = nodeList; } // get rid of the tagName tagName = 0; } pushTagsTo(elem); return tags }
...
```
[Open this example on Plunker](http://riotjs.com/examples/plunker/?app=timer)
#### Mounting
``` javascript
riot.mount('timer', { start: 0 })
```
#### Nesting
Custom tags lets you build complex views with HTML.
``` html
...
observable = function (el) {
/**
* Extend the original object or create a new empty one
* @type { Object }
*/
el = el || {};
/**
* Private variables
*/
var callbacks = {},
slice = Array.prototype.slice;
/**
* Public Api
*/
// extend the el object adding the observable methods
Object.defineProperties(el, {
/**
* Listen to the given `event` ands
* execute the `callback` each time an event is triggered.
* @param { String } event - event id
* @param { Function } fn - callback function
* @returns { Object } el
*/
on: {
value: function(event, fn) {
if (typeof fn == 'function')
{ (callbacks[event] = callbacks[event] || []).push(fn); }
return el
},
enumerable: false,
writable: false,
configurable: false
},
/**
* Removes the given `event` listeners
* @param { String } event - event id
* @param { Function } fn - callback function
* @returns { Object } el
*/
off: {
value: function(event, fn) {
if (event == '*' && !fn) { callbacks = {}; }
else {
if (fn) {
var arr = callbacks[event];
for (var i = 0, cb; cb = arr && arr[i]; ++i) {
if (cb == fn) { arr.splice(i--, 1); }
}
} else { delete callbacks[event]; }
}
return el
},
enumerable: false,
writable: false,
configurable: false
},
/**
* Listen to the given `event` and
* execute the `callback` at most once
* @param { String } event - event id
* @param { Function } fn - callback function
* @returns { Object } el
*/
one: {
value: function(event, fn) {
function on() {
el.off(event, on);
fn.apply(el, arguments);
}
return el.on(event, on)
},
enumerable: false,
writable: false,
configurable: false
},
/**
* Execute all callback functions that listen to
* the given `event`
* @param { String } event - event id
* @returns { Object } el
*/
trigger: {
value: function(event) {
var arguments$1 = arguments;
// getting the arguments
var arglen = arguments.length - 1,
args = new Array(arglen),
fns,
fn,
i;
for (i = 0; i < arglen; i++) {
args[i] = arguments$1[i + 1]; // skip first argument
}
fns = slice.call(callbacks[event] || [], 0);
for (i = 0; fn = fns[i]; ++i) {
fn.apply(el, args);
}
if (callbacks['*'] && event != '*')
{ el.trigger.apply(el, ['*', event].concat(args)); }
return el
},
enumerable: false,
writable: false,
configurable: false
}
});
return el
}
n/a
function tag$1(name, tmpl, css, attrs, fn) { if (isFunction(attrs)) { fn = attrs; if (/^[\w\-]+\s?=/.test(css)) { attrs = css; css = ''; } else { attrs = ''; } } if (css) { if (isFunction(css)) { fn = css; } else { styleManager.add(css); } } name = name.toLowerCase(); __TAG_IMPL[name] = { name: name, tmpl: tmpl, attrs: attrs, fn: fn }; return name }
...
/**
* Render riot tags returning a strings
* @param { String } tagName - tag identifier
* @param { Object } opts - options to pass to the tag
* @returns { String } tag resulting template
*/
function render(tagName, opts) {
var tag = render.tag(tagName, opts),
html = getTagHtml(tag)
// unmount the tag avoiding memory leaks
tag.unmount()
return html
}
/**
...
function tag2$1(name, tmpl, css, attrs, fn) { if (css) { styleManager.add(css, name); } __TAG_IMPL[name] = { name: name, tmpl: tmpl, attrs: attrs, fn: fn }; return name }
...
function mktag (name, html, css, attr, js, imports, opts) {
var
c = opts.debug ? ',\n ' : ', ',
s = '});';
if (js && js.slice(-1) !== '\n') { s = '\n' + s; }
return imports + 'riot.tag2(\'' + name + SQ +
c + _q(html, 1) +
c + _q(css) +
c + _q(attr) + ', function(opts) {\n' + js + s
}
function splitBlocks (str) {
if (/<[-\w]/.test(str)) {
...
function unregister$1(name) { delete __TAG_IMPL[name]; }
n/a
function update$1() { return each(__TAGS_CACHE, function (tag) { return tag.update(); }) }
...
<timer>
<p>Seconds Elapsed: { time }</p>
this.time = opts.start || 0
tick() {
this.update({ time: ++this.time })
}
var timer = setInterval(this.tick, 1000)
this.on('unmount', function() {
clearInterval(timer)
})
...
parse = function (html) { // parse html string to simple-dom document var blank = new simpleDom.Document() var parser = new simpleDom.HTMLParser(simpleTokenizer.tokenize, blank, simpleDom.voidMap) return parser.parse(html) }
...
.replace(/"/g, '"')
.replace(/'/g, '\'')
}
function getParserOptions (attribs) {
var opts = unescapeHTML(getAttrib(attribs, 'options'));
return opts ? JSON.parse(opts) : null
}
function getCode (code, opts, attribs, base) {
var
type = getType(attribs),
src = getAttrib(attribs, 'src'),
jsParserOptions = extend$1({}, opts.parserOptions.js);
...
serialize = function (doc) { // serialize simple-dom document to html string var serializer = new simpleDom.HTMLSerializer(simpleDom.voidMap) return serializer.serialize(doc) }
...
/**
* Get the html as string form any riot tag instance
* @param { Tag } tag - riot tag instance
* @returns { String } tag template
*/
function getTagHtml(tag) {
return sdom.serialize(tag.root)
}
/**
* Render riot tags returning a strings
* @param { String } tagName - tag identifier
* @param { Object } opts - options to pass to the tag
* @returns { String } tag resulting template
...
function _brackets(reOrIdx) { return reOrIdx instanceof RegExp ? _regex(reOrIdx) : _cache[reOrIdx] }
n/a
function _tmpl(str, data) { if (!str) { return str } return (_cache[str] || (_cache[str] = _create(str))).call(data, _logErr) }
n/a
function _brackets(reOrIdx) { return reOrIdx instanceof RegExp ? _regex(reOrIdx) : _cache[reOrIdx] }
n/a
function array(pair) { return pair ? _create(pair) : _cache }
...
pcex = opts;
opts = {};
} else {
if (!pcex) { pcex = []; }
if (!opts) { opts = {}; }
}
pcex._bp = brackets.array(opts.brackets);
return _compileHTML(cleanSource(html), opts, pcex)
}
var JS_ES6SIGN = /^[ \t]*(((?:async|\*)\s*)?([$_A-Za-z][$\w]*))\s*\([^()]*\)\s*{/m;
var JS_ES6END = RegExp('[{}]|' + brackets.S_QBLOCKS, 'g');
...
function hasExpr(str) { return _cache[4].test(str) }
...
var RefExpr = {
init: function init(dom, parent, attrName, attrValue) {
this.dom = dom;
this.attr = attrName;
this.rawValue = attrValue;
this.parent = parent;
this.hasExp = tmpl.hasExpr(attrValue);
return this
},
update: function update() {
var old = this.value;
var customParent = this.parent && getImmediateCustomParentTag(this.parent);
// if the referenced element is a custom tag, then we set the tag itself, rather than DOM
var tagOrDom = this.tag || this.dom;
...
function loopKeys(expr) { var m = expr.match(_cache[9]); return m ? { key: m[1], pos: m[2], val: _cache[0] + m[3].trim() + _cache[1] } : { val: expr.trim() } }
...
oldItems = [],
hasKeys,
isLoop = true,
isAnonymous = !__TAG_IMPL[tagName],
isVirtual = dom.tagName === 'VIRTUAL';
// parse the each expression
expr = tmpl.loopKeys(expr);
expr.isLoop = true;
if (ifExpr) { remAttr(dom, CONDITIONAL_DIRECTIVE); }
// insert a marked where the loop tags will be injected
parentNode.insertBefore(placeholder, dom);
parentNode.removeChild(dom);
...
function _reset(pair) { if ((pair || (pair = DEFAULT)) !== _cache[8]) { _cache = _create(pair); _regex = pair === DEFAULT ? _loopback : _rewrite; _cache[9] = _regex(_pairs[9]); } cachedBrackets = pair; }
n/a
function split(str, tmpl, _bp) { // istanbul ignore next: _bp is for the compiler if (!_bp) { _bp = _cache; } var parts = [], match, isexpr, start, pos, re = _bp[6]; isexpr = start = re.lastIndex = 0; while ((match = re.exec(str))) { pos = match.index; if (isexpr) { if (match[2]) { re.lastIndex = skipBraces(str, match[2], re.lastIndex); continue } if (!match[3]) { continue } } if (!match[1]) { unescapeStr(str.slice(start, pos)); start = re.lastIndex; re = _bp[6 + (isexpr ^= 1)]; re.lastIndex = start; } } if (str && start < str.length) { unescapeStr(str.slice(start)); } return parts function unescapeStr (s) { if (tmpl || isexpr) { parts.push(s && s.replace(_bp[5], '$1')); } else { parts.push(s); } } function skipBraces (s, ch, ix) { var match, recch = FINDBRACES[ch]; recch.lastIndex = ix; ix = 1; while ((match = recch.exec(s))) { if (match[1] && !(match[1] === ch ? ++ix : --ix)) { break } } return ix ? s.length : recch.lastIndex } }
...
re.source.replace(/{/g, bp[2]).replace(/}/g, bp[3]), re.global ? REGLOB : ''
)
}
function _create (pair) {
if (pair === DEFAULT) { return _pairs }
var arr = pair.split(' ');
if (arr.length !== 2 || UNSUPPORTED.test(pair)) {
throw new Error('Unsupported brackets "' + pair + '"')
}
arr = arr.concat(pair.replace(NEED_ESCAPE, '\\').split(' '));
arr[4] = _rewrite(arr[1].length > 1 ? /{[\S\s]*?}/ : _pairs[4], arr);
...
function isArray(value) { return Array.isArray(value) || value instanceof Array }
...
/**
* Check if passed argument is a kind of array
* @param { * } value -
* @returns { Boolean } -
*/
function isArray(value) {
return Array.isArray(value) || value instanceof Array
}
/**
* Check whether object's property could be overridden
* @param { Object } obj - source object
* @param { String } key - object property
* @returns { Boolean } -
...
function isBlank(value) { return isUndefined(value) || value === null || value === '' }
n/a
function isBoolAttr(value) { return RE_BOOL_ATTRS.test(value) }
n/a
function isFunction(value) { return typeof value === T_FUNCTION }
n/a
function isObject(value) { return value && typeof value === T_OBJECT // typeof null is 'object' }
n/a
function isReservedName(value) { return RE_RESERVED_NAMES.test(value) }
n/a
function isString(value) { return typeof value === T_STRING }
n/a
function isUndefined(value) { return typeof value === T_UNDEF }
n/a
function isWritable(obj, key) { var descriptor = Object.getOwnPropertyDescriptor(obj, key); return isUndefined(obj[key]) || descriptor && descriptor.writable }
n/a
function createDOMPlaceholder() { return document.createTextNode('') }
n/a
function createFrag() { return document.createDocumentFragment() }
n/a
function getAttr(dom, name) { return dom.getAttribute(name) }
n/a
function mkEl(name) { return document.createElement(name) }
n/a
function remAttr(dom, name) { dom.removeAttribute(name); }
n/a
function safeInsert(root, curr, next) { root.insertBefore(curr, next.parentNode && next); }
n/a
function setAttr(dom, name, val) { var xlink = XLINK_REGEX.exec(name); if (xlink && xlink[1]) { dom.setAttributeNS(XLINK_NS, xlink[1], val); } else { dom.setAttribute(name, val); } }
n/a
function setInnerHTML(container, html) { if (!isUndefined(container.innerHTML)) { container.innerHTML = html; } // some browsers do not support innerHTML on the SVGs tags else { var doc = new DOMParser().parseFromString(html, 'application/xml'); var node = container.ownerDocument.importNode(doc.documentElement, true); container.appendChild(node); } }
n/a
function styleObjectToString(style) { return Object.keys(style).reduce(function (acc, prop) { return (acc + " " + prop + ": " + (style[prop]) + ";") }, '') }
n/a
function toggleVisibility(dom, show) { dom.style.display = show ? '' : 'none'; dom['hidden'] = show ? false : true; }
n/a
function walkAttrs(html, fn) { if (!html) { return } var m; while (m = RE_HTML_ATTRS.exec(html)) { fn(m[1].toLowerCase(), m[2] || m[3] || m[4]); } }
n/a
function walkNodes(dom, fn, context) { if (dom) { var res = fn(dom, context); var next; // stop the recursion if (res === false) { return } dom = dom.firstChild; while (dom) { next = dom.nextSibling; walkNodes(dom, fn, res); dom = next; } } }
n/a
function contains(array, item) { return array.indexOf(item) !== -1 }
n/a
function defineProperty(el, key, value, options) { Object.defineProperty(el, key, extend({ value: value, enumerable: false, writable: false, configurable: true }, options)); return el }
...
}
function _setSettings (o) {
var b;
o = o || {};
b = o.brackets;
Object.defineProperty(o, 'brackets', {
set: _reset,
get: function () { return cachedBrackets },
enumerable: true
});
_settings = o;
_reset(b);
}
...
function each(list, fn) { var len = list ? list.length : 0; var i = 0; for (; i < len; ++i) { fn(list[i], i); } return list }
n/a
function extend(src) { var obj, args = arguments; for (var i = 1; i < args.length; ++i) { if (obj = args[i]) { for (var key in obj) { // check if this property of the source object could be overridden if (isWritable(src, key)) { src[key] = obj[key]; } } } } return src }
...
export const mount = core.mount
export const mixin = core.mixin
export const update = core.update
export const unregister = core.unregister
export const version = core.version
export const observable = o
export default misc.extend({}, core, {
observable: o,
settings,
util,
})
...
function startsWith(str, value) { return str.slice(0, value.length) === value }
n/a
function toCamel(str) { return str.replace(/-(\w)/g, function (_, c) { return c.toUpperCase(); }) }
n/a
function add(css, name) { if (name) { byName[name] = css; } else { remainder.push(css); } needsInject = true; }
...
{ attrs = ''; }
}
if (css) {
if (isFunction(css))
{ fn = css; }
else
{ styleManager.add(css); }
}
name = name.toLowerCase();
__TAG_IMPL[name] = { name: name, tmpl: tmpl, attrs: attrs, fn: fn };
return name
}
...
function inject() {
if (!WIN || !needsInject) { return }
needsInject = false;
var style = Object.keys(byName)
.map(function(k) { return byName[k] })
.concat(remainder).join('\n');
/* istanbul ignore next */
if (cssTextProp) { cssTextProp.cssText = style; }
else { styleNode.innerHTML = style; }
}
...
// cache the class constructor
__TAG_IMPL[name].class = this.constructor;
}
// mount the tag using the class instance
mountTo(el, name, opts, this);
// inject the component css
if (css) { styleManager.inject(); }
return this
}
/**
* Create a new riot tag implementation
* @param { String } name - name/id of the new riot tag
...
function arrayishAdd(obj, key, value, ensureArray, index) { var dest = obj[key]; var isArr = isArray(dest); var hasIndex = !isUndefined(index); if (dest && dest === value) { return } // if the key was never set, set it once if (!dest && ensureArray) { obj[key] = [value]; } else if (!dest) { obj[key] = value; } // if it was an array and not yet set else { if (isArr) { var oldIndex = dest.indexOf(value); // this item never changed its position if (oldIndex === index) { return } // remove the item from its old position if (oldIndex !== -1) { dest.splice(oldIndex, 1); } // move or add the item if (hasIndex) { dest.splice(index, 0, value); } else { dest.push(value); } } else { obj[key] = [dest, value]; } } }
n/a
function arrayishRemove(obj, key, value, ensureArray) { if (isArray(obj[key])) { var index = obj[key].indexOf(value); if (index !== -1) { obj[key].splice(index, 1); } if (!obj[key].length) { delete obj[key]; } else if (obj[key].length === 1 && !ensureArray) { obj[key] = obj[key][0]; } } else { delete obj[key]; } // otherwise just delete the key }
n/a
function cleanUpData(data) { if (!(data instanceof Tag$1) && !(data && isFunction(data.trigger))) { return data } var o = {}; for (var key in data) { if (!RE_RESERVED_NAMES.test(key)) { o[key] = data[key]; } } return o }
n/a
function getImmediateCustomParentTag(tag) { var ptag = tag; while (ptag.__.isAnonymous) { if (!ptag.parent) { break } ptag = ptag.parent; } return ptag }
n/a
function getTag(dom) { return dom.tagName && __TAG_IMPL[getAttr(dom, IS_DIRECTIVE) || getAttr(dom, IS_DIRECTIVE) || dom.tagName.toLowerCase()] }
n/a
function getTagName(dom, skipDataIs) { var child = getTag(dom), namedTag = !skipDataIs && getAttr(dom, IS_DIRECTIVE); return namedTag && !tmpl.hasExpr(namedTag) ? namedTag : child ? child.name : dom.tagName.toLowerCase() }
n/a
function inheritFrom(target, propsInSyncWithParent) { var this$1 = this; each(Object.keys(target), function (k) { // some properties must be always in sync with the parent tag var mustSync = !isReservedName(k) && contains(propsInSyncWithParent, k); if (isUndefined(this$1[k]) || mustSync) { // track the property to keep in sync // so we can keep it updated if (!mustSync) { propsInSyncWithParent.push(k); } this$1[k] = target[k]; } }); }
n/a
function initChildTag(child, opts, innerHTML, parent) { var tag = new Tag$1(child, opts, innerHTML), tagName = opts.tagName || getTagName(opts.root, true), ptag = getImmediateCustomParentTag(parent); // fix for the parent attribute in the looped elements defineProperty(tag, 'parent', ptag); // store the real parent tag // in some cases this could be different from the custom parent tag // for example in nested loops tag.__.parent = parent; // add this tag to the custom parent tag arrayishAdd(ptag.tags, tagName, tag); // and also to the real parent tag if (ptag !== parent) { arrayishAdd(parent.tags, tagName, tag); } // empty the child node once we got its template // to avoid that its children get compiled multiple times opts.root.innerHTML = ''; return tag }
n/a
function makeReplaceVirtual(tag, ref) { var frag = createFrag(); makeVirtual.call(tag, frag); ref.parentNode.replaceChild(frag, ref); }
n/a
function makeVirtual(src, target) { var this$1 = this; var head = createDOMPlaceholder(), tail = createDOMPlaceholder(), frag = createFrag(), sib, el; this.root.insertBefore(head, this.root.firstChild); this.root.appendChild(tail); this.__.head = el = head; this.__.tail = tail; while (el) { sib = el.nextSibling; frag.appendChild(el); this$1.__.virts.push(el); // hold for unmounting el = sib; } if (target) { src.insertBefore(frag, target.__.head); } else { src.appendChild(frag); } }
n/a
function mountTo(root, tagName, opts, ctx) { var impl = __TAG_IMPL[tagName], implClass = __TAG_IMPL[tagName].class, tag = ctx || (implClass ? Object.create(implClass.prototype) : {}), // cache the inner HTML to fix #855 innerHTML = root._innerHTML = root._innerHTML || root.innerHTML; // clear the inner html root.innerHTML = ''; var conf = extend({ root: root, opts: opts }, { parent: opts ? opts.parent : null }); if (impl && root) { Tag$1.apply(tag, [impl, conf, innerHTML]); } if (tag && tag.mount) { tag.mount(true); // add this tag to the virtualDom variable if (!contains(__TAGS_CACHE, tag)) { __TAGS_CACHE.push(tag); } } return tag }
n/a
function moveChildTag(tagName, newPos) { var parent = this.parent, tags; // no parent no move if (!parent) { return } tags = parent.tags[tagName]; if (isArray(tags)) { tags.splice(newPos, 0, tags.splice(tags.indexOf(this), 1)[0]); } else { arrayishAdd(parent.tags, tagName, this); } }
n/a
function moveVirtual(src, target) { var this$1 = this; var el = this.__.head, frag = createFrag(), sib; while (el) { sib = el.nextSibling; frag.appendChild(el); el = sib; if (el === this$1.__.tail) { frag.appendChild(el); src.insertBefore(frag, target.__.head); break } } }
n/a
function selectTags(tags) { // select all tags if (!tags) { var keys = Object.keys(__TAG_IMPL); return keys + selectTags(keys) } return tags .filter(function (t) { return !/[^-\w]/.test(t); }) .reduce(function (list, t) { var name = t.trim().toLowerCase(); return list + ",[" + IS_DIRECTIVE + "=\"" + name + "\"]" }, '') }
n/a
function unmountAll(expressions) { each(expressions, function(expr) { if (expr instanceof Tag$1) { expr.unmount(true); } else if (expr.tagName) { expr.tag.unmount(true); } else if (expr.unmount) { expr.unmount(); } }); }
n/a
function _tmpl(str, data) { if (!str) { return str } return (_cache[str] || (_cache[str] = _create(str))).call(data, _logErr) }
n/a
clearCache = function () { _cache = {}; }
n/a
function hasExpr(str) { return _cache[4].test(str) }
...
var RefExpr = {
init: function init(dom, parent, attrName, attrValue) {
this.dom = dom;
this.attr = attrName;
this.rawValue = attrValue;
this.parent = parent;
this.hasExp = tmpl.hasExpr(attrValue);
return this
},
update: function update() {
var old = this.value;
var customParent = this.parent && getImmediateCustomParentTag(this.parent);
// if the referenced element is a custom tag, then we set the tag itself, rather than DOM
var tagOrDom = this.tag || this.dom;
...
function loopKeys(expr) { var m = expr.match(_cache[9]); return m ? { key: m[1], pos: m[2], val: _cache[0] + m[3].trim() + _cache[1] } : { val: expr.trim() } }
...
oldItems = [],
hasKeys,
isLoop = true,
isAnonymous = !__TAG_IMPL[tagName],
isVirtual = dom.tagName === 'VIRTUAL';
// parse the each expression
expr = tmpl.loopKeys(expr);
expr.isLoop = true;
if (ifExpr) { remAttr(dom, CONDITIONAL_DIRECTIVE); }
// insert a marked where the loop tags will be injected
parentNode.insertBefore(placeholder, dom);
parentNode.removeChild(dom);
...