[Pkg-javascript-commits] [less.js] 17/285: move the browser file out into the same format as the node environment file

Jonas Smedegaard dr at jones.dk
Mon Oct 26 23:23:33 UTC 2015


This is an automated email from the git hooks/post-receive script.

js pushed a commit to annotated tag v2.0.0
in repository less.js.

commit 9d94e1c914364e68a4c8fb76d587a1ab43c6060f
Author: Luke Page <luke.a.page at gmail.com>
Date:   Sat Feb 22 18:02:17 2014 +0000

    move the browser file out into the same format as the node environment file
---
 build/build.yml                  |   2 +-
 lib/less/browser.js              | 208 +++------------------------------------
 lib/less/environments/api.js     |  40 ++++++++
 lib/less/environments/browser.js | 196 ++++++++++++++++++++++++++++++++++++
 lib/less/environments/node.js    |   8 +-
 lib/less/parser.js               |   2 +-
 6 files changed, 251 insertions(+), 205 deletions(-)

diff --git a/build/build.yml b/build/build.yml
index b5a2234..2dd328e 100644
--- a/build/build.yml
+++ b/build/build.yml
@@ -24,7 +24,7 @@ prepend:
 
 append:
   amd:     build/amd.js
-  browser: <%= build.lib %>/browser.js
+  browser: ['lib/less/environments/browser.js', '<%= build.lib %>/browser.js']
   rhino:   <%= build.lib %>/rhino.js
 
 
diff --git a/lib/less/browser.js b/lib/less/browser.js
index cbc6406..ce82952 100644
--- a/lib/less/browser.js
+++ b/lib/less/browser.js
@@ -1,7 +1,7 @@
 //
 // browser.js - client-side engine
 //
-/*global less, window, document, XMLHttpRequest, location */
+/*global less, window, document, location */
 
 var isFileProtocol = /^(file|chrome(-extension)?|resource|qrc|app):/.test(location.protocol);
 
