haml.js
This file
Path
lib/support/haml.js
395 lines · 10.1 KiB · JavaScript
Last changed by
Hacking haml-js to work with locals and Expressvisionmediabefore adoption46b3e23
History of this fileTake it
Started haml-js supportvisionmediabefore adoption39719af
lines 1–63why, one step back1/* ex:ts=2:et: */2/*jslint bitwise: true, browser: true, eqeqeq: true, evil: true, immed: true, newcap: true,3 nomen: true, plusplus: true, regexp: true, undef: true, white: true, indent: 2 */4/*globals */5 6function Haml() {}7 8Haml.to_html = function (json) {9 10 if (typeof json === 'string') {11 12 if (json.substr(0, 3) === '!!!') {13 switch (json.substr(4).toLowerCase()) {14 case 'xml':15 return "<?xml version='1.0' encoding='utf-8' ?>\n";16 case '':17 return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n';18 case '1.1':19 return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">\n';20 case 'strict':21 return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n';22 }23 }24 return json;25 }26 if (typeof json === 'object' && json.length !== undefined) {27 if (typeof json[0] === 'object')28 {29 if (json[0].tag !== undefined) {30 return (function () {31 var tag, element, html, attributes;32 element = json.shift();33 tag = element.tag;34 html = tag;35 for (var key in element) {36 if (element.hasOwnProperty(key) && key !== 'tag') {37 html += " " + key + "=\"" + element[key].38 replace("&", "&").39 replace("<", "<").40 replace(">", ">").41 replace("\"", """) + "\"";42 }43 }44 if (json.length === 0 && (tag === "link" || tag === 'br' || tag === 'input')) {45 return "\n<" + html + " />\n";46 }47 return "\n<" + html + ">" + Haml.to_html(json) + "</" + tag + ">\n";48 }());49 }50 if (json[0].plugin !== undefined) {51 switch (json.shift().plugin) {52 case "javascript":53 return '\n<script type="text/javascript">\n//<![CDATA[\n ' + json[0].split("\n").join("\n ") + "\n//]]>\n</script>\n";54 case "css":55 return '\n<style type="text/css">\n ' + json[0].split("\n").join("\n ") + "\n</style>\n";56 }57 }58 }59 return json.map(Haml.to_html).join('');60 }61 return JSON.stringify(json);62}63 Hacking haml-js to work with locals and Expressvisionmediabefore adoption46b3e23
line 64why, one step back64Haml.parse = function (text, locals) {Started haml-js supportvisionmediabefore adoption39719af
lines 65–74why, one step back65 66 var empty_regex = new RegExp("^[ \t]*$"),67 indent_regex = new RegExp("^ *"),68 element_regex = new RegExp("^(?::[a-z]+|(?:[%][a-z][a-z0-9]*)?(?:[#.][a-z0-9_-]+)*)", "i"),69 scope = this,70 haml, element, stack, indent, buffer, old_indent, mode, last_insert;71 72 // Sortof an instance_eval for Javascript73 function instance_eval(input) {74 var block;Hacking haml-js to work with locals and Expressvisionmediabefore adoption46b3e23
line 75why, one step back75 block = function () { with(scope, locals || {}) { return eval("(" + input + ")"); } };Started haml-js supportvisionmediabefore adoption39719af
lines 76–391why, one step back76 return block.call(scope);77 }78 79 function process_embedded_code(string) {80 if (typeof string !== 'string') {81 return string;82 }83 var matches = string.match(/#{([^}]*)}/g);84 if (matches) {85 matches.forEach(function (match) {86 var pair = match.match(/#{([^}]*)}/);87 string = string.replace(pair[0], instance_eval(pair[1]));88 })89 }90 return string;91 }92 93 function flush_buffer() {94 if (buffer.length > 0) {95 mode = "NORMAL";96 element.push(process_embedded_code(buffer.join("\n")));97 buffer = [];98 }99 }100 101 function parse_push() {102 stack.push({element: element, mode: mode});103 var new_element = [];104 mode = "NORMAL";105 element.push(new_element);106 element = new_element;107 }108 109 function parse_pop() {110 var last = stack.pop();111 112 if (element.length === 1) {113 if (typeof element[0] === "string") {114 if (element[0].match(element_regex)[0].length === 0) {115 // Collapse arrays with single string literal116 last.element[last.element.length - 1] = element[0];117 }118 }119 }120 element = last.element;121 mode = last.mode;122 }123 124 function get_indent(line) {125 if (line === undefined) {126 return 0;127 }128 var i = line.match(indent_regex);129 return i[0].length / 2;130 }131 132 function parse_attribs(line) {133 // Parse the attribute block using a state machine134 if (!(line.length > 0 && line.charAt(0) === '{')) {135 return line;136 }137 var l = line.length;138 var count = 1;139 var quote = false;140 var skip = false;141 for (var i = 1; count > 0; i += 1) {142 143 // If we reach the end of the line, then there is a problem144 if (i > l) {145 throw "Malformed attribute block";146 }147 148 var c = line.charAt(i);149 if (skip) {150 skip = false;151 } else {152 if (quote) {153 if (c === '\\') {154 skip = true;155 }156 if (c === quote) {157 quote = false;158 }159 } else {160 if (c === '"' || c === "'") {161 quote = c;162 }163 if (c === '{') {164 count += 1;165 }166 if (c === '}') {167 count -= 1;168 }169 }170 }171 }172 var block = line.substr(0, i);173 (function () {174 element.push(instance_eval(block))175 }.call(this));176 return line.substr(i);177 }178 179 function parse_content(line) {180 // Strip off leading whitespace181 line = line.replace(indent_regex, '');182 183 // Ignore blank lines184 if (line.length === 0) {185 return;186 }187 188 if (mode === 'ELEMENT') {189 parse_pop();190 }191 192 switch (line.charAt(0)) {193 case '/':194 break;195 case '=':196 (function () {197 buffer.push(instance_eval(line.substr(1)));198 }.call(this));199 break;200 case "\\":201 buffer.push(line.substr(1));202 break;203 default:204 buffer.push(line);205 break;206 }207 }208 209 function parse_element(line, selector) {210 211 flush_buffer();212 if (element.length > 0) {213 if (mode === 'ELEMENT') {214 parse_pop();215 }216 parse_push();217 }218 mode = 'ELEMENT';219 220 var classes = selector.match(/\.[^\.#]+/g),221 ids = selector.match(/#[^\.#]+/g),222 tag = selector.match(/^%([^\.#]+)/g),223 plugin = selector.match(/^:([^\.#]+)/g);224 tag = tag ? tag[0].substr(1) : (plugin ? null : 'div');225 plugin = plugin ? plugin[0].substr(1) : null;226 227 line = parse_attribs.call(this, line.substr(selector.length));228 229 var attrs;230 if (typeof element[element.length - 1] === "object") {231 attrs = element[element.length - 1];232 } else {233 attrs = {};234 element.push(attrs);235 }236 if (tag) {237 attrs.tag = tag;238 }239 if (plugin) {240 attrs.plugin = plugin;241 }242 if (ids) {243 for (var i = 0, l = ids.length; i < l; i += 1) {244 ids[i] = ids[i].substr(1);245 }246 if (attrs.id) {247 ids.push(attrs.id);248 }249 attrs.id = ids.join(" ");250 }251 if (classes) {252 for (var i = 0, l = classes.length; i < l; i += 1) {253 classes[i] = classes[i].substr(1);254 }255 if (attrs['class']) {256 classes.push(attrs['class']);257 }258 attrs['class'] = classes.join(" ");259 }260 261 if (selector.charAt(0) === ':') {262 mode = 'RAW';263 } else {264 if (!line.match(empty_regex)) {265 parse_push();266 parse_content.call(this, line, true);267 flush_buffer();268 parse_pop();269 }270 }271 }272 273 function process_plugins() {274 var contents, i;275 switch (element[0].plugin) {276 case 'if':277 var condition = element[0].condition;278 contents = element[1];279 for (i in element) {280 if (element.hasOwnProperty(i)) {281 delete element[i];282 }283 }284 if (condition) {285 var new_element = Haml.parse.call(this, contents);286 for (i in new_element) {287 if (new_element.hasOwnProperty(i)) {288 element[i] = new_element[i];289 }290 }291 element.length = new_element.length;292 }293 break;294 case 'foreach':295 var array, key, value, key_name, value_name;296 array = element[0].array;297 key_name = element[0].key;298 value_name = element[0].value;299 contents = element[1];300 for (i in element) {301 if (element.hasOwnProperty(i)) {302 delete element[i];303 }304 }305 element.length = 0;306 for (key in array) {307 if (array.hasOwnProperty(key)) {308 value = array[key];309 this[key_name] = key;310 this[value_name] = value;311 element.push(Haml.parse.call(this, contents));312 }313 }314 break;315 }316 }317 318 haml = [];319 element = haml;320 stack = [];321 buffer = [];322 mode = 'NORMAL';323 parse_push(); // Prime the pump so we can have multiple root elements324 indent = 0;325 old_indent = indent;326 327 var lines = text.split("\n"),328 line, line_index, line_count;329 330 line_count = lines.length;331 for (line_index = 0; line_index <= line_count; line_index += 1) {332 line = lines[line_index];333 334 switch (mode) {335 case 'ELEMENT':336 case 'NORMAL':337 338 // Do indentation339 indent = get_indent(line);340 if (indent === old_indent + 1) {341 parse_push();342 old_indent = indent;343 }344 while (indent < old_indent) {345 flush_buffer();346 parse_pop();347 old_indent -= 1;348 }349 350 if (line === undefined) {351 continue;352 }353 354 line = line.substr(indent * 2);355 356 // Pass doctype commands through as is357 if (line.substr(0, 3) === '!!!') {358 element.push(line);359 continue;360 }361 362 // Check for special element characters363 var match = line.match(element_regex);364 if (match && match[0].length > 0) {365 parse_element.call(this, line, match[0]);366 } else {367 parse_content.call(this, line);368 }369 break;370 case 'RAW':371 if (get_indent(line) <= indent) {372 flush_buffer();373 process_plugins.call(this);374 mode = "ELEMENT";375 line_index -= 1;376 continue;377 }378 line = line.substr((indent + 1) * 2);379 buffer.push(line);380 break;381 }382 }383 384 if (haml.length === 1 && typeof haml[0] !== 'string') {385 haml = haml[0];386 }387 return haml;388};389 390exports.render = function(content, options) {391 options = options || {}Hacking haml-js to work with locals and Expressvisionmediabefore adoption46b3e23
lines 392–393why, one step back392 var json = Haml.parse.call(options.context || GLOBAL, content, options.locals)393 return Haml.to_html(json).replace('\n\n', '\n')Started haml-js supportvisionmediabefore adoption39719af
lines 394–395why, one step back394}395