FEATURE: Use Glimmer compiler for widget templates
Widgets can now specify a template which is precompiled using Glimmer's
AST and then converted into our virtual dom code.
Example:
```javascript
createWidget('post-link-arrow', {
template: hbs`
{{#if attrs.above}}
<a class="post-info arrow" title={{i18n "topic.jump_reply_up"}}>
{{fa-icon "arrow-up"}}
</a>
{{else}}
<a class="post-info arrow" title={{i18n "topic.jump_reply_down"}}>
{{fa-icon "arrow-down"}}
</a>
{{/if}}
`,
click() {
DiscourseURL.routeTo(this.attrs.shareUrl);
}
});
```
This commit is contained in:
@@ -27,6 +27,7 @@ module Tilt
|
||||
# timeout any eval that takes longer than 15 seconds
|
||||
ctx = MiniRacer::Context.new(timeout: 15000)
|
||||
ctx.eval("var self = this; #{File.read("#{Rails.root}/vendor/assets/javascripts/babel.js")}")
|
||||
ctx.eval(File.read(Ember::Source.bundled_path_for('ember-template-compiler.js')))
|
||||
ctx.eval("module = {}; exports = {};");
|
||||
ctx.attach("rails.logger.info", proc { |err| Rails.logger.info(err.to_s) })
|
||||
ctx.attach("rails.logger.error", proc { |err| Rails.logger.error(err.to_s) })
|
||||
@@ -36,7 +37,13 @@ module Tilt
|
||||
log: function(msg){ rails.logger.info(console.prefix + msg); },
|
||||
error: function(msg){ rails.logger.error(console.prefix + msg); }
|
||||
}
|
||||
|
||||
JS
|
||||
source = File.read("#{Rails.root}/lib/javascripts/widget-hbs-compiler.js.es6")
|
||||
js_source = ::JSON.generate(source, quirks_mode: true)
|
||||
js = ctx.eval("Babel.transform(#{js_source}, { ast: false, plugins: ['check-es2015-constants', 'transform-es2015-arrow-functions', 'transform-es2015-block-scoped-functions', 'transform-es2015-block-scoping', 'transform-es2015-classes', 'transform-es2015-computed-properties', 'transform-es2015-destructuring', 'transform-es2015-duplicate-keys', 'transform-es2015-for-of', 'transform-es2015-function-name', 'transform-es2015-literals', 'transform-es2015-object-super', 'transform-es2015-parameters', 'transform-es2015-shorthand-properties', 'transform-es2015-spread', 'transform-es2015-sticky-regex', 'transform-es2015-template-literals', 'transform-es2015-typeof-symbol', 'transform-es2015-unicode-regex'] }).code")
|
||||
ctx.eval(js)
|
||||
|
||||
ctx
|
||||
end
|
||||
|
||||
@@ -105,7 +112,11 @@ JS
|
||||
klass = self.class
|
||||
klass.protect do
|
||||
klass.v8.eval("console.prefix = 'BABEL: babel-eval: ';")
|
||||
transpiled = babel_source(source, module_name: module_name(root_path, logical_path))
|
||||
transpiled = babel_source(
|
||||
source,
|
||||
module_name: module_name(root_path, logical_path),
|
||||
filename: logical_path
|
||||
)
|
||||
@output = klass.v8.eval(transpiled)
|
||||
end
|
||||
end
|
||||
@@ -116,7 +127,14 @@ JS
|
||||
klass = self.class
|
||||
klass.protect do
|
||||
klass.v8.eval("console.prefix = 'BABEL: #{scope.logical_path}: ';")
|
||||
@output = klass.v8.eval(babel_source(data, module_name: module_name(scope.root_path, scope.logical_path)))
|
||||
|
||||
source = babel_source(
|
||||
data,
|
||||
module_name: module_name(scope.root_path, scope.logical_path),
|
||||
filename: scope.logical_path
|
||||
)
|
||||
|
||||
@output = klass.v8.eval(source)
|
||||
end
|
||||
|
||||
# For backwards compatibility with plugins, for now export the Global format too.
|
||||
@@ -156,15 +174,15 @@ JS
|
||||
end
|
||||
|
||||
def babel_source(source, opts = nil)
|
||||
|
||||
opts ||= {}
|
||||
|
||||
js_source = ::JSON.generate(source, quirks_mode: true)
|
||||
|
||||
if opts[:module_name]
|
||||
"Babel.transform(#{js_source}, { moduleId: '#{opts[:module_name]}', ast: false, presets: ['es2015'], plugins: [['transform-es2015-modules-amd', {noInterop: true}], 'transform-decorators-legacy'] }).code"
|
||||
filename = opts[:filename] || 'unknown'
|
||||
"Babel.transform(#{js_source}, { moduleId: '#{opts[:module_name]}', filename: '#{filename}', ast: false, presets: ['es2015'], plugins: [['transform-es2015-modules-amd', {noInterop: true}], 'transform-decorators-legacy', exports.WidgetHbsCompiler] }).code"
|
||||
else
|
||||
"Babel.transform(#{js_source}, { ast: false, plugins: ['check-es2015-constants', 'transform-es2015-arrow-functions', 'transform-es2015-block-scoped-functions', 'transform-es2015-block-scoping', 'transform-es2015-classes', 'transform-es2015-computed-properties', 'transform-es2015-destructuring', 'transform-es2015-duplicate-keys', 'transform-es2015-for-of', 'transform-es2015-function-name', 'transform-es2015-literals', 'transform-es2015-object-super', 'transform-es2015-parameters', 'transform-es2015-shorthand-properties', 'transform-es2015-spread', 'transform-es2015-sticky-regex', 'transform-es2015-template-literals', 'transform-es2015-typeof-symbol', 'transform-es2015-unicode-regex', 'transform-regenerator', 'transform-decorators-legacy'] }).code"
|
||||
"Babel.transform(#{js_source}, { ast: false, plugins: ['check-es2015-constants', 'transform-es2015-arrow-functions', 'transform-es2015-block-scoped-functions', 'transform-es2015-block-scoping', 'transform-es2015-classes', 'transform-es2015-computed-properties', 'transform-es2015-destructuring', 'transform-es2015-duplicate-keys', 'transform-es2015-for-of', 'transform-es2015-function-name', 'transform-es2015-literals', 'transform-es2015-object-super', 'transform-es2015-parameters', 'transform-es2015-shorthand-properties', 'transform-es2015-spread', 'transform-es2015-sticky-regex', 'transform-es2015-template-literals', 'transform-es2015-typeof-symbol', 'transform-es2015-unicode-regex', 'transform-regenerator', 'transform-decorators-legacy', exports.WidgetHbsCompiler] }).code"
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
function resolve(path) {
|
||||
return (path.indexOf('settings') === 0) ? `this.${path}` : path;
|
||||
}
|
||||
|
||||
function mustacheValue(node) {
|
||||
let path = node.path.original;
|
||||
|
||||
switch(path) {
|
||||
case 'attach':
|
||||
const widgetName = node.hash.pairs.find(p => p.key === "widget").value.value;
|
||||
return `this.attach("${widgetName}", attrs, state)`;
|
||||
break;
|
||||
case 'yield':
|
||||
return `this.attrs.contents()`;
|
||||
break;
|
||||
case 'i18n':
|
||||
let value;
|
||||
if (node.params[0].type === "StringLiteral") {
|
||||
value = `"${node.params[0].value}"`;
|
||||
} else if (node.params[0].type === "PathExpression") {
|
||||
value = node.params[0].original;
|
||||
}
|
||||
|
||||
if (value) {
|
||||
return `I18n.t(${value})`;
|
||||
}
|
||||
|
||||
break;
|
||||
case 'fa-icon':
|
||||
let icon = node.params[0].value;
|
||||
return `virtualDom.h('i.fa.fa-${icon}')`;
|
||||
break;
|
||||
default:
|
||||
return `${resolve(path)}`;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
class Compiler {
|
||||
constructor(ast) {
|
||||
this.idx = 0;
|
||||
this.ast = ast;
|
||||
}
|
||||
|
||||
newAcc() {
|
||||
return `_a${this.idx++}`;
|
||||
}
|
||||
|
||||
processNode(parentAcc, node) {
|
||||
let instructions = [];
|
||||
let innerAcc;
|
||||
|
||||
switch(node.type) {
|
||||
case "Program":
|
||||
node.body.forEach(bodyNode => {
|
||||
instructions = instructions.concat(this.processNode(parentAcc, bodyNode));
|
||||
});
|
||||
break;
|
||||
case "ElementNode":
|
||||
innerAcc = this.newAcc();
|
||||
instructions.push(`var ${innerAcc} = [];`);
|
||||
node.children.forEach(child => {
|
||||
instructions = instructions.concat(this.processNode(innerAcc, child));
|
||||
});
|
||||
|
||||
if (node.attributes.length) {
|
||||
|
||||
let attributes = [];
|
||||
node.attributes.forEach(a => {
|
||||
const name = a.name === 'class' ? 'className' : a.name;
|
||||
if (a.value.type === "MustacheStatement") {
|
||||
attributes.push(`"${name}":${mustacheValue(a.value)}`);
|
||||
} else {
|
||||
attributes.push(`"${name}":"${a.value.chars}"`);
|
||||
}
|
||||
});
|
||||
|
||||
const attrString = `{${attributes.join(', ')}}`;
|
||||
instructions.push(`${parentAcc}.push(virtualDom.h('${node.tag}', ${attrString}, ${innerAcc}));`);
|
||||
} else {
|
||||
instructions.push(`${parentAcc}.push(virtualDom.h('${node.tag}', ${innerAcc}));`);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case "TextNode":
|
||||
return `${parentAcc}.push(${JSON.stringify(node.chars)});`;
|
||||
|
||||
case "MustacheStatement":
|
||||
const value = mustacheValue(node);
|
||||
if (value) {
|
||||
instructions.push(`${parentAcc}.push(${value})`);
|
||||
}
|
||||
break;
|
||||
case "BlockStatement":
|
||||
switch(node.path.original) {
|
||||
case 'if':
|
||||
instructions.push(`if (${node.params[0].original}) {`);
|
||||
node.program.body.forEach(child => {
|
||||
instructions = instructions.concat(this.processNode(parentAcc, child));
|
||||
});
|
||||
|
||||
if (node.inverse) {
|
||||
instructions.push(`} else {`);
|
||||
node.inverse.body.forEach(child => {
|
||||
instructions = instructions.concat(this.processNode(parentAcc, child));
|
||||
});
|
||||
}
|
||||
instructions.push(`}`);
|
||||
break;
|
||||
case 'each':
|
||||
const collection = node.params[0].original;
|
||||
instructions.push(`if (${collection} && ${collection}.length) {`);
|
||||
instructions.push(` ${collection}.forEach(${node.program.blockParams[0]} => {`);
|
||||
node.program.body.forEach(child => {
|
||||
instructions = instructions.concat(this.processNode(parentAcc, child));
|
||||
});
|
||||
instructions.push(` });`);
|
||||
instructions.push('}');
|
||||
|
||||
break;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return instructions.join("\n");
|
||||
}
|
||||
|
||||
compile() {
|
||||
return this.processNode('_r', this.ast);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function compile(template) {
|
||||
const preprocessor = Ember.__loader.require('@glimmer/syntax');
|
||||
const compiled = preprocessor.preprocess(template);
|
||||
const compiler = new Compiler(compiled);
|
||||
|
||||
return `function(attrs, state) { var _r = [];\n${compiler.compile()}\nreturn _r; }`;
|
||||
}
|
||||
|
||||
exports.compile = compile;
|
||||
|
||||
function error(path, state, msg) {
|
||||
const filename = state.file.opts.filename;
|
||||
return path.replaceWithSourceString(`function() { console.error("${filename}: ${msg}"); }`);
|
||||
}
|
||||
|
||||
exports.WidgetHbsCompiler = function(babel) {
|
||||
let t = babel.types;
|
||||
return {
|
||||
visitor: {
|
||||
ImportDeclaration(path, state) {
|
||||
let node = path.node;
|
||||
if (t.isLiteral(node.source, { value: "discourse/widgets/hbs-compiler" })) {
|
||||
let first = node.specifiers && node.specifiers[0];
|
||||
if (!t.isImportDefaultSpecifier(first)) {
|
||||
let input = state.file.code;
|
||||
let usedImportStatement = input.slice(node.start, node.end);
|
||||
let msg = `Only \`import hbs from 'discourse/widgets/hbs-compiler'\` is supported. You used: \`${usedImportStatement}\``;
|
||||
throw path.buildCodeFrameError(msg);
|
||||
}
|
||||
|
||||
state.importId = state.importId || path.scope.generateUidIdentifierBasedOnNode(path.node.id);
|
||||
path.scope.rename(first.local.name, state.importId.name);
|
||||
path.remove();
|
||||
}
|
||||
},
|
||||
|
||||
TaggedTemplateExpression(path, state) {
|
||||
if (!state.importId) { return; }
|
||||
|
||||
let tagPath = path.get('tag');
|
||||
if (tagPath.node.name !== state.importId.name) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (path.node.quasi.expressions.length) {
|
||||
return error(path, state, "placeholders inside a tagged template string are not supported");
|
||||
}
|
||||
|
||||
let template = path.node.quasi.quasis.map(quasi => quasi.value.cooked).join('');
|
||||
|
||||
try {
|
||||
path.replaceWithSourceString(compile(template));
|
||||
} catch(e) {
|
||||
return error(path, state, e.toString());
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user