@@ -54,7 +54,6 @@ if (dumpLineNumbers) {
 
 var typePattern = /^text\/(x-)?less$/;
 var cache = null;
-var fileCache = {};
 
 function log(str, level) {
     if (less.env == 'development' && typeof(console) !== 'undefined' && less.logLevel >= level) {
@@ -323,196 +322,6 @@ function loadStyles(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);
@@ -522,7 +331,16 @@ function loadStyleSheet(sheet, callback, reload, remaining, modifyVars) {
         env.useFileCache = true;
     }
 
-    loadFile(sheet.href, null, function(e, data, path, newFileInfo, webInfo) {
+    less.Parser.environment.loadFile(env, sheet.href, null, function loadInitialFileCallback(e, data, path, webInfo) {
+    
+        var newFileInfo = {
+            currentDirectory: less.Parser.environment.getPath(env, path),
+            filename: path,
+            rootFilename: path,
+            relativeUrls: env.relativeUrls};
+
+        newFileInfo.entryPath = newFileInfo.currentDirectory;
+        newFileInfo.rootpath = less.rootpath || newFileInfo.currentDirectory;
 
         if (webInfo) {
             webInfo.remaining = remaining;
@@ -582,8 +400,6 @@ function initRunningMode(){
     }
 }
 
-
-
 //
 // Watch mode
 //
@@ -656,6 +472,4 @@ less.refresh = function (reload, modifyVars) {
 
 less.refreshStyles = loadStyles;
 
-less.Parser.fileLoader = loadFile;
-
 less.refresh(less.env === 'development');
diff --git a/lib/less/environments/api.js b/lib/less/environments/api.js
new file mode 100644
index 0000000..483895f
--- /dev/null
+++ b/lib/less/environments/api.js
@@ -0,0 +1,40 @@
+module.exports = {
+    /**
+      * Warns the user about something
+      * @param {Object} env - the environment or options object
+      * @param {String} msg - the message about the warning
+      */
+    warn: function(env, msg) {
+    },
+    /**
+      * gets the path from the filename, e.g. "http://wwe.files.com/ha/ha.less" would return
+      * "http://wwe.files.com/ha/"
+      * If the filename is a file e.g. "file.less" it should return the empty string ""      
+      * @param {Object} env - the environment or options object
+      * @param {String} filename - the filename to extract the path.
+      * @returns {String}
+      */
+    getPath: function (env, filename) {
+    },
+    /**
+      * Returns whether the path is absolute, e.g. "/file.less" = true, "file.less" = false
+      * @param {Object} env - the environment or options object
+      * @param {String} filename - the filename
+      * @returns {Boolean}
+      */
+    isPathAbsolute: function(env, filename) {
+    },
+    /**
+      * Loads a file for an import aynscronously (or syncronously)
+      * @param {Object} env - the environment or options object
+      * @param {String} filename - the filename
+      * @param {String} currentDirectory - the current directory we are in
+      * @param {Function} callback - a function to callback when finished,
+      *                   taking the format callback(error, contents, fullfilename, reserved)
+      *                   where error is { type: {string}, message: {string} }, contents is {string} and fullfilename is {string}
+      *                   for reserved, see browser.js which uses this argument for cache information
+      * @returns {Boolean}
+      */
+    loadFile: function(env, filename, currentDirectory, callback) {
+    }
+};
\ No newline at end of file
diff --git a/lib/less/environments/browser.js b/lib/less/environments/browser.js
new file mode 100644
index 0000000..bb970b6
--- /dev/null
+++ b/lib/less/environments/browser.js
@@ -0,0 +1,196 @@
+/*global less, window, XMLHttpRequest, log, logLevel, isFileProtocol */
+
+var fileCache = {};
+
+//TODOS - move log somewhere. pathDiff and doing something similiar in node. use pathDiff in the other browser file for the initial load
+//        isFileProtocol is global
+
+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;
+        }
+    }
+}
+
+less.Parser.environment = {
+    // make generic but overriddable
+    warn: function warn(env, msg) {
+        console.warn(msg);
+    },
+    // make generic but overriddable
+    getPath: function getPath(env, filename) {
+        var j = filename.lastIndexOf('/');
+        if (j < 0) {
+            j = filename.lastIndexOf('\\');
+        }
+        if (j < 0) {
+            return "";
+        }
+        return filename.slice(0, j + 1);
+    },
+    // make generic but overriddable
+    isPathAbsolute: function isPathAbsolute(env, filename) {
+        return /^(?:[a-z-]+:|\/|\\)/.test(filename);
+    },
+    pathDiff: function pathDiff(url, baseUrl) {
+        // diff between two paths to create a relative path
+
+        var urlParts = this.extractUrlParts(url),
+            baseUrlParts = this.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;
+    },
+    // helper function, not part of API
+    extractUrlParts: 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;
+    },
+    doXHR: 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);
+        }
+    },
+    loadFile: function loadFile(env, filename, currentDirectory, callback) {
+        if (currentDirectory && !this.isPathAbsolute(env, filename)) {
+            filename = currentDirectory + filename;
+        }
+
+        // sheet may be set to the stylesheet for the initial load or a collection of properties including
+        // some env variables for imports
+        var hrefParts = this.extractUrlParts(filename, window.location.href);
+        var href      = hrefParts.url;
+
+        // TODO - use pathDiff in less.node
+        /*if (env.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, { lastModified: new Date() });
+            } catch (e) {
+                callback(e, null, href);
+            }
+            return;
+        }
+
+        this.doXHR(href, env.mime, function doXHRCallback(data, lastModified) {
+            // per file cache
+            fileCache[href] = data;
+
+            // Use remote copy (re-parse)
+            callback(null, data, href, { lastModified: lastModified });
+        }, function doXHRError(status, url) {
+            callback({ type: 'File', message: "'" + url + "' wasn't found (" + status + ")" }, null, href);
+        });
+
+    }
+};
\ No newline at end of file
diff --git a/lib/less/environments/node.js b/lib/less/environments/node.js
index 7184498..2fdb36b 100644
--- a/lib/less/environments/node.js
+++ b/lib/less/environments/node.js
@@ -73,12 +73,8 @@ module.exports = {
                     return;
                 }
 
-                try {
-                    data = fs.readFileSync(fullFilename, 'utf-8');
-                    callback(null, data, fullFilename);
-                } catch (e) {
-                    callback(e);
-                }
+                data = fs.readFileSync(fullFilename, 'utf-8');
+                callback(null, data, fullFilename);
             } else {
                 (function tryPathIndex(i) {
                     if (i < paths.length) {
diff --git a/lib/less/parser.js b/lib/less/parser.js
index 40e3592..0fa45b9 100644
--- a/lib/less/parser.js
+++ b/lib/less/parser.js
@@ -89,7 +89,7 @@ less.Parser = function Parser(env) {
                 rootFilename: currentFileInfo.rootFilename
                 };
             
-            less.Parser.environment.loadFile(env, path, currentFileInfo.currentDirectory, function (e, contents, resolvedFilename) {
+            less.Parser.environment.loadFile(env, path, currentFileInfo.currentDirectory, function loadFileCallback(e, contents, resolvedFilename) {
                 if (e) {
                     fileParsedFunc(e);
                     return;

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/less.js.git



More information about the Pkg-javascript-commits mailing list