Merge upstream into adding_gsub_function

This commit is contained in:
Jake Bellacera
2014-02-06 17:29:42 -08:00
255 changed files with 63962 additions and 2768 deletions

View File

@@ -1,16 +1,31 @@
//
// browser.js - client-side engine
//
/*global less, window, document, XMLHttpRequest, location */
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' ||
location.hostname == 'localhost' ||
location.port.length > 0 ||
(location.port &&
location.port.length > 0) ||
isFileProtocol ? 'development'
: 'production');
var logLevel = {
info: 2,
errors: 1,
none: 0
};
// The amount of logging in the javascript console.
// 2 - Information and errors
// 1 - Errors
// 0 - None
// Defaults to 2
less.logLevel = typeof(less.logLevel) != 'undefined' ? less.logLevel : logLevel.info;
// Load styles asynchronously (default: false)
//
// This is set to `false` by default, so that the body
@@ -26,7 +41,9 @@ 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];
if (less.functions.hasOwnProperty(func)) {
less.tree.functions[func] = less.functions[func];
}
}
}
@@ -35,303 +52,49 @@ if (dumpLineNumbers) {
less.dumpLineNumbers = dumpLineNumbers[1];
}
//
// Watch mode
//
less.watch = function () {
if (!less.watchMode ){
less.env = 'development';
initRunningMode();
}
return this.watchMode = true
};
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 (e) {
error(e, sheet.href);
} else if (root) {
createCSS(root.toCSS(less), sheet, env.lastModified);
}
});
}
}, less.poll);
} else {
less.optimization = 3;
}
}
if (/!watch/.test(location.hash)) {
less.watch();
}
var cache = null;
if (less.env != 'development') {
try {
cache = (typeof(window.localStorage) === 'undefined') ? null : window.localStorage;
} catch (_) {}
}
//
// Get all <link> tags with the 'rel' attribute set to "stylesheet/less"
//
var links = document.getElementsByTagName('link');
var typePattern = /^text\/(x-)?less$/;
var cache = null;
var fileCache = {};
less.sheets = [];
for (var i = 0; i < links.length; i++) {
if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) &&
(links[i].type.match(typePattern)))) {
less.sheets.push(links[i]);
function log(str, level) {
if (less.env == 'development' && typeof(console) !== 'undefined' && less.logLevel >= level) {
console.log('less: ' + str);
}
}
//
// 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 (var name in record) {
str += ((name.slice(0,1) === '@')? '' : '@') + name +': '+
((record[name].slice(-1) === ';')? record[name] : record[name] +';');
}
new(less.Parser)(new less.tree.parseEnv(less)).parse(str, function (e, root) {
if (e) {
error(e, "session_cache");
} else {
createCSS(root.toCSS(less), less.sheets[less.sheets.length - 1]);
}
});
};
less.refresh = function (reload) {
var startTime, endTime;
startTime = endTime = new(Date);
loadStyleSheets(function (e, root, _, sheet, env) {
if (e) {
return error(e, sheet.href);
}
if (env.local) {
log("loading " + sheet.href + " from cache.");
} else {
log("parsed " + sheet.href + " successfully.");
createCSS(root.toCSS(less), sheet, env.lastModified);
}
log("css for " + sheet.href + " generated in " + (new(Date) - endTime) + 'ms');
(env.remaining === 0) && log("css generated in " + (new(Date) - startTime) + 'ms');
endTime = new(Date);
}, reload);
loadStyles();
};
less.refreshStyles = loadStyles;
less.refresh(less.env === 'development');
function loadStyles() {
var styles = document.getElementsByTagName('style');
for (var i = 0; i < styles.length; i++) {
if (styles[i].type.match(typePattern)) {
var env = new less.tree.parseEnv(less);
env.filename = document.location.href.replace(/#.*$/, '');
new(less.Parser)(env).parse(styles[i].innerHTML || '', function (e, cssAST) {
if (e) {
return error(e, "inline");
}
var css = cssAST.toCSS(less);
var style = styles[i];
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.innerHTML = css;
}
});
}
}
}
function loadStyleSheets(callback, reload) {
for (var i = 0; i < less.sheets.length; i++) {
loadStyleSheet(less.sheets[i], callback, reload, less.sheets.length - (i + 1));
}
}
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-]+:)?\/+?(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/i,
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] = urlParts[1] || baseUrlParts[1] || "";
if (!urlParts[2]) {
urlParts[3] = baseUrlParts[3] + urlParts[3];
}
}
if (urlParts[3]) {
directories = urlParts[3].replace(/\\/g, "/").split("/");
// extract out . before .. so .. doesn't absorb a non-directory
for(i = 0; i < directories.length; i++) {
if (directories[i] === ".") {
directories.splice(i, 1);
i -= 1;
}
}
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) {
// sheet may be set to the stylesheet for the initial load or a collection of properties including
// some env variables for imports
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 env;
var newFileInfo = {
relativeUrls: less.relativeUrls,
currentDirectory: hrefParts.path,
filename: href
};
if (sheet instanceof less.tree.parseEnv) {
env = new less.tree.parseEnv(sheet);
newFileInfo.entryPath = env.currentFileInfo.entryPath;
newFileInfo.rootpath = env.currentFileInfo.rootpath;
newFileInfo.rootFilename = env.currentFileInfo.rootFilename;
} else {
env = new less.tree.parseEnv(less);
env.mime = sheet.type;
newFileInfo.entryPath = hrefParts.path;
newFileInfo.rootpath = less.rootpath || hrefParts.path;
newFileInfo.rootFilename = href;
}
if (env.relativeUrls) {
//todo - this relies on option being set on less object rather than being passed in as an option
// - need an originalRootpath
if (less.rootpath) {
newFileInfo.rootpath = extractUrlParts(less.rootpath + pathDiff(hrefParts.path, newFileInfo.entryPath)).path;
} else {
newFileInfo.rootpath = hrefParts.path;
}
}
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, null, data, sheet, { local: true, remaining: remaining }, href);
} else {
// Use remote copy (re-parse)
try {
env.contents[href] = data; // Updating content cache
env.paths = [hrefParts.path];
env.currentFileInfo = newFileInfo;
new(less.Parser)(env).parse(data, function (e, root) {
if (e) { return callback(e, null, null, sheet); }
try {
callback(e, root, data, sheet, { local: false, lastModified: lastModified, remaining: remaining }, href);
//TODO - there must be a better way? A generic less-to-css function that can both call error
//and removeNode where appropriate
//should also add tests
if (env.currentFileInfo.rootFilename === href) {
removeNode(document.getElementById('less-error-message:' + extractId(href)));
}
} catch (e) {
callback(e, null, null, sheet);
}
});
} catch (e) {
callback(e, null, null, sheet);
}
}
}, function (status, url) {
callback({ type: 'File', message: "'" + url + "' wasn't found (" + status + ")" }, null, null, sheet);
});
}
function extractId(href) {
return href.replace(/^[a-z-]+:\/+?[^\/]+/, '' ) // Remove protocol & domain
.replace(/^\//, '' ) // Remove root /
.replace(/\.[a-zA-Z]+$/, '' ) // Remove simple extension
.replace(/[^\.\w-]+/g, '-') // Replace illegal characters
.replace(/\./g, ':'); // Replace dots with colons(for valid id)
.replace(/^\//, '' ) // Remove root /
.replace(/\.[a-zA-Z]+$/, '' ) // Remove simple extension
.replace(/[^\.\w-]+/g, '-') // Replace illegal characters
.replace(/\./g, ':'); // Replace dots with colons(for valid id)
}
function errorConsole(e, rootHref) {
var template = '{line} {content}';
var filename = e.filename || rootHref;
var errors = [];
var content = (e.type || "Syntax") + "Error: " + (e.message || 'There is an error in your .less file') +
" in " + filename + " ";
var errorline = function (e, i, classname) {
if (e.extract[i] !== undefined) {
errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
.replace(/\{class\}/, classname)
.replace(/\{content\}/, e.extract[i]));
}
};
if (e.extract) {
errorline(e, 0, '');
errorline(e, 1, 'line');
errorline(e, 2, '');
content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':\n' +
errors.join('\n');
} else if (e.stack) {
content += e.stack;
}
log(content, logLevel.errors);
}
function createCSS(styles, sheet, lastModified) {
@@ -371,89 +134,35 @@ function createCSS(styles, sheet, lastModified) {
// If there is no oldCss, just append; otherwise, only append if we need
// to replace oldCss with an updated stylesheet
if (oldCss == null || keepOldCss === false) {
if (oldCss === null || keepOldCss === false) {
var nextEl = sheet && sheet.nextSibling || null;
(nextEl || document.getElementsByTagName('head')[0]).parentNode.insertBefore(css, nextEl);
if (nextEl) {
nextEl.parentNode.insertBefore(css, nextEl);
} else {
head.appendChild(css);
}
}
if (oldCss && keepOldCss === false) {
head.removeChild(oldCss);
oldCss.parentNode.removeChild(oldCss);
}
// Don't update the local store if the file wasn't modified
if (lastModified && cache) {
log('saving ' + href + ' to cache.');
log('saving ' + href + ' to cache.', logLevel.info);
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');
log('failed to save', logLevel.errors);
}
}
}
function xhr(url, type, callback, errback) {
var xhr = getXMLHttpRequest();
var async = isFileProtocol ? less.fileAsync : less.async;
if (typeof(xhr.overrideMimeType) === 'function') {
xhr.overrideMimeType('text/css');
}
xhr.open('GET', url, async);
xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5');
xhr.send(null);
if (isFileProtocol && !less.fileAsync) {
if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) {
callback(xhr.responseText);
} else {
errback(xhr.status, url);
}
} else if (async) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
handleResponse(xhr, callback, errback);
}
};
} else {
handleResponse(xhr, callback, errback);
}
function handleResponse(xhr, callback, errback) {
if (xhr.status >= 200 && xhr.status < 300) {
callback(xhr.responseText,
xhr.getResponseHeader("Last-Modified"));
} else if (typeof(errback) === 'function') {
errback(xhr.status, url);
}
}
}
function getXMLHttpRequest() {
if (window.XMLHttpRequest) {
return new(XMLHttpRequest);
} else {
try {
return new(ActiveXObject)("MSXML2.XMLHTTP.3.0");
} catch (e) {
log("browser doesn't support AJAX.");
return null;
}
}
}
function removeNode(node) {
return node && node.parentNode.removeChild(node);
}
function log(str) {
if (less.env == 'development' && typeof(console) !== "undefined") { console.log('less: ' + str) }
}
function error(e, rootHref) {
function errorHTML(e, rootHref) {
var id = 'less-error-message:' + extractId(rootHref || "");
var template = '<li><label>{line}</label><pre class="{class}">{content}</pre></li>';
var elem = document.createElement('div'), timer, content, error = [];
var elem = document.createElement('div'), timer, content, errors = [];
var filename = e.filename || rootHref;
var filenameNoPath = filename.match(/([^\/]+(\?.*)?)$/)[1];
@@ -461,13 +170,13 @@ function error(e, rootHref) {
elem.className = "less-error-message";
content = '<h3>' + (e.type || "Syntax") + "Error: " + (e.message || 'There is an error in your .less file') +
'</h3>' + '<p>in <a href="' + filename + '">' + filenameNoPath + "</a> ";
'</h3>' + '<p>in <a href="' + filename + '">' + filenameNoPath + "</a> ";
var errorline = function (e, i, classname) {
if (e.extract[i] != undefined) {
error.push(template.replace(/\{line\}/, (parseInt(e.line) || 0) + (i - 1))
.replace(/\{class\}/, classname)
.replace(/\{content\}/, e.extract[i]));
if (e.extract[i] !== undefined) {
errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
.replace(/\{class\}/, classname)
.replace(/\{content\}/, e.extract[i]));
}
};
@@ -476,7 +185,7 @@ function error(e, rootHref) {
errorline(e, 1, 'line');
errorline(e, 2, '');
content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':</p>' +
'<ul>' + error.join('') + '</ul>';
'<ul>' + errors.join('') + '</ul>';
} else if (e.stack) {
content += '<br/>' + e.stack.split('\n').slice(1).join('<br/>');
}
@@ -485,40 +194,40 @@ function error(e, rootHref) {
// CSS for error messages
createCSS([
'.less-error-message ul, .less-error-message li {',
'list-style-type: none;',
'margin-right: 15px;',
'padding: 4px 0;',
'margin: 0;',
'list-style-type: none;',
'margin-right: 15px;',
'padding: 4px 0;',
'margin: 0;',
'}',
'.less-error-message label {',
'font-size: 12px;',
'margin-right: 15px;',
'padding: 4px 0;',
'color: #cc7777;',
'font-size: 12px;',
'margin-right: 15px;',
'padding: 4px 0;',
'color: #cc7777;',
'}',
'.less-error-message pre {',
'color: #dd6666;',
'padding: 4px 0;',
'margin: 0;',
'display: inline-block;',
'color: #dd6666;',
'padding: 4px 0;',
'margin: 0;',
'display: inline-block;',
'}',
'.less-error-message pre.line {',
'color: #ff0000;',
'color: #ff0000;',
'}',
'.less-error-message h3 {',
'font-size: 20px;',
'font-weight: bold;',
'padding: 15px 0 5px 0;',
'margin: 0;',
'font-size: 20px;',
'font-weight: bold;',
'padding: 15px 0 5px 0;',
'margin: 0;',
'}',
'.less-error-message a {',
'color: #10a',
'color: #10a',
'}',
'.less-error-message .error {',
'color: red;',
'font-weight: bold;',
'padding-bottom: 2px;',
'border-bottom: 1px dashed red;',
'color: red;',
'font-weight: bold;',
'padding-bottom: 2px;',
'border-bottom: 1px dashed red;',
'}'
].join('\n'), { title: 'error-message' });
@@ -547,3 +256,409 @@ function error(e, rootHref) {
}, 10);
}
}
function error(e, rootHref) {
if (!less.errorReporting || less.errorReporting === "html") {
errorHTML(e, rootHref);
} else if (less.errorReporting === "console") {
errorConsole(e, rootHref);
} else if (typeof less.errorReporting === 'function') {
less.errorReporting("add", e, rootHref);
}
}
function removeErrorHTML(path) {
var node = document.getElementById('less-error-message:' + extractId(path));
if (node) {
node.parentNode.removeChild(node);
}
}
function removeErrorConsole(path) {
//no action
}
function removeError(path) {
if (!less.errorReporting || less.errorReporting === "html") {
removeErrorHTML(path);
} else if (less.errorReporting === "console") {
removeErrorConsole(path);
} else if (typeof less.errorReporting === 'function') {
less.errorReporting("remove", path);
}
}
function loadStyles(modifyVars) {
var styles = document.getElementsByTagName('style'),
style;
for (var i = 0; i < styles.length; i++) {
style = styles[i];
if (style.type.match(typePattern)) {
var env = new less.tree.parseEnv(less),
lessText = style.innerHTML || '';
env.filename = document.location.href.replace(/#.*$/, '');
if (modifyVars || less.globalVars) {
env.useFileCache = true;
}
/*jshint loopfunc:true */
// use closure to store current value of i
var callback = (function(style) {
return function (e, cssAST) {
if (e) {
return error(e, "inline");
}
var css = cssAST.toCSS(less);
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.innerHTML = css;
}
};
})(style);
new(less.Parser)(env).parse(lessText, callback, {globalVars: less.globalVars, modifyVars: modifyVars});
}
}
}
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-]+:)?\/+?(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/i,
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] = urlParts[1] || baseUrlParts[1] || "";
if (!urlParts[2]) {
urlParts[3] = baseUrlParts[3] + urlParts[3];
}
}
if (urlParts[3]) {
directories = urlParts[3].replace(/\\/g, "/").split("/");
// extract out . before .. so .. doesn't absorb a non-directory
for(i = 0; i < directories.length; i++) {
if (directories[i] === ".") {
directories.splice(i, 1);
i -= 1;
}
}
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 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 getXMLHttpRequest() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else {
try {
/*global ActiveXObject */
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
} catch (e) {
log("browser doesn't support AJAX.", logLevel.errors);
return null;
}
}
}
function doXHR(url, type, callback, errback) {
var xhr = getXMLHttpRequest();
var async = isFileProtocol ? less.fileAsync : less.async;
if (typeof(xhr.overrideMimeType) === 'function') {
xhr.overrideMimeType('text/css');
}
log("XHR: Getting '" + url + "'", logLevel.info);
xhr.open('GET', url, async);
xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5');
xhr.send(null);
function handleResponse(xhr, callback, errback) {
if (xhr.status >= 200 && xhr.status < 300) {
callback(xhr.responseText,
xhr.getResponseHeader("Last-Modified"));
} else if (typeof(errback) === 'function') {
errback(xhr.status, url);
}
}
if (isFileProtocol && !less.fileAsync) {
if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) {
callback(xhr.responseText);
} else {
errback(xhr.status, url);
}
} else if (async) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
handleResponse(xhr, callback, errback);
}
};
} else {
handleResponse(xhr, callback, errback);
}
}
function loadFile(originalHref, currentFileInfo, callback, env, modifyVars) {
if (currentFileInfo && currentFileInfo.currentDirectory && !/^([a-z-]+:)?\//.test(originalHref)) {
originalHref = currentFileInfo.currentDirectory + originalHref;
}
// sheet may be set to the stylesheet for the initial load or a collection of properties including
// some env variables for imports
var hrefParts = extractUrlParts(originalHref, window.location.href);
var href = hrefParts.url;
var newFileInfo = {
currentDirectory: hrefParts.path,
filename: href
};
if (currentFileInfo) {
newFileInfo.entryPath = currentFileInfo.entryPath;
newFileInfo.rootpath = currentFileInfo.rootpath;
newFileInfo.rootFilename = currentFileInfo.rootFilename;
newFileInfo.relativeUrls = currentFileInfo.relativeUrls;
} else {
newFileInfo.entryPath = hrefParts.path;
newFileInfo.rootpath = less.rootpath || hrefParts.path;
newFileInfo.rootFilename = href;
newFileInfo.relativeUrls = env.relativeUrls;
}
if (newFileInfo.relativeUrls) {
if (env.rootpath) {
newFileInfo.rootpath = extractUrlParts(env.rootpath + pathDiff(hrefParts.path, newFileInfo.entryPath)).path;
} else {
newFileInfo.rootpath = hrefParts.path;
}
}
if (env.useFileCache && fileCache[href]) {
try {
var lessText = fileCache[href];
callback(null, lessText, href, newFileInfo, { lastModified: new Date() });
} catch (e) {
callback(e, null, href);
}
return;
}
doXHR(href, env.mime, function (data, lastModified) {
// per file cache
fileCache[href] = data;
// Use remote copy (re-parse)
try {
callback(null, data, href, newFileInfo, { lastModified: lastModified });
} catch (e) {
callback(e, null, href);
}
}, function (status, url) {
callback({ type: 'File', message: "'" + url + "' wasn't found (" + status + ")" }, null, href);
});
}
function loadStyleSheet(sheet, callback, reload, remaining, modifyVars) {
var env = new less.tree.parseEnv(less);
env.mime = sheet.type;
if (modifyVars || less.globalVars) {
env.useFileCache = true;
}
loadFile(sheet.href, null, function(e, data, path, newFileInfo, webInfo) {
if (webInfo) {
webInfo.remaining = remaining;
var css = cache && cache.getItem(path),
timestamp = cache && cache.getItem(path + ':timestamp');
if (!reload && timestamp && webInfo.lastModified &&
(new(Date)(webInfo.lastModified).valueOf() ===
new(Date)(timestamp).valueOf())) {
// Use local copy
createCSS(css, sheet);
webInfo.local = true;
callback(null, null, data, sheet, webInfo, path);
return;
}
}
//TODO add tests around how this behaves when reloading
removeError(path);
if (data) {
env.currentFileInfo = newFileInfo;
new(less.Parser)(env).parse(data, function (e, root) {
if (e) { return callback(e, null, null, sheet); }
try {
callback(e, root, data, sheet, webInfo, path);
} catch (e) {
callback(e, null, null, sheet);
}
}, {modifyVars: modifyVars, globalVars: less.globalVars});
} else {
callback(e, null, null, sheet, webInfo, path);
}
}, env, modifyVars);
}
function loadStyleSheets(callback, reload, modifyVars) {
for (var i = 0; i < less.sheets.length; i++) {
loadStyleSheet(less.sheets[i], callback, reload, less.sheets.length - (i + 1), modifyVars);
}
}
function initRunningMode(){
if (less.env === 'development') {
less.optimization = 0;
less.watchTimer = setInterval(function () {
if (less.watchMode) {
loadStyleSheets(function (e, root, _, sheet, env) {
if (e) {
error(e, sheet.href);
} else if (root) {
createCSS(root.toCSS(less), sheet, env.lastModified);
}
});
}
}, less.poll);
} else {
less.optimization = 3;
}
}
//
// Watch mode
//
less.watch = function () {
if (!less.watchMode ){
less.env = 'development';
initRunningMode();
}
this.watchMode = true;
return true;
};
less.unwatch = function () {clearInterval(less.watchTimer); this.watchMode = false; return false; };
if (/!watch/.test(location.hash)) {
less.watch();
}
if (less.env != 'development') {
try {
cache = (typeof(window.localStorage) === 'undefined') ? null : window.localStorage;
} catch (_) {}
}
//
// Get all <link> tags with the 'rel' attribute set to "stylesheet/less"
//
var links = document.getElementsByTagName('link');
less.sheets = [];
for (var i = 0; i < links.length; i++) {
if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) &&
(links[i].type.match(typePattern)))) {
less.sheets.push(links[i]);
}
}
//
// With this function, it's possible to alter variables and re-render
// CSS without reloading less-files
//
less.modifyVars = function(record) {
less.refresh(false, record);
};
less.refresh = function (reload, modifyVars) {
var startTime, endTime;
startTime = endTime = new Date();
loadStyleSheets(function (e, root, _, sheet, env) {
if (e) {
return error(e, sheet.href);
}
if (env.local) {
log("loading " + sheet.href + " from cache.", logLevel.info);
} else {
log("parsed " + sheet.href + " successfully.", logLevel.info);
createCSS(root.toCSS(less), sheet, env.lastModified);
}
log("css for " + sheet.href + " generated in " + (new Date() - endTime) + 'ms', logLevel.info);
if (env.remaining === 0) {
log("css generated in " + (new Date() - startTime) + 'ms', logLevel.info);
}
endTime = new Date();
}, reload, modifyVars);
loadStyles(modifyVars);
};
less.refreshStyles = loadStyles;
less.Parser.fileLoader = loadFile;
less.refresh(less.env === 'development');

