From: Koeun Choi Date: Thu, 21 Feb 2013 08:14:32 +0000 (+0900) Subject: build-tools : upgrade less to v1.3.3 X-Git-Tag: accepted/tizen_2.1/20130425.023924~7^2~44 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=ffdeabe22ba767c4b4de601a551c1fe18a71b568;p=framework%2Fweb%2Fweb-ui-fw.git build-tools : upgrade less to v1.3.3 Change-Id: I277543bad8301affac58c678811373b1e04190a5 --- diff --git a/build-tools/README.txt b/build-tools/README.txt index 0efd403..cf716fd 100644 --- a/build-tools/README.txt +++ b/build-tools/README.txt @@ -1,6 +1,7 @@ Tizen Web UI Framework includes following tools used on build; * less (http://lesscss.org) + * Version: 1.3.3 * Description: A dynamic CSS language compiler based on node.js * Mods * Support rem unit (build-tools/lib/less/parser.js) diff --git a/build-tools/lib/less/browser.js b/build-tools/lib/less/browser.js index cba4c3b..e00ff27 100644 --- a/build-tools/lib/less/browser.js +++ b/build-tools/lib/less/browser.js @@ -2,10 +2,7 @@ // browser.js - client-side engine // -var isFileProtocol = (location.protocol === 'file:' || - location.protocol === 'chrome:' || - location.protocol === 'chrome-extension:' || - location.protocol === 'resource:'); +var isFileProtocol = /^(file|chrome(-extension)?|resource|qrc|app):/.test(location.protocol); less.env = less.env || (location.hostname == '127.0.0.1' || location.hostname == '0.0.0.0' || @@ -20,42 +17,64 @@ less.env = less.env || (location.hostname == '127.0.0.1' || // doesn't start loading before the stylesheets are parsed. // Setting this to `true` can result in flickering. // -less.async = false; +less.async = less.async || false; +less.fileAsync = less.fileAsync || false; // Interval between watch polls less.poll = less.poll || (isFileProtocol ? 1000 : 1500); +//Setup user functions +if (less.functions) { + for(var func in less.functions) { + less.tree.functions[func] = less.functions[func]; + } +} + +var dumpLineNumbers = /!dumpLineNumbers:(comments|mediaquery|all)/.exec(location.hash); +if (dumpLineNumbers) { + less.dumpLineNumbers = dumpLineNumbers[1]; +} + // // Watch mode // -less.watch = function () { return this.watchMode = true }; -less.unwatch = function () { return this.watchMode = false }; +less.watch = function () { + if (!less.watchMode ){ + less.env = 'development'; + initRunningMode(); + } + return this.watchMode = true +}; -if (less.env === 'development') { - less.optimization = 0; +less.unwatch = function () {clearInterval(less.watchTimer); return this.watchMode = false; }; + +function initRunningMode(){ + if (less.env === 'development') { + less.optimization = 0; + less.watchTimer = setInterval(function () { + if (less.watchMode) { + loadStyleSheets(function (e, root, _, sheet, env) { + if (root) { + createCSS(root.toCSS(), sheet, env.lastModified); + } + }); + } + }, less.poll); + } else { + less.optimization = 3; + } +} - if (/!watch/.test(location.hash)) { - less.watch(); - } - less.watchTimer = setInterval(function () { - if (less.watchMode) { - loadStyleSheets(function (root, sheet, env) { - if (root) { - createCSS(root.toCSS(), sheet, env.lastModified); - } - }); - } - }, less.poll); -} else { - less.optimization = 3; +if (/!watch/.test(location.hash)) { + less.watch(); } -var cache; +var cache = null; -try { - cache = (typeof(window.localStorage) === 'undefined') ? null : window.localStorage; -} catch (_) { - cache = null; +if (less.env != 'development') { + try { + cache = (typeof(window.localStorage) === 'undefined') ? null : window.localStorage; + } catch (_) {} } // @@ -73,12 +92,27 @@ for (var i = 0; i < links.length; i++) { } } +// +// With this function, it's possible to alter variables and re-render +// CSS without reloading less-files +// +var session_cache = ''; +less.modifyVars = function(record) { + var str = session_cache; + for (name in record) { + str += ((name.slice(0,1) === '@')? '' : '@') + name +': '+ + ((record[name].slice(-1) === ';')? record[name] : record[name] +';'); + } + new(less.Parser)().parse(str, function (e, root) { + createCSS(root.toCSS(), less.sheets[less.sheets.length - 1]); + }); +}; less.refresh = function (reload) { var startTime, endTime; startTime = endTime = new(Date); - loadStyleSheets(function (root, sheet, env) { + loadStyleSheets(function (e, root, _, sheet, env) { if (env.local) { log("loading " + sheet.href + " from cache."); } else { @@ -100,15 +134,18 @@ function loadStyles() { var styles = document.getElementsByTagName('style'); for (var i = 0; i < styles.length; i++) { if (styles[i].type.match(typePattern)) { - new(less.Parser)().parse(styles[i].innerHTML || '', function (e, tree) { + new(less.Parser)({ + filename: document.location.href.replace(/#.*$/, ''), + dumpLineNumbers: less.dumpLineNumbers + }).parse(styles[i].innerHTML || '', function (e, tree) { var css = tree.toCSS(); var style = styles[i]; - try { + style.type = 'text/css'; + if (style.styleSheet) { + style.styleSheet.cssText = css; + } else { style.innerHTML = css; - } catch (_) { - style.styleSheets.cssText = css; } - style.type = 'text/css'; }); } } @@ -120,40 +157,139 @@ function loadStyleSheets(callback, reload) { } } +function pathDiff(url, baseUrl) { + // diff between two paths to create a relative path + + var urlParts = extractUrlParts(url), + baseUrlParts = extractUrlParts(baseUrl), + i, max, urlDirectories, baseUrlDirectories, diff = ""; + if (urlParts.hostPart !== baseUrlParts.hostPart) { + return ""; + } + max = Math.max(baseUrlParts.directories.length, urlParts.directories.length); + for(i = 0; i < max; i++) { + if (baseUrlParts.directories[i] !== urlParts.directories[i]) { break; } + } + baseUrlDirectories = baseUrlParts.directories.slice(i); + urlDirectories = urlParts.directories.slice(i); + for(i = 0; i < baseUrlDirectories.length-1; i++) { + diff += "../"; + } + for(i = 0; i < urlDirectories.length-1; i++) { + diff += urlDirectories[i] + "/"; + } + return diff; +} + +function extractUrlParts(url, baseUrl) { + // urlParts[1] = protocol&hostname || / + // urlParts[2] = / if path relative to host base + // urlParts[3] = directories + // urlParts[4] = filename + // urlParts[5] = parameters + + var urlPartsRegex = /^((?:[a-z-]+:)?\/\/(?:[^\/\?#]+\/)|([\/\\]))?((?:[^\/\\\?#]+[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/, + urlParts = url.match(urlPartsRegex), + returner = {}, directories = [], i, baseUrlParts; + + if (!urlParts) { + throw new Error("Could not parse sheet href - '"+url+"'"); + } + + // Stylesheets in IE don't always return the full path + if (!urlParts[1] || urlParts[2]) { + baseUrlParts = baseUrl.match(urlPartsRegex); + if (!baseUrlParts) { + throw new Error("Could not parse page url - '"+baseUrl+"'"); + } + urlParts[1] = baseUrlParts[1]; + if (!urlParts[2]) { + urlParts[3] = baseUrlParts[3] + urlParts[3]; + } + } + + if (urlParts[3]) { + directories = urlParts[3].replace("\\", "/").split("/"); + + for(i = 0; i < directories.length; i++) { + if (directories[i] === ".." && i > 0) { + directories.splice(i-1, 2); + i -= 2; + } + } + } + + returner.hostPart = urlParts[1]; + returner.directories = directories; + returner.path = urlParts[1] + directories.join("/"); + returner.fileUrl = returner.path + (urlParts[4] || ""); + returner.url = returner.fileUrl + (urlParts[5] || ""); + return returner; +} + function loadStyleSheet(sheet, callback, reload, remaining) { - var url = window.location.href.replace(/[#?].*$/, ''); - var href = sheet.href.replace(/\?.*$/, ''); + // sheet may be set to the stylesheet for the initial load or a collection of properties including + // some env variables for imports + var contents = sheet.contents || {}; + var files = sheet.files || {}; + var hrefParts = extractUrlParts(sheet.href, window.location.href); + var href = hrefParts.url; var css = cache && cache.getItem(href); var timestamp = cache && cache.getItem(href + ':timestamp'); var styles = { css: css, timestamp: timestamp }; + var rootpath; - // Stylesheets in IE don't always return the full path - if (! /^(https?|file):/.test(href)) { - if (href.charAt(0) == "/") { - href = window.location.protocol + "//" + window.location.host + href; + if (less.relativeUrls) { + if (less.rootpath) { + if (sheet.entryPath) { + rootpath = extractUrlParts(less.rootpath + pathDiff(hrefParts.path, sheet.entryPath)).path; + } else { + rootpath = less.rootpath; + } + } else { + rootpath = hrefParts.path; + } + } else { + if (less.rootpath) { + rootpath = less.rootpath; } else { - href = url.slice(0, url.lastIndexOf('/') + 1) + href; + if (sheet.entryPath) { + rootpath = sheet.entryPath; + } else { + rootpath = hrefParts.path; + } } } - xhr(sheet.href, sheet.type, function (data, lastModified) { + xhr(href, sheet.type, function (data, lastModified) { + // Store data this session + session_cache += data.replace(/@import .+?;/ig, ''); + if (!reload && styles && lastModified && (new(Date)(lastModified).valueOf() === new(Date)(styles.timestamp).valueOf())) { // Use local copy createCSS(styles.css, sheet); - callback(null, sheet, { local: true, remaining: remaining }); + callback(null, null, data, sheet, { local: true, remaining: remaining }, href); } else { // Use remote copy (re-parse) try { + contents[href] = data; // Updating top importing parser content cache new(less.Parser)({ optimization: less.optimization, - paths: [href.replace(/[\w\.-]+$/, '')], - mime: sheet.type + paths: [hrefParts.path], + entryPath: sheet.entryPath || hrefParts.path, + mime: sheet.type, + filename: href, + rootpath: rootpath, + relativeUrls: sheet.relativeUrls, + contents: contents, // Passing top importing parser content cache ref down. + files: files, + dumpLineNumbers: less.dumpLineNumbers }).parse(data, function (e, root) { if (e) { return error(e, href) } try { - callback(root, sheet, { local: false, lastModified: lastModified, remaining: remaining }); + callback(e, root, data, sheet, { local: false, lastModified: lastModified, remaining: remaining }, href); removeNode(document.getElementById('less-error-message:' + extractId(href))); } catch (e) { error(e, href); @@ -171,8 +307,7 @@ function loadStyleSheet(sheet, callback, reload, remaining) { function extractId(href) { return href.replace(/^[a-z]+:\/\/?[^\/]+/, '' ) // Remove protocol & domain .replace(/^\//, '' ) // Remove root / - .replace(/\?.*$/, '' ) // Remove query - .replace(/\.[^\.\/]+$/, '' ) // Remove file extension + .replace(/\.[a-zA-Z]+$/, '' ) // Remove simple extension .replace(/[^\.\w-]+/g, '-') // Replace illegal characters .replace(/\./g, ':'); // Replace dots with colons(for valid id) } @@ -181,7 +316,7 @@ function createCSS(styles, sheet, lastModified) { var css; // Strip the query-string - var href = sheet.href ? sheet.href.replace(/\?.*$/, '') : ''; + var href = sheet.href || ''; // If there is no title set, use the filename, minus the extension var id = 'less:' + (sheet.title || extractId(href)); @@ -190,9 +325,10 @@ function createCSS(styles, sheet, lastModified) { if ((css = document.getElementById(id)) === null) { css = document.createElement('style'); css.type = 'text/css'; - css.media = sheet.media || 'screen'; + if( sheet.media ){ css.media = sheet.media; } css.id = id; - document.getElementsByTagName('head')[0].appendChild(css); + var nextEl = sheet && sheet.nextSibling || null; + (nextEl || document.getElementsByTagName('head')[0]).parentNode.insertBefore(css, nextEl); } if (css.styleSheet) { // IE @@ -216,14 +352,19 @@ function createCSS(styles, sheet, lastModified) { // Don't update the local store if the file wasn't modified if (lastModified && cache) { log('saving ' + href + ' to cache.'); - cache.setItem(href, styles); - cache.setItem(href + ':timestamp', lastModified); + try { + cache.setItem(href, styles); + cache.setItem(href + ':timestamp', lastModified); + } catch(e) { + //TODO - could do with adding more robust error handling + log('failed to save'); + } } } function xhr(url, type, callback, errback) { var xhr = getXMLHttpRequest(); - var async = isFileProtocol ? false : less.async; + var async = isFileProtocol ? less.fileAsync : less.async; if (typeof(xhr.overrideMimeType) === 'function') { xhr.overrideMimeType('text/css'); @@ -232,8 +373,8 @@ function xhr(url, type, callback, errback) { xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5'); xhr.send(null); - if (isFileProtocol) { - if (xhr.status === 0) { + if (isFileProtocol && !less.fileAsync) { + if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) { callback(xhr.responseText); } else { errback(xhr.status, url); @@ -281,29 +422,33 @@ function log(str) { function error(e, href) { var id = 'less-error-message:' + extractId(href); - - var template = [''].join('\n'); - - var elem = document.createElement('div'), timer, content; + var template = '
  • {content}
  • '; + var elem = document.createElement('div'), timer, content, error = []; + var filename = e.filename || href; + var filenameNoPath = filename.match(/([^\/]+(\?.*)?)$/)[1]; elem.id = id; elem.className = "less-error-message"; content = '

    ' + (e.message || 'There is an error in your .less file') + - '

    ' + '

    ' + href + " "; + '' + '

    in ' + filenameNoPath + " "; - if (e.extract) { + var errorline = function (e, i, classname) { + if (e.extract[i]) { + error.push(template.replace(/\{line\}/, parseInt(e.line) + (i - 1)) + .replace(/\{class\}/, classname) + .replace(/\{content\}/, e.extract[i])); + } + }; + + if (e.stack) { + content += '
    ' + e.stack.split('\n').slice(1).join('
    '); + } else if (e.extract) { + errorline(e, 0, ''); + errorline(e, 1, 'line'); + errorline(e, 2, ''); content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':

    ' + - template.replace(/\[(-?\d)\]/g, function (_, i) { - return (parseInt(e.line) + parseInt(i)) || ''; - }).replace(/\{(\d)\}/g, function (_, i) { - return e.extract[parseInt(i)] || ''; - }).replace(/\{current\}/, e.extract[1].slice(0, e.column) + '' + - e.extract[1].slice(e.column) + ''); + ''; } elem.innerHTML = content; @@ -322,13 +467,13 @@ function error(e, href) { 'color: #cc7777;', '}', '.less-error-message pre {', - 'color: #ee4444;', + 'color: #dd6666;', 'padding: 4px 0;', 'margin: 0;', 'display: inline-block;', '}', - '.less-error-message pre.ctx {', - 'color: #dd4444;', + '.less-error-message pre.line {', + 'color: #ff0000;', '}', '.less-error-message h3 {', 'font-size: 20px;', @@ -372,4 +517,3 @@ function error(e, href) { }, 10); } } - diff --git a/build-tools/lib/less/colors.js b/build-tools/lib/less/colors.js new file mode 100644 index 0000000..b417af6 --- /dev/null +++ b/build-tools/lib/less/colors.js @@ -0,0 +1,152 @@ +(function (tree) { + tree.colors = { + 'aliceblue':'#f0f8ff', + 'antiquewhite':'#faebd7', + 'aqua':'#00ffff', + 'aquamarine':'#7fffd4', + 'azure':'#f0ffff', + 'beige':'#f5f5dc', + 'bisque':'#ffe4c4', + 'black':'#000000', + 'blanchedalmond':'#ffebcd', + 'blue':'#0000ff', + 'blueviolet':'#8a2be2', + 'brown':'#a52a2a', + 'burlywood':'#deb887', + 'cadetblue':'#5f9ea0', + 'chartreuse':'#7fff00', + 'chocolate':'#d2691e', + 'coral':'#ff7f50', + 'cornflowerblue':'#6495ed', + 'cornsilk':'#fff8dc', + 'crimson':'#dc143c', + 'cyan':'#00ffff', + 'darkblue':'#00008b', + 'darkcyan':'#008b8b', + 'darkgoldenrod':'#b8860b', + 'darkgray':'#a9a9a9', + 'darkgrey':'#a9a9a9', + 'darkgreen':'#006400', + 'darkkhaki':'#bdb76b', + 'darkmagenta':'#8b008b', + 'darkolivegreen':'#556b2f', + 'darkorange':'#ff8c00', + 'darkorchid':'#9932cc', + 'darkred':'#8b0000', + 'darksalmon':'#e9967a', + 'darkseagreen':'#8fbc8f', + 'darkslateblue':'#483d8b', + 'darkslategray':'#2f4f4f', + 'darkslategrey':'#2f4f4f', + 'darkturquoise':'#00ced1', + 'darkviolet':'#9400d3', + 'deeppink':'#ff1493', + 'deepskyblue':'#00bfff', + 'dimgray':'#696969', + 'dimgrey':'#696969', + 'dodgerblue':'#1e90ff', + 'firebrick':'#b22222', + 'floralwhite':'#fffaf0', + 'forestgreen':'#228b22', + 'fuchsia':'#ff00ff', + 'gainsboro':'#dcdcdc', + 'ghostwhite':'#f8f8ff', + 'gold':'#ffd700', + 'goldenrod':'#daa520', + 'gray':'#808080', + 'grey':'#808080', + 'green':'#008000', + 'greenyellow':'#adff2f', + 'honeydew':'#f0fff0', + 'hotpink':'#ff69b4', + 'indianred':'#cd5c5c', + 'indigo':'#4b0082', + 'ivory':'#fffff0', + 'khaki':'#f0e68c', + 'lavender':'#e6e6fa', + 'lavenderblush':'#fff0f5', + 'lawngreen':'#7cfc00', + 'lemonchiffon':'#fffacd', + 'lightblue':'#add8e6', + 'lightcoral':'#f08080', + 'lightcyan':'#e0ffff', + 'lightgoldenrodyellow':'#fafad2', + 'lightgray':'#d3d3d3', + 'lightgrey':'#d3d3d3', + 'lightgreen':'#90ee90', + 'lightpink':'#ffb6c1', + 'lightsalmon':'#ffa07a', + 'lightseagreen':'#20b2aa', + 'lightskyblue':'#87cefa', + 'lightslategray':'#778899', + 'lightslategrey':'#778899', + 'lightsteelblue':'#b0c4de', + 'lightyellow':'#ffffe0', + 'lime':'#00ff00', + 'limegreen':'#32cd32', + 'linen':'#faf0e6', + 'magenta':'#ff00ff', + 'maroon':'#800000', + 'mediumaquamarine':'#66cdaa', + 'mediumblue':'#0000cd', + 'mediumorchid':'#ba55d3', + 'mediumpurple':'#9370d8', + 'mediumseagreen':'#3cb371', + 'mediumslateblue':'#7b68ee', + 'mediumspringgreen':'#00fa9a', + 'mediumturquoise':'#48d1cc', + 'mediumvioletred':'#c71585', + 'midnightblue':'#191970', + 'mintcream':'#f5fffa', + 'mistyrose':'#ffe4e1', + 'moccasin':'#ffe4b5', + 'navajowhite':'#ffdead', + 'navy':'#000080', + 'oldlace':'#fdf5e6', + 'olive':'#808000', + 'olivedrab':'#6b8e23', + 'orange':'#ffa500', + 'orangered':'#ff4500', + 'orchid':'#da70d6', + 'palegoldenrod':'#eee8aa', + 'palegreen':'#98fb98', + 'paleturquoise':'#afeeee', + 'palevioletred':'#d87093', + 'papayawhip':'#ffefd5', + 'peachpuff':'#ffdab9', + 'peru':'#cd853f', + 'pink':'#ffc0cb', + 'plum':'#dda0dd', + 'powderblue':'#b0e0e6', + 'purple':'#800080', + 'red':'#ff0000', + 'rosybrown':'#bc8f8f', + 'royalblue':'#4169e1', + 'saddlebrown':'#8b4513', + 'salmon':'#fa8072', + 'sandybrown':'#f4a460', + 'seagreen':'#2e8b57', + 'seashell':'#fff5ee', + 'sienna':'#a0522d', + 'silver':'#c0c0c0', + 'skyblue':'#87ceeb', + 'slateblue':'#6a5acd', + 'slategray':'#708090', + 'slategrey':'#708090', + 'snow':'#fffafa', + 'springgreen':'#00ff7f', + 'steelblue':'#4682b4', + 'tan':'#d2b48c', + 'teal':'#008080', + 'thistle':'#d8bfd8', + 'tomato':'#ff6347', + // 'transparent':'rgba(0,0,0,0)', + 'turquoise':'#40e0d0', + 'violet':'#ee82ee', + 'wheat':'#f5deb3', + 'white':'#ffffff', + 'whitesmoke':'#f5f5f5', + 'yellow':'#ffff00', + 'yellowgreen':'#9acd32' + }; +})(require('./tree')); diff --git a/build-tools/lib/less/functions.js b/build-tools/lib/less/functions.js index fc9d86f..b077123 100644 --- a/build-tools/lib/less/functions.js +++ b/build-tools/lib/less/functions.js @@ -5,8 +5,8 @@ tree.functions = { return this.rgba(r, g, b, 1.0); }, rgba: function (r, g, b, a) { - var rgb = [r, g, b].map(function (c) { return number(c) }), - a = number(a); + var rgb = [r, g, b].map(function (c) { return scaled(c, 256); }); + a = number(a); return new(tree.Color)(rgb, a); }, hsl: function (h, s, l) { @@ -32,6 +32,36 @@ tree.functions = { else return m1; } }, + + hsv: function(h, s, v) { + return this.hsva(h, s, v, 1.0); + }, + + hsva: function(h, s, v, a) { + h = ((number(h) % 360) / 360) * 360; + s = number(s); v = number(v); a = number(a); + + var i, f; + i = Math.floor((h / 60) % 6); + f = (h / 60) - i; + + var vs = [v, + v * (1 - s), + v * (1 - f * s), + v * (1 - (1 - f) * s)]; + var perm = [[0, 3, 1], + [2, 0, 1], + [1, 0, 3], + [1, 2, 0], + [3, 1, 0], + [0, 1, 2]]; + + return this.rgba(vs[perm[i][0]] * 255, + vs[perm[i][1]] * 255, + vs[perm[i][2]] * 255, + a); + }, + hue: function (color) { return new(tree.Dimension)(Math.round(color.toHSL().h)); }, @@ -41,9 +71,24 @@ tree.functions = { lightness: function (color) { return new(tree.Dimension)(Math.round(color.toHSL().l * 100), '%'); }, + red: function (color) { + return new(tree.Dimension)(color.rgb[0]); + }, + green: function (color) { + return new(tree.Dimension)(color.rgb[1]); + }, + blue: function (color) { + return new(tree.Dimension)(color.rgb[2]); + }, alpha: function (color) { return new(tree.Dimension)(color.toHSL().a); }, + luma: function (color) { + return new(tree.Dimension)(Math.round((0.2126 * (color.rgb[0]/255) + + 0.7152 * (color.rgb[1]/255) + + 0.0722 * (color.rgb[2]/255)) * + color.alpha * 100), '%'); + }, saturate: function (color, amount) { var hsl = color.toHSL(); @@ -106,6 +151,9 @@ tree.functions = { // http://sass-lang.com // mix: function (color1, color2, weight) { + if (!weight) { + weight = new(tree.Dimension)(50); + } var p = weight.value / 100.0; var w = p * 2 - 1; var a = color1.toHSL().a - color2.toHSL().a; @@ -124,6 +172,29 @@ tree.functions = { greyscale: function (color) { return this.desaturate(color, new(tree.Dimension)(100)); }, + contrast: function (color, dark, light, threshold) { + // filter: contrast(3.2); + // should be kept as is, so check for color + if (!color.rgb) { + return null; + } + if (typeof light === 'undefined') { + light = this.rgba(255, 255, 255, 1.0); + } + if (typeof dark === 'undefined') { + dark = this.rgba(0, 0, 0, 1.0); + } + if (typeof threshold === 'undefined') { + threshold = 0.43; + } else { + threshold = threshold.value; + } + if (((0.2126 * (color.rgb[0]/255) + 0.7152 * (color.rgb[1]/255) + 0.0722 * (color.rgb[2]/255)) * color.alpha) < threshold) { + return light; + } else { + return dark; + } + }, e: function (str) { return new(tree.Anonymous)(str instanceof tree.JavaScript ? str.evaluated : str); }, @@ -143,26 +214,147 @@ tree.functions = { str = str.replace(/%%/g, '%'); return new(tree.Quoted)('"' + str + '"', str); }, - round: function (n) { + unit: function (val, unit) { + return new(tree.Dimension)(val.value, unit ? unit.toCSS() : ""); + }, + round: function (n, f) { + var fraction = typeof(f) === "undefined" ? 0 : f.value; + return this._math(function(num) { return num.toFixed(fraction); }, n); + }, + ceil: function (n) { + return this._math(Math.ceil, n); + }, + floor: function (n) { + return this._math(Math.floor, n); + }, + _math: function (fn, n) { if (n instanceof tree.Dimension) { - return new(tree.Dimension)(Math.round(number(n)), n.unit); + return new(tree.Dimension)(fn(parseFloat(n.value)), n.unit); } else if (typeof(n) === 'number') { - return Math.round(n); + return fn(n); } else { - throw { - error: "RuntimeError", - message: "math functions take numbers as parameters" - }; + throw { type: "Argument", message: "argument must be a number" }; } }, argb: function (color) { return new(tree.Anonymous)(color.toARGB()); + }, + percentage: function (n) { + return new(tree.Dimension)(n.value * 100, '%'); + }, + color: function (n) { + if (n instanceof tree.Quoted) { + return new(tree.Color)(n.value.slice(1)); + } else { + throw { type: "Argument", message: "argument must be a string" }; + } + }, + iscolor: function (n) { + return this._isa(n, tree.Color); + }, + isnumber: function (n) { + return this._isa(n, tree.Dimension); + }, + isstring: function (n) { + return this._isa(n, tree.Quoted); + }, + iskeyword: function (n) { + return this._isa(n, tree.Keyword); + }, + isurl: function (n) { + return this._isa(n, tree.URL); + }, + ispixel: function (n) { + return (n instanceof tree.Dimension) && n.unit === 'px' ? tree.True : tree.False; + }, + ispercentage: function (n) { + return (n instanceof tree.Dimension) && n.unit === '%' ? tree.True : tree.False; + }, + isem: function (n) { + return (n instanceof tree.Dimension) && n.unit === 'em' ? tree.True : tree.False; + }, + _isa: function (n, Type) { + return (n instanceof Type) ? tree.True : tree.False; + }, + + /* Blending modes */ + + multiply: function(color1, color2) { + var r = color1.rgb[0] * color2.rgb[0] / 255; + var g = color1.rgb[1] * color2.rgb[1] / 255; + var b = color1.rgb[2] * color2.rgb[2] / 255; + return this.rgb(r, g, b); + }, + screen: function(color1, color2) { + var r = 255 - (255 - color1.rgb[0]) * (255 - color2.rgb[0]) / 255; + var g = 255 - (255 - color1.rgb[1]) * (255 - color2.rgb[1]) / 255; + var b = 255 - (255 - color1.rgb[2]) * (255 - color2.rgb[2]) / 255; + return this.rgb(r, g, b); + }, + overlay: function(color1, color2) { + var r = color1.rgb[0] < 128 ? 2 * color1.rgb[0] * color2.rgb[0] / 255 : 255 - 2 * (255 - color1.rgb[0]) * (255 - color2.rgb[0]) / 255; + var g = color1.rgb[1] < 128 ? 2 * color1.rgb[1] * color2.rgb[1] / 255 : 255 - 2 * (255 - color1.rgb[1]) * (255 - color2.rgb[1]) / 255; + var b = color1.rgb[2] < 128 ? 2 * color1.rgb[2] * color2.rgb[2] / 255 : 255 - 2 * (255 - color1.rgb[2]) * (255 - color2.rgb[2]) / 255; + return this.rgb(r, g, b); + }, + softlight: function(color1, color2) { + var t = color2.rgb[0] * color1.rgb[0] / 255; + var r = t + color1.rgb[0] * (255 - (255 - color1.rgb[0]) * (255 - color2.rgb[0]) / 255 - t) / 255; + t = color2.rgb[1] * color1.rgb[1] / 255; + var g = t + color1.rgb[1] * (255 - (255 - color1.rgb[1]) * (255 - color2.rgb[1]) / 255 - t) / 255; + t = color2.rgb[2] * color1.rgb[2] / 255; + var b = t + color1.rgb[2] * (255 - (255 - color1.rgb[2]) * (255 - color2.rgb[2]) / 255 - t) / 255; + return this.rgb(r, g, b); + }, + hardlight: function(color1, color2) { + var r = color2.rgb[0] < 128 ? 2 * color2.rgb[0] * color1.rgb[0] / 255 : 255 - 2 * (255 - color2.rgb[0]) * (255 - color1.rgb[0]) / 255; + var g = color2.rgb[1] < 128 ? 2 * color2.rgb[1] * color1.rgb[1] / 255 : 255 - 2 * (255 - color2.rgb[1]) * (255 - color1.rgb[1]) / 255; + var b = color2.rgb[2] < 128 ? 2 * color2.rgb[2] * color1.rgb[2] / 255 : 255 - 2 * (255 - color2.rgb[2]) * (255 - color1.rgb[2]) / 255; + return this.rgb(r, g, b); + }, + difference: function(color1, color2) { + var r = Math.abs(color1.rgb[0] - color2.rgb[0]); + var g = Math.abs(color1.rgb[1] - color2.rgb[1]); + var b = Math.abs(color1.rgb[2] - color2.rgb[2]); + return this.rgb(r, g, b); + }, + exclusion: function(color1, color2) { + var r = color1.rgb[0] + color2.rgb[0] * (255 - color1.rgb[0] - color1.rgb[0]) / 255; + var g = color1.rgb[1] + color2.rgb[1] * (255 - color1.rgb[1] - color1.rgb[1]) / 255; + var b = color1.rgb[2] + color2.rgb[2] * (255 - color1.rgb[2] - color1.rgb[2]) / 255; + return this.rgb(r, g, b); + }, + average: function(color1, color2) { + var r = (color1.rgb[0] + color2.rgb[0]) / 2; + var g = (color1.rgb[1] + color2.rgb[1]) / 2; + var b = (color1.rgb[2] + color2.rgb[2]) / 2; + return this.rgb(r, g, b); + }, + negation: function(color1, color2) { + var r = 255 - Math.abs(255 - color2.rgb[0] - color1.rgb[0]); + var g = 255 - Math.abs(255 - color2.rgb[1] - color1.rgb[1]); + var b = 255 - Math.abs(255 - color2.rgb[2] - color1.rgb[2]); + return this.rgb(r, g, b); + }, + tint: function(color, amount) { + return this.mix(this.rgb(255,255,255), color, amount); + }, + shade: function(color, amount) { + return this.mix(this.rgb(0, 0, 0), color, amount); } }; -function hsla(hsla) { - return tree.functions.hsla(hsla.h, hsla.s, hsla.l, hsla.a); +function hsla(color) { + return tree.functions.hsla(color.h, color.s, color.l, color.a); +} + +function scaled(n, size) { + if (n instanceof tree.Dimension && n.unit == '%') { + return parseFloat(n.value * size / 100); + } else { + return number(n); + } } function number(n) { @@ -182,4 +374,4 @@ function clamp(val) { return Math.min(1, Math.max(0, val)); } -})(require('less/tree')); +})(require('./tree')); diff --git a/build-tools/lib/less/index.js b/build-tools/lib/less/index.js index c2c248d..37fc902 100644 --- a/build-tools/lib/less/index.js +++ b/build-tools/lib/less/index.js @@ -1,18 +1,14 @@ var path = require('path'), sys = require('util'), + url = require('url'), + http = require('http'), fs = require('fs'); -try { - // For old node.js versions - require.paths.unshift( path.join( __dirname, '..' ) ); -} catch ( ex ) { -} - var less = { - version: [1, 1, 3], - Parser: require('less/parser').Parser, - importer: require('less/parser').importer, - tree: require('less/tree'), + version: [1, 3, 3], + Parser: require('./parser').Parser, + importer: require('./parser').importer, + tree: require('./tree'), render: function (input, options, callback) { options = options || {}; @@ -20,12 +16,12 @@ var less = { callback = options, options = {}; } - var parser = new(this.Parser)(options), + var parser = new(less.Parser)(options), ee; if (callback) { parser.parse(input, function (e, root) { - callback(e, root.toCSS(options)); + callback(e, root && root.toCSS && root.toCSS(options)); }); } else { ee = new(require('events').EventEmitter); @@ -39,105 +35,182 @@ var less = { return ee; } }, - writeError: function (ctx, options) { + formatError: function(ctx, options) { + options = options || {}; + var message = ""; var extract = ctx.extract; var error = []; - var stylize = options.color ? less.stylize : function (str) { return str }; + var stylize = options.color ? require('./lessc_helper').stylize : function (str) { return str }; - options = options || {}; - - if (options.silent) { return } + // only output a stack if it isn't a less error + if (ctx.stack && !ctx.type) { return stylize(ctx.stack, 'red') } - if (!ctx.index) { - return sys.error(ctx.stack || ctx.message); + if (!ctx.hasOwnProperty('index') || !extract) { + return ctx.stack || ctx.message; } if (typeof(extract[0]) === 'string') { error.push(stylize((ctx.line - 1) + ' ' + extract[0], 'grey')); } - error.push(ctx.line + ' ' + extract[1].slice(0, ctx.column) - + stylize(stylize(extract[1][ctx.column], 'bold') - + extract[1].slice(ctx.column + 1), 'yellow')); + if (extract[1]) { + error.push(ctx.line + ' ' + extract[1].slice(0, ctx.column) + + stylize(stylize(stylize(extract[1][ctx.column], 'bold') + + extract[1].slice(ctx.column + 1), 'red'), 'inverse')); + } if (typeof(extract[2]) === 'string') { error.push(stylize((ctx.line + 1) + ' ' + extract[2], 'grey')); } - error = error.join('\n') + '\033[0m\n'; + error = error.join('\n') + stylize('', 'reset') + '\n'; - message += stylize(ctx.message, 'red'); - ctx.filename && (message += stylize(' in ', 'red') + ctx.filename); + message += stylize(ctx.type + 'Error: ' + ctx.message, 'red'); + ctx.filename && (message += stylize(' in ', 'red') + ctx.filename + + stylize(':' + ctx.line + ':' + ctx.column, 'grey')); - sys.error(message, error); + message += '\n' + error; if (ctx.callLine) { - sys.error(stylize('from ', 'red') + (ctx.filename || '')); - sys.error(stylize(ctx.callLine, 'grey') + ' ' + ctx.callExtract); + message += stylize('from ', 'red') + (ctx.filename || '') + '/n'; + message += stylize(ctx.callLine, 'grey') + ' ' + ctx.callExtract + '/n'; } - if (ctx.stack) { sys.error(stylize(ctx.stack, 'red')) } + + return message; + }, + writeError: function (ctx, options) { + options = options || {}; + if (options.silent) { return } + sys.error(less.formatError(ctx, options)); } }; -['color', 'directive', 'operation', 'dimension', - 'keyword', 'variable', 'ruleset', 'element', - 'selector', 'quoted', 'expression', 'rule', - 'call', 'url', 'alpha', 'import', - 'mixin', 'comment', 'anonymous', 'value', 'javascript' +['color', 'directive', 'operation', 'dimension', + 'keyword', 'variable', 'ruleset', 'element', + 'selector', 'quoted', 'expression', 'rule', + 'call', 'url', 'alpha', 'import', + 'mixin', 'comment', 'anonymous', 'value', + 'javascript', 'assignment', 'condition', 'paren', + 'media', 'ratio', 'unicode-descriptor' ].forEach(function (n) { - require(path.join('less', 'tree', n)); + require('./tree/' + n); }); -less.Parser.importer = function (file, paths, callback) { - var pathname; - paths.unshift('.'); +var isUrlRe = /^(?:https?:)?\/\//i; + +less.Parser.importer = function (file, paths, callback, env) { + var pathname, dirname, data; - for (var i = 0; i < paths.length; i++) { - try { - pathname = path.join(paths[i], file); - fs.statSync(pathname); - break; - } catch (e) { - pathname = null; + function parseFile(e, data) { + if (e) return callback(e); + + var rootpath = env.rootpath, + j = file.lastIndexOf('/'); + + // Pass on an updated rootpath if path of imported file is relative and file + // is in a (sub|sup) directory + // + // Examples: + // - If path of imported file is 'module/nav/nav.less' and rootpath is 'less/', + // then rootpath should become 'less/module/nav/' + // - If path of imported file is '../mixins.less' and rootpath is 'less/', + // then rootpath should become 'less/../' + if(env.relativeUrls && !/^(?:[a-z-]+:|\/)/.test(file) && j != -1) { + rootpath = rootpath + file.slice(0, j+1); // append (sub|sup) directory path of imported file } - } - if (pathname) { - fs.readFile(pathname, 'utf-8', function(e, data) { - if (e) sys.error(e); - - new(less.Parser)({ - paths: [path.dirname(pathname)].concat(paths), - filename: pathname - }).parse(data, function (e, root) { - if (e) less.writeError(e); - callback(root); - }); + env.contents[pathname] = data; // Updating top importing parser content cache. + new(less.Parser)({ + paths: [dirname].concat(paths), + filename: pathname, + contents: env.contents, + files: env.files, + syncImport: env.syncImport, + relativeUrls: env.relativeUrls, + rootpath: rootpath, + dumpLineNumbers: env.dumpLineNumbers + }).parse(data, function (e, root) { + callback(e, root, pathname); }); + }; + + var isUrl = isUrlRe.test( file ); + if (isUrl || isUrlRe.test(paths[0])) { + + var urlStr = isUrl ? file : url.resolve(paths[0], file), + urlObj = url.parse(urlStr), + req = { + host: urlObj.hostname, + port: urlObj.port || 80, + path: urlObj.pathname + (urlObj.search||'') + }; + + http.get(req, function (res) { + var body = ''; + res.on('data', function (chunk) { + body += chunk.toString(); + }); + res.on('end', function () { + if (res.statusCode === 404) { + callback({ type: 'File', message: "resource '" + urlStr + "' was not found\n" }); + } + if (!body) { + sys.error( 'Warning: Empty body (HTTP '+ res.statusCode + ') returned by "' + urlStr +'"' ); + } + pathname = urlStr; + dirname = urlObj.protocol +'//'+ urlObj.host + urlObj.pathname.replace(/[^\/]*$/, ''); + parseFile(null, body); + }); + }).on('error', function (err) { + callback({ type: 'File', message: "resource '" + urlStr + "' gave this Error:\n "+ err +"\n" }); + }); + } else { - sys.error("file '" + file + "' wasn't found.\n"); - process.exit(1); - } -} -require('less/functions'); + // TODO: Undo this at some point, + // or use different approach. + var paths = [].concat(paths); + paths.push('.'); + + for (var i = 0; i < paths.length; i++) { + try { + pathname = path.join(paths[i], file); + fs.statSync(pathname); + break; + } catch (e) { + pathname = null; + } + } + + paths = paths.slice(0, paths.length - 1); -for (var k in less) { exports[k] = less[k] } + if (!pathname) { -// Stylize a string -function stylize(str, style) { - var styles = { - 'bold' : [1, 22], - 'inverse' : [7, 27], - 'underline' : [4, 24], - 'yellow' : [33, 39], - 'green' : [32, 39], - 'red' : [31, 39], - 'grey' : [90, 39] - }; - return '\033[' + styles[style][0] + 'm' + str + - '\033[' + styles[style][1] + 'm'; + if (typeof(env.errback) === "function") { + env.errback(file, paths, callback); + } else { + callback({ type: 'File', message: "'" + file + "' wasn't found.\n" }); + } + return; + } + + dirname = path.dirname(pathname); + + if (env.syncImport) { + try { + data = fs.readFileSync(pathname, 'utf-8'); + parseFile(null, data); + } catch (e) { + parseFile(e); + } + } else { + fs.readFile(pathname, 'utf-8', parseFile); + } + } } -less.stylize = stylize; +require('./functions'); +require('./colors'); + +for (var k in less) { exports[k] = less[k] } diff --git a/build-tools/lib/less/lessc_helper.js b/build-tools/lib/less/lessc_helper.js new file mode 100644 index 0000000..1a82ef9 --- /dev/null +++ b/build-tools/lib/less/lessc_helper.js @@ -0,0 +1,62 @@ +// lessc_helper.js +// +// helper functions for lessc +sys = require('util'); + +var lessc_helper = { + + //Stylize a string + stylize : function(str, style) { + var styles = { + 'reset' : [0, 0], + 'bold' : [1, 22], + 'inverse' : [7, 27], + 'underline' : [4, 24], + 'yellow' : [33, 39], + 'green' : [32, 39], + 'red' : [31, 39], + 'grey' : [90, 39] + }; + return '\033[' + styles[style][0] + 'm' + str + + '\033[' + styles[style][1] + 'm'; + }, + + //Print command line options + printUsage: function() { + sys.puts("usage: lessc [option option=parameter ...] [destination]"); + sys.puts(""); + sys.puts("If source is set to `-' (dash or hyphen-minus), input is read from stdin."); + sys.puts(""); + sys.puts("options:"); + sys.puts(" -h, --help Print help (this message) and exit."); + sys.puts(" --include-path Set include paths. Separated by `:'. Use `;' on Windows."); + sys.puts(" --no-color Disable colorized output."); + sys.puts(" -s, --silent Suppress output of error messages."); + sys.puts(" --strict-imports Force evaluation of imports."); + sys.puts(" --verbose Be verbose."); + sys.puts(" -v, --version Print version number and exit."); + sys.puts(" -x, --compress Compress output by removing some whitespaces."); + sys.puts(" --yui-compress Compress output using ycssmin"); + sys.puts(" -O0, -O1, -O2 Set the parser's optimization level. The lower"); + sys.puts(" the number, the less nodes it will create in the"); + sys.puts(" tree. This could matter for debugging, or if you"); + sys.puts(" want to access the individual nodes in the tree."); + sys.puts(" --line-numbers=TYPE Outputs filename and line numbers."); + sys.puts(" TYPE can be either 'comments', which will output"); + sys.puts(" the debug info within comments, 'mediaquery'"); + sys.puts(" that will output the information within a fake"); + sys.puts(" media query which is compatible with the SASS"); + sys.puts(" format, and 'all' which will do both."); + sys.puts(" -rp, --rootpath Set rootpath for url rewriting in relative imports and urls."); + sys.puts(" Works with or withour the relative-urls option."); + sys.puts(" -ru, --relative-urls re-write relative urls to the base less file."); + sys.puts(""); + sys.puts("Report bugs to: http://github.com/cloudhead/less.js/issues"); + sys.puts("Home page: "); + } + + +} + +// Exports helper functions +for (var h in lessc_helper) { exports[h] = lessc_helper[h] } diff --git a/build-tools/lib/less/parser.js b/build-tools/lib/less/parser.js index fae248e..c8c280b 100644 --- a/build-tools/lib/less/parser.js +++ b/build-tools/lib/less/parser.js @@ -1,16 +1,17 @@ -var less, tree; +var less, tree, charset; if (typeof environment === "object" && ({}).toString.call(environment) === "[object Environment]") { // Rhino // Details on how to detect Rhino: https://github.com/ringo/ringojs/issues/88 - less = {}; + if (typeof(window) === 'undefined') { less = {} } + else { less = window.less = {} } tree = less.tree = {}; less.mode = 'rhino'; } else if (typeof(window) === 'undefined') { // Node.js less = exports, - tree = require('less/tree'); - less.mode = 'rhino'; + tree = require('./tree'); + less.mode = 'node'; } else { // Browser if (typeof(window.less) === 'undefined') { window.less = {} } @@ -64,15 +65,25 @@ less.Parser = function Parser(env) { var that = this; + // Top parser on an import tree must be sure there is one "env" + // which will then be passed arround by reference. + var env = env || { }; + // env.contents and files must be passed arround with top env + if (!env.contents) { env.contents = {}; } + env.rootpath = env.rootpath || ''; // env.rootpath must be initialized to '' if not provided + if (!env.files) { env.files = {}; } + // This function is called after all files // have been imported through `@import`. var finish = function () {}; var imports = this.imports = { - paths: env && env.paths || [], // Search paths, when importing - queue: [], // Files which haven't been imported yet - files: {}, // Holds the imported parse trees - mime: env && env.mime, // MIME type of .less files + paths: env.paths || [], // Search paths, when importing + queue: [], // Files which haven't been imported yet + files: env.files, // Holds the imported parse trees + contents: env.contents, // Holds the imported file contents + mime: env.mime, // MIME type of .less files + error: null, // Error in parsing/evaluating an import push: function (path, callback) { var that = this; this.queue.push(path); @@ -80,13 +91,18 @@ less.Parser = function Parser(env) { // // Import a file asynchronously // - less.Parser.importer(path, this.paths, function (root) { + less.Parser.importer(path, this.paths, function (e, root, fullPath) { that.queue.splice(that.queue.indexOf(path), 1); // Remove the path from the queue - that.files[path] = root; // Store the root - callback(root); + var imported = fullPath in that.files; + + that.files[fullPath] = root; // Store the root - if (that.queue.length === 0) { finish() } // Call `finish` if we're done importing + if (e && !that.error) { that.error = e } + + callback(e, root, imported); + + if (that.queue.length === 0) { finish(that.error) } // Call `finish` if we're done importing }, env); } }; @@ -100,11 +116,16 @@ less.Parser = function Parser(env) { current = i; } } + function isWhitespace(c) { + // Could change to \s? + var code = c.charCodeAt(0); + return code === 32 || code === 10 || code === 9; + } // // Parse from a token, regexp or string, and move forward if match // function $(tok) { - var match, args, length, c, index, endIndex, k, mem; + var match, args, length, index, k; // // Non-terminal @@ -137,18 +158,7 @@ less.Parser = function Parser(env) { // grammar is mostly white-space insensitive. // if (match) { - mem = i += length; - endIndex = i + chunks[j].length - length; - - while (i < endIndex) { - c = input.charCodeAt(i); - if (! (c === 32 || c === 10 || c === 9)) { break } - i++; - } - chunks[j] = chunks[j].slice(length + (i - mem)); - current = i; - - if (chunks[j].length === 0 && j < chunks.length - 1) { j++ } + skipWhitespace(length); if(typeof(match) === 'string') { return match; @@ -158,6 +168,40 @@ less.Parser = function Parser(env) { } } + function skipWhitespace(length) { + var oldi = i, oldj = j, + endIndex = i + chunks[j].length, + mem = i += length; + + while (i < endIndex) { + if (! isWhitespace(input.charAt(i))) { break } + i++; + } + chunks[j] = chunks[j].slice(length + (i - mem)); + current = i; + + if (chunks[j].length === 0 && j < chunks.length - 1) { j++ } + + return oldi !== i || oldj !== j; + } + + function expect(arg, msg) { + var result = $(arg); + if (! result) { + error(msg || (typeof(arg) === 'string' ? "expected '" + arg + "' got '" + input.charAt(i) + "'" + : "unexpected token")); + } else { + return result; + } + } + + function error(msg, type) { + var e = new Error(msg); + e.index = i; + e.type = type || 'Syntax'; + throw e; + } + // Same as $(), but don't change the state of the parser, // just return the match. function peek(tok) { @@ -172,6 +216,60 @@ less.Parser = function Parser(env) { } } + function getInput(e, env) { + if (e.filename && env.filename && (e.filename !== env.filename)) { + return parser.imports.contents[e.filename]; + } else { + return input; + } + } + + function getLocation(index, input) { + for (var n = index, column = -1; + n >= 0 && input.charAt(n) !== '\n'; + n--) { column++ } + + return { line: typeof(index) === 'number' ? (input.slice(0, index).match(/\n/g) || "").length : null, + column: column }; + } + + function getFileName(e) { + if(less.mode === 'browser' || less.mode === 'rhino') + return e.filename; + else + return require('path').resolve(e.filename); + } + + function getDebugInfo(index, inputStream, e) { + return { + lineNumber: getLocation(index, inputStream).line + 1, + fileName: getFileName(e) + }; + } + + function LessError(e, env) { + var input = getInput(e, env), + loc = getLocation(e.index, input), + line = loc.line, + col = loc.column, + lines = input.split('\n'); + + this.type = e.type || 'Syntax'; + this.message = e.message; + this.filename = e.filename || env.filename; + this.index = e.index; + this.line = typeof(line) === 'number' ? line + 1 : null; + this.callLine = e.call && (getLocation(e.call, input).line + 1); + this.callExtract = lines[getLocation(e.call, input).line]; + this.stack = e.stack; + this.column = col; + this.extract = [ + lines[line - 1], + lines[line], + lines[line + 1] + ]; + } + this.env = env = env || {}; // The optimization level dictates the thoroughness of the parser, @@ -196,21 +294,23 @@ less.Parser = function Parser(env) { var root, start, end, zone, line, lines, buff = [], c, error = null; i = j = current = furthest = 0; - chunks = []; input = str.replace(/\r\n/g, '\n'); + // Remove potential UTF Byte Order Mark + input = input.replace(/^\uFEFF/, ''); + // Split the input into chunks. chunks = (function (chunks) { var j = 0, - skip = /[^"'`\{\}\/\(\)]+/g, + skip = /(?:@\{[\w-]+\}|[^"'`\{\}\/\(\)\\])+/g, comment = /\/\*(?:[^*]|\*+[^\/*])*\*+\/|\/\/.*/g, + string = /"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'|`((?:[^`]|\\.)*)`/g, level = 0, match, chunk = chunks[0], - inParam, - inString; + inParam; - for (var i = 0, c, cc; i < input.length; i++) { + for (var i = 0, c, cc; i < input.length;) { skip.lastIndex = i; if (match = skip.exec(input)) { if (match.index === i) { @@ -219,66 +319,71 @@ less.Parser = function Parser(env) { } } c = input.charAt(i); - comment.lastIndex = i; + comment.lastIndex = string.lastIndex = i; + + if (match = string.exec(input)) { + if (match.index === i) { + i += match[0].length; + chunk.push(match[0]); + continue; + } + } - if (!inString && !inParam && c === '/') { + if (!inParam && c === '/') { cc = input.charAt(i + 1); if (cc === '/' || cc === '*') { if (match = comment.exec(input)) { if (match.index === i) { i += match[0].length; chunk.push(match[0]); - c = input.charAt(i); + continue; } } } } - - if (c === '{' && !inString && !inParam) { level ++; - chunk.push(c); - } else if (c === '}' && !inString && !inParam) { level --; - chunk.push(c); - chunks[++j] = chunk = []; - } else if (c === '(' && !inString && !inParam) { - chunk.push(c); - inParam = true; - } else if (c === ')' && !inString && inParam) { - chunk.push(c); - inParam = false; - } else { - if (c === '"' || c === "'" || c === '`') { - if (! inString) { - inString = c; - } else { - inString = inString === c ? false : inString; - } - } - chunk.push(c); + + switch (c) { + case '{': if (! inParam) { level ++; chunk.push(c); break } + case '}': if (! inParam) { level --; chunk.push(c); chunks[++j] = chunk = []; break } + case '(': if (! inParam) { inParam = true; chunk.push(c); break } + case ')': if ( inParam) { inParam = false; chunk.push(c); break } + default: chunk.push(c); } + + i++; } - if (level > 0) { - throw { - type: 'Syntax', - message: "Missing closing `}`", + if (level != 0) { + error = new(LessError)({ + index: i-1, + type: 'Parse', + message: (level > 0) ? "missing closing `}`" : "missing opening `{`", filename: env.filename - }; + }, env); } return chunks.map(function (c) { return c.join('') });; })([[]]); + if (error) { + return callback(error, env); + } + // Start with the primary rule. // The whole syntax tree is held under a Ruleset node, // with the `root` property set to true, so no `{}` are // output. The callback is called when the input is parsed. - root = new(tree.Ruleset)([], $(this.parsers.primary)); - root.root = true; + try { + root = new(tree.Ruleset)([], $(this.parsers.primary)); + root.root = true; + } catch (e) { + return callback(new(LessError)(e, env)); + } root.toCSS = (function (evaluate) { var line, lines, column; return function (options, variables) { - var frames = []; + var frames = [], importError; options = options || {}; // @@ -311,41 +416,23 @@ less.Parser = function Parser(env) { try { var css = evaluate.call(this, { frames: frames }) - .toCSS([], { compress: options.compress || false }); + .toCSS([], { compress: options.compress || false, dumpLineNumbers: env.dumpLineNumbers }); } catch (e) { - lines = input.split('\n'); - line = getLine(e.index); - - for (var n = e.index, column = -1; - n >= 0 && input.charAt(n) !== '\n'; - n--) { column++ } - - throw { - type: e.type, - message: e.message, - filename: env.filename, - index: e.index, - line: typeof(line) === 'number' ? line + 1 : null, - callLine: e.call && (getLine(e.call) + 1), - callExtract: lines[getLine(e.call)], - stack: e.stack, - column: column, - extract: [ - lines[line - 1], - lines[line], - lines[line + 1] - ] - }; + throw new(LessError)(e, env); } - if (options.compress) { + + if ((importError = parser.imports.error)) { // Check if there was an error during importing + if (importError instanceof LessError) throw importError; + else throw new(LessError)(importError, env); + } + + if (options.yuicompress && less.mode === 'node') { + return require('ycssmin').cssmin(css); + } else if (options.compress) { return css.replace(/(\s)+/g, "$1"); } else { return css; } - - function getLine(index) { - return index ? (input.slice(0, index).match(/\n/g) || "").length : null; - } }; })(root.eval); @@ -365,7 +452,7 @@ less.Parser = function Parser(env) { for (var n = i, column = -1; n >= 0 && input.charAt(n) !== '\n'; n--) { column++ } error = { - name: "ParseError", + type: "Parse", message: "Syntax Error on line " + line, index: i, filename: env.filename, @@ -380,7 +467,11 @@ less.Parser = function Parser(env) { } if (this.imports.queue.length > 0) { - finish = function () { callback(error, root) }; + finish = function (e) { + e = error || e; + if (e) callback(e); + else callback(null, root); + }; } else { callback(error, root); } @@ -436,7 +527,7 @@ less.Parser = function Parser(env) { while ((node = $(this.mixin.definition) || $(this.rule) || $(this.ruleset) || $(this.mixin.call) || $(this.comment) || $(this.directive)) - || $(/^[\s\n]+/)) { + || $(/^[\s\n]+/) || $(/^;+/)) { node && root.push(node); } return root; @@ -486,7 +577,15 @@ less.Parser = function Parser(env) { // keyword: function () { var k; - if (k = $(/^[_A-Za-z-][_A-Za-z0-9-]*/)) { return new(tree.Keyword)(k) } + + if (k = $(/^[_A-Za-z-][_A-Za-z0-9-]*/)) { + if (tree.colors.hasOwnProperty(k)) { + // detect named color + return new(tree.Color)(tree.colors[k].slice(1)); + } else { + return new(tree.Keyword)(k); + } + } }, // @@ -500,16 +599,22 @@ less.Parser = function Parser(env) { // The arguments are parsed with the `entities.arguments` parser. // call: function () { - var name, args, index = i; + var name, nameLC, args, alpha_ret, index = i; - if (! (name = /^([\w-]+|%)\(/.exec(chunks[j]))) return; + if (! (name = /^([\w-]+|%|progid:[\w\.]+)\(/.exec(chunks[j]))) return; - name = name[1].toLowerCase(); + name = name[1]; + nameLC = name.toLowerCase(); - if (name === 'url') { return null } + if (nameLC === 'url') { return null } else { i += name.length } - if (name === 'alpha') { return $(this.alpha) } + if (nameLC === 'alpha') { + alpha_ret = $(this.alpha); + if(typeof alpha_ret !== 'undefined') { + return alpha_ret; + } + } $('('); // Parse the '(' and consume whitespace. @@ -517,21 +622,36 @@ less.Parser = function Parser(env) { if (! $(')')) return; - if (name) { return new(tree.Call)(name, args, index) } + if (name) { return new(tree.Call)(name, args, index, env.filename) } }, arguments: function () { var args = [], arg; - while (arg = $(this.expression)) { + while (arg = $(this.entities.assignment) || $(this.expression)) { args.push(arg); if (! $(',')) { break } } return args; }, literal: function () { - return $(this.entities.dimension) || + return $(this.entities.ratio) || + $(this.entities.dimension) || $(this.entities.color) || - $(this.entities.quoted); + $(this.entities.quoted) || + $(this.entities.unicodeDescriptor); + }, + + // Assignments are argument entities for calls. + // They are present in ie filter properties as shown below. + // + // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* ) + // + + assignment: function () { + var key, value; + if ((key = $(/^\w+(?=\s?=)/i)) && $('=') && (value = $(this.entity))) { + return new(tree.Assignment)(key, value); + } }, // @@ -546,25 +666,12 @@ less.Parser = function Parser(env) { if (input.charAt(i) !== 'u' || !$(/^url\(/)) return; value = $(this.entities.quoted) || $(this.entities.variable) || - $(this.entities.dataURI) || $(/^[-\w%@$\/.&=:;#+?~]+/) || ""; - if (! $(')')) throw new(Error)("missing closing ) for url()"); - - return new(tree.URL)((value.value || value.data || value instanceof tree.Variable) - ? value : new(tree.Anonymous)(value), imports.paths); - }, + $(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || ""; - dataURI: function () { - var obj; + expect(')'); - if ($(/^data:/)) { - obj = {}; - obj.mime = $(/^[^\/]+\/[^,;)]+/) || ''; - obj.charset = $(/^;\s*charset=[^,;)]+/) || ''; - obj.base64 = $(/^;\s*base64/) || ''; - obj.data = $(/^,\s*[^)]+/); - - if (obj.data) { return obj } - } + return new(tree.URL)((value.value != null || value instanceof tree.Variable) + ? value : new(tree.Anonymous)(value), env.rootpath); }, // @@ -579,7 +686,16 @@ less.Parser = function Parser(env) { var name, index = i; if (input.charAt(i) === '@' && (name = $(/^@@?[\w-]+/))) { - return new(tree.Variable)(name, index); + return new(tree.Variable)(name, index, env.filename); + } + }, + + // A variable entity useing the protective {} e.g. @{var} + variableCurly: function () { + var name, curly, index = i; + + if (input.charAt(i) === '@' && (curly = $(/^@\{([\w-]+)\}/))) { + return new(tree.Variable)("@" + curly[1], index, env.filename); } }, @@ -593,7 +709,7 @@ less.Parser = function Parser(env) { color: function () { var rgb; - if (input.charAt(i) === '#' && (rgb = $(/^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})/))) { + if (input.charAt(i) === '#' && (rgb = $(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/))) { return new(tree.Color)(rgb[1]); } }, @@ -605,14 +721,42 @@ less.Parser = function Parser(env) { // dimension: function () { var value, c = input.charCodeAt(i); - if ((c > 57 || c < 45) || c === 47) return; + //Is the first char of the dimension 0-9, '.', '+' or '-' + if ((c > 57 || c < 43) || c === 47 || c == 44) return; - if (value = $(/^(-?\d*\.?\d+)(px|%|em|rem|pc|ex|in|deg|s|ms|pt|cm|mm|rad|grad|turn)?/)) { + if (value = $(/^([+-]?\d*\.?\d+)(px|%|em|pc|ex|in|deg|s|ms|pt|cm|mm|rad|grad|turn|dpi|dpcm|dppx|rem|vw|vh|vmin|vm|ch)?/)) { return new(tree.Dimension)(value[1], value[2]); } }, // + // A Ratio + // + // 16/9 + // + ratio: function () { + var value, c = input.charCodeAt(i); + if (c > 57 || c < 48) return; + + if (value = $(/^(\d+\/\d+)/)) { + return new(tree.Ratio)(value[1]); + } + }, + + // + // A unicode descriptor, as is used in unicode-range + // + // U+0?? or U+00A1-00A9 + // + unicodeDescriptor: function () { + var ud; + + if (ud = $(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/)) { + return new(tree.UnicodeDescriptor)(ud[0]); + } + }, + + // // JavaScript code to be evaluated // // `window.location.href` @@ -654,9 +798,13 @@ less.Parser = function Parser(env) { if (! peek(/^[@\w.%-]+\/[@\w.-]+/)) return; + save(); + if ((a = $(this.entity)) && $('/') && (b = $(this.entity))) { return new(tree.Shorthand)(a, b); } + + restore(); }, // @@ -675,19 +823,80 @@ less.Parser = function Parser(env) { // selector for now. // call: function () { - var elements = [], e, c, args, index = i, s = input.charAt(i); + var elements = [], e, c, argsSemiColon = [], argsComma = [], args, delim, arg, nameLoop, expressions, isSemiColonSeperated, expressionContainsNamed, index = i, s = input.charAt(i), name, value, important = false; if (s !== '.' && s !== '#') { return } + + save(); // stop us absorbing part of an invalid selector - while (e = $(/^[#.](?:[\w-]|\\(?:[a-fA-F0-9]{1,6} ?|[^a-fA-F0-9]))+/)) { - elements.push(new(tree.Element)(c, e)); + while (e = $(/^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/)) { + elements.push(new(tree.Element)(c, e, i)); c = $('>'); } - $('(') && (args = $(this.entities.arguments)) && $(')'); + if ($('(')) { + expressions = []; + while (arg = $(this.expression)) { + nameLoop = null; + value = arg; + + // Variable + if (arg.value.length == 1) { + var val = arg.value[0]; + if (val instanceof tree.Variable) { + if ($(':')) { + if (expressions.length > 0) { + if (isSemiColonSeperated) { + error("Cannot mix ; and , as delimiter types"); + } + expressionContainsNamed = true; + } + value = expect(this.expression); + nameLoop = (name = val.name); + } + } + } + + expressions.push(value); + + argsComma.push({ name: nameLoop, value: value }); + + if ($(',')) { + continue; + } + + if ($(';') || isSemiColonSeperated) { + + if (expressionContainsNamed) { + error("Cannot mix ; and , as delimiter types"); + } + + isSemiColonSeperated = true; + + if (expressions.length > 1) { + value = new(tree.Value)(expressions); + } + argsSemiColon.push({ name: name, value: value }); + + name = null; + expressions = []; + expressionContainsNamed = false; + } + } + + expect(')'); + } + + args = isSemiColonSeperated ? argsSemiColon : argsComma; + + if ($(this.important)) { + important = true; + } if (elements.length > 0 && ($(';') || peek('}'))) { - return new(tree.mixin.Call)(elements, args, index); + return new(tree.mixin.Call)(elements, args, index, env.filename, important); } + + restore(); }, // @@ -710,38 +919,62 @@ less.Parser = function Parser(env) { // the `{...}` block. // definition: function () { - var name, params = [], match, ruleset, param, value; - + var name, params = [], match, ruleset, param, value, cond, variadic = false; if ((input.charAt(i) !== '.' && input.charAt(i) !== '#') || - peek(/^[^{]*(;|})/)) return; + peek(/^[^{]*\}/)) return; + + save(); - if (match = $(/^([#.](?:[\w-]|\\(?:[a-fA-F0-9]{1,6} ?|[^a-fA-F0-9]))+)\s*\(/)) { + if (match = $(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/)) { name = match[1]; - while (param = $(this.entities.variable) || $(this.entities.literal) - || $(this.entities.keyword)) { - // Variable - if (param instanceof tree.Variable) { - if ($(':')) { - if (value = $(this.expression)) { + do { + $(this.comment); + if (input.charAt(i) === '.' && $(/^\.{3}/)) { + variadic = true; + params.push({ variadic: true }); + break; + } else if (param = $(this.entities.variable) || $(this.entities.literal) + || $(this.entities.keyword)) { + // Variable + if (param instanceof tree.Variable) { + if ($(':')) { + value = expect(this.expression, 'expected expression'); params.push({ name: param.name, value: value }); + } else if ($(/^\.{3}/)) { + params.push({ name: param.name, variadic: true }); + variadic = true; + break; } else { - throw new(Error)("Expected value"); + params.push({ name: param.name }); } } else { - params.push({ name: param.name }); + params.push({ value: param }); } } else { - params.push({ value: param }); + break; } - if (! $(',')) { break } + } while ($(',') || $(';')) + + // .mixincall("@{a}"); + // looks a bit like a mixin definition.. so we have to be nice and restore + if (!$(')')) { + furthest = i; + restore(); + } + + $(this.comment); + + if ($(/^when/)) { // Guard + cond = expect(this.conditions, 'expected condition'); } - if (! $(')')) throw new(Error)("Expected )"); ruleset = $(this.block); if (ruleset) { - return new(tree.mixin.Definition)(name, params, ruleset); + return new(tree.mixin.Definition)(name, params, ruleset, cond, variadic); + } else { + restore(); } } } @@ -753,7 +986,7 @@ less.Parser = function Parser(env) { // entity: function () { return $(this.entities.literal) || $(this.entities.variable) || $(this.entities.url) || - $(this.entities.call) || $(this.entities.keyword) || $(this.entities.javascript) || + $(this.entities.call) || $(this.entities.keyword) ||$(this.entities.javascript) || $(this.comment); }, @@ -776,7 +1009,7 @@ less.Parser = function Parser(env) { if (! $(/^\(opacity=/i)) return; if (value = $(/^\d+/) || $(this.entities.variable)) { - if (! $(')')) throw new(Error)("missing closing ) for alpha()"); + expect(')'); return new(tree.Alpha)(value); } }, @@ -794,16 +1027,25 @@ less.Parser = function Parser(env) { // and an element name, such as a tag a class, or `*`. // element: function () { - var e, t, c; + var e, t, c, v; c = $(this.combinator); - e = $(/^(?:[.#]?|:*)(?:[\w-]|\\(?:[a-fA-F0-9]{1,6} ?|[^a-fA-F0-9]))+/) || $('*') || $(this.attribute) || $(/^\([^)@]+\)/) || $(/^(?:\d*\.)?\d+%/); - if (e) { return new(tree.Element)(c, e) } + e = $(/^(?:\d+\.\d+|\d+)%/) || $(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) || + $('*') || $('&') || $(this.attribute) || $(/^\([^()@]+\)/) || $(/^[\.#](?=@)/) || $(this.entities.variableCurly); - if (c.value && c.value[0] === '&') { - return new(tree.Element)(c, null); + if (! e) { + if ($('(')) { + if ((v = ($(this.entities.variableCurly) || + $(this.entities.variable) || + $(this.selector))) && + $(')')) { + e = new(tree.Paren)(v); + } + } } + + if (e) { return new(tree.Element)(c, e, i) } }, // @@ -818,23 +1060,11 @@ less.Parser = function Parser(env) { combinator: function () { var match, c = input.charAt(i); - if (c === '>' || c === '+' || c === '~') { + if (c === '>' || c === '+' || c === '~' || c === '|') { i++; - while (input.charAt(i) === ' ') { i++ } + while (input.charAt(i).match(/\s/)) { i++ } return new(tree.Combinator)(c); - } else if (c === '&') { - match = '&'; - i++; - if(input.charAt(i) === ' ') { - match = '& '; - } - while (input.charAt(i) === ' ') { i++ } - return new(tree.Combinator)(match); - } else if (c === ':' && input.charAt(i + 1) === ':') { - i += 2; - while (input.charAt(i) === ' ') { i++ } - return new(tree.Combinator)('::'); - } else if (input.charAt(i - 1) === ' ') { + } else if (input.charAt(i - 1).match(/\s/)) { return new(tree.Combinator)(" "); } else { return new(tree.Combinator)(null); @@ -852,23 +1082,27 @@ less.Parser = function Parser(env) { selector: function () { var sel, e, elements = [], c, match; + // depreciated, will be removed soon + if ($('(')) { + sel = $(this.entity); + if (!$(')')) { return null; } + return new(tree.Selector)([new(tree.Element)('', sel, i)]); + } + while (e = $(this.element)) { c = input.charAt(i); elements.push(e) - if (c === '{' || c === '}' || c === ';' || c === ',') { break } + if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') { break } } if (elements.length > 0) { return new(tree.Selector)(elements) } }, - tag: function () { - return $(/^[a-zA-Z][a-zA-Z-]*[0-9]?/) || $('*'); - }, attribute: function () { var attr = '', key, val, op; if (! $('[')) return; - if (key = $(/^[a-zA-Z-]+/) || $(this.entities.quoted)) { + if (key = $(/^(?:[_A-Za-z0-9-]|\\.)+/) || $(this.entities.quoted)) { if ((op = $(/^[|~*$^]?=/)) && (val = $(this.entities.quoted) || $(/^[\w-]+/))) { attr = [key, op, val.toCSS ? val.toCSS() : val].join(''); @@ -886,7 +1120,6 @@ less.Parser = function Parser(env) { // block: function () { var content; - if ($('{') && (content = $(this.primary)) && $('}')) { return content; } @@ -896,9 +1129,13 @@ less.Parser = function Parser(env) { // div, .class, body > p {...} // ruleset: function () { - var selectors = [], s, rules, match; + var selectors = [], s, rules, match, debugInfo; + save(); + if (env.dumpLineNumbers) + debugInfo = getDebugInfo(i, input, env); + while (s = $(this.selector)) { selectors.push(s); $(this.comment); @@ -907,7 +1144,10 @@ less.Parser = function Parser(env) { } if (selectors.length > 0 && (rules = $(this.block))) { - return new(tree.Ruleset)(selectors, rules); + var ruleset = new(tree.Ruleset)(selectors, rules, env.strictImports); + if (env.dumpLineNumbers) + ruleset.debugInfo = debugInfo; + return ruleset; } else { // Backtrack furthest = i; @@ -951,11 +1191,79 @@ less.Parser = function Parser(env) { // stored in `import`, which we pass to the Import constructor. // "import": function () { - var path; - if ($(/^@import\s+/) && - (path = $(this.entities.quoted) || $(this.entities.url)) && - $(';')) { - return new(tree.Import)(path, imports); + var path, features, index = i; + + save(); + + var dir = $(/^@import(?:-(once))?\s+/); + + if (dir && (path = $(this.entities.quoted) || $(this.entities.url))) { + features = $(this.mediaFeatures); + if ($(';')) { + return new(tree.Import)(path, imports, features, (dir[1] === 'once'), index, env.rootpath); + } + } + + restore(); + }, + + mediaFeature: function () { + var e, p, nodes = []; + + do { + if (e = $(this.entities.keyword)) { + nodes.push(e); + } else if ($('(')) { + p = $(this.property); + e = $(this.entity); + if ($(')')) { + if (p && e) { + nodes.push(new(tree.Paren)(new(tree.Rule)(p, e, null, i, true))); + } else if (e) { + nodes.push(new(tree.Paren)(e)); + } else { + return null; + } + } else { return null } + } + } while (e); + + if (nodes.length > 0) { + return new(tree.Expression)(nodes); + } + }, + + mediaFeatures: function () { + var e, features = []; + + do { + if (e = $(this.mediaFeature)) { + features.push(e); + if (! $(',')) { break } + } else if (e = $(this.entities.variable)) { + features.push(e); + if (! $(',')) { break } + } + } while (e); + + return features.length > 0 ? features : null; + }, + + media: function () { + var features, rules, media, debugInfo; + + if (env.dumpLineNumbers) + debugInfo = getDebugInfo(i, input, env); + + if ($(/^@media/)) { + features = $(this.mediaFeatures); + + if (rules = $(this.block)) { + media = new(tree.Media)(rules, features); + if(env.dumpLineNumbers) + media.debugInfo = debugInfo; + return media; + } } }, @@ -965,26 +1273,81 @@ less.Parser = function Parser(env) { // @charset "utf-8"; // directive: function () { - var name, value, rules, types; + var name, value, rules, identifier, e, nodes, nonVendorSpecificName, + hasBlock, hasIdentifier, hasExpression; if (input.charAt(i) !== '@') return; - if (value = $(this['import'])) { + if (value = $(this['import']) || $(this.media)) { return value; - } else if (name = $(/^@media|@page/) || $(/^@(?:-webkit-|-moz-)?keyframes/)) { - types = ($(/^[^{]+/) || '').trim(); + } + + save(); + + name = $(/^@[a-z-]+/); + + if (!name) return; + + nonVendorSpecificName = name; + if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) { + nonVendorSpecificName = "@" + name.slice(name.indexOf('-', 2) + 1); + } + + switch(nonVendorSpecificName) { + case "@font-face": + hasBlock = true; + break; + case "@viewport": + case "@top-left": + case "@top-left-corner": + case "@top-center": + case "@top-right": + case "@top-right-corner": + case "@bottom-left": + case "@bottom-left-corner": + case "@bottom-center": + case "@bottom-right": + case "@bottom-right-corner": + case "@left-top": + case "@left-middle": + case "@left-bottom": + case "@right-top": + case "@right-middle": + case "@right-bottom": + hasBlock = true; + break; + case "@page": + case "@document": + case "@supports": + case "@keyframes": + hasBlock = true; + hasIdentifier = true; + break; + case "@namespace": + hasExpression = true; + break; + } + + if (hasIdentifier) { + name += " " + ($(/^[^{]+/) || '').trim(); + } + + if (hasBlock) + { if (rules = $(this.block)) { - return new(tree.Directive)(name + " " + types, rules); + return new(tree.Directive)(name, rules); } - } else if (name = $(/^@[-a-z]+/)) { - if (name === '@font-face') { - if (rules = $(this.block)) { - return new(tree.Directive)(name, rules); + } else { + if ((value = hasExpression ? $(this.expression) : $(this.entity)) && $(';')) { + var directive = new(tree.Directive)(name, value); + if (env.dumpLineNumbers) { + directive.debugInfo = getDebugInfo(i, input, env); } - } else if ((value = $(this.entity)) && $(';')) { - return new(tree.Directive)(name, value); + return directive; } } + + restore(); }, font: function () { var value = [], expression = [], weight, shorthand, font, e; @@ -1038,7 +1401,7 @@ less.Parser = function Parser(env) { multiplication: function () { var m, a, op, operation; if (m = $(this.operand)) { - while ((op = ($('/') || $('*'))) && (a = $(this.operand))) { + while (!peek(/^\/[*\/]/) && (op = ($('/') || $('*'))) && (a = $(this.operand))) { operation = new(tree.Operation)(op, [operation || m, a]); } return operation || m; @@ -1047,13 +1410,42 @@ less.Parser = function Parser(env) { addition: function () { var m, a, op, operation; if (m = $(this.multiplication)) { - while ((op = $(/^[-+]\s+/) || (input.charAt(i - 1) != ' ' && ($('+') || $('-')))) && + while ((op = $(/^[-+]\s+/) || (!isWhitespace(input.charAt(i - 1)) && ($('+') || $('-')))) && (a = $(this.multiplication))) { operation = new(tree.Operation)(op, [operation || m, a]); } return operation || m; } }, + conditions: function () { + var a, b, index = i, condition; + + if (a = $(this.condition)) { + while ($(',') && (b = $(this.condition))) { + condition = new(tree.Condition)('or', condition || a, b, index); + } + return condition || a; + } + }, + condition: function () { + var a, b, c, op, index = i, negate = false; + + if ($(/^not/)) { negate = true } + expect('('); + if (a = $(this.addition) || $(this.entities.keyword) || $(this.entities.quoted)) { + if (op = $(/^(?:>=|=<|[<=>])/)) { + if (b = $(this.addition) || $(this.entities.keyword) || $(this.entities.quoted)) { + c = new(tree.Condition)(op, a, b, index, negate); + } else { + error('expected expression'); + } + } else { + c = new(tree.Condition)('=', a, new(tree.Keyword)('true'), index, negate); + } + expect(')'); + return $(/^and/) ? new(tree.Condition)('and', c, $(this.condition)) : c; + } + }, // // An operand is anything that can be part of an operation, @@ -1090,7 +1482,7 @@ less.Parser = function Parser(env) { property: function () { var name; - if (name = $(/^(\*?-?[-a-z_0-9]+)\s*:/)) { + if (name = $(/^(\*?-?[_a-z0-9-]+)\s*:/)) { return name[1]; } } @@ -1103,13 +1495,28 @@ if (less.mode === 'browser' || less.mode === 'rhino') { // Used by `@import` directives // less.Parser.importer = function (path, paths, callback, env) { - if (path.charAt(0) !== '/' && paths.length > 0) { + if (!/^([a-z-]+:)?\//.test(path) && paths.length > 0) { path = paths[0] + path; } // We pass `true` as 3rd argument, to force the reload of the import. // This is so we can get the syntax tree as opposed to just the CSS output, // as we need this to evaluate the current stylesheet. - loadStyleSheet({ href: path, title: path, type: env.mime }, callback, true); + loadStyleSheet({ + href: path, + title: path, + type: env.mime, + contents: env.contents, + files: env.files, + rootpath: env.rootpath, + entryPath: env.entryPath, + relativeUrls: env.relativeUrls }, + function (e, root, data, sheet, _, path) { + if (e && typeof(env.errback) === "function") { + env.errback.call(null, path, paths, callback, env); + } else { + callback.call(null, e, root, path); + } + }, true); }; } diff --git a/build-tools/lib/less/rhino.js b/build-tools/lib/less/rhino.js index ab1c886..57d60f5 100644 --- a/build-tools/lib/less/rhino.js +++ b/build-tools/lib/less/rhino.js @@ -1,18 +1,27 @@ var name; function loadStyleSheet(sheet, callback, reload, remaining) { - var sheetName = name.slice(0, name.lastIndexOf('/') + 1) + sheet.href; - var input = readFile(sheetName); - var parser = new less.Parser(); + var endOfPath = Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\')), + sheetName = name.slice(0, endOfPath + 1) + sheet.href, + contents = sheet.contents || {}, + input = readFile(sheetName); + + contents[sheetName] = input; + + var parser = new less.Parser({ + paths: [sheet.href.replace(/[\w\.-]+$/, '')], + contents: contents + }); parser.parse(input, function (e, root) { if (e) { - print("Error: " + e); - quit(1); + return error(e, sheetName); + } + try { + callback(e, root, input, sheet, { local: false, lastModified: 0, remaining: remaining }, sheetName); + } catch(e) { + error(e, sheetName); } - callback(root, sheet, { local: false, lastModified: 0, remaining: remaining }); }); - - // callback({}, sheet, { local: true, remaining: remaining }); } function writeFile(filename, content) { @@ -24,8 +33,26 @@ function writeFile(filename, content) { // Command line integration via Rhino (function (args) { - name = args[0]; - var output = args[1]; + var output, + compress = false, + i; + + for(i = 0; i < args.length; i++) { + switch(args[i]) { + case "-x": + compress = true; + break; + default: + if (!name) { + name = args[i]; + } else if (!output) { + output = args[i]; + } else { + print("unrecognised parameters"); + print("input_file [output_file] [-x]"); + } + } + } if (!name) { print('No files present in the fileset; Check your pattern match in build.xml'); @@ -41,20 +68,56 @@ function writeFile(filename, content) { } var result; - var parser = new less.Parser(); - parser.parse(input, function (e, root) { - if (e) { - quit(1); - } else { - result = root.toCSS(); - if (output) { - writeFile(output, result); - print("Written to " + output); + try { + var parser = new less.Parser(); + parser.parse(input, function (e, root) { + if (e) { + error(e, name); + quit(1); } else { - print(result); + result = root.toCSS({compress: compress || false}); + if (output) { + writeFile(output, result); + print("Written to " + output); + } else { + print(result); + } + quit(0); } - quit(0); - } - }); + }); + } + catch(e) { + error(e, name); + quit(1); + } print("done"); }(arguments)); + +function error(e, filename) { + + var content = "Error : " + filename + "\n"; + + filename = e.filename || filename; + + if (e.message) { + content += e.message + "\n"; + } + + var errorline = function (e, i, classname) { + if (e.extract[i]) { + content += + String(parseInt(e.line) + (i - 1)) + + ":" + e.extract[i] + "\n"; + } + }; + + if (e.stack) { + content += e.stack; + } else if (e.extract) { + content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':\n'; + errorline(e, 0); + errorline(e, 1); + errorline(e, 2); + } + print(content); +} \ No newline at end of file diff --git a/build-tools/lib/less/tree.js b/build-tools/lib/less/tree.js index eb08aa4..134adbd 100644 --- a/build-tools/lib/less/tree.js +++ b/build-tools/lib/less/tree.js @@ -1,13 +1,45 @@ -require('less/tree').find = function (obj, fun) { +(function (tree) { + +tree.debugInfo = function(env, ctx) { + var result=""; + if (env.dumpLineNumbers && !env.compress) { + switch(env.dumpLineNumbers) { + case 'comments': + result = tree.debugInfo.asComment(ctx); + break; + case 'mediaquery': + result = tree.debugInfo.asMediaQuery(ctx); + break; + case 'all': + result = tree.debugInfo.asComment(ctx)+tree.debugInfo.asMediaQuery(ctx); + break; + } + } + return result; +}; + +tree.debugInfo.asComment = function(ctx) { + return '/* line ' + ctx.debugInfo.lineNumber + ', ' + ctx.debugInfo.fileName + ' */\n'; +}; + +tree.debugInfo.asMediaQuery = function(ctx) { + return '@media -sass-debug-info{filename{font-family:' + + ('file://' + ctx.debugInfo.fileName).replace(/[\/:.]/g, '\\$&') + + '}line{font-family:\\00003' + ctx.debugInfo.lineNumber + '}}\n'; +}; + +tree.find = function (obj, fun) { for (var i = 0, r; i < obj.length; i++) { if (r = fun.call(obj, obj[i])) { return r } } return null; }; -require('less/tree').jsify = function (obj) { +tree.jsify = function (obj) { if (Array.isArray(obj.value) && (obj.value.length > 1)) { return '[' + obj.value.map(function (v) { return v.toCSS(false) }).join(', ') + ']'; } else { return obj.toCSS(false); } }; + +})(require('./tree')); diff --git a/build-tools/lib/less/tree/alpha.js b/build-tools/lib/less/tree/alpha.js index 551ccba..139ae92 100644 --- a/build-tools/lib/less/tree/alpha.js +++ b/build-tools/lib/less/tree/alpha.js @@ -14,4 +14,4 @@ tree.Alpha.prototype = { } }; -})(require('less/tree')); +})(require('../tree')); diff --git a/build-tools/lib/less/tree/anonymous.js b/build-tools/lib/less/tree/anonymous.js index 89840d0..4461490 100644 --- a/build-tools/lib/less/tree/anonymous.js +++ b/build-tools/lib/less/tree/anonymous.js @@ -7,7 +7,21 @@ tree.Anonymous.prototype = { toCSS: function () { return this.value; }, - eval: function () { return this } + eval: function () { return this }, + compare: function (x) { + if (!x.toCSS) { + return -1; + } + + var left = this.toCSS(), + right = x.toCSS(); + + if (left === right) { + return 0; + } + + return left < right ? -1 : 1; + } }; -})(require('less/tree')); +})(require('../tree')); diff --git a/build-tools/lib/less/tree/assignment.js b/build-tools/lib/less/tree/assignment.js new file mode 100644 index 0000000..a5559ad --- /dev/null +++ b/build-tools/lib/less/tree/assignment.js @@ -0,0 +1,19 @@ +(function (tree) { + +tree.Assignment = function (key, val) { + this.key = key; + this.value = val; +}; +tree.Assignment.prototype = { + toCSS: function () { + return this.key + '=' + (this.value.toCSS ? this.value.toCSS() : this.value); + }, + eval: function (env) { + if (this.value.eval) { + return new(tree.Assignment)(this.key, this.value.eval(env)); + } + return this; + } +}; + +})(require('../tree')); \ No newline at end of file diff --git a/build-tools/lib/less/tree/call.js b/build-tools/lib/less/tree/call.js index 4a72932..f8045ed 100644 --- a/build-tools/lib/less/tree/call.js +++ b/build-tools/lib/less/tree/call.js @@ -3,17 +3,19 @@ // // A function call node. // -tree.Call = function (name, args, index) { +tree.Call = function (name, args, index, filename) { this.name = name; this.args = args; this.index = index; + this.filename = filename; }; tree.Call.prototype = { // // When evaluating a function call, // we either find the function in `tree.functions` [1], // in which case we call it, passing the evaluated arguments, - // or we simply print it out as it appeared originally [2]. + // if this returns null or we cannot find the function, we + // simply print it out as it appeared originally [2]. // // The *functions.js* file contains the built-in functions. // @@ -22,19 +24,26 @@ tree.Call.prototype = { // The function should receive the value, not the variable. // eval: function (env) { - var args = this.args.map(function (a) { return a.eval(env) }); + var args = this.args.map(function (a) { return a.eval(env) }), + result; if (this.name in tree.functions) { // 1. try { - return tree.functions[this.name].apply(tree.functions, args); + result = tree.functions[this.name].apply(tree.functions, args); + if (result != null) { + return result; + } } catch (e) { - throw { message: "error evaluating function `" + this.name + "`", - index: this.index }; + throw { type: e.type || "Runtime", + message: "error evaluating function `" + this.name + "`" + + (e.message ? ': ' + e.message : ''), + index: this.index, filename: this.filename }; } - } else { // 2. - return new(tree.Anonymous)(this.name + - "(" + args.map(function (a) { return a.toCSS() }).join(', ') + ")"); } + + // 2. + return new(tree.Anonymous)(this.name + + "(" + args.map(function (a) { return a.toCSS(env) }).join(', ') + ")"); }, toCSS: function (env) { @@ -42,4 +51,4 @@ tree.Call.prototype = { } }; -})(require('less/tree')); +})(require('../tree')); diff --git a/build-tools/lib/less/tree/color.js b/build-tools/lib/less/tree/color.js index bb7646a..6adf317 100644 --- a/build-tools/lib/less/tree/color.js +++ b/build-tools/lib/less/tree/color.js @@ -94,8 +94,18 @@ tree.Color.prototype = { i = (i > 255 ? 255 : (i < 0 ? 0 : i)).toString(16); return i.length === 1 ? '0' + i : i; }).join(''); + }, + compare: function (x) { + if (!x.rgb) { + return -1; + } + + return (x.rgb[0] === this.rgb[0] && + x.rgb[1] === this.rgb[1] && + x.rgb[2] === this.rgb[2] && + x.alpha === this.alpha) ? 0 : -1; } }; -})(require('less/tree')); +})(require('../tree')); diff --git a/build-tools/lib/less/tree/comment.js b/build-tools/lib/less/tree/comment.js index 2d95dff..f4a3384 100644 --- a/build-tools/lib/less/tree/comment.js +++ b/build-tools/lib/less/tree/comment.js @@ -11,4 +11,4 @@ tree.Comment.prototype = { eval: function () { return this } }; -})(require('less/tree')); +})(require('../tree')); diff --git a/build-tools/lib/less/tree/condition.js b/build-tools/lib/less/tree/condition.js new file mode 100644 index 0000000..6b79dc9 --- /dev/null +++ b/build-tools/lib/less/tree/condition.js @@ -0,0 +1,42 @@ +(function (tree) { + +tree.Condition = function (op, l, r, i, negate) { + this.op = op.trim(); + this.lvalue = l; + this.rvalue = r; + this.index = i; + this.negate = negate; +}; +tree.Condition.prototype.eval = function (env) { + var a = this.lvalue.eval(env), + b = this.rvalue.eval(env); + + var i = this.index, result; + + var result = (function (op) { + switch (op) { + case 'and': + return a && b; + case 'or': + return a || b; + default: + if (a.compare) { + result = a.compare(b); + } else if (b.compare) { + result = b.compare(a); + } else { + throw { type: "Type", + message: "Unable to perform comparison", + index: i }; + } + switch (result) { + case -1: return op === '<' || op === '=<'; + case 0: return op === '=' || op === '>=' || op === '=<'; + case 1: return op === '>' || op === '>='; + } + } + })(this.op); + return this.negate ? !result : result; +}; + +})(require('../tree')); diff --git a/build-tools/lib/less/tree/dimension.js b/build-tools/lib/less/tree/dimension.js index 41f3ca2..22241b8 100644 --- a/build-tools/lib/less/tree/dimension.js +++ b/build-tools/lib/less/tree/dimension.js @@ -28,7 +28,24 @@ tree.Dimension.prototype = { return new(tree.Dimension) (tree.operate(op, this.value, other.value), this.unit || other.unit); + }, + + compare: function (other) { + if (other instanceof tree.Dimension) { + if (other.value > this.value) { + return -1; + } else if (other.value < this.value) { + return 1; + } else { + if (other.unit && this.unit !== other.unit) { + return -1; + } + return 0; + } + } else { + return -1; + } } }; -})(require('less/tree')); +})(require('../tree')); diff --git a/build-tools/lib/less/tree/directive.js b/build-tools/lib/less/tree/directive.js index fbe9a93..4d682e6 100644 --- a/build-tools/lib/less/tree/directive.js +++ b/build-tools/lib/less/tree/directive.js @@ -2,8 +2,10 @@ tree.Directive = function (name, value) { this.name = name; + if (Array.isArray(value)) { this.ruleset = new(tree.Ruleset)([], value); + this.ruleset.allowImports = true; } else { this.value = value; } @@ -20,14 +22,18 @@ tree.Directive.prototype = { } }, eval: function (env) { - env.frames.unshift(this); - this.ruleset = this.ruleset && this.ruleset.eval(env); - env.frames.shift(); - return this; + var evaldDirective = this; + if (this.ruleset) { + env.frames.unshift(this); + evaldDirective = new(tree.Directive)(this.name); + evaldDirective.ruleset = this.ruleset.eval(env); + env.frames.shift(); + } + return evaldDirective; }, variable: function (name) { return tree.Ruleset.prototype.variable.call(this.ruleset, name) }, find: function () { return tree.Ruleset.prototype.find.apply(this.ruleset, arguments) }, rulesets: function () { return tree.Ruleset.prototype.rulesets.apply(this.ruleset) } }; -})(require('less/tree')); +})(require('../tree')); diff --git a/build-tools/lib/less/tree/element.js b/build-tools/lib/less/tree/element.js index 27cf822..4e251ee 100644 --- a/build-tools/lib/less/tree/element.js +++ b/build-tools/lib/less/tree/element.js @@ -1,19 +1,35 @@ (function (tree) { -tree.Element = function (combinator, value) { +tree.Element = function (combinator, value, index) { this.combinator = combinator instanceof tree.Combinator ? combinator : new(tree.Combinator)(combinator); - this.value = value ? value.trim() : ""; + + if (typeof(value) === 'string') { + this.value = value.trim(); + } else if (value) { + this.value = value; + } else { + this.value = ""; + } + this.index = index; +}; +tree.Element.prototype.eval = function (env) { + return new(tree.Element)(this.combinator, + this.value.eval ? this.value.eval(env) : this.value, + this.index); }; tree.Element.prototype.toCSS = function (env) { - return this.combinator.toCSS(env || {}) + this.value; + var value = (this.value.toCSS ? this.value.toCSS(env) : this.value); + if (value == '' && this.combinator.value.charAt(0) == '&') { + return ''; + } else { + return this.combinator.toCSS(env || {}) + value; + } }; tree.Combinator = function (value) { if (value === ' ') { this.value = ' '; - } else if (value === '& ') { - this.value = '& '; } else { this.value = value ? value.trim() : ""; } @@ -22,14 +38,12 @@ tree.Combinator.prototype.toCSS = function (env) { return { '' : '', ' ' : ' ', - '&' : '', - '& ' : ' ', ':' : ' :', - '::': '::', '+' : env.compress ? '+' : ' + ', '~' : env.compress ? '~' : ' ~ ', - '>' : env.compress ? '>' : ' > ' + '>' : env.compress ? '>' : ' > ', + '|' : env.compress ? '|' : ' | ' }[this.value]; }; -})(require('less/tree')); +})(require('../tree')); diff --git a/build-tools/lib/less/tree/expression.js b/build-tools/lib/less/tree/expression.js index f638a1b..fbfa9c5 100644 --- a/build-tools/lib/less/tree/expression.js +++ b/build-tools/lib/less/tree/expression.js @@ -15,9 +15,9 @@ tree.Expression.prototype = { }, toCSS: function (env) { return this.value.map(function (e) { - return e.toCSS(env); + return e.toCSS ? e.toCSS(env) : ''; }).join(' '); } }; -})(require('less/tree')); +})(require('../tree')); diff --git a/build-tools/lib/less/tree/import.js b/build-tools/lib/less/tree/import.js index 427c109..02594a7 100644 --- a/build-tools/lib/less/tree/import.js +++ b/build-tools/lib/less/tree/import.js @@ -11,27 +11,30 @@ // `import,push`, we also pass it a callback, which it'll call once // the file has been fetched, and parsed. // -tree.Import = function (path, imports) { +tree.Import = function (path, imports, features, once, index, rootpath) { var that = this; + this.once = once; + this.index = index; this._path = path; - + this.features = features && new(tree.Value)(features); + this.rootpath = rootpath; + // The '.less' extension is optional if (path instanceof tree.Quoted) { - this.path = /\.(le?|c)ss(\?.*)?$/.test(path.value) ? path.value : path.value + '.less'; + this.path = /(\.[a-z]*$)|([\?;].*)$/.test(path.value) ? path.value : path.value + '.less'; } else { this.path = path.value.value || path.value; } - this.css = /css(\?.*)?$/.test(this.path); + this.css = /css([\?;].*)?$/.test(this.path); // Only pre-compile .less files if (! this.css) { - imports.push(this.path, function (root) { - if (! root) { - throw new(Error)("Error parsing " + that.path); - } - that.root = root; + imports.push(this.path, function (e, root, imported) { + if (e) { e.index = index } + if (imported && that.once) that.skip = imported; + that.root = root || new(tree.Ruleset)([], []); }); } }; @@ -46,32 +49,34 @@ tree.Import = function (path, imports) { // ruleset. // tree.Import.prototype = { - toCSS: function () { + toCSS: function (env) { + var features = this.features ? ' ' + this.features.toCSS(env) : ''; + if (this.css) { - return "@import " + this._path.toCSS() + ';\n'; + // Add the base path if the import is relative + if (typeof this._path.value === "string" && !/^(?:[a-z-]+:|\/)/.test(this._path.value)) { + this._path.value = this.rootpath + this._path.value; + } + return "@import " + this._path.toCSS() + features + ';\n'; } else { return ""; } }, eval: function (env) { - var ruleset; + var ruleset, features = this.features && this.features.eval(env); + + if (this.skip) return []; if (this.css) { return this; } else { - ruleset = new(tree.Ruleset)(null, this.root.rules.slice(0)); + ruleset = new(tree.Ruleset)([], this.root.rules.slice(0)); - for (var i = 0; i < ruleset.rules.length; i++) { - if (ruleset.rules[i] instanceof tree.Import) { - Array.prototype - .splice - .apply(ruleset.rules, - [i, 1].concat(ruleset.rules[i].eval(env))); - } - } - return ruleset.rules; + ruleset.evalImports(env); + + return this.features ? new(tree.Media)(ruleset.rules, this.features.value) : ruleset.rules; } } }; -})(require('less/tree')); +})(require('../tree')); diff --git a/build-tools/lib/less/tree/javascript.js b/build-tools/lib/less/tree/javascript.js index 4ec66b9..772a31d 100644 --- a/build-tools/lib/less/tree/javascript.js +++ b/build-tools/lib/less/tree/javascript.js @@ -47,5 +47,5 @@ tree.JavaScript.prototype = { } }; -})(require('less/tree')); +})(require('../tree')); diff --git a/build-tools/lib/less/tree/keyword.js b/build-tools/lib/less/tree/keyword.js index a4431ba..701b79e 100644 --- a/build-tools/lib/less/tree/keyword.js +++ b/build-tools/lib/less/tree/keyword.js @@ -3,7 +3,17 @@ tree.Keyword = function (value) { this.value = value }; tree.Keyword.prototype = { eval: function () { return this }, - toCSS: function () { return this.value } + toCSS: function () { return this.value }, + compare: function (other) { + if (other instanceof tree.Keyword) { + return other.value === this.value ? 0 : 1; + } else { + return -1; + } + } }; -})(require('less/tree')); +tree.True = new(tree.Keyword)('true'); +tree.False = new(tree.Keyword)('false'); + +})(require('../tree')); diff --git a/build-tools/lib/less/tree/media.js b/build-tools/lib/less/tree/media.js new file mode 100644 index 0000000..d2a5347 --- /dev/null +++ b/build-tools/lib/less/tree/media.js @@ -0,0 +1,121 @@ +(function (tree) { + +tree.Media = function (value, features) { + var selectors = this.emptySelectors(); + + this.features = new(tree.Value)(features); + this.ruleset = new(tree.Ruleset)(selectors, value); + this.ruleset.allowImports = true; +}; +tree.Media.prototype = { + toCSS: function (ctx, env) { + var features = this.features.toCSS(env); + + this.ruleset.root = (ctx.length === 0 || ctx[0].multiMedia); + return '@media ' + features + (env.compress ? '{' : ' {\n ') + + this.ruleset.toCSS(ctx, env).trim().replace(/\n/g, '\n ') + + (env.compress ? '}': '\n}\n'); + }, + eval: function (env) { + if (!env.mediaBlocks) { + env.mediaBlocks = []; + env.mediaPath = []; + } + + var media = new(tree.Media)([], []); + if(this.debugInfo) { + this.ruleset.debugInfo = this.debugInfo; + media.debugInfo = this.debugInfo; + } + media.features = this.features.eval(env); + + env.mediaPath.push(media); + env.mediaBlocks.push(media); + + env.frames.unshift(this.ruleset); + media.ruleset = this.ruleset.eval(env); + env.frames.shift(); + + env.mediaPath.pop(); + + return env.mediaPath.length === 0 ? media.evalTop(env) : + media.evalNested(env) + }, + variable: function (name) { return tree.Ruleset.prototype.variable.call(this.ruleset, name) }, + find: function () { return tree.Ruleset.prototype.find.apply(this.ruleset, arguments) }, + rulesets: function () { return tree.Ruleset.prototype.rulesets.apply(this.ruleset) }, + emptySelectors: function() { + var el = new(tree.Element)('', '&', 0); + return [new(tree.Selector)([el])]; + }, + + evalTop: function (env) { + var result = this; + + // Render all dependent Media blocks. + if (env.mediaBlocks.length > 1) { + var selectors = this.emptySelectors(); + result = new(tree.Ruleset)(selectors, env.mediaBlocks); + result.multiMedia = true; + } + + delete env.mediaBlocks; + delete env.mediaPath; + + return result; + }, + evalNested: function (env) { + var i, value, + path = env.mediaPath.concat([this]); + + // Extract the media-query conditions separated with `,` (OR). + for (i = 0; i < path.length; i++) { + value = path[i].features instanceof tree.Value ? + path[i].features.value : path[i].features; + path[i] = Array.isArray(value) ? value : [value]; + } + + // Trace all permutations to generate the resulting media-query. + // + // (a, b and c) with nested (d, e) -> + // a and d + // a and e + // b and c and d + // b and c and e + this.features = new(tree.Value)(this.permute(path).map(function (path) { + path = path.map(function (fragment) { + return fragment.toCSS ? fragment : new(tree.Anonymous)(fragment); + }); + + for(i = path.length - 1; i > 0; i--) { + path.splice(i, 0, new(tree.Anonymous)("and")); + } + + return new(tree.Expression)(path); + })); + + // Fake a tree-node that doesn't output anything. + return new(tree.Ruleset)([], []); + }, + permute: function (arr) { + if (arr.length === 0) { + return []; + } else if (arr.length === 1) { + return arr[0]; + } else { + var result = []; + var rest = this.permute(arr.slice(1)); + for (var i = 0; i < rest.length; i++) { + for (var j = 0; j < arr[0].length; j++) { + result.push([arr[0][j]].concat(rest[i])); + } + } + return result; + } + }, + bubbleSelectors: function (selectors) { + this.ruleset = new(tree.Ruleset)(selectors.slice(0), [this.ruleset]); + } +}; + +})(require('../tree')); diff --git a/build-tools/lib/less/tree/mixin.js b/build-tools/lib/less/tree/mixin.js index 24cb8e4..0533036 100644 --- a/build-tools/lib/less/tree/mixin.js +++ b/build-tools/lib/less/tree/mixin.js @@ -1,50 +1,84 @@ (function (tree) { tree.mixin = {}; -tree.mixin.Call = function (elements, args, index) { +tree.mixin.Call = function (elements, args, index, filename, important) { this.selector = new(tree.Selector)(elements); this.arguments = args; this.index = index; + this.filename = filename; + this.important = important; }; tree.mixin.Call.prototype = { eval: function (env) { - var mixins, args, rules = [], match = false; + var mixins, mixin, args, rules = [], match = false, i, m, f, isRecursive, isOneFound; - for (var i = 0; i < env.frames.length; i++) { + args = this.arguments && this.arguments.map(function (a) { + return { name: a.name, value: a.value.eval(env) }; + }); + + for (i = 0; i < env.frames.length; i++) { if ((mixins = env.frames[i].find(this.selector)).length > 0) { - args = this.arguments && this.arguments.map(function (a) { return a.eval(env) }); - for (var m = 0; m < mixins.length; m++) { - if (mixins[m].match(args, env)) { - try { - Array.prototype.push.apply( - rules, mixins[m].eval(env, this.arguments).rules); - match = true; - } catch (e) { - throw { message: e.message, index: e.index, stack: e.stack, call: this.index }; + isOneFound = true; + for (m = 0; m < mixins.length; m++) { + mixin = mixins[m]; + isRecursive = false; + for(f = 0; f < env.frames.length; f++) { + if ((!(mixin instanceof tree.mixin.Definition)) && mixin === (env.frames[f].originalRuleset || env.frames[f])) { + isRecursive = true; + break; } } + if (isRecursive) { + continue; + } + if (mixin.matchArgs(args, env)) { + if (!mixin.matchCondition || mixin.matchCondition(args, env)) { + try { + Array.prototype.push.apply( + rules, mixin.eval(env, args, this.important).rules); + } catch (e) { + throw { message: e.message, index: this.index, filename: this.filename, stack: e.stack }; + } + } + match = true; + } } if (match) { return rules; - } else { - throw { message: 'No matching definition was found for `' + - this.selector.toCSS().trim() + '(' + - this.arguments.map(function (a) { - return a.toCSS(); - }).join(', ') + ")`", - index: this.index }; } } } - throw { message: this.selector.toCSS().trim() + " is undefined", - index: this.index }; + if (isOneFound) { + throw { type: 'Runtime', + message: 'No matching definition was found for `' + + this.selector.toCSS().trim() + '(' + + (args ? args.map(function (a) { + var argValue = ""; + if (a.name) { + argValue += a.name + ":"; + } + if (a.value.toCSS) { + argValue += a.value.toCSS(); + } else { + argValue += "???"; + } + return argValue; + }).join(', ') : "") + ")`", + index: this.index, filename: this.filename }; + } else { + throw { type: 'Name', + message: this.selector.toCSS().trim() + " is undefined", + index: this.index, filename: this.filename }; + } } }; -tree.mixin.Definition = function (name, params, rules) { +tree.mixin.Definition = function (name, params, rules, condition, variadic) { this.name = name; this.selectors = [new(tree.Selector)([new(tree.Element)(null, name)])]; this.params = params; + this.condition = condition; + this.variadic = variadic; this.arity = params.length; this.rules = rules; this._lookups = {}; @@ -62,39 +96,111 @@ tree.mixin.Definition.prototype = { find: function () { return this.parent.find.apply(this, arguments) }, rulesets: function () { return this.parent.rulesets.apply(this) }, - eval: function (env, args) { - var frame = new(tree.Ruleset)(null, []), context, _arguments = []; + evalParams: function (env, mixinEnv, args, evaldArguments) { + var frame = new(tree.Ruleset)(null, []), varargs, arg, params = this.params.slice(0), i, j, val, name, isNamedFound, argIndex; + + if (args) { + args = args.slice(0); + + for(i = 0; i < args.length; i++) { + arg = args[i]; + if (name = (arg && arg.name)) { + isNamedFound = false; + for(j = 0; j < params.length; j++) { + if (!evaldArguments[j] && name === params[j].name) { + evaldArguments[j] = arg.value.eval(env); + frame.rules.unshift(new(tree.Rule)(name, arg.value.eval(env))); + isNamedFound = true; + break; + } + } + if (isNamedFound) { + args.splice(i, 1); + i--; + continue; + } else { + throw { type: 'Runtime', message: "Named argument for " + this.name + + ' ' + args[i].name + ' not found' }; + } + } + } + } + argIndex = 0; + for (i = 0; i < params.length; i++) { + if (evaldArguments[i]) continue; + + arg = args && args[argIndex]; - for (var i = 0, val; i < this.params.length; i++) { - if (this.params[i].name) { - if (val = (args && args[i]) || this.params[i].value) { - frame.rules.unshift(new(tree.Rule)(this.params[i].name, val.eval(env))); + if (name = params[i].name) { + if (params[i].variadic && args) { + varargs = []; + for (j = argIndex; j < args.length; j++) { + varargs.push(args[j].value.eval(env)); + } + frame.rules.unshift(new(tree.Rule)(name, new(tree.Expression)(varargs).eval(env))); } else { - throw { message: "wrong number of arguments for " + this.name + + val = arg && arg.value; + if (val) { + val = val.eval(env); + } else if (params[i].value) { + val = params[i].value.eval(mixinEnv); + } else { + throw { type: 'Runtime', message: "wrong number of arguments for " + this.name + ' (' + args.length + ' for ' + this.arity + ')' }; + } + + frame.rules.unshift(new(tree.Rule)(name, val)); + evaldArguments[i] = val; } } + + if (params[i].variadic && args) { + for (j = argIndex; j < args.length; j++) { + evaldArguments[j] = args[j].value.eval(env); + } + } + argIndex++; } - for (var i = 0; i < Math.max(this.params.length, args && args.length); i++) { - _arguments.push(args[i] || this.params[i].value); - } + + return frame; + }, + eval: function (env, args, important) { + var _arguments = [], + mixinFrames = this.frames.concat(env.frames), + frame = this.evalParams(env, {frames: mixinFrames}, args, _arguments), + context, rules, start, ruleset; + frame.rules.unshift(new(tree.Rule)('@arguments', new(tree.Expression)(_arguments).eval(env))); - return new(tree.Ruleset)(null, this.rules.slice(0)).eval({ - frames: [this, frame].concat(this.frames, env.frames) + rules = important ? + this.parent.makeImportant.apply(this).rules : this.rules.slice(0); + + ruleset = new(tree.Ruleset)(null, rules).eval({ + frames: [this, frame].concat(mixinFrames) }); + ruleset.originalRuleset = this; + return ruleset; }, - match: function (args, env) { - var argsLength = (args && args.length) || 0, len; + matchCondition: function (args, env) { + if (this.condition && !this.condition.eval({ + frames: [this.evalParams(env, {frames: this.frames.concat(env.frames)}, args, [])].concat(env.frames) + })) { return false } + return true; + }, + matchArgs: function (args, env) { + var argsLength = (args && args.length) || 0, len, frame; - if (argsLength < this.required) { return false } - if ((this.required > 0) && (argsLength > this.params.length)) { return false } + if (! this.variadic) { + if (argsLength < this.required) { return false } + if (argsLength > this.params.length) { return false } + if ((this.required > 0) && (argsLength > this.params.length)) { return false } + } len = Math.min(argsLength, this.arity); for (var i = 0; i < len; i++) { - if (!this.params[i].name) { - if (args[i].eval(env).toCSS() != this.params[i].value.eval(env).toCSS()) { + if (!this.params[i].name && !this.params[i].variadic) { + if (args[i].value.eval(env).toCSS() != this.params[i].value.eval(env).toCSS()) { return false; } } @@ -103,4 +209,4 @@ tree.mixin.Definition.prototype = { } }; -})(require('less/tree')); +})(require('../tree')); diff --git a/build-tools/lib/less/tree/operation.js b/build-tools/lib/less/tree/operation.js index d2e4d57..3c4f093 100644 --- a/build-tools/lib/less/tree/operation.js +++ b/build-tools/lib/less/tree/operation.js @@ -17,6 +17,11 @@ tree.Operation.prototype.eval = function (env) { message: "Can't substract or divide a color from a number" }; } } + if (!a.operate) { + throw { name: "OperationError", + message: "Operation on an invalid type" }; + } + return a.operate(this.op, b); }; @@ -29,4 +34,4 @@ tree.operate = function (op, a, b) { } }; -})(require('less/tree')); +})(require('../tree')); diff --git a/build-tools/lib/less/tree/paren.js b/build-tools/lib/less/tree/paren.js new file mode 100644 index 0000000..384a43c --- /dev/null +++ b/build-tools/lib/less/tree/paren.js @@ -0,0 +1,16 @@ + +(function (tree) { + +tree.Paren = function (node) { + this.value = node; +}; +tree.Paren.prototype = { + toCSS: function (env) { + return '(' + this.value.toCSS(env) + ')'; + }, + eval: function (env) { + return new(tree.Paren)(this.value.eval(env)); + } +}; + +})(require('../tree')); diff --git a/build-tools/lib/less/tree/quoted.js b/build-tools/lib/less/tree/quoted.js index 6ddfa40..4ec6713 100644 --- a/build-tools/lib/less/tree/quoted.js +++ b/build-tools/lib/less/tree/quoted.js @@ -20,10 +20,24 @@ tree.Quoted.prototype = { return new(tree.JavaScript)(exp, that.index, true).eval(env).value; }).replace(/@\{([\w-]+)\}/g, function (_, name) { var v = new(tree.Variable)('@' + name, that.index).eval(env); - return v.value || v.toCSS(); + return (v instanceof tree.Quoted) ? v.value : v.toCSS(); }); return new(tree.Quoted)(this.quote + value + this.quote, value, this.escaped, this.index); + }, + compare: function (x) { + if (!x.toCSS) { + return -1; + } + + var left = this.toCSS(), + right = x.toCSS(); + + if (left === right) { + return 0; + } + + return left < right ? -1 : 1; } }; -})(require('less/tree')); +})(require('../tree')); diff --git a/build-tools/lib/less/tree/ratio.js b/build-tools/lib/less/tree/ratio.js new file mode 100644 index 0000000..f7622fb --- /dev/null +++ b/build-tools/lib/less/tree/ratio.js @@ -0,0 +1,13 @@ +(function (tree) { + +tree.Ratio = function (value) { + this.value = value; +}; +tree.Ratio.prototype = { + toCSS: function (env) { + return this.value; + }, + eval: function () { return this } +}; + +})(require('../tree')); diff --git a/build-tools/lib/less/tree/rule.js b/build-tools/lib/less/tree/rule.js index 18cc49b..8990fef 100644 --- a/build-tools/lib/less/tree/rule.js +++ b/build-tools/lib/less/tree/rule.js @@ -1,10 +1,11 @@ (function (tree) { -tree.Rule = function (name, value, important, index) { +tree.Rule = function (name, value, important, index, inline) { this.name = name; this.value = (value instanceof tree.Value) ? value : new(tree.Value)([value]); this.important = important ? ' ' + important.trim() : ''; this.index = index; + this.inline = inline || false; if (name.charAt(0) === '@') { this.variable = true; @@ -15,12 +16,22 @@ tree.Rule.prototype.toCSS = function (env) { else { return this.name + (env.compress ? ':' : ': ') + this.value.toCSS(env) + - this.important + ";"; + this.important + (this.inline ? "" : ";"); } }; tree.Rule.prototype.eval = function (context) { - return new(tree.Rule)(this.name, this.value.eval(context), this.important, this.index); + return new(tree.Rule)(this.name, + this.value.eval(context), + this.important, + this.index, this.inline); +}; + +tree.Rule.prototype.makeImportant = function () { + return new(tree.Rule)(this.name, + this.value, + "!important", + this.index, this.inline); }; tree.Shorthand = function (a, b) { @@ -35,4 +46,4 @@ tree.Shorthand.prototype = { eval: function () { return this } }; -})(require('less/tree')); +})(require('../tree')); diff --git a/build-tools/lib/less/tree/ruleset.js b/build-tools/lib/less/tree/ruleset.js index cc9a60a..a198617 100644 --- a/build-tools/lib/less/tree/ruleset.js +++ b/build-tools/lib/less/tree/ruleset.js @@ -1,27 +1,31 @@ (function (tree) { -tree.Ruleset = function (selectors, rules) { +tree.Ruleset = function (selectors, rules, strictImports) { this.selectors = selectors; this.rules = rules; this._lookups = {}; + this.strictImports = strictImports; }; tree.Ruleset.prototype = { eval: function (env) { - var ruleset = new(tree.Ruleset)(this.selectors, this.rules.slice(0)); - + var selectors = this.selectors && this.selectors.map(function (s) { return s.eval(env) }); + var ruleset = new(tree.Ruleset)(selectors, this.rules.slice(0), this.strictImports); + var rules; + + ruleset.originalRuleset = this; ruleset.root = this.root; + ruleset.allowImports = this.allowImports; + + if(this.debugInfo) { + ruleset.debugInfo = this.debugInfo; + } // push the current ruleset to the frames stack env.frames.unshift(ruleset); // Evaluate imports - if (ruleset.root) { - for (var i = 0; i < ruleset.rules.length; i++) { - if (ruleset.rules[i] instanceof tree.Import) { - Array.prototype.splice - .apply(ruleset.rules, [i, 1].concat(ruleset.rules[i].eval(env))); - } - } + if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) { + ruleset.evalImports(env); } // Store the frames around mixin definitions, @@ -31,12 +35,16 @@ tree.Ruleset.prototype = { ruleset.rules[i].frames = env.frames.slice(0); } } + + var mediaBlockCount = (env.mediaBlocks && env.mediaBlocks.length) || 0; // Evaluate mixin calls. for (var i = 0; i < ruleset.rules.length; i++) { if (ruleset.rules[i] instanceof tree.mixin.Call) { - Array.prototype.splice - .apply(ruleset.rules, [i, 1].concat(ruleset.rules[i].eval(env))); + rules = ruleset.rules[i].eval(env); + ruleset.rules.splice.apply(ruleset.rules, [i, 1].concat(rules)); + i += rules.length-1; + ruleset.resetCache(); } } @@ -51,12 +59,47 @@ tree.Ruleset.prototype = { // Pop the stack env.frames.shift(); + + if (env.mediaBlocks) { + for(var i = mediaBlockCount; i < env.mediaBlocks.length; i++) { + env.mediaBlocks[i].bubbleSelectors(selectors); + } + } return ruleset; }, - match: function (args) { + evalImports: function(env) { + var i, rules; + for (i = 0; i < this.rules.length; i++) { + if (this.rules[i] instanceof tree.Import) { + rules = this.rules[i].eval(env); + if (typeof rules.length === "number") { + this.rules.splice.apply(this.rules, [i, 1].concat(rules)); + i+= rules.length-1; + } else { + this.rules.splice(i, 1, rules); + } + this.resetCache(); + } + } + }, + makeImportant: function() { + return new tree.Ruleset(this.selectors, this.rules.map(function (r) { + if (r.makeImportant) { + return r.makeImportant(); + } else { + return r; + } + }), this.strictImports); + }, + matchArgs: function (args) { return !args || args.length === 0; }, + resetCache: function () { + this._rulesets = null; + this._variables = null; + this._lookups = {}; + }, variables: function () { if (this._variables) { return this._variables } else { @@ -111,25 +154,41 @@ tree.Ruleset.prototype = { toCSS: function (context, env) { var css = [], // The CSS output rules = [], // node.Rule instances + _rules = [], // rulesets = [], // node.Ruleset instances paths = [], // Current selectors selector, // The fully rendered selector + debugInfo, // Line number debugging rule; if (! this.root) { - if (context.length === 0) { - paths = this.selectors.map(function (s) { return [s] }); - } else { - this.joinSelectors( paths, context, this.selectors ); - } + this.joinSelectors(paths, context, this.selectors); } // Compile rules and rulesets for (var i = 0; i < this.rules.length; i++) { rule = this.rules[i]; - if (rule.rules || (rule instanceof tree.Directive)) { + if (rule.rules || (rule instanceof tree.Media)) { rulesets.push(rule.toCSS(paths, env)); + } else if (rule instanceof tree.Directive) { + var cssValue = rule.toCSS(paths, env); + // Output only the first @charset definition as such - convert the others + // to comments in case debug is enabled + if (rule.name === "@charset") { + // Only output the debug info together with subsequent @charset definitions + // a comment (or @media statement) before the actual @charset directive would + // be considered illegal css as it has to be on the first line + if (env.charset) { + if (rule.debugInfo) { + rulesets.push(tree.debugInfo(env, rule)); + rulesets.push(new tree.Comment("/* "+cssValue.replace(/\n/g, "")+" */\n").toCSS(env)); + } + continue; + } + env.charset = true; + } + rulesets.push(cssValue); } else if (rule instanceof tree.Comment) { if (!rule.silent) { if (this.root) { @@ -156,12 +215,22 @@ tree.Ruleset.prototype = { css.push(rules.join(env.compress ? '' : '\n')); } else { if (rules.length > 0) { + debugInfo = tree.debugInfo(env, this); selector = paths.map(function (p) { return p.map(function (s) { return s.toCSS(env); }).join('').trim(); - }).join(env.compress ? ',' : (paths.length > 3 ? ',\n' : ', ')); - css.push(selector, + }).join(env.compress ? ',' : ',\n'); + + // Remove duplicates + for (var i = rules.length - 1; i >= 0; i--) { + if (_rules.indexOf(rules[i]) === -1) { + _rules.unshift(rules[i]); + } + } + rules = _rules; + + css.push(debugInfo + selector + (env.compress ? '{' : ' {\n ') + rules.join(env.compress ? '' : '\n ') + (env.compress ? '}' : '\n}\n')); @@ -169,7 +238,7 @@ tree.Ruleset.prototype = { } css.push(rulesets); - return css.join('') + (env.compress ? '\n' : ''); + return css.join('') + (env.compress ? '\n' : ''); }, joinSelectors: function (paths, context, selectors) { @@ -179,34 +248,167 @@ tree.Ruleset.prototype = { }, joinSelector: function (paths, context, selector) { - var before = [], after = [], beforeElements = [], - afterElements = [], hasParentSelector = false, el; - for (var i = 0; i < selector.elements.length; i++) { + var i, j, k, + hasParentSelector, newSelectors, el, sel, parentSel, + newSelectorPath, afterParentJoin, newJoinedSelector, + newJoinedSelectorEmpty, lastSelector, currentElements, + selectorsMultiplied; + + for (i = 0; i < selector.elements.length; i++) { el = selector.elements[i]; - if (el.combinator.value[0] === '&') { + if (el.value === '&') { hasParentSelector = true; } - if (hasParentSelector) afterElements.push(el); - else beforeElements.push(el); + } + + if (!hasParentSelector) { + if (context.length > 0) { + for(i = 0; i < context.length; i++) { + paths.push(context[i].concat(selector)); + } + } + else { + paths.push([selector]); + } + return; } - if (! hasParentSelector) { - afterElements = beforeElements; - beforeElements = []; + // The paths are [[Selector]] + // The first list is a list of comma seperated selectors + // The inner list is a list of inheritance seperated selectors + // e.g. + // .a, .b { + // .c { + // } + // } + // == [[.a] [.c]] [[.b] [.c]] + // + + // the elements from the current selector so far + currentElements = []; + // the current list of new selectors to add to the path. + // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors + // by the parents + newSelectors = [[]]; + + for (i = 0; i < selector.elements.length; i++) { + el = selector.elements[i]; + // non parent reference elements just get added + if (el.value !== "&") { + currentElements.push(el); + } else { + // the new list of selectors to add + selectorsMultiplied = []; + + // merge the current list of non parent selector elements + // on to the current list of selectors to add + if (currentElements.length > 0) { + this.mergeElementsOnToSelectors(currentElements, newSelectors); + } + + // loop through our current selectors + for(j = 0; j < newSelectors.length; j++) { + sel = newSelectors[j]; + // if we don't have any parent paths, the & might be in a mixin so that it can be used + // whether there are parents or not + if (context.length == 0) { + // the combinator used on el should now be applied to the next element instead so that + // it is not lost + if (sel.length > 0) { + sel[0].elements = sel[0].elements.slice(0); + sel[0].elements.push(new(tree.Element)(el.combinator, '', 0)); //new Element(el.Combinator, "")); + } + selectorsMultiplied.push(sel); + } + else { + // and the parent selectors + for(k = 0; k < context.length; k++) { + parentSel = context[k]; + // We need to put the current selectors + // then join the last selector's elements on to the parents selectors + + // our new selector path + newSelectorPath = []; + // selectors from the parent after the join + afterParentJoin = []; + newJoinedSelectorEmpty = true; + + //construct the joined selector - if & is the first thing this will be empty, + // if not newJoinedSelector will be the last set of elements in the selector + if (sel.length > 0) { + newSelectorPath = sel.slice(0); + lastSelector = newSelectorPath.pop(); + newJoinedSelector = new(tree.Selector)(lastSelector.elements.slice(0)); + newJoinedSelectorEmpty = false; + } + else { + newJoinedSelector = new(tree.Selector)([]); + } + + //put together the parent selectors after the join + if (parentSel.length > 1) { + afterParentJoin = afterParentJoin.concat(parentSel.slice(1)); + } + + if (parentSel.length > 0) { + newJoinedSelectorEmpty = false; + + // join the elements so far with the first part of the parent + newJoinedSelector.elements.push(new(tree.Element)(el.combinator, parentSel[0].elements[0].value, 0)); + newJoinedSelector.elements = newJoinedSelector.elements.concat(parentSel[0].elements.slice(1)); + } + + if (!newJoinedSelectorEmpty) { + // now add the joined selector + newSelectorPath.push(newJoinedSelector); + } + + // and the rest of the parent + newSelectorPath = newSelectorPath.concat(afterParentJoin); + + // add that to our new set of selectors + selectorsMultiplied.push(newSelectorPath); + } + } + } + + // our new selectors has been multiplied, so reset the state + newSelectors = selectorsMultiplied; + currentElements = []; + } + } + + // if we have any elements left over (e.g. .a& .b == .b) + // add them on to all the current selectors + if (currentElements.length > 0) { + this.mergeElementsOnToSelectors(currentElements, newSelectors); } - if (beforeElements.length > 0) { - before.push(new(tree.Selector)(beforeElements)); + for(i = 0; i < newSelectors.length; i++) { + paths.push(newSelectors[i]); } + }, + + mergeElementsOnToSelectors: function(elements, selectors) { + var i, sel; - if (afterElements.length > 0) { - after.push(new(tree.Selector)(afterElements)); + if (selectors.length == 0) { + selectors.push([ new(tree.Selector)(elements) ]); + return; } - for (var c = 0; c < context.length; c++) { - paths.push(before.concat(context[c]).concat(after)); + for(i = 0; i < selectors.length; i++) { + sel = selectors[i]; + + // if the previous thing in sel is a parent this needs to join on to it + if (sel.length > 0) { + sel[sel.length - 1] = new(tree.Selector)(sel[sel.length - 1].elements.concat(elements)); + } + else { + sel.push(new(tree.Selector)(elements)); + } } } }; -})(require('less/tree')); +})(require('../tree')); diff --git a/build-tools/lib/less/tree/selector.js b/build-tools/lib/less/tree/selector.js index ddc6842..1ce2c30 100644 --- a/build-tools/lib/less/tree/selector.js +++ b/build-tools/lib/less/tree/selector.js @@ -2,41 +2,51 @@ tree.Selector = function (elements) { this.elements = elements; - if (this.elements[0].combinator.value === "") { - this.elements[0].combinator.value = ' '; - } }; tree.Selector.prototype.match = function (other) { - var value = this.elements[0].value, - len = this.elements.length, - olen = other.elements.length; + var elements = this.elements, + len = elements.length, + oelements, olen, max, i; - if (len > olen) { - return value === other.elements[0].value; - } + oelements = other.elements.slice( + (other.elements.length && other.elements[0].value === "&") ? 1 : 0); + olen = oelements.length; + max = Math.min(len, olen) - for (var i = 0; i < olen; i ++) { - if (value === other.elements[i].value) { - for (var j = 1; j < len; j ++) { - if (this.elements[j].value !== other.elements[i + j].value) { - return false; - } + if (olen === 0 || len < olen) { + return false; + } else { + for (i = 0; i < max; i++) { + if (elements[i].value !== oelements[i].value) { + return false; } - return true; } } - return false; + return true; +}; +tree.Selector.prototype.eval = function (env) { + return new(tree.Selector)(this.elements.map(function (e) { + return e.eval(env); + })); }; tree.Selector.prototype.toCSS = function (env) { if (this._css) { return this._css } - - return this._css = this.elements.map(function (e) { + + if (this.elements[0].combinator.value === "") { + this._css = ' '; + } else { + this._css = ''; + } + + this._css += this.elements.map(function (e) { if (typeof(e) === 'string') { return ' ' + e.trim(); } else { return e.toCSS(env); } }).join(''); + + return this._css; }; -})(require('less/tree')); +})(require('../tree')); diff --git a/build-tools/lib/less/tree/unicode-descriptor.js b/build-tools/lib/less/tree/unicode-descriptor.js new file mode 100644 index 0000000..79b6b23 --- /dev/null +++ b/build-tools/lib/less/tree/unicode-descriptor.js @@ -0,0 +1,13 @@ +(function (tree) { + +tree.UnicodeDescriptor = function (value) { + this.value = value; +}; +tree.UnicodeDescriptor.prototype = { + toCSS: function (env) { + return this.value; + }, + eval: function () { return this } +}; + +})(require('../tree')); diff --git a/build-tools/lib/less/tree/url.js b/build-tools/lib/less/tree/url.js index f427070..e37dbef 100644 --- a/build-tools/lib/less/tree/url.js +++ b/build-tools/lib/less/tree/url.js @@ -1,25 +1,27 @@ (function (tree) { -tree.URL = function (val, paths) { - if (val.data) { - this.attrs = val; - } else { - // Add the base path if the URL is relative and we are in the browser - if (!/^(?:https?:\/|file:\/|data:\/)?\//.test(val.value) && paths.length > 0 && typeof(window) !== 'undefined') { - val.value = paths[0] + (val.value.charAt(0) === '/' ? val.value.slice(1) : val.value); - } - this.value = val; - this.paths = paths; - } +tree.URL = function (val, rootpath) { + this.value = val; + this.rootpath = rootpath; }; tree.URL.prototype = { toCSS: function () { - return "url(" + (this.attrs ? 'data:' + this.attrs.mime + this.attrs.charset + this.attrs.base64 + this.attrs.data - : this.value.toCSS()) + ")"; + return "url(" + this.value.toCSS() + ")"; }, eval: function (ctx) { - return this.attrs ? this : new(tree.URL)(this.value.eval(ctx), this.paths); + var val = this.value.eval(ctx), rootpath; + + // Add the base path if the URL is relative + if (typeof val.value === "string" && !/^(?:[a-z-]+:|\/)/.test(val.value)) { + rootpath = this.rootpath; + if (!val.quote) { + rootpath = rootpath.replace(/[\(\)'"\s]/g, function(match) { return "\\"+match; }); + } + val.value = rootpath + val.value; + } + + return new(tree.URL)(val, this.rootpath); } }; -})(require('less/tree')); +})(require('../tree')); diff --git a/build-tools/lib/less/tree/value.js b/build-tools/lib/less/tree/value.js index 922096c..3c1eb29 100644 --- a/build-tools/lib/less/tree/value.js +++ b/build-tools/lib/less/tree/value.js @@ -21,4 +21,4 @@ tree.Value.prototype = { } }; -})(require('less/tree')); +})(require('../tree')); diff --git a/build-tools/lib/less/tree/variable.js b/build-tools/lib/less/tree/variable.js index 10f7c08..674ca8e 100644 --- a/build-tools/lib/less/tree/variable.js +++ b/build-tools/lib/less/tree/variable.js @@ -1,6 +1,6 @@ (function (tree) { -tree.Variable = function (name, index) { this.name = name, this.index = index }; +tree.Variable = function (name, index, file) { this.name = name, this.index = index, this.file = file }; tree.Variable.prototype = { eval: function (env) { var variable, v, name = this.name; @@ -8,17 +8,31 @@ tree.Variable.prototype = { if (name.indexOf('@@') == 0) { name = '@' + new(tree.Variable)(name.slice(1)).eval(env).value; } + + if (this.evaluating) { + throw { type: 'Name', + message: "Recursive variable definition for " + name, + filename: this.file, + index: this.index }; + } + + this.evaluating = true; if (variable = tree.find(env.frames, function (frame) { if (v = frame.variable(name)) { return v.value.eval(env); } - })) { return variable } + })) { + this.evaluating = false; + return variable; + } else { - throw { message: "variable " + name + " is undefined", + throw { type: 'Name', + message: "variable " + name + " is undefined", + filename: this.file, index: this.index }; } } }; -})(require('less/tree')); +})(require('../tree')); diff --git a/src/themes/tizen/common/jquery.mobile.forms.textinput.less b/src/themes/tizen/common/jquery.mobile.forms.textinput.less index faed987..56ea191 100644 --- a/src/themes/tizen/common/jquery.mobile.forms.textinput.less +++ b/src/themes/tizen/common/jquery.mobile.forms.textinput.less @@ -78,7 +78,7 @@ textarea.ui-input-text { } /* code for label+inputbox : remove this code if webApp dev. controls input area */ -@media all and (min-width: 721*@unit_base) { +@media all and (min-width: 721px) { label.ui-input-text:not([data-type='search']) { vertical-align: top; display: inline-block;