View File

@@ -140,7 +140,6 @@
'teal':'#008080',
'thistle':'#d8bfd8',
'tomato':'#ff6347',
// 'transparent':'rgba(0,0,0,0)',
'turquoise':'#40e0d0',
'violet':'#ee82ee',
'wheat':'#f5deb3',

4
lib/less/encoder.js Normal file
View File

@@ -0,0 +1,4 @@
// base64 encoder implementation for node
exports.encodeBase64 = function(str) {
return new Buffer(str).toString('base64');
};

View File

@@ -4,14 +4,19 @@
'paths', // option - unmodified - paths to search for imports on
'optimization', // option - optimization level (for the chunker)
'files', // list of files that have been imported, used for import-once
'contents', // browser-only, contents of all the files
'contents', // map - filename to contents of all the files
'contentsIgnoredChars', // map - filename to lines at the begining of each file to ignore
'relativeUrls', // option - whether to adjust URL's to be relative
'rootpath', // option - rootpath to append to URL's
'strictImports', // option -
'insecure', // option - whether to allow imports from insecure ssl hosts
'dumpLineNumbers', // option - whether to dump line numbers
'compress', // option - whether to compress
'processImports', // option - whether to process imports. if false then imports will not be imported
'syncImport', // option - whether to import synchronously
'javascriptEnabled',// option - whether JavaScript is enabled. if undefined, defaults to true
'mime', // browser only - mime type for sheet import
'useFileCache', // browser only - whether to use the per file session cache
'currentFileInfo' // information about the current file - for error reporting and importing and making urls relative etc.
];
@@ -21,12 +26,14 @@
// 'rootpath' - path to append to normal URLs for this node
// 'currentDirectory' - path to the current file, absolute
// 'rootFilename' - filename of the base file
// 'entryPath' = absolute path to the entry file
// 'entryPath' - absolute path to the entry file
// 'reference' - whether the file should not be output and only output parts that are referenced
tree.parseEnv = function(options) {
copyFromOriginal(options, this, parseCopyProperties);
if (!this.contents) { this.contents = {}; }
if (!this.contentsIgnoredChars) { this.contentsIgnoredChars = {}; }
if (!this.files) { this.files = {}; }
if (!this.currentFileInfo) {
@@ -46,22 +53,18 @@
}
};
tree.parseEnv.prototype.toSheet = function (path) {
var env = new tree.parseEnv(this);
env.href = path;
//env.title = path;
env.type = this.mime;
return env;
};
var evalCopyProperties = [
'silent', // whether to swallow errors and warnings
'verbose', // whether to log more activity
'compress', // whether to compress
'yuicompress', // whether to compress with the outside tool yui compressor
'ieCompat', // whether to enforce IE compatibility (IE8 data-uri)
'strictMath', // whether math has to be within parenthesis
'strictUnits' // whether units need to evaluate correctly
'silent', // whether to swallow errors and warnings
'verbose', // whether to log more activity
'compress', // whether to compress
'yuicompress', // whether to compress with the outside tool yui compressor
'ieCompat', // whether to enforce IE compatibility (IE8 data-uri)
'strictMath', // whether math has to be within parenthesis
'strictUnits', // whether units need to evaluate correctly
'cleancss', // whether to compress with clean-css
'sourceMap', // whether to output a source map
'importMultiple', // whether we are currently importing multiple copies
'urlArgs' // whether to add args into url tokens
];
tree.evalEnv = function(options, frames) {
@@ -89,6 +92,33 @@
return !/^(?:[a-z-]+:|\/)/.test(path);
};
tree.evalEnv.prototype.normalizePath = function( path ) {
var
segments = path.split("/").reverse(),
segment;
path = [];
while (segments.length !== 0 ) {
segment = segments.pop();
switch( segment ) {
case ".":
break;
case "..":
if ((path.length === 0) || (path[path.length - 1] === "..")) {
path.push( segment );
} else {
path.pop();
}
break;
default:
path.push( segment );
break;
}
}
return path.join("/");
};
//todo - do the same for the toCSS env
//tree.toCSSEnv = function (options) {
//};
@@ -101,5 +131,6 @@
destination[propertiesToCopy[i]] = original[propertiesToCopy[i]];
}
}
}
})(require('./tree'));
};
})(require('./tree'));

View File

@@ -1,4 +1,6 @@
(function (tree) {
/*jshint loopfunc:true */
tree.extendFinderVisitor = function() {
this._visitor = new tree.visitor(this);
this.contexts = [];
@@ -18,7 +20,6 @@
visitArgs.visitDeeper = false;
},
visitRuleset: function (rulesetNode, visitArgs) {
if (rulesetNode.root) {
return;
}
@@ -26,20 +27,31 @@
var i, j, extend, allSelectorsExtendList = [], extendList;
// get &:extend(.a); rules which apply to all selectors in this ruleset
for(i = 0; i < rulesetNode.rules.length; i++) {
var rules = rulesetNode.rules, ruleCnt = rules ? rules.length : 0;
for(i = 0; i < ruleCnt; i++) {
if (rulesetNode.rules[i] instanceof tree.Extend) {
allSelectorsExtendList.push(rulesetNode.rules[i]);
allSelectorsExtendList.push(rules[i]);
rulesetNode.extendOnEveryPath = true;
}
}
// now find every selector and apply the extends that apply to all extends
// and the ones which apply to an individual extend
for(i = 0; i < rulesetNode.paths.length; i++) {
var selectorPath = rulesetNode.paths[i],
selector = selectorPath[selectorPath.length-1];
extendList = selector.extendList.slice(0).concat(allSelectorsExtendList).map(function(allSelectorsExtend) {
return allSelectorsExtend.clone();
});
var paths = rulesetNode.paths;
for(i = 0; i < paths.length; i++) {
var selectorPath = paths[i],
selector = selectorPath[selectorPath.length - 1],
selExtendList = selector.extendList;
extendList = selExtendList ? selExtendList.slice(0).concat(allSelectorsExtendList)
: allSelectorsExtendList;
if (extendList) {
extendList = extendList.map(function(allSelectorsExtend) {
return allSelectorsExtend.clone();
});
}
for(j = 0; j < extendList.length; j++) {
this.foundExtends = true;
extend = extendList[j];
@@ -113,7 +125,7 @@
targetExtend = extendsListTarget[targetExtendIndex];
// look for circular references
if (this.inInheritanceChain(targetExtend, extend)) { continue; }
if( extend.parent_ids.indexOf( targetExtend.object_id ) >= 0 ){ continue; }
// find a match in the target extends self selector (the bit before :extend)
selectorPath = [targetExtend.selfSelectors[0]];
@@ -139,7 +151,7 @@
newExtend.ruleset = targetExtend.ruleset;
//remember its parents for circular references
newExtend.parents = [targetExtend, extend];
newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids);
// only process the selector once.. if we have :extend(.a,.b) then multiple
// extends will look at the same selector path, so when extending
@@ -175,20 +187,6 @@
return extendsToAdd;
}
},
inInheritanceChain: function (possibleParent, possibleChild) {
if (possibleParent === possibleChild) {
return true;
}
if (possibleChild.parents) {
if (this.inInheritanceChain(possibleParent, possibleChild.parents[0])) {
return true;
}
if (this.inInheritanceChain(possibleParent, possibleChild.parents[1])) {
return true;
}
}
return false;
},
visitRule: function (ruleNode, visitArgs) {
visitArgs.visitDeeper = false;
},
@@ -208,11 +206,12 @@
for(extendIndex = 0; extendIndex < allExtends.length; extendIndex++) {
for(pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) {
selectorPath = rulesetNode.paths[pathIndex];
// extending extends happens initially, before the main pass
if (selectorPath[selectorPath.length-1].extendList.length) { continue; }
if (rulesetNode.extendOnEveryPath) { continue; }
var extendList = selectorPath[selectorPath.length-1].extendList;
if (extendList && extendList.length) { continue; }
matches = this.findMatch(allExtends[extendIndex], selectorPath);
@@ -246,7 +245,7 @@
haystackElement = hackstackSelector.elements[hackstackElementIndex];
// if we allow elements before our match we can add a potential match every time. otherwise only at the first element.
if (extend.allowBefore || (haystackSelectorIndex == 0 && hackstackElementIndex == 0)) {
if (extend.allowBefore || (haystackSelectorIndex === 0 && hackstackElementIndex === 0)) {
potentialMatches.push({pathIndex: haystackSelectorIndex, index: hackstackElementIndex, matched: 0, initialCombinator: haystackElement.combinator});
}
@@ -257,7 +256,7 @@
// then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to work out
// what the resulting combinator will be
targetCombinator = haystackElement.combinator.value;
if (targetCombinator == '' && hackstackElementIndex === 0) {
if (targetCombinator === '' && hackstackElementIndex === 0) {
targetCombinator = ' ';
}
@@ -313,6 +312,24 @@
elementValue2 = elementValue2.value.value || elementValue2.value;
return elementValue1 === elementValue2;
}
elementValue1 = elementValue1.value;
elementValue2 = elementValue2.value;
if (elementValue1 instanceof tree.Selector) {
if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) {
return false;
}
for(var i = 0; i <elementValue1.elements.length; i++) {
if (elementValue1.elements[i].combinator.value !== elementValue2.elements[i].combinator.value) {
if (i !== 0 || (elementValue1.elements[i].combinator.value || ' ') !== (elementValue2.elements[i].combinator.value || ' ')) {
return false;
}
}
if (!this.isElementValuesEqual(elementValue1.elements[i].value, elementValue2.elements[i].value)) {
return false;
}
}
return true;
}
return false;
},
extendSelector:function (matches, selectorPath, replacementSelector) {
@@ -325,7 +342,8 @@
matchIndex,
selector,
firstElement,
match;
match,
newElements;
for (matchIndex = 0; matchIndex < matches.length; matchIndex++) {
match = matches[matchIndex];
@@ -333,7 +351,8 @@
firstElement = new tree.Element(
match.initialCombinator,
replacementSelector.elements[0].value,
replacementSelector.elements[0].index
replacementSelector.elements[0].index,
replacementSelector.elements[0].currentFileInfo
);
if (match.pathIndex > currentSelectorPathIndex && currentSelectorPathElementIndex > 0) {
@@ -342,17 +361,24 @@
currentSelectorPathIndex++;
}
path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex));
newElements = selector.elements
.slice(currentSelectorPathElementIndex, match.index)
.concat([firstElement])
.concat(replacementSelector.elements.slice(1));
path.push(new tree.Selector(
selector.elements
.slice(currentSelectorPathElementIndex, match.index)
.concat([firstElement])
.concat(replacementSelector.elements.slice(1))
));
if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) {
path[path.length - 1].elements =
path[path.length - 1].elements.concat(newElements);
} else {
path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex));
path.push(new tree.Selector(
newElements
));
}
currentSelectorPathIndex = match.endPathIndex;
currentSelectorPathElementIndex = match.endPathElementIndex;
if (currentSelectorPathElementIndex >= selector.elements.length) {
if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) {
currentSelectorPathElementIndex = 0;
currentSelectorPathIndex++;
}
@@ -360,7 +386,6 @@
if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) {
path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
currentSelectorPathElementIndex = 0;
currentSelectorPathIndex++;
}
@@ -388,4 +413,4 @@
}
};
})(require('./tree'));
})(require('./tree'));

View File

@@ -5,7 +5,7 @@ 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 scaled(c, 256); });
var rgb = [r, g, b].map(function (c) { return scaled(c, 255); });
a = number(a);
return new(tree.Color)(rgb, a);
},
@@ -13,6 +13,14 @@ tree.functions = {
return this.hsla(h, s, l, 1.0);
},
hsla: function (h, s, l, a) {
function hue(h) {
h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h);
if (h * 6 < 1) { return m1 + (m2 - m1) * h * 6; }
else if (h * 2 < 1) { return m2; }
else if (h * 3 < 2) { return m1 + (m2 - m1) * (2/3 - h) * 6; }
else { return m1; }
}
h = (number(h) % 360) / 360;
s = clamp(number(s)); l = clamp(number(l)); a = clamp(number(a));
@@ -23,14 +31,6 @@ tree.functions = {
hue(h) * 255,
hue(h - 1/3) * 255,
a);
function hue(h) {
h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h);
if (h * 6 < 1) return m1 + (m2 - m1) * h * 6;
else if (h * 2 < 1) return m2;
else if (h * 3 < 2) return m1 + (m2 - m1) * (2/3 - h) * 6;
else return m1;
}
},
hsv: function(h, s, v) {
@@ -96,6 +96,11 @@ tree.functions = {
return new(tree.Dimension)(Math.round(color.luma() * color.alpha * 100), '%');
},
saturate: function (color, amount) {
// filter: saturate(3.2);
// should be kept as is, so check for color
if (!color.rgb) {
return null;
}
var hsl = color.toHSL();
hsl.s += amount.value / 100;
@@ -201,7 +206,7 @@ tree.functions = {
} else {
threshold = number(threshold);
}
if ((color.luma() * color.alpha) < threshold) {
if (color.luma() < threshold) {
return light;
} else {
return dark;
@@ -225,6 +230,7 @@ tree.functions = {
str = quoted.value;
for (var i = 0; i < args.length; i++) {
/*jshint loopfunc:true */
str = str.replace(/%[sda]/i, function(token) {
var value = token.match(/s/i) ? args[i].value : args[i].toCSS();
return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value;
@@ -234,6 +240,9 @@ tree.functions = {
return new(tree.Quoted)('"' + str + '"', str);
},
unit: function (val, unit) {
if(!(val instanceof tree.Dimension)) {
throw { type: "Argument", message: "the first argument to unit must be a number" + (val instanceof tree.Operation ? ". Have you forgotten parenthesis?" : "") };
}
return new(tree.Dimension)(val.value, unit ? unit.toCSS() : "");
},
convert: function (val, unit) {
@@ -241,7 +250,7 @@ tree.functions = {
},
round: function (n, f) {
var fraction = typeof(f) === "undefined" ? 0 : f.value;
return this._math(function(num) { return num.toFixed(fraction); }, null, n);
return _math(function(num) { return num.toFixed(fraction); }, null, n);
},
pi: function () {
return new(tree.Dimension)(Math.PI);
@@ -259,25 +268,67 @@ tree.functions = {
return new(tree.Dimension)(Math.pow(x.value, y.value), x.unit);
},
_math: function (fn, unit, n) {
if (n instanceof tree.Dimension) {
return new(tree.Dimension)(fn(parseFloat(n.value)), unit == null ? n.unit : unit);
} else if (typeof(n) === 'number') {
return fn(n);
} else {
throw { type: "Argument", message: "argument must be a number" };
_minmax: function (isMin, args) {
args = Array.prototype.slice.call(args);
switch(args.length) {
case 0: throw { type: "Argument", message: "one or more arguments required" };
case 1: return args[0];
}
var i, j, current, currentUnified, referenceUnified, unit,
order = [], // elems only contains original argument values.
values = {}; // key is the unit.toString() for unified tree.Dimension values,
// value is the index into the order array.
for (i = 0; i < args.length; i++) {
current = args[i];
if (!(current instanceof tree.Dimension)) {
order.push(current);
continue;
}
currentUnified = current.unify();
unit = currentUnified.unit.toString();
j = values[unit];
if (j === undefined) {
values[unit] = order.length;
order.push(current);
continue;
}
referenceUnified = order[j].unify();
if ( isMin && currentUnified.value < referenceUnified.value ||
!isMin && currentUnified.value > referenceUnified.value) {
order[j] = current;
}
}
if (order.length == 1) {
return order[0];
}
args = order.map(function (a) { return a.toCSS(this.env); })
.join(this.env.compress ? "," : ", ");
return new(tree.Anonymous)((isMin ? "min" : "max") + "(" + args + ")");
},
min: function () {
return this._minmax(true, arguments);
},
max: function () {
return this._minmax(false, arguments);
},
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));
var colorCandidate = n.value,
returnColor;
returnColor = tree.Color.fromKeyword(colorCandidate);
if (returnColor) {
return returnColor;
}
if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/.test(colorCandidate)) {
return new(tree.Color)(colorCandidate.slice(1));
}
throw { type: "Argument", message: "argument must be a color keyword or 3/6 digit hex e.g. #FFF" };
} else {
throw { type: "Argument", message: "argument must be a string" };
}
@@ -312,75 +363,22 @@ tree.functions = {
_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);
},
},
extract: function(values, index) {
index = index.value - 1; // (1-based index)
return values.value[index];
index = index.value - 1; // (1-based index)
// handle non-array values as an array of length 1
// return 'undefined' if index is invalid
return Array.isArray(values.value)
? values.value[index] : Array(values)[index];
},
length: function(values) {
var n = Array.isArray(values.value) ? values.value.length : 1;
return new tree.Dimension(n);
},
"data-uri": function(mimetypeNode, filePathNode) {
@@ -392,8 +390,8 @@ tree.functions = {
var mimetype = mimetypeNode.value;
var filePath = (filePathNode && filePathNode.value);
var fs = require("fs"),
path = require("path"),
var fs = require('fs'),
path = require('path'),
useBase64 = false;
if (arguments.length < 2) {
@@ -422,10 +420,10 @@ tree.functions = {
// use base 64 unless it's an ASCII or UTF-8 format
var charset = mime.charsets.lookup(mimetype);
useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
if (useBase64) mimetype += ';base64';
if (useBase64) { mimetype += ';base64'; }
}
else {
useBase64 = /;base64$/.test(mimetype)
useBase64 = /;base64$/.test(mimetype);
}
var buf = fs.readFileSync(filePath);
@@ -442,17 +440,90 @@ tree.functions = {
}
return new tree.URL(filePathNode || mimetypeNode, this.currentFileInfo).eval(this.env);
} else if (!this.env.silent) {
// if explicitly disabled (via --no-ie-compat on CLI, or env.ieCompat === false), merely warn
console.warn("WARNING: Embedding %s (%dKB) exceeds IE8's data-uri size limit of %dKB!", filePath, fileSizeInKB, DATA_URI_MAX_KB);
}
}
buf = useBase64 ? buf.toString('base64')
: encodeURIComponent(buf);
var uri = "'data:" + mimetype + ',' + buf + "'";
var uri = "\"data:" + mimetype + ',' + buf + "\"";
return new(tree.URL)(new(tree.Anonymous)(uri));
},
"svg-gradient": function(direction) {
function throwArgumentDescriptor() {
throw { type: "Argument", message: "svg-gradient expects direction, start_color [start_position], [color position,]..., end_color [end_position]" };
}
if (arguments.length < 3) {
throwArgumentDescriptor();
}
var stops = Array.prototype.slice.call(arguments, 1),
gradientDirectionSvg,
gradientType = "linear",
rectangleDimension = 'x="0" y="0" width="1" height="1"',
useBase64 = true,
renderEnv = {compress: false},
returner,
directionValue = direction.toCSS(renderEnv),
i, color, position, positionValue, alpha;
switch (directionValue) {
case "to bottom":
gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"';
break;
case "to right":
gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"';
break;
case "to bottom right":
gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"';
break;
case "to top right":
gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"';
break;
case "ellipse":
case "ellipse at center":
gradientType = "radial";
gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"';
rectangleDimension = 'x="-50" y="-50" width="101" height="101"';
break;
default:
throw { type: "Argument", message: "svg-gradient direction must be 'to bottom', 'to right', 'to bottom right', 'to top right' or 'ellipse at center'" };
}
returner = '<?xml version="1.0" ?>' +
'<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">' +
'<' + gradientType + 'Gradient id="gradient" gradientUnits="userSpaceOnUse" ' + gradientDirectionSvg + '>';
for (i = 0; i < stops.length; i+= 1) {
if (stops[i].value) {
color = stops[i].value[0];
position = stops[i].value[1];
} else {
color = stops[i];
position = undefined;
}
if (!(color instanceof tree.Color) || (!((i === 0 || i+1 === stops.length) && position === undefined) && !(position instanceof tree.Dimension))) {
throwArgumentDescriptor();
}
positionValue = position ? position.toCSS(renderEnv) : i === 0 ? "0%" : "100%";
alpha = color.alpha;
returner += '<stop offset="' + positionValue + '" stop-color="' + color.toRGB() + '"' + (alpha < 1 ? ' stop-opacity="' + alpha + '"' : '') + '/>';
}
returner += '</' + gradientType + 'Gradient>' +
'<rect ' + rectangleDimension + ' fill="url(#gradient)" /></svg>';
if (useBase64) {
try {
returner = require('./encoder').encodeBase64(returner); // TODO browser implementation
} catch(e) {
useBase64 = false;
}
}
returner = "'data:image/svg+xml" + (useBase64 ? ";base64" : "") + "," + returner + "'";
return new(tree.URL)(new(tree.Anonymous)(returner));
}
};
@@ -484,22 +555,146 @@ tree._mime = {
}
};
var mathFunctions = [{name:"ceil"}, {name:"floor"}, {name: "sqrt"}, {name:"abs"},
{name:"tan", unit: ""}, {name:"sin", unit: ""}, {name:"cos", unit: ""},
{name:"atan", unit: "rad"}, {name:"asin", unit: "rad"}, {name:"acos", unit: "rad"}],
createMathFunction = function(name, unit) {
return function(n) {
if (unit != null) {
n = n.unify();
}
return this._math(Math[name], unit, n);
};
};
// Math
for(var i = 0; i < mathFunctions.length; i++) {
tree.functions[mathFunctions[i].name] = createMathFunction(mathFunctions[i].name, mathFunctions[i].unit);
var mathFunctions = {
// name, unit
ceil: null,
floor: null,
sqrt: null,
abs: null,
tan: "",
sin: "",
cos: "",
atan: "rad",
asin: "rad",
acos: "rad"
};
function _math(fn, unit, n) {
if (!(n instanceof tree.Dimension)) {
throw { type: "Argument", message: "argument must be a number" };
}
if (unit == null) {
unit = n.unit;
} else {
n = n.unify();
}
return new(tree.Dimension)(fn(parseFloat(n.value)), unit);
}
// ~ End of Math
// Color Blending
// ref: http://www.w3.org/TR/compositing-1
function colorBlend(mode, color1, color2) {
var ab = color1.alpha, cb, // backdrop
as = color2.alpha, cs, // source
ar, cr, r = []; // result
ar = as + ab * (1 - as);
for (var i = 0; i < 3; i++) {
cb = color1.rgb[i] / 255;
cs = color2.rgb[i] / 255;
cr = mode(cb, cs);
if (ar) {
cr = (as * cs + ab * (cb
- as * (cb + cs - cr))) / ar;
}
r[i] = cr * 255;
}
return new(tree.Color)(r, ar);
}
var colorBlendMode = {
multiply: function(cb, cs) {
return cb * cs;
},
screen: function(cb, cs) {
return cb + cs - cb * cs;
},
overlay: function(cb, cs) {
cb *= 2;
return (cb <= 1)
? colorBlendMode.multiply(cb, cs)
: colorBlendMode.screen(cb - 1, cs);
},
softlight: function(cb, cs) {
var d = 1, e = cb;
if (cs > 0.5) {
e = 1;
d = (cb > 0.25) ? Math.sqrt(cb)
: ((16 * cb - 12) * cb + 4) * cb;
}
return cb - (1 - 2 * cs) * e * (d - cb);
},
hardlight: function(cb, cs) {
return colorBlendMode.overlay(cs, cb);
},
difference: function(cb, cs) {
return Math.abs(cb - cs);
},
exclusion: function(cb, cs) {
return cb + cs - 2 * cb * cs;
},
// non-w3c functions:
average: function(cb, cs) {
return (cb + cs) / 2;
},
negation: function(cb, cs) {
return 1 - Math.abs(cb + cs - 1);
}
};
// ~ End of Color Blending
tree.defaultFunc = {
eval: function () {
var v = this.value_, e = this.error_;
if (e) {
throw e;
}
if (v != null) {
return v ? tree.True : tree.False;
}
},
value: function (v) {
this.value_ = v;
},
error: function (e) {
this.error_ = e;
},
reset: function () {
this.value_ = this.error_ = null;
}
};
function initFunctions() {
var f, tf = tree.functions;
// math
for (f in mathFunctions) {
if (mathFunctions.hasOwnProperty(f)) {
tf[f] = _math.bind(null, Math[f], mathFunctions[f]);
}
}
// color blending
for (f in colorBlendMode) {
if (colorBlendMode.hasOwnProperty(f)) {
tf[f] = colorBlend.bind(null, colorBlendMode[f]);
}
}
// default
f = tree.defaultFunc;
tf["default"] = f.eval.bind(f);
} initFunctions();
function hsla(color) {
return tree.functions.hsla(color.h, color.s, color.l, color.a);
}
@@ -529,6 +724,16 @@ function clamp(val) {
return Math.min(1, Math.max(0, val));
}
tree.fround = function(env, value) {
var p;
if (env && (env.numPrecision != null)) {
p = Math.pow(10, env.numPrecision);
return Math.round(value * p) / p;
} else {
return value;
}
};
tree.functionCall = function(env, currentFileInfo) {
this.env = env;
this.currentFileInfo = currentFileInfo;

View File

@@ -27,9 +27,10 @@
},
visitImport: function (importNode, visitArgs) {
var importVisitor = this,
evaldImportNode;
if (!importNode.css) {
evaldImportNode,
inlineCSS = importNode.options.inline;
if (!importNode.css || inlineCSS) {
try {
evaldImportNode = importNode.evalForImport(this.env);
@@ -41,13 +42,19 @@
importNode.error = e;
}
if (evaldImportNode && !evaldImportNode.css) {
if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) {
importNode = evaldImportNode;
this.importCount++;
var env = new tree.evalEnv(this.env, this.env.frames.slice(0));
this._importer.push(importNode.getPath(), importNode.currentFileInfo, function (e, root, imported) {
if (importNode.options.multiple) {
env.importMultiple = true;
}
this._importer.push(importNode.getPath(), importNode.currentFileInfo, importNode.options, function (e, root, imported, fullPath) {
if (e && !e.filename) { e.index = importNode.index; e.filename = importNode.currentFileInfo.filename; }
if (imported && !importNode.options.multiple) { importNode.skip = imported; }
if (imported && !env.importMultiple) { importNode.skip = imported; }
var subFinish = function(e) {
importVisitor.importCount--;
@@ -59,11 +66,15 @@
if (root) {
importNode.root = root;
new(tree.importVisitor)(importVisitor._importer, subFinish, env)
.run(root);
} else {
subFinish();
importNode.importedFilename = fullPath;
if (!inlineCSS && !importNode.skip) {
new(tree.importVisitor)(importVisitor._importer, subFinish, env)
.run(root);
return;
}
}
subFinish();
});
}
}

View File

@@ -1,19 +1,18 @@
var path = require('path'),
sys = require('util'),
url = require('url'),
request,
fs = require('fs');
var less = {
version: [1, 4, 2],
version: [1, 6, 2],
Parser: require('./parser').Parser,
importer: require('./parser').importer,
tree: require('./tree'),
render: function (input, options, callback) {
options = options || {};
if (typeof(options) === 'function') {
callback = options, options = {};
callback = options;
options = {};
}
var parser = new(less.Parser)(options),
@@ -21,15 +20,17 @@ var less = {
if (callback) {
parser.parse(input, function (e, root) {
callback(e, root && root.toCSS && root.toCSS(options));
try { callback(e, root && root.toCSS && root.toCSS(options)); }
catch (err) { callback(err); }
});
} else {
ee = new(require('events').EventEmitter);
ee = new (require('events').EventEmitter)();
process.nextTick(function () {
parser.parse(input, function (e, root) {
if (e) { ee.emit('error', e) }
else { ee.emit('success', root.toCSS(options)) }
if (e) { return ee.emit('error', e); }
try { ee.emit('success', root.toCSS(options)); }
catch (err) { ee.emit('error', err); }
});
});
return ee;
@@ -41,10 +42,10 @@ var less = {
var message = "";
var extract = ctx.extract;
var error = [];
var stylize = options.color ? require('./lessc_helper').stylize : function (str) { return str };
var stylize = options.color ? require('./lessc_helper').stylize : function (str) { return str; };
// only output a stack if it isn't a less error
if (ctx.stack && !ctx.type) { return stylize(ctx.stack, 'red') }
if (ctx.stack && !ctx.type) { return stylize(ctx.stack, 'red'); }
if (!ctx.hasOwnProperty('index') || !extract) {
return ctx.stack || ctx.message;
@@ -70,8 +71,10 @@ var less = {
error = error.join('\n') + stylize('', 'reset') + '\n';
message += stylize(ctx.type + 'Error: ' + ctx.message, 'red');
ctx.filename && (message += stylize(' in ', 'red') + ctx.filename +
stylize(' on line ' + ctx.line + ', column ' + (ctx.column + 1) + ':', 'grey'));
if (ctx.filename) {
message += stylize(' in ', 'red') + ctx.filename +
stylize(' on line ' + ctx.line + ', column ' + (ctx.column + 1) + ':', 'grey');
}
message += '\n' + error;
@@ -84,26 +87,44 @@ var less = {
},
writeError: function (ctx, options) {
options = options || {};
if (options.silent) { return }
sys.error(less.formatError(ctx, options));
if (options.silent) { return; }
console.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', 'assignment', 'condition', 'paren',
'media', 'unicode-descriptor', 'negative', 'extend'
].forEach(function (n) {
require('./tree/' + n);
});
require('./tree/color');
require('./tree/directive');
require('./tree/operation');
require('./tree/dimension');
require('./tree/keyword');
require('./tree/variable');
require('./tree/ruleset');
require('./tree/element');
require('./tree/selector');
require('./tree/quoted');
require('./tree/expression');
require('./tree/rule');
require('./tree/call');
require('./tree/url');
require('./tree/alpha');
require('./tree/import');
require('./tree/mixin');
require('./tree/comment');
require('./tree/anonymous');
require('./tree/value');
require('./tree/javascript');
require('./tree/assignment');
require('./tree/condition');
require('./tree/paren');
require('./tree/media');
require('./tree/unicode-descriptor');
require('./tree/negative');
require('./tree/extend');
var isUrlRe = /^(?:https?:)?\/\//i;
less.Parser.importer = function (file, currentFileInfo, callback, env) {
less.Parser.fileLoader = function (file, currentFileInfo, callback, env) {
var pathname, dirname, data,
newFileInfo = {
relativeUrls: env.relativeUrls,
@@ -112,12 +133,7 @@ less.Parser.importer = function (file, currentFileInfo, callback, env) {
rootFilename: currentFileInfo.rootFilename
};
function parseFile(e, data) {
if (e) { return callback(e); }
env = new less.tree.parseEnv(env);
env.processImports = false;
function handleDataAndCallCallback(data) {
var j = file.lastIndexOf('/');
// Pass on an updated rootpath if path of imported file is relative and file
@@ -135,12 +151,8 @@ less.Parser.importer = function (file, currentFileInfo, callback, env) {
newFileInfo.currentDirectory = pathname.replace(/[^\\\/]*$/, "");
newFileInfo.filename = pathname;
env.contents[pathname] = data; // Updating top importing parser content cache.
env.currentFileInfo = newFileInfo;
new(less.Parser)(env).parse(data, function (e, root) {
callback(e, root, pathname);
});
};
callback(null, data, pathname, newFileInfo);
}
var isUrl = isUrlRe.test( file );
if (isUrl || isUrlRe.test(currentFileInfo.currentDirectory)) {
@@ -154,63 +166,71 @@ less.Parser.importer = function (file, currentFileInfo, callback, env) {
}
var urlStr = isUrl ? file : url.resolve(currentFileInfo.currentDirectory, file),
urlObj = url.parse(urlStr),
req = {
host: urlObj.hostname,
port: urlObj.port || 80,
path: urlObj.pathname + (urlObj.search||'')
};
urlObj = url.parse(urlStr);
request.get(urlStr, function (error, res, body) {
request.get({uri: urlStr, strictSSL: !env.insecure }, function (error, res, body) {
if (res.statusCode === 404) {
callback({ type: 'File', message: "resource '" + urlStr + "' was not found\n" });
return;
}
if (!body) {
sys.error( 'Warning: Empty body (HTTP '+ res.statusCode + ') returned by "' + urlStr +'"' );
console.error( 'Warning: Empty body (HTTP '+ res.statusCode + ') returned by "' + urlStr +'"' );
}
if (error) {
callback({ type: 'File', message: "resource '" + urlStr + "' gave this Error:\n "+ error +"\n" });
}
pathname = urlStr;
dirname = urlObj.protocol +'//'+ urlObj.host + urlObj.pathname.replace(/[^\/]*$/, '');
parseFile(null, body);
handleDataAndCallCallback(body);
});
} else {
var paths = [currentFileInfo.currentDirectory].concat(env.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;
}
}
if (!pathname) {
callback({ type: 'File', message: "'" + file + "' wasn't found" });
return;
}
dirname = path.dirname(pathname);
if (env.syncImport) {
for (var i = 0; i < paths.length; i++) {
try {
pathname = path.join(paths[i], file);
fs.statSync(pathname);
break;
} catch (e) {
pathname = null;
}
}
if (!pathname) {
callback({ type: 'File', message: "'" + file + "' wasn't found" });
return;
}
try {
data = fs.readFileSync(pathname, 'utf-8');
parseFile(null, data);
handleDataAndCallCallback(data);
} catch (e) {
parseFile(e);
callback(e);
}
} else {
fs.readFile(pathname, 'utf-8', parseFile);
(function tryPathIndex(i) {
if (i < paths.length) {
pathname = path.join(paths[i], file);
fs.stat(pathname, function (err) {
if (err) {
tryPathIndex(i + 1);
} else {
fs.readFile(pathname, 'utf-8', function(e, data) {
if (e) { callback(e); }
handleDataAndCallCallback(data);
});
}
});
} else {
callback({ type: 'File', message: "'" + file + "' wasn't found" });
}
}(0));
}
}
}
};
require('./env');
require('./functions');
@@ -219,5 +239,7 @@ require('./visitor.js');
require('./import-visitor.js');
require('./extend-visitor.js');
require('./join-selector-visitor.js');
require('./to-css-visitor.js');
require('./source-map-output.js');
for (var k in less) { exports[k] = less[k]; }
for (var k in less) { if (less.hasOwnProperty(k)) { exports[k] = less[k]; }}

View File

@@ -16,12 +16,19 @@
},
visitRuleset: function (rulesetNode, visitArgs) {
var context = this.contexts[this.contexts.length - 1];
var paths = [];
var context = this.contexts[this.contexts.length - 1],
paths = [], selectors;
this.contexts.push(paths);
if (! rulesetNode.root) {
rulesetNode.joinSelectors(paths, context, rulesetNode.selectors);
selectors = rulesetNode.selectors;
if (selectors) {
selectors = selectors.filter(function(selector) { return selector.getIsOutput(); });
rulesetNode.selectors = selectors.length ? selectors : (selectors = null);
if (selectors) { rulesetNode.joinSelectors(paths, context, selectors); }
}
if (!selectors) { rulesetNode.rules = null; }
rulesetNode.paths = paths;
}
},
@@ -30,7 +37,7 @@
},
visitMedia: function (mediaNode, visitArgs) {
var context = this.contexts[this.contexts.length - 1];
mediaNode.ruleset.root = (context.length === 0 || context[0].multiMedia);
mediaNode.rules[0].root = (context.length === 0 || context[0].multiMedia);
}
};

View File

@@ -1,8 +1,6 @@
// lessc_helper.js
//
// helper functions for lessc
var sys = require('util');
var lessc_helper = {
//Stylize a string
@@ -23,49 +21,62 @@ var lessc_helper = {
//Print command line options
printUsage: function() {
sys.puts("usage: lessc [option option=parameter ...] <source> [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=PATHS Set include paths. Separated by `:'. Use `;' on Windows.");
sys.puts(" -M, --depends Output a makefile import dependency list to stdout");
sys.puts(" --no-color Disable colorized output.");
sys.puts(" --no-ie-compat Disable IE compatibility checks.");
sys.puts(" -l, --lint Syntax check only (lint).");
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(" --max-line-len=LINELEN Max line length used by 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=URL Set rootpath for url rewriting in relative imports and urls.");
sys.puts(" Works with or without the relative-urls option.");
sys.puts(" -ru, --relative-urls re-write relative urls to the base less file.");
sys.puts(" -sm=on|off Turn on or off strict math, where in strict mode, math");
sys.puts(" --strict-math=on|off requires brackets. This option may default to on and then");
sys.puts(" be removed in the future.");
sys.puts(" -su=on|off Allow mixed units, e.g. 1px+1em or 1px*1px which have units");
sys.puts(" --strict-units=on|off that cannot be represented.");
sys.puts("");
sys.puts("Report bugs to: http://github.com/cloudhead/less.js/issues");
sys.puts("Home page: <http://lesscss.org/>");
console.log("usage: lessc [option option=parameter ...] <source> [destination]");
console.log("");
console.log("If source is set to `-' (dash or hyphen-minus), input is read from stdin.");
console.log("");
console.log("options:");
console.log(" -h, --help Print help (this message) and exit.");
console.log(" --include-path=PATHS Set include paths. Separated by `:'. Use `;' on Windows.");
console.log(" -M, --depends Output a makefile import dependency list to stdout");
console.log(" --no-color Disable colorized output.");
console.log(" --no-ie-compat Disable IE compatibility checks.");
console.log(" --no-js Disable JavaScript in less files");
console.log(" -l, --lint Syntax check only (lint).");
console.log(" -s, --silent Suppress output of error messages.");
console.log(" --strict-imports Force evaluation of imports.");
console.log(" --insecure Allow imports from insecure https hosts.");
console.log(" -v, --version Print version number and exit.");
console.log(" -x, --compress Compress output by removing some whitespaces.");
console.log(" --clean-css Compress output using clean-css");
console.log(" --clean-option=opt:val Pass an option to clean css, using CLI arguments from ");
console.log(" https://github.com/GoalSmashers/clean-css e.g.");
console.log(" --clean-option=--selectors-merge-mode:ie8");
console.log(" and to switch on advanced use --clean-option=--advanced");
console.log(" --source-map[=FILENAME] Outputs a v3 sourcemap to the filename (or output filename.map)");
console.log(" --source-map-rootpath=X adds this path onto the sourcemap filename and less file paths");
console.log(" --source-map-basepath=X Sets sourcemap base path, defaults to current working directory.");
console.log(" --source-map-less-inline puts the less files into the map instead of referencing them");
console.log(" --source-map-map-inline puts the map (and any less files) into the output css file");
console.log(" --source-map-url=URL the complete url and filename put in the less file");
console.log(" -rp, --rootpath=URL Set rootpath for url rewriting in relative imports and urls.");
console.log(" Works with or without the relative-urls option.");
console.log(" -ru, --relative-urls re-write relative urls to the base less file.");
console.log(" -sm=on|off Turn on or off strict math, where in strict mode, math");
console.log(" --strict-math=on|off requires brackets. This option may default to on and then");
console.log(" be removed in the future.");
console.log(" -su=on|off Allow mixed units, e.g. 1px+1em or 1px*1px which have units");
console.log(" --strict-units=on|off that cannot be represented.");
console.log(" --global-var='VAR=VALUE' Defines a variable that can be referenced by the file.");
console.log(" --modify-var='VAR=VALUE' Modifies a variable already declared in the file.");
console.log("");
console.log("-------------------------- Deprecated ----------------");
console.log(" -O0, -O1, -O2 Set the parser's optimization level. The lower");
console.log(" the number, the less nodes it will create in the");
console.log(" tree. This could matter for debugging, or if you");
console.log(" want to access the individual nodes in the tree.");
console.log(" --line-numbers=TYPE Outputs filename and line numbers.");
console.log(" TYPE can be either 'comments', which will output");
console.log(" the debug info within comments, 'mediaquery'");
console.log(" that will output the information within a fake");
console.log(" media query which is compatible with the SASS");
console.log(" format, and 'all' which will do both.");
console.log(" --verbose Be verbose.");
console.log("");
console.log("Report bugs to: http://github.com/less/less.js/issues");
console.log("Home page: <http://lesscss.org/>");
}
}
};
// Exports helper functions
for (var h in lessc_helper) { exports[h] = lessc_helper[h] }
for (var h in lessc_helper) { if (lessc_helper.hasOwnProperty(h)) { exports[h] = lessc_helper[h]; }}

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,63 @@
var name;
/*jshint rhino:true, unused: false */
/*global name:true, less, loadStyleSheet, os */
function formatError(ctx, options) {
options = options || {};
var message = "";
var extract = ctx.extract;
var error = [];
// var stylize = options.color ? require('./lessc_helper').stylize : function (str) { return str; };
var stylize = function (str) { return str; };
// only output a stack if it isn't a less error
if (ctx.stack && !ctx.type) { return stylize(ctx.stack, 'red'); }
if (!ctx.hasOwnProperty('index') || !extract) {
return ctx.stack || ctx.message;
}
if (typeof(extract[0]) === 'string') {
error.push(stylize((ctx.line - 1) + ' ' + extract[0], 'grey'));
}
if (typeof(extract[1]) === 'string') {
var errorTxt = ctx.line + ' ';
if (extract[1]) {
errorTxt += extract[1].slice(0, ctx.column) +
stylize(stylize(stylize(extract[1][ctx.column], 'bold') +
extract[1].slice(ctx.column + 1), 'red'), 'inverse');
}
error.push(errorTxt);
}
if (typeof(extract[2]) === 'string') {
error.push(stylize((ctx.line + 1) + ' ' + extract[2], 'grey'));
}
error = error.join('\n') + stylize('', 'reset') + '\n';
message += stylize(ctx.type + 'Error: ' + ctx.message, 'red');
if (ctx.filename) {
message += stylize(' in ', 'red') + ctx.filename +
stylize(' on line ' + ctx.line + ', column ' + (ctx.column + 1) + ':', 'grey');
}
message += '\n' + error;
if (ctx.callLine) {
message += stylize('from ', 'red') + (ctx.filename || '') + '/n';
message += stylize(ctx.callLine, 'grey') + ' ' + ctx.callExtract + '/n';
}
return message;
}
function writeError(ctx, options) {
options = options || {};
if (options.silent) { return; }
print(formatError(ctx, options));
}
function loadStyleSheet(sheet, callback, reload, remaining) {
var endOfPath = Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\')),
@@ -16,16 +75,66 @@ function loadStyleSheet(sheet, callback, reload, remaining) {
});
parser.parse(input, function (e, root) {
if (e) {
return error(e, sheetName);
return writeError(e);
}
try {
callback(e, root, input, sheet, { local: false, lastModified: 0, remaining: remaining }, sheetName);
} catch(e) {
error(e, sheetName);
writeError(e);
}
});
}
less.Parser.fileLoader = function (file, currentFileInfo, callback, env) {
var href = file;
if (currentFileInfo && currentFileInfo.currentDirectory && !/^\//.test(file)) {
href = less.modules.path.join(currentFileInfo.currentDirectory, file);
}
var path = less.modules.path.dirname(href);
var newFileInfo = {
currentDirectory: path + '/',
filename: href
};
if (currentFileInfo) {
newFileInfo.entryPath = currentFileInfo.entryPath;
newFileInfo.rootpath = currentFileInfo.rootpath;
newFileInfo.rootFilename = currentFileInfo.rootFilename;
newFileInfo.relativeUrls = currentFileInfo.relativeUrls;
} else {
newFileInfo.entryPath = path;
newFileInfo.rootpath = less.rootpath || path;
newFileInfo.rootFilename = href;
newFileInfo.relativeUrls = env.relativeUrls;
}
var j = file.lastIndexOf('/');
if(newFileInfo.relativeUrls && !/^(?:[a-z-]+:|\/)/.test(file) && j != -1) {
var relativeSubDirectory = file.slice(0, j+1);
newFileInfo.rootpath = newFileInfo.rootpath + relativeSubDirectory; // append (sub|sup) directory path of imported file
}
newFileInfo.currentDirectory = path;
newFileInfo.filename = href;
var data = null;
try {
data = readFile(href);
} catch (e) {
callback({ type: 'File', message: "'" + less.modules.path.basename(href) + "' wasn't found" });
return;
}
try {
callback(null, data, href, newFileInfo, { lastModified: 0 });
} catch (e) {
callback(e, null, href);
}
};
function writeFile(filename, content) {
var fstream = new java.io.FileWriter(filename);
var out = new java.io.BufferedWriter(fstream);
@@ -35,53 +144,295 @@ function writeFile(filename, content) {
// Command line integration via Rhino
(function (args) {
var output,
compress = false,
i,
path;
var options = {
depends: false,
compress: false,
cleancss: false,
max_line_len: -1,
optimization: 1,
silent: false,
verbose: false,
lint: false,
paths: [],
color: true,
strictImports: false,
rootpath: '',
relativeUrls: false,
ieCompat: true,
strictMath: false,
strictUnits: false
};
var continueProcessing = true,
currentErrorcode;
var checkArgFunc = function(arg, option) {
if (!option) {
print(arg + " option requires a parameter");
continueProcessing = false;
return false;
}
return true;
};
var checkBooleanArg = function(arg) {
var onOff = /^((on|t|true|y|yes)|(off|f|false|n|no))$/i.exec(arg);
if (!onOff) {
print(" unable to parse "+arg+" as a boolean. use one of on/t/true/y/yes/off/f/false/n/no");
continueProcessing = false;
return false;
}
return Boolean(onOff[2]);
};
var warningMessages = "";
var sourceMapFileInline = false;
args = args.filter(function (arg) {
var match = arg.match(/^-I(.+)$/);
for(i = 0; i < args.length; i++) {
switch(args[i]) {
case "-x":
compress = true;
if (match) {
options.paths.push(match[1]);
return false;
}
match = arg.match(/^--?([a-z][0-9a-z-]*)(?:=(.*))?$/i);
if (match) { arg = match[1]; } // was (?:=([^\s]*)), check!
else { return arg; }
switch (arg) {
case 'v':
case 'version':
console.log("lessc " + less.version.join('.') + " (LESS Compiler) [JavaScript]");
continueProcessing = false;
break;
case 'verbose':
options.verbose = true;
break;
case 's':
case 'silent':
options.silent = true;
break;
case 'l':
case 'lint':
options.lint = true;
break;
case 'strict-imports':
options.strictImports = true;
break;
case 'h':
case 'help':
//TODO
// require('../lib/less/lessc_helper').printUsage();
continueProcessing = false;
break;
case 'x':
case 'compress':
options.compress = true;
break;
case 'M':
case 'depends':
options.depends = true;
break;
case 'yui-compress':
warningMessages += "yui-compress option has been removed. assuming clean-css.";
options.cleancss = true;
break;
case 'clean-css':
options.cleancss = true;
break;
case 'max-line-len':
if (checkArgFunc(arg, match[2])) {
options.maxLineLen = parseInt(match[2], 10);
if (options.maxLineLen <= 0) {
options.maxLineLen = -1;
}
}
break;
case 'no-color':
options.color = false;
break;
case 'no-ie-compat':
options.ieCompat = false;
break;
case 'no-js':
options.javascriptEnabled = false;
break;
case 'include-path':
if (checkArgFunc(arg, match[2])) {
options.paths = match[2].split(os.type().match(/Windows/) ? ';' : ':')
.map(function(p) {
if (p) {
// return path.resolve(process.cwd(), p);
return p;
}
});
}
break;
case 'O0': options.optimization = 0; break;
case 'O1': options.optimization = 1; break;
case 'O2': options.optimization = 2; break;
case 'line-numbers':
if (checkArgFunc(arg, match[2])) {
options.dumpLineNumbers = match[2];
}
break;
case 'source-map':
if (!match[2]) {
options.sourceMap = true;
} else {
options.sourceMap = match[2];
}
break;
case 'source-map-rootpath':
if (checkArgFunc(arg, match[2])) {
options.sourceMapRootpath = match[2];
}
break;
case 'source-map-basepath':
if (checkArgFunc(arg, match[2])) {
options.sourceMapBasepath = match[2];
}
break;
case 'source-map-map-inline':
sourceMapFileInline = true;
options.sourceMap = true;
break;
case 'source-map-less-inline':
options.outputSourceFiles = true;
break;
case 'source-map-url':
if (checkArgFunc(arg, match[2])) {
options.sourceMapURL = match[2];
}
break;
case 'source-map-output-map-file':
if (checkArgFunc(arg, match[2])) {
options.writeSourceMap = function(sourceMapContent) {
writeFile(match[2], sourceMapContent);
};
}
break;
case 'rp':
case 'rootpath':
if (checkArgFunc(arg, match[2])) {
options.rootpath = match[2].replace(/\\/g, '/');
}
break;
case "ru":
case "relative-urls":
options.relativeUrls = true;
break;
case "sm":
case "strict-math":
if (checkArgFunc(arg, match[2])) {
options.strictMath = checkBooleanArg(match[2]);
}
break;
case "su":
case "strict-units":
if (checkArgFunc(arg, match[2])) {
options.strictUnits = checkBooleanArg(match[2]);
}
break;
default:
if (!name) {
name = args[i];
} else if (!output) {
output = args[i];
} else {
print("unrecognised parameters");
print("input_file [output_file] [-x]");
}
console.log('invalid option ' + arg);
continueProcessing = false;
}
});
if (!continueProcessing) {
return;
}
var name = args[0];
if (name && name != '-') {
// name = path.resolve(process.cwd(), name);
}
var output = args[1];
var outputbase = args[1];
if (output) {
options.sourceMapOutputFilename = output;
// output = path.resolve(process.cwd(), output);
if (warningMessages) {
console.log(warningMessages);
}
}
// options.sourceMapBasepath = process.cwd();
// options.sourceMapBasepath = '';
if (options.sourceMap === true) {
console.log("output: " + output);
if (!output && !sourceMapFileInline) {
console.log("the sourcemap option only has an optional filename if the css filename is given");
return;
}
options.sourceMapFullFilename = options.sourceMapOutputFilename + ".map";
options.sourceMap = less.modules.path.basename(options.sourceMapFullFilename);
} else if (options.sourceMap) {
options.sourceMapOutputFilename = options.sourceMap;
}
if (!name) {
print('No files present in the fileset; Check your pattern match in build.xml');
quit(1);
console.log("lessc: no inout files");
console.log("");
// TODO
// require('../lib/less/lessc_helper').printUsage();
currentErrorcode = 1;
return;
}
path = name.split("/");path.pop();path=path.join("/")
var input = readFile(name);
// var ensureDirectory = function (filepath) {
// var dir = path.dirname(filepath),
// cmd,
// existsSync = fs.existsSync || path.existsSync;
// if (!existsSync(dir)) {
// if (mkdirp === undefined) {
// try {mkdirp = require('mkdirp');}
// catch(e) { mkdirp = null; }
// }
// cmd = mkdirp && mkdirp.sync || fs.mkdirSync;
// cmd(dir);
// }
// };
if (!input) {
print('lesscss: couldn\'t open file ' + name);
if (options.depends) {
if (!outputbase) {
console.log("option --depends requires an output path to be specified");
return;
}
console.log(outputbase + ": ");
}
if (!name) {
console.log('No files present in the fileset');
quit(1);
}
var input = null;
try {
input = readFile(name, 'utf-8');
} catch (e) {
console.log('lesscss: couldn\'t open file ' + name);
quit(1);
}
options.filename = name;
var result;
try {
var parser = new less.Parser();
var parser = new less.Parser(options);
parser.parse(input, function (e, root) {
if (e) {
error(e, name);
writeError(e, options);
quit(1);
} else {
result = root.toCSS({compress: compress || false});
result = root.toCSS(options);
if (output) {
writeFile(output, result);
print("Written to " + output);
console.log("Written to " + output);
} else {
print(result);
}
@@ -90,37 +441,8 @@ function writeFile(filename, content) {
});
}
catch(e) {
error(e, name);
writeError(e, options);
quit(1);
}
print("done");
console.log("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);
}

View File

@@ -0,0 +1,141 @@
(function (tree) {
tree.sourceMapOutput = function (options) {
this._css = [];
this._rootNode = options.rootNode;
this._writeSourceMap = options.writeSourceMap;
this._contentsMap = options.contentsMap;
this._contentsIgnoredCharsMap = options.contentsIgnoredCharsMap;
this._sourceMapFilename = options.sourceMapFilename;
this._outputFilename = options.outputFilename;
this._sourceMapURL = options.sourceMapURL;
if (options.sourceMapBasepath) {
this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/');
}
this._sourceMapRootpath = options.sourceMapRootpath;
this._outputSourceFiles = options.outputSourceFiles;
this._sourceMapGeneratorConstructor = options.sourceMapGenerator || require("source-map").SourceMapGenerator;
if (this._sourceMapRootpath && this._sourceMapRootpath.charAt(this._sourceMapRootpath.length-1) !== '/') {
this._sourceMapRootpath += '/';
}
this._lineNumber = 0;
this._column = 0;
};
tree.sourceMapOutput.prototype.normalizeFilename = function(filename) {
filename = filename.replace(/\\/g, '/');
if (this._sourceMapBasepath && filename.indexOf(this._sourceMapBasepath) === 0) {
filename = filename.substring(this._sourceMapBasepath.length);
if (filename.charAt(0) === '\\' || filename.charAt(0) === '/') {
filename = filename.substring(1);
}
}
return (this._sourceMapRootpath || "") + filename;
};
tree.sourceMapOutput.prototype.add = function(chunk, fileInfo, index, mapLines) {
//ignore adding empty strings
if (!chunk) {
return;
}
var lines,
sourceLines,
columns,
sourceColumns,
i;
if (fileInfo) {
var inputSource = this._contentsMap[fileInfo.filename];
// remove vars/banner added to the top of the file
if (this._contentsIgnoredCharsMap[fileInfo.filename]) {
// adjust the index
index -= this._contentsIgnoredCharsMap[fileInfo.filename];
if (index < 0) { index = 0; }
// adjust the source
inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]);
}
inputSource = inputSource.substring(0, index);
sourceLines = inputSource.split("\n");
sourceColumns = sourceLines[sourceLines.length-1];
}
lines = chunk.split("\n");
columns = lines[lines.length-1];
if (fileInfo) {
if (!mapLines) {
this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + 1, column: this._column},
original: { line: sourceLines.length, column: sourceColumns.length},
source: this.normalizeFilename(fileInfo.filename)});
} else {
for(i = 0; i < lines.length; i++) {
this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + i + 1, column: i === 0 ? this._column : 0},
original: { line: sourceLines.length + i, column: i === 0 ? sourceColumns.length : 0},
source: this.normalizeFilename(fileInfo.filename)});
}
}
}
if (lines.length === 1) {
this._column += columns.length;
} else {
this._lineNumber += lines.length - 1;
this._column = columns.length;
}
this._css.push(chunk);
};
tree.sourceMapOutput.prototype.isEmpty = function() {
return this._css.length === 0;
};
tree.sourceMapOutput.prototype.toCSS = function(env) {
this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({ file: this._outputFilename, sourceRoot: null });
if (this._outputSourceFiles) {
for(var filename in this._contentsMap) {
if (this._contentsMap.hasOwnProperty(filename))
{
var source = this._contentsMap[filename];
if (this._contentsIgnoredCharsMap[filename]) {
source = source.slice(this._contentsIgnoredCharsMap[filename]);
}
this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), source);
}
}
}
this._rootNode.genCSS(env, this);
if (this._css.length > 0) {
var sourceMapURL,
sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON());
if (this._sourceMapURL) {
sourceMapURL = this._sourceMapURL;
} else if (this._sourceMapFilename) {
sourceMapURL = this.normalizeFilename(this._sourceMapFilename);
}
if (this._writeSourceMap) {
this._writeSourceMap(sourceMapContent);
} else {
sourceMapURL = "data:application/json," + encodeURIComponent(sourceMapContent);
}
if (sourceMapURL) {
this._css.push("/*# sourceMappingURL=" + sourceMapURL + " */");
}
}
return this._css.join('');
};
})(require('./tree'));

215
lib/less/to-css-visitor.js Normal file
View File

@@ -0,0 +1,215 @@
(function (tree) {
tree.toCSSVisitor = function(env) {
this._visitor = new tree.visitor(this);
this._env = env;
};
tree.toCSSVisitor.prototype = {
isReplacing: true,
run: function (root) {
return this._visitor.visit(root);
},
visitRule: function (ruleNode, visitArgs) {
if (ruleNode.variable) {
return [];
}
return ruleNode;
},
visitMixinDefinition: function (mixinNode, visitArgs) {
return [];
},
visitExtend: function (extendNode, visitArgs) {
return [];
},
visitComment: function (commentNode, visitArgs) {
if (commentNode.isSilent(this._env)) {
return [];
}
return commentNode;
},
visitMedia: function(mediaNode, visitArgs) {
mediaNode.accept(this._visitor);
visitArgs.visitDeeper = false;
if (!mediaNode.rules.length) {
return [];
}
return mediaNode;
},
visitDirective: function(directiveNode, visitArgs) {
if (directiveNode.currentFileInfo.reference && !directiveNode.isReferenced) {
return [];
}
if (directiveNode.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 (this.charset) {
if (directiveNode.debugInfo) {
var comment = new tree.Comment("/* " + directiveNode.toCSS(this._env).replace(/\n/g, "")+" */\n");
comment.debugInfo = directiveNode.debugInfo;
return this._visitor.visit(comment);
}
return [];
}
this.charset = true;
}
return directiveNode;
},
checkPropertiesInRoot: function(rules) {
var ruleNode;
for(var i = 0; i < rules.length; i++) {
ruleNode = rules[i];
if (ruleNode instanceof tree.Rule && !ruleNode.variable) {
throw { message: "properties must be inside selector blocks, they cannot be in the root.",
index: ruleNode.index, filename: ruleNode.currentFileInfo ? ruleNode.currentFileInfo.filename : null};
}
}
},
visitRuleset: function (rulesetNode, visitArgs) {
var rule, rulesets = [];
if (rulesetNode.firstRoot) {
this.checkPropertiesInRoot(rulesetNode.rules);
}
if (! rulesetNode.root) {
if (rulesetNode.paths) {
rulesetNode.paths = rulesetNode.paths
.filter(function(p) {
var i;
if (p[0].elements[0].combinator.value === ' ') {
p[0].elements[0].combinator = new(tree.Combinator)('');
}
for(i = 0; i < p.length; i++) {
if (p[i].getIsReferenced() && p[i].getIsOutput()) {
return true;
}
}
return false;
});
}
// Compile rules and rulesets
var nodeRules = rulesetNode.rules, nodeRuleCnt = nodeRules ? nodeRules.length : 0;
for (var i = 0; i < nodeRuleCnt; ) {
rule = nodeRules[i];
if (rule && rule.rules) {
// visit because we are moving them out from being a child
rulesets.push(this._visitor.visit(rule));
nodeRules.splice(i, 1);
nodeRuleCnt--;
continue;
}
i++;
}
// accept the visitor to remove rules and refactor itself
// then we can decide now whether we want it or not
if (nodeRuleCnt > 0) {
rulesetNode.accept(this._visitor);
} else {
rulesetNode.rules = null;
}
visitArgs.visitDeeper = false;
nodeRules = rulesetNode.rules;
if (nodeRules) {
this._mergeRules(nodeRules);
nodeRules = rulesetNode.rules;
}
if (nodeRules) {
this._removeDuplicateRules(nodeRules);
nodeRules = rulesetNode.rules;
}
// now decide whether we keep the ruleset
if (nodeRules && nodeRules.length > 0 && rulesetNode.paths.length > 0) {
rulesets.splice(0, 0, rulesetNode);
}
} else {
rulesetNode.accept(this._visitor);
visitArgs.visitDeeper = false;
if (rulesetNode.firstRoot || (rulesetNode.rules && rulesetNode.rules.length > 0)) {
rulesets.splice(0, 0, rulesetNode);
}
}
if (rulesets.length === 1) {
return rulesets[0];
}
return rulesets;
},
_removeDuplicateRules: function(rules) {
if (!rules) { return; }
// remove duplicates
var ruleCache = {},
ruleList, rule, i;
for(i = rules.length - 1; i >= 0 ; i--) {
rule = rules[i];
if (rule instanceof tree.Rule) {
if (!ruleCache[rule.name]) {
ruleCache[rule.name] = rule;
} else {
ruleList = ruleCache[rule.name];
if (ruleList instanceof tree.Rule) {
ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._env)];
}
var ruleCSS = rule.toCSS(this._env);
if (ruleList.indexOf(ruleCSS) !== -1) {
rules.splice(i, 1);
} else {
ruleList.push(ruleCSS);
}
}
}
}
},
_mergeRules: function (rules) {
if (!rules) { return; }
var groups = {},
parts,
rule,
key;
for (var i = 0; i < rules.length; i++) {
rule = rules[i];
if ((rule instanceof tree.Rule) && rule.merge) {
key = [rule.name,
rule.important ? "!" : ""].join(",");
if (!groups[key]) {
groups[key] = [];
} else {
rules.splice(i--, 1);
}
groups[key].push(rule);
}
}
Object.keys(groups).map(function (k) {
parts = groups[k];
if (parts.length > 1) {
rule = parts[0];
rule.value = new (tree.Value)(parts.map(function (p) {
return p.value;
}));
}
});
}
};
})(require('./tree'));

View File

@@ -1,6 +1,6 @@
(function (tree) {
tree.debugInfo = function(env, ctx) {
tree.debugInfo = function(env, ctx, lineSeperator) {
var result="";
if (env.dumpLineNumbers && !env.compress) {
switch(env.dumpLineNumbers) {
@@ -11,7 +11,7 @@ tree.debugInfo = function(env, ctx) {
result = tree.debugInfo.asMediaQuery(ctx);
break;
case 'all':
result = tree.debugInfo.asComment(ctx)+tree.debugInfo.asMediaQuery(ctx);
result = tree.debugInfo.asComment(ctx) + (lineSeperator || "") + tree.debugInfo.asMediaQuery(ctx);
break;
}
}
@@ -24,22 +24,74 @@ tree.debugInfo.asComment = function(ctx) {
tree.debugInfo.asMediaQuery = function(ctx) {
return '@media -sass-debug-info{filename{font-family:' +
('file://' + ctx.debugInfo.fileName).replace(/([.:/\\])/g, function(a){if(a=='\\') a = '\/'; return '\\' + a}) +
('file://' + ctx.debugInfo.fileName).replace(/([.:\/\\])/g, function (a) {
if (a == '\\') {
a = '\/';
}
return '\\' + a;
}) +
'}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 }
r = fun.call(obj, obj[i]);
if (r) { return r; }
}
return null;
};
tree.jsify = function (obj) {
if (Array.isArray(obj.value) && (obj.value.length > 1)) {
return '[' + obj.value.map(function (v) { return v.toCSS(false) }).join(', ') + ']';
return '[' + obj.value.map(function (v) { return v.toCSS(false); }).join(', ') + ']';
} else {
return obj.toCSS(false);
}
};
tree.toCSS = function (env) {
var strs = [];
this.genCSS(env, {
add: function(chunk, fileInfo, index) {
strs.push(chunk);
},
isEmpty: function () {
return strs.length === 0;
}
});
return strs.join('');
};
tree.outputRuleset = function (env, output, rules) {
var ruleCnt = rules.length, i;
env.tabLevel = (env.tabLevel | 0) + 1;
// Compressed
if (env.compress) {
output.add('{');
for (i = 0; i < ruleCnt; i++) {
rules[i].genCSS(env, output);
}
output.add('}');
env.tabLevel--;
return;
}
// Non-compressed
var tabSetStr = '\n' + Array(env.tabLevel).join(" "), tabRuleStr = tabSetStr + " ";
if (!ruleCnt) {
output.add(" {" + tabSetStr + '}');
} else {
output.add(" {" + tabRuleStr);
rules[0].genCSS(env, output);
for (i = 1; i < ruleCnt; i++) {
output.add(tabRuleStr);
rules[i].genCSS(env, output);
}
output.add(tabSetStr + '}');
}
env.tabLevel--;
};
})(require('./tree'));

View File

@@ -9,13 +9,21 @@ tree.Alpha.prototype = {
this.value = visitor.visit(this.value);
},
eval: function (env) {
if (this.value.eval) { this.value = this.value.eval(env) }
if (this.value.eval) { return new tree.Alpha(this.value.eval(env)); }
return this;
},
toCSS: function () {
return "alpha(opacity=" +
(this.value.toCSS ? this.value.toCSS() : this.value) + ")";
}
genCSS: function (env, output) {
output.add("alpha(opacity=");
if (this.value.genCSS) {
this.value.genCSS(env, output);
} else {
output.add(this.value);
}
output.add(")");
},
toCSS: tree.toCSS
};
})(require('../tree'));

View File

@@ -1,14 +1,16 @@
(function (tree) {
tree.Anonymous = function (string) {
tree.Anonymous = function (string, index, currentFileInfo, mapLines) {
this.value = string.value || string;
this.index = index;
this.mapLines = mapLines;
this.currentFileInfo = currentFileInfo;
};
tree.Anonymous.prototype = {
type: "Anonymous",
toCSS: function () {
return this.value;
eval: function () {
return new tree.Anonymous(this.value, this.index, this.currentFileInfo, this.mapLines);
},
eval: function () { return this },
compare: function (x) {
if (!x.toCSS) {
return -1;
@@ -22,7 +24,11 @@ tree.Anonymous.prototype = {
}
return left < right ? -1 : 1;
}
},
genCSS: function (env, output) {
output.add(this.value, this.currentFileInfo, this.index, this.mapLines);
},
toCSS: tree.toCSS
};
})(require('../tree'));

View File

@@ -9,15 +9,21 @@ tree.Assignment.prototype = {
accept: function (visitor) {
this.value = visitor.visit(this.value);
},
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;
}
},
genCSS: function (env, output) {
output.add(this.key + '=');
if (this.value.genCSS) {
this.value.genCSS(env, output);
} else {
output.add(this.value);
}
},
toCSS: tree.toCSS
};
})(require('../tree'));
})(require('../tree'));

View File

@@ -12,7 +12,9 @@ tree.Call = function (name, args, index, currentFileInfo) {
tree.Call.prototype = {
type: "Call",
accept: function (visitor) {
this.args = visitor.visit(this.args);
if (this.args) {
this.args = visitor.visitArray(this.args);
}
},
//
// When evaluating a function call,
@@ -46,15 +48,24 @@ tree.Call.prototype = {
index: this.index, filename: this.currentFileInfo.filename };
}
}
// 2.
return new(tree.Anonymous)(this.name +
"(" + args.map(function (a) { return a.toCSS(env); }).join(', ') + ")");
return new tree.Call(this.name, args, this.index, this.currentFileInfo);
},
toCSS: function (env) {
return this.eval(env).toCSS();
}
genCSS: function (env, output) {
output.add(this.name + "(", this.currentFileInfo, this.index);
for(var i = 0; i < this.args.length; i++) {
this.args[i].genCSS(env, output);
if (i + 1 < this.args.length) {
output.add(", ");
}
}
output.add(")");
},
toCSS: tree.toCSS
};
})(require('../tree'));

View File

@@ -22,42 +22,46 @@ tree.Color = function (rgb, a) {
}
this.alpha = typeof(a) === 'number' ? a : 1;
};
var transparentKeyword = "transparent";
tree.Color.prototype = {
type: "Color",
eval: function () { return this },
eval: function () { return this; },
luma: function () { return (0.2126 * this.rgb[0] / 255) + (0.7152 * this.rgb[1] / 255) + (0.0722 * this.rgb[2] / 255); },
//
// If we have some transparency, the only way to represent it
// is via `rgba`. Otherwise, we use the hex representation,
// which has better compatibility with older browsers.
// Values are capped between `0` and `255`, rounded and zero-padded.
//
genCSS: function (env, output) {
output.add(this.toCSS(env));
},
toCSS: function (env, doNotCompress) {
var compress = env && env.compress && !doNotCompress;
if (this.alpha < 1.0) {
var compress = env && env.compress && !doNotCompress,
alpha = tree.fround(env, this.alpha);
// If we have some transparency, the only way to represent it
// is via `rgba`. Otherwise, we use the hex representation,
// which has better compatibility with older browsers.
// Values are capped between `0` and `255`, rounded and zero-padded.
if (alpha < 1) {
if (alpha === 0 && this.isTransparentKeyword) {
return transparentKeyword;
}
return "rgba(" + this.rgb.map(function (c) {
return Math.round(c);
}).concat(this.alpha).join(',' + (compress ? '' : ' ')) + ")";
return clamp(Math.round(c), 255);
}).concat(clamp(alpha, 1))
.join(',' + (compress ? '' : ' ')) + ")";
} else {
var color = this.rgb.map(function (i) {
i = Math.round(i);
i = (i > 255 ? 255 : (i < 0 ? 0 : i)).toString(16);
return i.length === 1 ? '0' + i : i;
}).join('');
var color = this.toRGB();
if (compress) {
color = color.split('');
var splitcolor = color.split('');
// Convert color to short format
if (color[0] == color[1] && color[2] == color[3] && color[4] == color[5]) {
color = color[0] + color[2] + color[4];
} else {
color = color.join('');
if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) {
color = '#' + splitcolor[1] + splitcolor[3] + splitcolor[5];
}
}
return '#' + color;
return color;
}
},
@@ -68,16 +72,16 @@ tree.Color.prototype = {
// we create a new Color node to hold the result.
//
operate: function (env, op, other) {
var result = [];
if (! (other instanceof tree.Color)) {
other = other.toColor();
}
var rgb = [];
var alpha = this.alpha * (1 - other.alpha) + other.alpha;
for (var c = 0; c < 3; c++) {
result[c] = tree.operate(env, op, this.rgb[c], other.rgb[c]);
rgb[c] = tree.operate(env, op, this.rgb[c], other.rgb[c]);
}
return new(tree.Color)(result, this.alpha + other.alpha);
return new(tree.Color)(rgb, alpha);
},
toRGB: function () {
return toHex(this.rgb);
},
toHSL: function () {
@@ -133,12 +137,7 @@ tree.Color.prototype = {
return { h: h * 360, s: s, v: v, a: a };
},
toARGB: function () {
var argb = [Math.round(this.alpha * 255)].concat(this.rgb);
return '#' + argb.map(function (i) {
i = Math.round(i);
i = (i > 255 ? 255 : (i < 0 ? 0 : i)).toString(16);
return i.length === 1 ? '0' + i : i;
}).join('');
return toHex([this.alpha * 255].concat(this.rgb));
},
compare: function (x) {
if (!x.rgb) {
@@ -152,5 +151,29 @@ tree.Color.prototype = {
}
};
tree.Color.fromKeyword = function(keyword) {
keyword = keyword.toLowerCase();
if (tree.colors.hasOwnProperty(keyword)) {
// detect named color
return new(tree.Color)(tree.colors[keyword].slice(1));
}
if (keyword === transparentKeyword) {
var transparent = new(tree.Color)([0, 0, 0], 0);
transparent.isTransparentKeyword = true;
return transparent;
}
};
function toHex(v) {
return '#' + v.map(function (c) {
c = clamp(Math.round(c), 255);
return (c < 16 ? '0' : '') + c.toString(16);
}).join('');
}
function clamp(v, max) {
return Math.min(Math.max(v, 0), max);
}
})(require('../tree'));

View File

@@ -1,15 +1,28 @@
(function (tree) {
tree.Comment = function (value, silent) {
tree.Comment = function (value, silent, index, currentFileInfo) {
this.value = value;
this.silent = !!silent;
this.currentFileInfo = currentFileInfo;
};
tree.Comment.prototype = {
type: "Comment",
toCSS: function (env) {
return env.compress ? '' : this.value;
genCSS: function (env, output) {
if (this.debugInfo) {
output.add(tree.debugInfo(env, this), this.currentFileInfo, this.index);
}
output.add(this.value.trim()); //TODO shouldn't need to trim, we shouldn't grab the \n
},
eval: function () { return this }
toCSS: tree.toCSS,
isSilent: function(env) {
var isReference = (this.currentFileInfo && this.currentFileInfo.reference && !this.isReferenced),
isCompressed = env.compress && !this.value.match(/^\/\*!/);
return this.silent || isReference || isCompressed;
},
eval: function () { return this; },
markReferenced: function () {
this.isReferenced = true;
}
};
})(require('../tree'));

View File

@@ -19,7 +19,7 @@ tree.Condition.prototype = {
var i = this.index, result;
var result = (function (op) {
result = (function (op) {
switch (op) {
case 'and':
return a && b;
@@ -36,8 +36,8 @@ tree.Condition.prototype = {
index: i };
}
switch (result) {
case -1: return op === '<' || op === '=<';
case 0: return op === '=' || op === '>=' || op === '=<';
case -1: return op === '<' || op === '=<' || op === '<=';
case 0: return op === '=' || op === '>=' || op === '=<' || op === '<=';
case 1: return op === '>' || op === '>=';
}
}

View File

@@ -20,12 +20,12 @@ tree.Dimension.prototype = {
toColor: function () {
return new(tree.Color)([this.value, this.value, this.value]);
},
toCSS: function (env) {
genCSS: function (env, output) {
if ((env && env.strictUnits) && !this.unit.isSingular()) {
throw new Error("Multiple units in dimension. Correct the units or use the unit function. Bad unit: "+this.unit.toString());
}
var value = this.value,
var value = tree.fround(env, this.value),
strValue = String(value);
if (value !== 0 && value < 0.000001 && value > -0.000001) {
@@ -35,8 +35,9 @@ tree.Dimension.prototype = {
if (env && env.compress) {
// Zero values doesn't need a unit
if (value === 0 && !this.unit.isAngle()) {
return strValue;
if (value === 0 && this.unit.isLength()) {
output.add(strValue);
return;
}
// Float values doesn't need a leading zero
@@ -45,13 +46,16 @@ tree.Dimension.prototype = {
}
}
return strValue + this.unit.toCSS(env);
output.add(strValue);
this.unit.genCSS(env, output);
},
toCSS: tree.toCSS,
// In an operation between two Dimensions,
// we default to the first Dimension's unit,
// so `1px + 2` will yield `3px`.
operate: function (env, op, other) {
/*jshint noempty:false */
var value = tree.operate(env, op, this.value, other.value),
unit = this.unit.clone();
@@ -59,7 +63,7 @@ tree.Dimension.prototype = {
if (unit.numerator.length === 0 && unit.denominator.length === 0) {
unit.numerator = other.unit.numerator.slice(0);
unit.denominator = other.unit.denominator.slice(0);
} else if (other.unit.numerator.length == 0 && unit.denominator.length == 0) {
} else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) {
// do nothing
} else {
other = other.convertTo(this.unit.usedUnits());
@@ -104,202 +108,206 @@ tree.Dimension.prototype = {
},
unify: function () {
return this.convertTo({ length: 'm', duration: 's', angle: 'rad' });
return this.convertTo({ length: 'm', duration: 's', angle: 'rad' });
},
convertTo: function (conversions) {
var value = this.value, unit = this.unit.clone(),
i, groupName, group, conversion, targetUnit, derivedConversions = {};
var value = this.value, unit = this.unit.clone(),
i, groupName, group, targetUnit, derivedConversions = {}, applyUnit;
if (typeof conversions === 'string') {
for(i in tree.UnitConversions) {
if (tree.UnitConversions[i].hasOwnProperty(conversions)) {
derivedConversions = {};
derivedConversions[i] = conversions;
}
}
conversions = derivedConversions;
}
for (groupName in conversions) {
if (conversions.hasOwnProperty(groupName)) {
targetUnit = conversions[groupName];
group = tree.UnitConversions[groupName];
unit.map(function (atomicUnit, denominator) {
if (typeof conversions === 'string') {
for(i in tree.UnitConversions) {
if (tree.UnitConversions[i].hasOwnProperty(conversions)) {
derivedConversions = {};
derivedConversions[i] = conversions;
}
}
conversions = derivedConversions;
}
applyUnit = function (atomicUnit, denominator) {
/*jshint loopfunc:true */
if (group.hasOwnProperty(atomicUnit)) {
if (denominator) {
value = value / (group[atomicUnit] / group[targetUnit]);
} else {
value = value * (group[atomicUnit] / group[targetUnit]);
}
if (denominator) {
value = value / (group[atomicUnit] / group[targetUnit]);
} else {
value = value * (group[atomicUnit] / group[targetUnit]);
}
return targetUnit;
return targetUnit;
}
return atomicUnit;
});
};
for (groupName in conversions) {
if (conversions.hasOwnProperty(groupName)) {
targetUnit = conversions[groupName];
group = tree.UnitConversions[groupName];
unit.map(applyUnit);
}
}
}
unit.cancel();
unit.cancel();
return new(tree.Dimension)(value, unit);
return new(tree.Dimension)(value, unit);
}
};
// http://www.w3.org/TR/css3-values/#absolute-lengths
tree.UnitConversions = {
length: {
'm': 1,
'cm': 0.01,
'mm': 0.001,
'in': 0.0254,
'pt': 0.0254 / 72,
'pc': 0.0254 / 72 * 12
},
duration: {
's': 1,
'ms': 0.001
},
angle: {
'rad': 1/(2*Math.PI),
'deg': 1/360,
'grad': 1/400,
'turn': 1
}
length: {
'm': 1,
'cm': 0.01,
'mm': 0.001,
'in': 0.0254,
'pt': 0.0254 / 72,
'pc': 0.0254 / 72 * 12
},
duration: {
's': 1,
'ms': 0.001
},
angle: {
'rad': 1/(2*Math.PI),
'deg': 1/360,
'grad': 1/400,
'turn': 1
}
};
tree.Unit = function (numerator, denominator, backupUnit) {
this.numerator = numerator ? numerator.slice(0).sort() : [];
this.denominator = denominator ? denominator.slice(0).sort() : [];
this.backupUnit = backupUnit;
this.numerator = numerator ? numerator.slice(0).sort() : [];
this.denominator = denominator ? denominator.slice(0).sort() : [];
this.backupUnit = backupUnit;
};
tree.Unit.prototype = {
type: "Unit",
clone: function () {
return new tree.Unit(this.numerator.slice(0), this.denominator.slice(0), this.backupUnit);
},
type: "Unit",
clone: function () {
return new tree.Unit(this.numerator.slice(0), this.denominator.slice(0), this.backupUnit);
},
genCSS: function (env, output) {
if (this.numerator.length >= 1) {
output.add(this.numerator[0]);
} else
if (this.denominator.length >= 1) {
output.add(this.denominator[0]);
} else
if ((!env || !env.strictUnits) && this.backupUnit) {
output.add(this.backupUnit);
}
},
toCSS: tree.toCSS,
toCSS: function (env) {
if (this.numerator.length >= 1) {
return this.numerator[0];
}
if (this.denominator.length >= 1) {
return this.denominator[0];
}
if ((!env || !env.strictUnits) && this.backupUnit) {
return this.backupUnit;
}
return "";
},
toString: function () {
toString: function () {
var i, returnStr = this.numerator.join("*");
for (i = 0; i < this.denominator.length; i++) {
returnStr += "/" + this.denominator[i];
}
return returnStr;
},
compare: function (other) {
return this.is(other.toString()) ? 0 : -1;
},
},
is: function (unitString) {
return this.toString() === unitString;
},
compare: function (other) {
return this.is(other.toString()) ? 0 : -1;
},
isAngle: function () {
return tree.UnitConversions.angle.hasOwnProperty(this.toCSS());
},
is: function (unitString) {
return this.toString() === unitString;
},
isEmpty: function () {
return this.numerator.length == 0 && this.denominator.length == 0;
},
isLength: function () {
return Boolean(this.toCSS().match(/px|em|%|in|cm|mm|pc|pt|ex/));
},
isSingular: function() {
return this.numerator.length <= 1 && this.denominator.length == 0;
},
isEmpty: function () {
return this.numerator.length === 0 && this.denominator.length === 0;
},
map: function(callback) {
var i;
isSingular: function() {
return this.numerator.length <= 1 && this.denominator.length === 0;
},
for (i = 0; i < this.numerator.length; i++) {
this.numerator[i] = callback(this.numerator[i], false);
}
map: function(callback) {
var i;
for (i = 0; i < this.denominator.length; i++) {
this.denominator[i] = callback(this.denominator[i], true);
}
},
usedUnits: function() {
var group, groupName, result = {};
for (groupName in tree.UnitConversions) {
if (tree.UnitConversions.hasOwnProperty(groupName)) {
group = tree.UnitConversions[groupName];
this.map(function (atomicUnit) {
if (group.hasOwnProperty(atomicUnit) && !result[groupName]) {
result[groupName] = atomicUnit;
}
return atomicUnit;
});
}
}
return result;
},
cancel: function () {
var counter = {}, atomicUnit, i, backup;
for (i = 0; i < this.numerator.length; i++) {
atomicUnit = this.numerator[i];
if (!backup) {
backup = atomicUnit;
for (i = 0; i < this.numerator.length; i++) {
this.numerator[i] = callback(this.numerator[i], false);
}
counter[atomicUnit] = (counter[atomicUnit] || 0) + 1;
}
for (i = 0; i < this.denominator.length; i++) {
atomicUnit = this.denominator[i];
if (!backup) {
backup = atomicUnit;
for (i = 0; i < this.denominator.length; i++) {
this.denominator[i] = callback(this.denominator[i], true);
}
counter[atomicUnit] = (counter[atomicUnit] || 0) - 1;
}
},
this.numerator = [];
this.denominator = [];
usedUnits: function() {
var group, result = {}, mapUnit;
for (atomicUnit in counter) {
if (counter.hasOwnProperty(atomicUnit)) {
var count = counter[atomicUnit];
mapUnit = function (atomicUnit) {
/*jshint loopfunc:true */
if (group.hasOwnProperty(atomicUnit) && !result[groupName]) {
result[groupName] = atomicUnit;
}
if (count > 0) {
for (i = 0; i < count; i++) {
this.numerator.push(atomicUnit);
}
} else if (count < 0) {
for (i = 0; i < -count; i++) {
this.denominator.push(atomicUnit);
}
return atomicUnit;
};
for (var groupName in tree.UnitConversions) {
if (tree.UnitConversions.hasOwnProperty(groupName)) {
group = tree.UnitConversions[groupName];
this.map(mapUnit);
}
}
}
}
if (this.numerator.length === 0 && this.denominator.length === 0 && backup) {
this.backupUnit = backup;
}
return result;
},
this.numerator.sort();
this.denominator.sort();
}
cancel: function () {
var counter = {}, atomicUnit, i, backup;
for (i = 0; i < this.numerator.length; i++) {
atomicUnit = this.numerator[i];
if (!backup) {
backup = atomicUnit;
}
counter[atomicUnit] = (counter[atomicUnit] || 0) + 1;
}
for (i = 0; i < this.denominator.length; i++) {
atomicUnit = this.denominator[i];
if (!backup) {
backup = atomicUnit;
}
counter[atomicUnit] = (counter[atomicUnit] || 0) - 1;
}
this.numerator = [];
this.denominator = [];
for (atomicUnit in counter) {
if (counter.hasOwnProperty(atomicUnit)) {
var count = counter[atomicUnit];
if (count > 0) {
for (i = 0; i < count; i++) {
this.numerator.push(atomicUnit);
}
} else if (count < 0) {
for (i = 0; i < -count; i++) {
this.denominator.push(atomicUnit);
}
}
}
}
if (this.numerator.length === 0 && this.denominator.length === 0 && backup) {
this.backupUnit = backup;
}
this.numerator.sort();
this.denominator.sort();
}
};
})(require('../tree'));

View File

@@ -1,44 +1,65 @@
(function (tree) {
tree.Directive = function (name, value) {
tree.Directive = function (name, value, index, currentFileInfo) {
this.name = name;
if (Array.isArray(value)) {
this.ruleset = new(tree.Ruleset)([], value);
this.ruleset.allowImports = true;
this.rules = [new(tree.Ruleset)(null, value)];
this.rules[0].allowImports = true;
} else {
this.value = value;
}
this.index = index;
this.currentFileInfo = currentFileInfo;
};
tree.Directive.prototype = {
type: "Directive",
accept: function (visitor) {
this.ruleset = visitor.visit(this.ruleset);
this.value = visitor.visit(this.value);
},
toCSS: function (env) {
if (this.ruleset) {
this.ruleset.root = true;
return this.name + (env.compress ? '{' : ' {\n ') +
this.ruleset.toCSS(env).trim().replace(/\n/g, '\n ') +
(env.compress ? '}': '\n}\n');
} else {
return this.name + ' ' + this.value.toCSS() + ';\n';
if (this.rules) {
this.rules = visitor.visitArray(this.rules);
}
if (this.value) {
this.value = visitor.visit(this.value);
}
},
genCSS: function (env, output) {
output.add(this.name, this.currentFileInfo, this.index);
if (this.rules) {
tree.outputRuleset(env, output, this.rules);
} else {
output.add(' ');
this.value.genCSS(env, output);
output.add(';');
}
},
toCSS: tree.toCSS,
eval: function (env) {
var evaldDirective = this;
if (this.ruleset) {
if (this.rules) {
env.frames.unshift(this);
evaldDirective = new(tree.Directive)(this.name);
evaldDirective.ruleset = this.ruleset.eval(env);
evaldDirective = new(tree.Directive)(this.name, null, this.index, this.currentFileInfo);
evaldDirective.rules = [this.rules[0].eval(env)];
evaldDirective.rules[0].root = true;
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) }
variable: function (name) { return tree.Ruleset.prototype.variable.call(this.rules[0], name); },
find: function () { return tree.Ruleset.prototype.find.apply(this.rules[0], arguments); },
rulesets: function () { return tree.Ruleset.prototype.rulesets.apply(this.rules[0]); },
markReferenced: function () {
var i, rules;
this.isReferenced = true;
if (this.rules) {
rules = this.rules[0].rules;
for (i = 0; i < rules.length; i++) {
if (rules[i].markReferenced) {
rules[i].markReferenced();
}
}
}
}
};
})(require('../tree'));

View File

@@ -1,6 +1,6 @@
(function (tree) {
tree.Element = function (combinator, value, index) {
tree.Element = function (combinator, value, index, currentFileInfo) {
this.combinator = combinator instanceof tree.Combinator ?
combinator : new(tree.Combinator)(combinator);
@@ -12,21 +12,29 @@ tree.Element = function (combinator, value, index) {
this.value = "";
}
this.index = index;
this.currentFileInfo = currentFileInfo;
};
tree.Element.prototype = {
type: "Element",
accept: function (visitor) {
var value = this.value;
this.combinator = visitor.visit(this.combinator);
this.value = visitor.visit(this.value);
if (typeof value === "object") {
this.value = visitor.visit(value);
}
},
eval: function (env) {
return new(tree.Element)(this.combinator,
this.value.eval ? this.value.eval(env) : this.value,
this.index);
this.index,
this.currentFileInfo);
},
genCSS: function (env, output) {
output.add(this.toCSS(env), this.currentFileInfo, this.index);
},
toCSS: function (env) {
var value = (this.value.toCSS ? this.value.toCSS(env) : this.value);
if (value == '' && this.combinator.value.charAt(0) == '&') {
if (value === '' && this.combinator.value.charAt(0) === '&') {
return '';
} else {
return this.combinator.toCSS(env || {}) + value;
@@ -41,13 +49,13 @@ tree.Attribute = function (key, op, value) {
};
tree.Attribute.prototype = {
type: "Attribute",
accept: function (visitor) {
this.value = visitor.visit(this.value);
},
eval: function (env) {
return new(tree.Attribute)(this.key.eval ? this.key.eval(env) : this.key,
this.op, (this.value && this.value.eval) ? this.value.eval(env) : this.value);
},
genCSS: function (env, output) {
output.add(this.toCSS(env));
},
toCSS: function (env) {
var value = this.key.toCSS ? this.key.toCSS(env) : this.key;
@@ -69,17 +77,32 @@ tree.Combinator = function (value) {
};
tree.Combinator.prototype = {
type: "Combinator",
toCSS: function (env) {
return {
'' : '',
' ' : ' ',
':' : ' :',
'+' : env.compress ? '+' : ' + ',
'~' : env.compress ? '~' : ' ~ ',
'>' : env.compress ? '>' : ' > ',
'|' : env.compress ? '|' : ' | '
}[this.value];
}
_outputMap: {
'' : '',
' ' : ' ',
':' : ' :',
'+' : ' + ',
'~' : ' ~ ',
'>' : ' > ',
'|' : '|',
'^' : ' ^ ',
'^^' : ' ^^ '
},
_outputMapCompressed: {
'' : '',
' ' : ' ',
':' : ' :',
'+' : '+',
'~' : '~',
'>' : '>',
'|' : '|',
'^' : '^',
'^^' : '^^'
},
genCSS: function (env, output) {
output.add((env.compress ? this._outputMapCompressed : this._outputMap)[this.value]);
},
toCSS: tree.toCSS
};
})(require('../tree'));

View File

@@ -4,7 +4,9 @@ tree.Expression = function (value) { this.value = value; };
tree.Expression.prototype = {
type: "Expression",
accept: function (visitor) {
this.value = visitor.visit(this.value);
if (this.value) {
this.value = visitor.visitArray(this.value);
}
},
eval: function (env) {
var returnValue,
@@ -33,11 +35,15 @@ tree.Expression.prototype = {
}
return returnValue;
},
toCSS: function (env) {
return this.value.map(function (e) {
return e.toCSS ? e.toCSS(env) : '';
}).join(' ');
genCSS: function (env, output) {
for(var i = 0; i < this.value.length; i++) {
this.value[i].genCSS(env, output);
if (i + 1 < this.value.length) {
output.add(" ");
}
}
},
toCSS: tree.toCSS,
throwAwayComments: function () {
this.value = this.value.filter(function(v) {
return !(v instanceof tree.Comment);

View File

@@ -4,6 +4,8 @@ tree.Extend = function Extend(selector, option, index) {
this.selector = selector;
this.option = option;
this.index = index;
this.object_id = tree.Extend.next_id++;
this.parent_ids = [this.object_id];
switch(option) {
case "all":
@@ -16,6 +18,7 @@ tree.Extend = function Extend(selector, option, index) {
break;
}
};
tree.Extend.next_id = 0;
tree.Extend.prototype = {
type: "Extend",
@@ -30,9 +33,16 @@ tree.Extend.prototype = {
},
findSelfSelectors: function (selectors) {
var selfElements = [],
i;
i,
selectorElements;
for(i = 0; i < selectors.length; i++) {
selectorElements = selectors[i].elements;
// duplicate the logic in genCSS function inside the selector node.
// future TODO - move both logics into the selector joiner visitor
if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === "") {
selectorElements[0].combinator.value = ' ';
}
selfElements = selfElements.concat(selectors[i].elements);
}

View File

@@ -12,16 +12,14 @@
// the file has been fetched, and parsed.
//
tree.Import = function (path, features, options, index, currentFileInfo) {
var that = this;
this.options = options;
this.index = index;
this.path = path;
this.features = features;
this.currentFileInfo = currentFileInfo;
if (this.options.less !== undefined) {
this.css = !this.options.less;
if (this.options.less !== undefined || this.options.inline) {
this.css = !this.options.less || this.options.inline;
} else {
var pathValue = this.getPath();
if (pathValue && /css([\?;].*)?$/.test(pathValue)) {
@@ -42,19 +40,26 @@ tree.Import = function (path, features, options, index, currentFileInfo) {
tree.Import.prototype = {
type: "Import",
accept: function (visitor) {
this.features = visitor.visit(this.features);
if (this.features) {
this.features = visitor.visit(this.features);
}
this.path = visitor.visit(this.path);
this.root = visitor.visit(this.root);
},
toCSS: function (env) {
var features = this.features ? ' ' + this.features.toCSS(env) : '';
if (this.css) {
return "@import " + this.path.toCSS() + features + ';\n';
} else {
return "";
if (!this.options.inline && this.root) {
this.root = visitor.visit(this.root);
}
},
genCSS: function (env, output) {
if (this.css) {
output.add("@import ", this.currentFileInfo, this.index);
this.path.genCSS(env, output);
if (this.features) {
output.add(" ");
this.features.genCSS(env, output);
}
output.add(';');
}
},
toCSS: tree.toCSS,
getPath: function () {
if (this.path instanceof tree.Quoted) {
var path = this.path.value;
@@ -70,28 +75,37 @@ tree.Import.prototype = {
evalPath: function (env) {
var path = this.path.eval(env);
var rootpath = this.currentFileInfo && this.currentFileInfo.rootpath;
if (rootpath && !(path instanceof tree.URL)) {
var pathValue = path.value;
// Add the base path if the import is relative
if (pathValue && env.isPathRelative(pathValue)) {
path.value = rootpath + pathValue;
if (!(path instanceof tree.URL)) {
if (rootpath) {
var pathValue = path.value;
// Add the base path if the import is relative
if (pathValue && env.isPathRelative(pathValue)) {
path.value = rootpath +pathValue;
}
}
path.value = env.normalizePath(path.value);
}
return path;
},
eval: function (env) {
var ruleset, features = this.features && this.features.eval(env);
if (this.skip) { return []; }
if (this.css) {
if (this.options.inline) {
//todo needs to reference css file not import
var contents = new(tree.Anonymous)(this.root, 0, {filename: this.importedFilename}, true);
return this.features ? new(tree.Media)([contents], this.features.value) : [contents];
} else if (this.css) {
var newImport = new(tree.Import)(this.evalPath(env), features, this.options, this.index);
if (!newImport.css && this.error) {
throw this.error;
}
return newImport;
} else {
ruleset = new(tree.Ruleset)([], this.root.rules.slice(0));
ruleset = new(tree.Ruleset)(null, this.root.rules.slice(0));
ruleset.evalImports(env);

View File

@@ -19,26 +19,32 @@ tree.JavaScript.prototype = {
try {
expression = new(Function)('return (' + expression + ')');
} catch (e) {
throw { message: "JavaScript evaluation error: `" + expression + "`" ,
throw { message: "JavaScript evaluation error: " + e.message + " from `" + expression + "`" ,
index: this.index };
}
for (var k in env.frames[0].variables()) {
context[k.slice(1)] = {
value: env.frames[0].variables()[k].value,
toJS: function () {
return this.value.eval(env).toCSS();
}
};
var variables = env.frames[0].variables();
for (var k in variables) {
if (variables.hasOwnProperty(k)) {
/*jshint loopfunc:true */
context[k.slice(1)] = {
value: variables[k].value,
toJS: function () {
return this.value.eval(env).toCSS();
}
};
}
}
try {
result = expression.call(context);
} catch (e) {
throw { message: "JavaScript evaluation error: '" + e.name + ': ' + e.message + "'" ,
throw { message: "JavaScript evaluation error: '" + e.name + ': ' + e.message.replace(/["]/g, "'") + "'" ,
index: this.index };
}
if (typeof(result) === 'string') {
if (typeof(result) === 'number') {
return new(tree.Dimension)(result);
} else if (typeof(result) === 'string') {
return new(tree.Quoted)('"' + result + '"', result, this.escaped, this.index);
} else if (Array.isArray(result)) {
return new(tree.Anonymous)(result.join(', '));

View File

@@ -1,10 +1,13 @@
(function (tree) {
tree.Keyword = function (value) { this.value = value };
tree.Keyword = function (value) { this.value = value; };
tree.Keyword.prototype = {
type: "Keyword",
eval: function () { return this; },
toCSS: function () { return this.value; },
genCSS: function (env, output) {
output.add(this.value);
},
toCSS: tree.toCSS,
compare: function (other) {
if (other instanceof tree.Keyword) {
return other.value === this.value ? 0 : 1;

View File

@@ -1,34 +1,40 @@
(function (tree) {
tree.Media = function (value, features) {
tree.Media = function (value, features, index, currentFileInfo) {
this.index = index;
this.currentFileInfo = currentFileInfo;
var selectors = this.emptySelectors();
this.features = new(tree.Value)(features);
this.ruleset = new(tree.Ruleset)(selectors, value);
this.ruleset.allowImports = true;
this.rules = [new(tree.Ruleset)(selectors, value)];
this.rules[0].allowImports = true;
};
tree.Media.prototype = {
type: "Media",
accept: function (visitor) {
this.features = visitor.visit(this.features);
this.ruleset = visitor.visit(this.ruleset);
if (this.features) {
this.features = visitor.visit(this.features);
}
if (this.rules) {
this.rules = visitor.visitArray(this.rules);
}
},
toCSS: function (env) {
var features = this.features.toCSS(env);
return '@media ' + features + (env.compress ? '{' : ' {\n ') +
this.ruleset.toCSS(env).trim().replace(/\n/g, '\n ') +
(env.compress ? '}': '\n}\n');
genCSS: function (env, output) {
output.add('@media ', this.currentFileInfo, this.index);
this.features.genCSS(env, output);
tree.outputRuleset(env, output, this.rules);
},
toCSS: tree.toCSS,
eval: function (env) {
if (!env.mediaBlocks) {
env.mediaBlocks = [];
env.mediaPath = [];
}
var media = new(tree.Media)([], []);
var media = new(tree.Media)(null, [], this.index, this.currentFileInfo);
if(this.debugInfo) {
this.ruleset.debugInfo = this.debugInfo;
this.rules[0].debugInfo = this.debugInfo;
media.debugInfo = this.debugInfo;
}
var strictMathBypass = false;
@@ -48,21 +54,32 @@ tree.Media.prototype = {
env.mediaPath.push(media);
env.mediaBlocks.push(media);
env.frames.unshift(this.ruleset);
media.ruleset = this.ruleset.eval(env);
env.frames.unshift(this.rules[0]);
media.rules = [this.rules[0].eval(env)];
env.frames.shift();
env.mediaPath.pop();
return env.mediaPath.length === 0 ? media.evalTop(env) :
media.evalNested(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) },
variable: function (name) { return tree.Ruleset.prototype.variable.call(this.rules[0], name); },
find: function () { return tree.Ruleset.prototype.find.apply(this.rules[0], arguments); },
rulesets: function () { return tree.Ruleset.prototype.rulesets.apply(this.rules[0]); },
emptySelectors: function() {
var el = new(tree.Element)('', '&', 0);
return [new(tree.Selector)([el])];
var el = new(tree.Element)('', '&', this.index, this.currentFileInfo),
sels = [new(tree.Selector)([el], null, null, this.index, this.currentFileInfo)];
sels[0].mediaEmpty = true;
return sels;
},
markReferenced: function () {
var i, rules = this.rules[0].rules;
this.isReferenced = true;
for (i = 0; i < rules.length; i++) {
if (rules[i].markReferenced) {
rules[i].markReferenced();
}
}
},
evalTop: function (env) {
@@ -130,7 +147,7 @@ tree.Media.prototype = {
}
},
bubbleSelectors: function (selectors) {
this.ruleset = new(tree.Ruleset)(selectors.slice(0), [this.ruleset]);
this.rules = [new(tree.Ruleset)(selectors.slice(0), [this.rules[0]])];
}
};

View File

@@ -3,7 +3,7 @@
tree.mixin = {};
tree.mixin.Call = function (elements, args, index, currentFileInfo, important) {
this.selector = new(tree.Selector)(elements);
this.arguments = args;
this.arguments = (args && args.length) ? args : null;
this.index = index;
this.currentFileInfo = currentFileInfo;
this.important = important;
@@ -11,11 +11,17 @@ tree.mixin.Call = function (elements, args, index, currentFileInfo, important) {
tree.mixin.Call.prototype = {
type: "MixinCall",
accept: function (visitor) {
this.selector = visitor.visit(this.selector);
this.arguments = visitor.visit(this.arguments);
if (this.selector) {
this.selector = visitor.visit(this.selector);
}
if (this.arguments) {
this.arguments = visitor.visitArray(this.arguments);
}
},
eval: function (env) {
var mixins, mixin, args, rules = [], match = false, i, m, f, isRecursive, isOneFound;
var mixins, mixin, args, rules = [], match = false, i, m, f, isRecursive, isOneFound, rule,
candidates = [], candidate, conditionResult = [], defaultFunc = tree.defaultFunc,
defaultResult, defNone = 0, defTrue = 1, defFalse = 2, count;
args = this.arguments && this.arguments.map(function (a) {
return { name: a.name, value: a.value.eval(env) };
@@ -24,6 +30,12 @@ tree.mixin.Call.prototype = {
for (i = 0; i < env.frames.length; i++) {
if ((mixins = env.frames[i].find(this.selector)).length > 0) {
isOneFound = true;
// To make `default()` function independent of definition order we have two "subpasses" here.
// At first we evaluate each guard *twice* (with `default() == true` and `default() == false`),
// and build candidate list with corresponding flags. Then, when we know all possible matches,
// we make a final decision.
for (m = 0; m < mixins.length; m++) {
mixin = mixins[m];
isRecursive = false;
@@ -36,51 +48,111 @@ tree.mixin.Call.prototype = {
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.currentFileInfo.filename, stack: e.stack };
if (mixin.matchArgs(args, env)) {
candidate = {mixin: mixin, group: defNone};
if (mixin.matchCondition) {
for (f = 0; f < 2; f++) {
defaultFunc.value(f);
conditionResult[f] = mixin.matchCondition(args, env);
}
if (conditionResult[0] || conditionResult[1]) {
if (conditionResult[0] != conditionResult[1]) {
candidate.group = conditionResult[1] ?
defTrue : defFalse;
}
candidates.push(candidate);
}
}
else {
candidates.push(candidate);
}
match = true;
}
}
defaultFunc.reset();
count = [0, 0, 0];
for (m = 0; m < candidates.length; m++) {
count[candidates[m].group]++;
}
if (count[defNone] > 0) {
defaultResult = defFalse;
} else {
defaultResult = defTrue;
if ((count[defTrue] + count[defFalse]) > 1) {
throw { type: 'Runtime',
message: 'Ambiguous use of `default()` found when matching for `'
+ this.format(args) + '`',
index: this.index, filename: this.currentFileInfo.filename };
}
}
for (m = 0; m < candidates.length; m++) {
candidate = candidates[m].group;
if ((candidate === defNone) || (candidate === defaultResult)) {
try {
mixin = candidates[m].mixin;
if (!(mixin instanceof tree.mixin.Definition)) {
mixin = new tree.mixin.Definition("", [], mixin.rules, null, false);
mixin.originalRuleset = mixins[m].originalRuleset || mixins[m];
}
Array.prototype.push.apply(
rules, mixin.eval(env, args, this.important).rules);
} catch (e) {
throw { message: e.message, index: this.index, filename: this.currentFileInfo.filename, stack: e.stack };
}
}
}
if (match) {
if (!this.currentFileInfo || !this.currentFileInfo.reference) {
for (i = 0; i < rules.length; i++) {
rule = rules[i];
if (rule.markReferenced) {
rule.markReferenced();
}
}
}
return rules;
}
}
}
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(', ') : "") + ")`",
message: 'No matching definition was found for `' + this.format(args) + '`',
index: this.index, filename: this.currentFileInfo.filename };
} else {
throw { type: 'Name',
message: this.selector.toCSS().trim() + " is undefined",
index: this.index, filename: this.currentFileInfo.filename };
throw { type: 'Name',
message: this.selector.toCSS().trim() + " is undefined",
index: this.index, filename: this.currentFileInfo.filename };
}
},
format: function (args) {
return 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(', ') : "") + ")";
}
};
tree.mixin.Definition = function (name, params, rules, condition, variadic) {
this.name = name;
this.selectors = [new(tree.Selector)([new(tree.Element)(null, name)])];
this.selectors = [new(tree.Selector)([new(tree.Element)(null, name, this.index, this.currentFileInfo)])];
this.params = params;
this.condition = condition;
this.variadic = variadic;
@@ -88,8 +160,8 @@ tree.mixin.Definition = function (name, params, rules, condition, variadic) {
this.rules = rules;
this._lookups = {};
this.required = params.reduce(function (count, p) {
if (!p.name || (p.name && !p.value)) { return count + 1 }
else { return count }
if (!p.name || (p.name && !p.value)) { return count + 1; }
else { return count; }
}, 0);
this.parent = tree.Ruleset.prototype;
this.frames = [];
@@ -97,24 +169,28 @@ tree.mixin.Definition = function (name, params, rules, condition, variadic) {
tree.mixin.Definition.prototype = {
type: "MixinDefinition",
accept: function (visitor) {
this.params = visitor.visit(this.params);
this.rules = visitor.visit(this.rules);
this.condition = visitor.visit(this.condition);
if (this.params && this.params.length) {
this.params = visitor.visitArray(this.params);
}
this.rules = visitor.visitArray(this.rules);
if (this.condition) {
this.condition = visitor.visit(this.condition);
}
},
toCSS: function () { return ""; },
variable: function (name) { return this.parent.variable.call(this, name); },
variables: function () { return this.parent.variables.call(this); },
find: function () { return this.parent.find.apply(this, arguments); },
rulesets: function () { return this.parent.rulesets.apply(this); },
evalParams: function (env, mixinEnv, args, evaldArguments) {
var frame = new(tree.Ruleset)(null, []),
/*jshint boss:true */
var frame = new(tree.Ruleset)(null, null),
varargs, arg,
params = this.params.slice(0),
i, j, val, name, isNamedFound, argIndex;
mixinEnv = new tree.evalEnv(mixinEnv, [frame].concat(mixinEnv.frames));
if (args) {
args = args.slice(0);
@@ -125,7 +201,7 @@ tree.mixin.Definition.prototype = {
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)));
frame.prependRule(new(tree.Rule)(name, arg.value.eval(env)));
isNamedFound = true;
break;
}
@@ -143,8 +219,8 @@ tree.mixin.Definition.prototype = {
}
argIndex = 0;
for (i = 0; i < params.length; i++) {
if (evaldArguments[i]) continue;
if (evaldArguments[i]) { continue; }
arg = args && args[argIndex];
if (name = params[i].name) {
@@ -153,7 +229,7 @@ tree.mixin.Definition.prototype = {
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)));
frame.prependRule(new(tree.Rule)(name, new(tree.Expression)(varargs).eval(env)));
} else {
val = arg && arg.value;
if (val) {
@@ -166,11 +242,11 @@ tree.mixin.Definition.prototype = {
' (' + args.length + ' for ' + this.arity + ')' };
}
frame.rules.unshift(new(tree.Rule)(name, val));
frame.prependRule(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);
@@ -185,35 +261,38 @@ tree.mixin.Definition.prototype = {
var _arguments = [],
mixinFrames = this.frames.concat(env.frames),
frame = this.evalParams(env, new(tree.evalEnv)(env, mixinFrames), args, _arguments),
context, rules, start, ruleset;
rules, ruleset;
frame.rules.unshift(new(tree.Rule)('@arguments', new(tree.Expression)(_arguments).eval(env)));
frame.prependRule(new(tree.Rule)('@arguments', new(tree.Expression)(_arguments).eval(env)));
rules = important ?
this.parent.makeImportant.apply(this).rules : this.rules.slice(0);
rules = this.rules.slice(0);
ruleset = new(tree.Ruleset)(null, rules).eval(new(tree.evalEnv)(env,
[this, frame].concat(mixinFrames)));
ruleset = new(tree.Ruleset)(null, rules);
ruleset.originalRuleset = this;
ruleset = ruleset.eval(new(tree.evalEnv)(env, [this, frame].concat(mixinFrames)));
if (important) {
ruleset = this.parent.makeImportant.apply(ruleset);
}
return ruleset;
},
matchCondition: function (args, env) {
if (this.condition && !this.condition.eval(
new(tree.evalEnv)(env,
[this.evalParams(env, new(tree.evalEnv)(env, this.frames.concat(env.frames)), args, [])]
.concat(env.frames)))) {
[this.evalParams(env, new(tree.evalEnv)(env, this.frames.concat(env.frames)), args, [])] // the parameter variables
.concat(this.frames) // the parent namespace/mixin frames
.concat(env.frames)))) { // the current environment frames
return false;
}
return true;
},
matchArgs: function (args, env) {
var argsLength = (args && args.length) || 0, len, frame;
var argsLength = (args && args.length) || 0, len;
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 }
if (argsLength < this.required) { return false; }
if (argsLength > this.params.length) { return false; }
} else {
if (argsLength < (this.required - 1)) { return false; }
}
len = Math.min(argsLength, this.arity);

View File

@@ -8,9 +8,11 @@ tree.Negative.prototype = {
accept: function (visitor) {
this.value = visitor.visit(this.value);
},
toCSS: function (env) {
return '-' + this.value.toCSS(env);
genCSS: function (env, output) {
output.add('-');
this.value.genCSS(env, output);
},
toCSS: tree.toCSS,
eval: function (env) {
if (env.isMathOn()) {
return (new(tree.Operation)('*', [new(tree.Dimension)(-1), this.value])).eval(env);

View File

@@ -12,17 +12,14 @@ tree.Operation.prototype = {
},
eval: function (env) {
var a = this.operands[0].eval(env),
b = this.operands[1].eval(env),
temp;
b = this.operands[1].eval(env);
if (env.isMathOn()) {
if (a instanceof tree.Dimension && b instanceof tree.Color) {
if (this.op === '*' || this.op === '+') {
temp = b, b = a, a = temp;
} else {
throw { type: "Operation",
message: "Can't substract or divide a color from a number" };
}
a = a.toColor();
}
if (b instanceof tree.Dimension && a instanceof tree.Color) {
b = b.toColor();
}
if (!a.operate) {
throw { type: "Operation",
@@ -34,10 +31,18 @@ tree.Operation.prototype = {
return new(tree.Operation)(this.op, [a, b], this.isSpaced);
}
},
toCSS: function (env) {
var separator = this.isSpaced ? " " : "";
return this.operands[0].toCSS() + separator + this.op + separator + this.operands[1].toCSS();
}
genCSS: function (env, output) {
this.operands[0].genCSS(env, output);
if (this.isSpaced) {
output.add(" ");
}
output.add(this.op);
if (this.isSpaced) {
output.add(" ");
}
this.operands[1].genCSS(env, output);
},
toCSS: tree.toCSS
};
tree.operate = function (env, op, a, b) {

View File

@@ -9,9 +9,12 @@ tree.Paren.prototype = {
accept: function (visitor) {
this.value = visitor.visit(this.value);
},
toCSS: function (env) {
return '(' + this.value.toCSS(env).trim() + ')';
genCSS: function (env, output) {
output.add('(');
this.value.genCSS(env, output);
output.add(')');
},
toCSS: tree.toCSS,
eval: function (env) {
return new(tree.Paren)(this.value.eval(env));
}

View File

@@ -9,13 +9,16 @@ tree.Quoted = function (str, content, escaped, index, currentFileInfo) {
};
tree.Quoted.prototype = {
type: "Quoted",
toCSS: function () {
if (this.escaped) {
return this.value;
} else {
return this.quote + this.value + this.quote;
genCSS: function (env, output) {
if (!this.escaped) {
output.add(this.quote, this.currentFileInfo, this.index);
}
output.add(this.value);
if (!this.escaped) {
output.add(this.quote);
}
},
toCSS: tree.toCSS,
eval: function (env) {
var that = this;
var value = this.value.replace(/`([^`]+)`/g, function (_, exp) {
@@ -24,7 +27,7 @@ tree.Quoted.prototype = {
var v = new(tree.Variable)('@' + name, that.index, that.currentFileInfo).eval(env, true);
return (v instanceof tree.Quoted) ? v.value : v.toCSS();
});
return new(tree.Quoted)(this.quote + value + this.quote, value, this.escaped, this.index);
return new(tree.Quoted)(this.quote + value + this.quote, value, this.escaped, this.index, this.currentFileInfo);
},
compare: function (x) {
if (!x.toCSS) {

View File

@@ -1,16 +1,14 @@
(function (tree) {
tree.Rule = function (name, value, important, index, currentFileInfo, inline) {
tree.Rule = function (name, value, important, merge, index, currentFileInfo, inline) {
this.name = name;
this.value = (value instanceof tree.Value) ? value : new(tree.Value)([value]);
this.important = important ? ' ' + important.trim() : '';
this.merge = merge;
this.index = index;
this.currentFileInfo = currentFileInfo;
this.inline = inline || false;
if (name.charAt(0) === '@') {
this.variable = true;
} else { this.variable = false }
this.variable = name.charAt && (name.charAt(0) === '@');
};
tree.Rule.prototype = {
@@ -18,33 +16,43 @@ tree.Rule.prototype = {
accept: function (visitor) {
this.value = visitor.visit(this.value);
},
toCSS: function (env) {
if (this.variable) { return "" }
else {
try {
return this.name + (env.compress ? ':' : ': ') +
this.value.toCSS(env) +
this.important + (this.inline ? "" : ";");
}
catch(e) {
e.index = this.index;
e.filename = this.currentFileInfo.filename;
throw e;
}
genCSS: function (env, output) {
output.add(this.name + (env.compress ? ':' : ': '), this.currentFileInfo, this.index);
try {
this.value.genCSS(env, output);
}
catch(e) {
e.index = this.index;
e.filename = this.currentFileInfo.filename;
throw e;
}
output.add(this.important + ((this.inline || (env.lastRule && env.compress)) ? "" : ";"), this.currentFileInfo, this.index);
},
toCSS: tree.toCSS,
eval: function (env) {
var strictMathBypass = false;
if (this.name === "font" && !env.strictMath) {
var strictMathBypass = false, name = this.name;
if (typeof name !== "string") {
// expand 'primitive' name directly to get
// things faster (~10% for benchmark.less):
name = (name.length === 1)
&& (name[0] instanceof tree.Keyword)
? name[0].value : evalName(env, name);
}
if (name === "font" && !env.strictMath) {
strictMathBypass = true;
env.strictMath = true;
}
try {
return new(tree.Rule)(this.name,
return new(tree.Rule)(name,
this.value.eval(env),
this.important,
this.merge,
this.index, this.currentFileInfo, this.inline);
}
catch(e) {
e.index = e.index || this.index;
throw e;
}
finally {
if (strictMathBypass) {
env.strictMath = false;
@@ -55,8 +63,18 @@ tree.Rule.prototype = {
return new(tree.Rule)(this.name,
this.value,
"!important",
this.merge,
this.index, this.currentFileInfo, this.inline);
}
};
function evalName(env, name) {
var value = "", i, n = name.length,
output = {add: function (s) {value += s;}};
for (i = 0; i < n; i++) {
name[i].eval(env).genCSS(env, output);
}
return value;
}
})(require('../tree'));

View File

@@ -9,14 +9,34 @@ tree.Ruleset = function (selectors, rules, strictImports) {
tree.Ruleset.prototype = {
type: "Ruleset",
accept: function (visitor) {
this.selectors = visitor.visit(this.selectors);
this.rules = visitor.visit(this.rules);
if (this.paths) {
visitor.visitArray(this.paths, true);
} else if (this.selectors) {
this.selectors = visitor.visitArray(this.selectors);
}
if (this.rules && this.rules.length) {
this.rules = visitor.visitArray(this.rules);
}
},
eval: function (env) {
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;
var thisSelectors = this.selectors, selectors,
selCnt, i, defaultFunc = tree.defaultFunc;
if (thisSelectors && (selCnt = thisSelectors.length)) {
selectors = [];
defaultFunc.error({
type: "Syntax",
message: "it is currently only allowed in parametric mixin guards,"
});
for (i = 0; i < selCnt; i++) {
selectors.push(thisSelectors[i].eval(env));
}
defaultFunc.reset();
}
var rules = this.rules ? this.rules.slice(0) : null,
ruleset = new(tree.Ruleset)(selectors, rules, this.strictImports),
rule, subRule;
ruleset.originalRuleset = this;
ruleset.root = this.root;
ruleset.firstRoot = this.firstRoot;
@@ -27,13 +47,15 @@ tree.Ruleset.prototype = {
}
// push the current ruleset to the frames stack
env.frames.unshift(ruleset);
var envFrames = env.frames;
envFrames.unshift(ruleset);
// currrent selectors
if (!env.selectors) {
env.selectors = [];
var envSelectors = env.selectors;
if (!envSelectors) {
env.selectors = envSelectors = [];
}
env.selectors.unshift(this.selectors);
envSelectors.unshift(this.selectors);
// Evaluate imports
if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) {
@@ -42,18 +64,20 @@ tree.Ruleset.prototype = {
// Store the frames around mixin definitions,
// so they can be evaluated like closures when the time comes.
for (var i = 0; i < ruleset.rules.length; i++) {
if (ruleset.rules[i] instanceof tree.mixin.Definition) {
ruleset.rules[i].frames = env.frames.slice(0);
var rsRules = ruleset.rules, rsRuleCnt = rsRules ? rsRules.length : 0;
for (i = 0; i < rsRuleCnt; i++) {
if (rsRules[i] instanceof tree.mixin.Definition) {
rsRules[i].frames = envFrames.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) {
rules = ruleset.rules[i].eval(env).filter(function(r) {
for (i = 0; i < rsRuleCnt; i++) {
if (rsRules[i] instanceof tree.mixin.Call) {
/*jshint loopfunc:true */
rules = rsRules[i].eval(env).filter(function(r) {
if ((r instanceof tree.Rule) && r.variable) {
// do not pollute the scope if the variable is
// already there. consider returning false here
@@ -62,27 +86,44 @@ tree.Ruleset.prototype = {
}
return true;
});
ruleset.rules.splice.apply(ruleset.rules, [i, 1].concat(rules));
rsRules.splice.apply(rsRules, [i, 1].concat(rules));
rsRuleCnt += rules.length - 1;
i += rules.length-1;
ruleset.resetCache();
}
}
// Evaluate everything else
for (var i = 0, rule; i < ruleset.rules.length; i++) {
rule = ruleset.rules[i];
// Evaluate everything else
for (i = 0; i < rsRules.length; i++) {
rule = rsRules[i];
if (! (rule instanceof tree.mixin.Definition)) {
ruleset.rules[i] = rule.eval ? rule.eval(env) : rule;
rsRules[i] = rule = rule.eval ? rule.eval(env) : rule;
// for rulesets, check if it is a css guard and can be removed
if (rule instanceof tree.Ruleset && rule.selectors && rule.selectors.length === 1) {
// check if it can be folded in (e.g. & where)
if (rule.selectors[0].isJustParentSelector()) {
rsRules.splice(i--, 1);
// cannot call if there is no selector, so we can just continue
if (!rule.selectors[0].evaldCondition) {
continue;
}
for(var j = 0; j < rule.rules.length; j++) {
subRule = rule.rules[j];
if (!(subRule instanceof tree.Rule) || !subRule.variable) {
rsRules.splice(++i, 0, subRule);
}
}
}
}
}
}
// Pop the stack
env.frames.shift();
env.selectors.shift();
envFrames.shift();
envSelectors.shift();
if (env.mediaBlocks) {
for(var i = mediaBlockCount; i < env.mediaBlocks.length; i++) {
for (i = mediaBlockCount; i < env.mediaBlocks.length; i++) {
env.mediaBlocks[i].bubbleSelectors(selectors);
}
}
@@ -90,15 +131,17 @@ tree.Ruleset.prototype = {
return ruleset;
},
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;
var rules = this.rules, i, importRules;
if (!rules) { return; }
for (i = 0; i < rules.length; i++) {
if (rules[i] instanceof tree.Import) {
importRules = rules[i].eval(env);
if (importRules && importRules.length) {
rules.splice.apply(rules, [i, 1].concat(importRules));
i+= importRules.length-1;
} else {
this.rules.splice(i, 1, rules);
rules.splice(i, 1, importRules);
}
this.resetCache();
}
@@ -116,44 +159,74 @@ tree.Ruleset.prototype = {
matchArgs: function (args) {
return !args || args.length === 0;
},
// lets you call a css selector with a guard
matchCondition: function (args, env) {
var lastSelector = this.selectors[this.selectors.length-1];
if (!lastSelector.evaldCondition) {
return false;
}
if (lastSelector.condition &&
!lastSelector.condition.eval(
new(tree.evalEnv)(env,
env.frames))) {
return false;
}
return true;
},
resetCache: function () {
this._rulesets = null;
this._variables = null;
this._lookups = {};
},
variables: function () {
if (this._variables) { return this._variables }
else {
return this._variables = this.rules.reduce(function (hash, r) {
if (!this._variables) {
this._variables = !this.rules ? {} : this.rules.reduce(function (hash, r) {
if (r instanceof tree.Rule && r.variable === true) {
hash[r.name] = r;
}
return hash;
}, {});
}
return this._variables;
},
variable: function (name) {
return this.variables()[name];
},
rulesets: function () {
return this.rules.filter(function (r) {
return (r instanceof tree.Ruleset) || (r instanceof tree.mixin.Definition);
});
if (!this.rules) { return null; }
var _Ruleset = tree.Ruleset, _MixinDefinition = tree.mixin.Definition,
filtRules = [], rules = this.rules, cnt = rules.length,
i, rule;
for (i = 0; i < cnt; i++) {
rule = rules[i];
if ((rule instanceof _Ruleset) || (rule instanceof _MixinDefinition)) {
filtRules.push(rule);
}
}
return filtRules;
},
prependRule: function (rule) {
var rules = this.rules;
if (rules) { rules.unshift(rule); } else { this.rules = [ rule ]; }
},
find: function (selector, self) {
self = self || this;
var rules = [], rule, match,
var rules = [], match,
key = selector.toCSS();
if (key in this._lookups) { return this._lookups[key] }
if (key in this._lookups) { return this._lookups[key]; }
this.rulesets().forEach(function (rule) {
if (rule !== self) {
for (var j = 0; j < rule.selectors.length; j++) {
if (match = selector.match(rule.selectors[j])) {
if (selector.elements.length > rule.selectors[j].elements.length) {
match = selector.match(rule.selectors[j]);
if (match) {
if (selector.elements.length > match) {
Array.prototype.push.apply(rules, rule.find(
new(tree.Selector)(selector.elements.slice(1)), self));
new(tree.Selector)(selector.elements.slice(match)), self));
} else {
rules.push(rule);
}
@@ -162,108 +235,119 @@ tree.Ruleset.prototype = {
}
}
});
return this._lookups[key] = rules;
this._lookups[key] = rules;
return rules;
},
//
// Entry point for code generation
//
// `context` holds an array of arrays.
//
toCSS: function (env) {
var css = [], // The CSS output
rules = [], // node.Rule instances
_rules = [], //
rulesets = [], // node.Ruleset instances
selector, // The fully rendered selector
genCSS: function (env, output) {
var i, j,
ruleNodes = [],
rulesetNodes = [],
rulesetNodeCnt,
debugInfo, // Line number debugging
rule;
rule,
path;
// Compile rules and rulesets
for (var i = 0; i < this.rules.length; i++) {
rule = this.rules[i];
env.tabLevel = (env.tabLevel || 0);
if (rule.rules || (rule instanceof tree.Media)) {
rulesets.push(rule.toCSS(env));
} else if (rule instanceof tree.Directive) {
var cssValue = rule.toCSS(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) {
rulesets.push(rule.toCSS(env));
} else {
rules.push(rule.toCSS(env));
}
}
} else {
if (rule.toCSS && !rule.variable) {
if (this.firstRoot && rule instanceof tree.Rule) {
throw { message: "properties must be inside selector blocks, they cannot be in the root.",
index: rule.index, filename: rule.currentFileInfo ? rule.currentFileInfo.filename : null};
}
rules.push(rule.toCSS(env));
} else if (rule.value && !rule.variable) {
rules.push(rule.value.toString());
}
}
}
// Remove last semicolon
if (env.compress && rules.length) {
rule = rules[rules.length - 1];
if (rule.charAt(rule.length - 1) === ';') {
rules[rules.length - 1] = rule.substring(0, rule.length - 1);
}
if (!this.root) {
env.tabLevel++;
}
rulesets = rulesets.join('');
var tabRuleStr = env.compress ? '' : Array(env.tabLevel + 1).join(" "),
tabSetStr = env.compress ? '' : Array(env.tabLevel).join(" "),
sep;
for (i = 0; i < this.rules.length; i++) {
rule = this.rules[i];
if (rule.rules || (rule instanceof tree.Media) || rule instanceof tree.Directive || (this.root && rule instanceof tree.Comment)) {
rulesetNodes.push(rule);
} else {
ruleNodes.push(rule);
}
}
// If this is the root node, we don't render
// a selector, or {}.
// Otherwise, only output if this ruleset has rules.
if (this.root) {
css.push(rules.join(env.compress ? '' : '\n'));
} else {
if (rules.length > 0) {
debugInfo = tree.debugInfo(env, this);
selector = this.paths.map(function (p) {
return p.map(function (s) {
return s.toCSS(env);
}).join('').trim();
}).join(env.compress ? ',' : ',\n');
if (!this.root) {
debugInfo = tree.debugInfo(env, this, tabSetStr);
// Remove duplicates
for (var i = rules.length - 1; i >= 0; i--) {
if (rules[i].slice(0, 2) === "/*" || _rules.indexOf(rules[i]) === -1) {
_rules.unshift(rules[i]);
}
if (debugInfo) {
output.add(debugInfo);
output.add(tabSetStr);
}
var paths = this.paths, pathCnt = paths.length,
pathSubCnt;
sep = env.compress ? ',' : (',\n' + tabSetStr);
for (i = 0; i < pathCnt; i++) {
path = paths[i];
if (!(pathSubCnt = path.length)) { continue; }
if (i > 0) { output.add(sep); }
env.firstSelector = true;
path[0].genCSS(env, output);
env.firstSelector = false;
for (j = 1; j < pathSubCnt; j++) {
path[j].genCSS(env, output);
}
rules = _rules;
}
css.push(debugInfo + selector +
(env.compress ? '{' : ' {\n ') +
rules.join(env.compress ? '' : '\n ') +
(env.compress ? '}' : '\n}\n'));
output.add((env.compress ? '{' : ' {\n') + tabRuleStr);
}
// Compile rules and rulesets
for (i = 0; i < ruleNodes.length; i++) {
rule = ruleNodes[i];
// @page{ directive ends up with root elements inside it, a mix of rules and rulesets
// In this instance we do not know whether it is the last property
if (i + 1 === ruleNodes.length && (!this.root || rulesetNodes.length === 0 || this.firstRoot)) {
env.lastRule = true;
}
if (rule.genCSS) {
rule.genCSS(env, output);
} else if (rule.value) {
output.add(rule.value.toString());
}
if (!env.lastRule) {
output.add(env.compress ? '' : ('\n' + tabRuleStr));
} else {
env.lastRule = false;
}
}
css.push(rulesets);
return css.join('') + (env.compress ? '\n' : '');
if (!this.root) {
output.add((env.compress ? '}' : '\n' + tabSetStr + '}'));
env.tabLevel--;
}
sep = (env.compress ? "" : "\n") + (this.root ? tabRuleStr : tabSetStr);
rulesetNodeCnt = rulesetNodes.length;
if (rulesetNodeCnt) {
if (ruleNodes.length && sep) { output.add(sep); }
rulesetNodes[0].genCSS(env, output);
for (i = 1; i < rulesetNodeCnt; i++) {
if (sep) { output.add(sep); }
rulesetNodes[i].genCSS(env, output);
}
}
if (!output.isEmpty() && !env.compress && this.firstRoot) {
output.add('\n');
}
},
toCSS: tree.toCSS,
markReferenced: function () {
for (var s = 0; s < this.selectors.length; s++) {
this.selectors[s].markReferenced();
}
},
joinSelectors: function (paths, context, selectors) {
@@ -289,7 +373,7 @@ tree.Ruleset.prototype = {
if (!hasParentSelector) {
if (context.length > 0) {
for(i = 0; i < context.length; i++) {
for (i = 0; i < context.length; i++) {
paths.push(context[i].concat(selector));
}
}
@@ -333,22 +417,22 @@ tree.Ruleset.prototype = {
}
// loop through our current selectors
for(j = 0; j < newSelectors.length; j++) {
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) {
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, ""));
sel[0].elements.push(new(tree.Element)(el.combinator, '', el.index, el.currentFileInfo));
}
selectorsMultiplied.push(sel);
}
else {
// and the parent selectors
for(k = 0; k < context.length; k++) {
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
@@ -364,11 +448,11 @@ tree.Ruleset.prototype = {
if (sel.length > 0) {
newSelectorPath = sel.slice(0);
lastSelector = newSelectorPath.pop();
newJoinedSelector = new(tree.Selector)(lastSelector.elements.slice(0), selector.extendList);
newJoinedSelector = selector.createDerived(lastSelector.elements.slice(0));
newJoinedSelectorEmpty = false;
}
else {
newJoinedSelector = new(tree.Selector)([], selector.extendList);
newJoinedSelector = selector.createDerived([]);
}
//put together the parent selectors after the join
@@ -380,7 +464,7 @@ tree.Ruleset.prototype = {
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.push(new(tree.Element)(el.combinator, parentSel[0].elements[0].value, el.index, el.currentFileInfo));
newJoinedSelector.elements = newJoinedSelector.elements.concat(parentSel[0].elements.slice(1));
}
@@ -410,7 +494,7 @@ tree.Ruleset.prototype = {
this.mergeElementsOnToSelectors(currentElements, newSelectors);
}
for(i = 0; i < newSelectors.length; i++) {
for (i = 0; i < newSelectors.length; i++) {
if (newSelectors[i].length > 0) {
paths.push(newSelectors[i]);
}
@@ -418,19 +502,19 @@ tree.Ruleset.prototype = {
},
mergeElementsOnToSelectors: function(elements, selectors) {
var i, sel, extendList;
var i, sel;
if (selectors.length == 0) {
if (selectors.length === 0) {
selectors.push([ new(tree.Selector)(elements) ]);
return;
}
for(i = 0; i < selectors.length; i++) {
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), sel[sel.length - 1].extendList);
sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements));
}
else {
sel.push(new(tree.Selector)(elements));

View File

@@ -1,61 +1,128 @@
(function (tree) {
tree.Selector = function (elements, extendList) {
tree.Selector = function (elements, extendList, condition, index, currentFileInfo, isReferenced) {
this.elements = elements;
this.extendList = extendList || [];
this.extendList = extendList;
this.condition = condition;
this.currentFileInfo = currentFileInfo || {};
this.isReferenced = isReferenced;
if (!condition) {
this.evaldCondition = true;
}
};
tree.Selector.prototype = {
type: "Selector",
accept: function (visitor) {
this.elements = visitor.visit(this.elements);
this.extendList = visitor.visit(this.extendList)
if (this.elements) {
this.elements = visitor.visitArray(this.elements);
}
if (this.extendList) {
this.extendList = visitor.visitArray(this.extendList);
}
if (this.condition) {
this.condition = visitor.visit(this.condition);
}
},
createDerived: function(elements, extendList, evaldCondition) {
evaldCondition = (evaldCondition != null) ? evaldCondition : this.evaldCondition;
var newSelector = new(tree.Selector)(elements, extendList || this.extendList, null, this.index, this.currentFileInfo, this.isReferenced);
newSelector.evaldCondition = evaldCondition;
newSelector.mediaEmpty = this.mediaEmpty;
return newSelector;
},
match: function (other) {
var elements = this.elements,
len = elements.length,
oelements, olen, max, i;
olen, i;
oelements = other.elements.slice(
(other.elements.length && other.elements[0].value === "&") ? 1 : 0);
olen = oelements.length;
max = Math.min(len, olen);
other.CacheElements();
olen = other._elements.length;
if (olen === 0 || len < olen) {
return false;
return 0;
} else {
for (i = 0; i < max; i++) {
if (elements[i].value !== oelements[i].value) {
return false;
for (i = 0; i < olen; i++) {
if (elements[i].value !== other._elements[i]) {
return 0;
}
}
}
return true;
return olen; // return number of matched elements
},
CacheElements: function(){
var css = '', len, v, i;
if( !this._elements ){
len = this.elements.length;
for(i = 0; i < len; i++){
v = this.elements[i];
css += v.combinator.value;
if( !v.value.value ){
css += v.value;
continue;
}
if( typeof v.value.value !== "string" ){
css = '';
break;
}
css += v.value.value;
}
this._elements = css.match(/[,&#\.\w-]([\w-]|(\\.))*/g);
if (this._elements) {
if (this._elements[0] === "&") {
this._elements.shift();
}
} else {
this._elements = [];
}
}
},
isJustParentSelector: function() {
return !this.mediaEmpty &&
this.elements.length === 1 &&
this.elements[0].value === '&' &&
(this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === '');
},
eval: function (env) {
return new(tree.Selector)(this.elements.map(function (e) {
return e.eval(env);
}), this.extendList.map(function(extend) {
return extend.eval(env);
}));
var evaldCondition = this.condition && this.condition.eval(env),
elements = this.elements, extendList = this.extendList;
elements = elements && elements.map(function (e) { return e.eval(env); });
extendList = extendList && extendList.map(function(extend) { return extend.eval(env); });
return this.createDerived(elements, extendList, evaldCondition);
},
toCSS: function (env) {
if (this._css) { return this._css }
if (this.elements[0].combinator.value === "") {
this._css = ' ';
} else {
this._css = '';
genCSS: function (env, output) {
var i, element;
if ((!env || !env.firstSelector) && this.elements[0].combinator.value === "") {
output.add(' ', this.currentFileInfo, this.index);
}
this._css += this.elements.map(function (e) {
if (typeof(e) === 'string') {
return ' ' + e.trim();
} else {
return e.toCSS(env);
if (!this._css) {
//TODO caching? speed comparison?
for(i = 0; i < this.elements.length; i++) {
element = this.elements[i];
element.genCSS(env, output);
}
}).join('');
return this._css;
}
},
toCSS: tree.toCSS,
markReferenced: function () {
this.isReferenced = true;
},
getIsReferenced: function() {
return !this.currentFileInfo.reference || this.isReferenced;
},
getIsOutput: function() {
return this.evaldCondition;
}
};

View File

@@ -5,10 +5,11 @@ tree.UnicodeDescriptor = function (value) {
};
tree.UnicodeDescriptor.prototype = {
type: "UnicodeDescriptor",
toCSS: function (env) {
return this.value;
genCSS: function (env, output) {
output.add(this.value);
},
eval: function () { return this }
toCSS: tree.toCSS,
eval: function () { return this; }
};
})(require('../tree'));

View File

@@ -1,30 +1,52 @@
(function (tree) {
tree.URL = function (val, currentFileInfo) {
tree.URL = function (val, currentFileInfo, isEvald) {
this.value = val;
this.currentFileInfo = currentFileInfo;
this.isEvald = isEvald;
};
tree.URL.prototype = {
type: "Url",
accept: function (visitor) {
this.value = visitor.visit(this.value);
},
toCSS: function () {
return "url(" + this.value.toCSS() + ")";
genCSS: function (env, output) {
output.add("url(");
this.value.genCSS(env, output);
output.add(")");
},
toCSS: tree.toCSS,
eval: function (ctx) {
var val = this.value.eval(ctx), rootpath;
var val = this.value.eval(ctx),
rootpath;
// Add the base path if the URL is relative
rootpath = this.currentFileInfo && this.currentFileInfo.rootpath;
if (rootpath && typeof val.value === "string" && ctx.isPathRelative(val.value)) {
if (!val.quote) {
rootpath = rootpath.replace(/[\(\)'"\s]/g, function(match) { return "\\"+match; });
if (!this.isEvald) {
// Add the base path if the URL is relative
rootpath = this.currentFileInfo && this.currentFileInfo.rootpath;
if (rootpath && typeof val.value === "string" && ctx.isPathRelative(val.value)) {
if (!val.quote) {
rootpath = rootpath.replace(/[\(\)'"\s]/g, function(match) { return "\\"+match; });
}
val.value = rootpath + val.value;
}
val.value = ctx.normalizePath(val.value);
// Add url args if enabled
if (ctx.urlArgs) {
if (!val.value.match(/^\s*data:/)) {
var delimiter = val.value.indexOf('?') === -1 ? '?' : '&';
var urlArgs = delimiter + ctx.urlArgs;
if (val.value.indexOf('#') !== -1) {
val.value = val.value.replace('#', urlArgs + '#');
} else {
val.value += urlArgs;
}
}
}
val.value = rootpath + val.value;
}
return new(tree.URL)(val, null);
return new(tree.URL)(val, this.currentFileInfo, true);
}
};

View File

@@ -6,7 +6,9 @@ tree.Value = function (value) {
tree.Value.prototype = {
type: "Value",
accept: function (visitor) {
this.value = visitor.visit(this.value);
if (this.value) {
this.value = visitor.visitArray(this.value);
}
},
eval: function (env) {
if (this.value.length === 1) {
@@ -17,11 +19,16 @@ tree.Value.prototype = {
}));
}
},
toCSS: function (env) {
return this.value.map(function (e) {
return e.toCSS(env);
}).join(env.compress ? ',' : ', ');
}
genCSS: function (env, output) {
var i;
for(i = 0; i < this.value.length; i++) {
this.value[i].genCSS(env, output);
if (i+1 < this.value.length) {
output.add((env && env.compress) ? ',' : ', ');
}
}
},
toCSS: tree.toCSS
};
})(require('../tree'));

View File

@@ -1,12 +1,16 @@
(function (tree) {
tree.Variable = function (name, index, currentFileInfo) { this.name = name, this.index = index, this.currentFileInfo = currentFileInfo };
tree.Variable = function (name, index, currentFileInfo) {
this.name = name;
this.index = index;
this.currentFileInfo = currentFileInfo || {};
};
tree.Variable.prototype = {
type: "Variable",
eval: function (env) {
var variable, v, name = this.name;
var variable, name = this.name;
if (name.indexOf('@@') == 0) {
if (name.indexOf('@@') === 0) {
name = '@' + new(tree.Variable)(name.slice(1)).eval(env).value;
}
@@ -19,15 +23,16 @@ tree.Variable.prototype = {
this.evaluating = true;
if (variable = tree.find(env.frames, function (frame) {
if (v = frame.variable(name)) {
variable = tree.find(env.frames, function (frame) {
var v = frame.variable(name);
if (v) {
return v.value.eval(env);
}
})) {
});
if (variable) {
this.evaluating = false;
return variable;
}
else {
} else {
throw { type: 'Name',
message: "variable " + name + " is undefined",
filename: this.currentFileInfo.filename,

View File

@@ -1,53 +1,145 @@
(function (tree) {
var _visitArgs = { visitDeeper: true },
_hasIndexed = false;
function _noop(node) {
return node;
}
function indexNodeTypes(parent, ticker) {
// add .typeIndex to tree node types for lookup table
var key, child;
for (key in parent) {
if (parent.hasOwnProperty(key)) {
child = parent[key];
switch (typeof child) {
case "function":
// ignore bound functions directly on tree which do not have a prototype
// or aren't nodes
if (child.prototype && child.prototype.type) {
child.prototype.typeIndex = ticker++;
}
break;
case "object":
ticker = indexNodeTypes(child, ticker);
break;
}
}
}
return ticker;
}
tree.visitor = function(implementation) {
this._implementation = implementation;
this._visitFnCache = [];
if (!_hasIndexed) {
indexNodeTypes(tree, 1);
_hasIndexed = true;
}
};
tree.visitor.prototype = {
visit: function(node) {
if (node instanceof Array) {
return this.visitArray(node);
}
if (!node || !node.type) {
if (!node) {
return node;
}
var funcName = "visit" + node.type,
func = this._implementation[funcName],
visitArgs, newNode;
if (func) {
visitArgs = {visitDeeper: true};
newNode = func.call(this._implementation, node, visitArgs);
if (this._implementation.isReplacing) {
var nodeTypeIndex = node.typeIndex;
if (!nodeTypeIndex) {
return node;
}
var visitFnCache = this._visitFnCache,
impl = this._implementation,
aryIndx = nodeTypeIndex << 1,
outAryIndex = aryIndx | 1,
func = visitFnCache[aryIndx],
funcOut = visitFnCache[outAryIndex],
visitArgs = _visitArgs,
fnName;
visitArgs.visitDeeper = true;
if (!func) {
fnName = "visit" + node.type;
func = impl[fnName] || _noop;
funcOut = impl[fnName + "Out"] || _noop;
visitFnCache[aryIndx] = func;
visitFnCache[outAryIndex] = funcOut;
}
if (func !== _noop) {
var newNode = func.call(impl, node, visitArgs);
if (impl.isReplacing) {
node = newNode;
}
}
if ((!visitArgs || visitArgs.visitDeeper) && node && node.accept) {
if (visitArgs.visitDeeper && node && node.accept) {
node.accept(this);
}
funcName = funcName + "Out";
if (this._implementation[funcName]) {
this._implementation[funcName](node);
if (funcOut != _noop) {
funcOut.call(impl, node);
}
return node;
},
visitArray: function(nodes) {
var i, newNodes = [];
for(i = 0; i < nodes.length; i++) {
visitArray: function(nodes, nonReplacing) {
if (!nodes) {
return nodes;
}
var cnt = nodes.length, i;
// Non-replacing
if (nonReplacing || !this._implementation.isReplacing) {
for (i = 0; i < cnt; i++) {
this.visit(nodes[i]);
}
return nodes;
}
// Replacing
var out = [];
for (i = 0; i < cnt; i++) {
var evald = this.visit(nodes[i]);
if (evald instanceof Array) {
newNodes = newNodes.concat(evald);
} else {
newNodes.push(evald);
if (!evald.splice) {
out.push(evald);
} else if (evald.length) {
this.flatten(evald, out);
}
}
if (this._implementation.isReplacing) {
return newNodes;
return out;
},
flatten: function(arr, out) {
if (!out) {
out = [];
}
return nodes;
var cnt, i, item,
nestedCnt, j, nestedItem;
for (i = 0, cnt = arr.length; i < cnt; i++) {
item = arr[i];
if (!item.splice) {
out.push(item);
continue;
}
for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) {
nestedItem = item[j];
if (!nestedItem.splice) {
out.push(nestedItem);
} else if (nestedItem.length) {
this.flatten(nestedItem, out);
}
}
}
return out;
}
};