Permalink
Browse files

Remote fetching, css loading, combo handler, inline docs, broke out i…

…nto modules
  • Loading branch information...
1 parent f7737da commit cb5da0948320bcdaaaa1778c94caf43ecc118e5f @davglass committed Sep 10, 2010
View
1 .npmignore
@@ -1,2 +1,3 @@
.git
sandbox
+yui3
View
1 examples/express/assets/main.js
@@ -0,0 +1 @@
+alert('Loaded..');
View
5 examples/express/assets/tabview.js
@@ -0,0 +1,5 @@
+YUI({ fetchCSS: false }).use('tabview', function(Y) {
+ new Y.TabView({
+ srcNode: '#demo .yui3-tabview-content'
+ }).render();
+});
View
92 examples/express/express.js
@@ -0,0 +1,92 @@
+#!/usr/bin/env node
+
+var express = require('express'),
+ YUI = require('yui3').YUI;
+
+
+YUI({ debug: false, filter: 'min' }).use('express', 'node', function(Y) {
+
+ var app = express.createServer();
+
+ app.configure(function(){
+ app.use(express.methodOverride());
+ app.use(express.bodyDecoder());
+ app.use(app.router);
+ app.use(express.staticProvider(__dirname + '/assets'));
+ });
+
+ app.register('.html', YUI);
+
+ app.get('/combo', YUI.combo);
+
+ app.get('/tabview', function(req, res) {
+ YUI().use('node', function(Y) {
+ Y.Env._loader.ignoreRegistered = true;
+ Y.use('tabview', function(Y) {
+ var div = Y.Node.create('<div id="demo"></div>');
+ Y.one('title').set('innerHTML', 'YUI3 tabView Page');
+ Y.one('body').addClass('yui3-skin-sam').appendChild(div);
+
+ Y.log('Creating the TabView from script..');
+ var tabview = new Y.TabView({
+ children: [{
+ label: 'foo',
+ content: '<p>foo content</p>'
+ }, {
+ label: 'bar',
+ content: '<p>bar content</p>'
+ }, {
+ label: 'baz',
+ content: '<p>baz content</p>'
+ }]
+ });
+ tabview.render('#demo');
+
+ res.render('tabview.html', {
+ locals: {
+ instance: Y,
+ use: ['tabview'],
+ //filter: 'debug',
+ content: '#content',
+ after: function(Y) {
+ Y.Get.domScript('/tabview.js');
+ }
+ }
+ });
+ });
+ });
+ });
+
+ app.get('/', function(req, res){
+ res.render('index.html', {
+ locals: {
+ content: '#content',
+ sub: {
+ title1: 'Title #1',
+ title2: 'Title #2',
+ title3: 'Title #3',
+ title4: 'Title #4'
+ },
+ after: function(Y, options, partial) {
+ Y.Get.domScript('/main.js');
+ Y.one('title').set('innerHTML', 'This is a test');
+
+ var str = partial('test');
+ var html = '';
+ var data = ['one', 'two', 'three'];
+ data.forEach(function(v) {
+ html += Y.Lang.sub(str, { name: v })
+ });
+ Y.one('#content').prepend('<ul>' + html + '</ul>');
+ },
+ yui: function(Y) {
+ Y.one('h1').set('innerHTML', 'BooYah!!');
+ }
+ }
+ });
+ });
+
+ app.listen(3000);
+
+});
+
View
8 examples/express/views/index.html
@@ -0,0 +1,8 @@
+<h1>{title}</h1>
+<p>This is only a test. This is only a test. This is only a test. This is only a test. This is only a test. This is only a test. </p>
+<h2>{title2}</h2>
+<p>This is only a test. This is only a test. This is only a test. This is only a test. This is only a test. This is only a test. </p>
+<h3>{title3}</h3>
+<p>This is only a test. This is only a test. This is only a test. This is only a test. This is only a test. This is only a test. </p>
+<h4>{title3}</h4>
+<p>This is only a test. This is only a test. This is only a test. This is only a test. This is only a test. This is only a test. </p>
View
7 examples/express/views/layout.html
@@ -0,0 +1,7 @@
+Above normal content
+<hr>
+<div id="content">
+
+</div>
+<hr>
+Below normal content
View
1 examples/express/views/partials/test.html
@@ -0,0 +1 @@
+<li>{name}</li>
View
1 examples/express/views/tabview.html
@@ -0,0 +1 @@
+<p>This is only a test. This is only a test. This is only a test. This is only a test. This is only a test. This is only a test. </p>
View
38 examples/scrape.js
@@ -0,0 +1,38 @@
+#!/usr/bin/env node
+
+var YUI = require("yui3").YUI;
+
+YUI({
+ debug: true
+}).use('node', 'io', function(Y) {
+
+ //Messing with the main page..
+ Y.one('title').set('innerHTML', 'Digg News Headlines');
+ //Creating the list that we will append the remote data to
+ var ul = Y.one('body').appendChild(Y.Node.create('<ul></ul>'));
+
+ //Creating a sandboxed instance that we will bind to the remote page that we fetch
+ YUI().use('node', function(remotePage) {
+ //The page we are fetching
+ var url = 'http://digg.com/news';
+
+ //This will call io under the hood and get the content of the URL,
+ //It will then dump the content of that page into this sandboxed document.
+ remotePage.fetch(url, function() {
+ //Get all the news items from the remote page.
+ var newsItems = remotePage.all('#story-items h3');
+ //Iterate them
+ newsItems.each(function(n) {
+ //Import this "A" node into the outside instances document
+ var a = ul.importNode(n.one('a'), true);
+ //Clean up the relative URL's of hrefs
+ a.set('href', 'http://digg.com' + a.get('href'));
+ //Append the new node to the list
+ ul.appendChild(Y.Node.create('<li></li>')).append(a);
+ });
+ //Now, we can print the "outer" instances html and drop it to the screen
+ console.log(Y.get('doc').get('outerHTML'));
+ });
+ });
+
+});
View
24 lib/dom.js
@@ -0,0 +1,24 @@
+/**
+* Module loads jsdom & htmlparser support into YUI. Should be autoloaded once DOM is needed.
+* @module nodejs-dom
+*/
+YUI.add('nodejs-dom', function(Y) {
+ var jsdom = YUI.require('jsdom'),
+ browser, dom;
+
+ dom = jsdom.defaultLevel;
+ browser = jsdom.windowAugmentation(dom, {
+ parser: YUI.require('htmlparser')
+ });
+
+ browser.window.eval = eval;
+
+ Y.config.doc = browser.window.document;
+ Y.config.win = browser.window;
+
+ Y.Browser = browser;
+
+ Y.processCSS();
+
+}, 'NODE', { requires: ['yui-base'], after: ['yui-base'] });
+
View
195 lib/express.js
@@ -0,0 +1,195 @@
+/**
+* ExpressJS view engine for YUI3
+* @module express
+*/
+YUI.add('express', function(Y) {
+
+ /**
+ * List of docTypes that can be used in the views
+ * @static
+ * @property docTypes
+ */
+ YUI.docTypes = {
+ '5': '<!DOCTYPE html>', //DEFAULT
+ '4-strict': '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">',
+ '4-trans': '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
+ 'x-strict': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
+ 'x-trans': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
+ };
+
+ /**
+ * The default docType to use when rendering content, defaults to HTML5: <!DOCTYPE html>
+ * @static
+ * @property defaultDocType
+ */
+ YUI.defaultDocType = '5';
+
+ /**
+ * Default handler for expressjs view rendering. app.register('.html', YUI);
+ * @static
+ * @method YUI.render
+ */
+ YUI.render = function(content, options) {
+
+ var eY, locals = options.locals;
+ if (locals.instance) {
+ eY = locals.instance;
+ } else {
+ eY = YUI().use('node');
+ };
+
+ if (locals.sub) {
+ content = eY.Lang.sub(content, locals.sub);
+ }
+ if (locals.instance) {
+ if (!options.isLayout) {
+ eY.one('body').prepend(content);
+ } else {
+ var html = eY.one('body').get('innerHTML');
+ eY.one('body').set('innerHTML', content);
+ content = html;
+ }
+ } else {
+ eY.one('body').set('innerHTML', content);
+ }
+
+ if (options.isLayout) {
+ var docType = YUI.defaultDocType;
+ if (locals.docType) {
+ if (YUI.docTypes[locals.docType]) {
+ docType = locals.docType;
+ }
+ }
+ docType = YUI.docTypes[docType];
+ var html = docType + "\n";
+ var content = eY.one(locals.content);
+ if (content && locals.body) {
+ content.set('innerHTML', locals.body);
+ }
+ if (locals.use) {
+ eY.Get.domScript('/combo?' + locals.use.join('&') + ((locals.filter) ? '&filter=' + locals.filter : ''));
+ }
+ if (locals.after) {
+ locals.after(eY, options, locals.partial);
+ }
+ html += eY.config.doc.outerHTML;
+ return html;
+ } else {
+
+ if (locals.yui) {
+ locals.yui(eY, options, locals.partial);
+ }
+ return eY.one('body').get('innerHTML');
+ }
+
+ };
+
+ var fs = YUI.require('fs');
+
+ /**
+ * Simple YUI based combo handler (only for YUI files and has a custom url signature)
+ */
+ YUI.comboCache = {};
+ YUI.comboSent = {};
+
+ /**
+ * Method is designed to be dropped into an express get handler, should really be "combo": app.get('/combo', YUI.combo);
+ * @method YUI.combo
+ * @static
+ */
+ YUI.combo = function(req, res) {
+ var filter = 'min';
+ if (req.query.filter) {
+ filter = req.query.filter;
+ delete req.query.filter;
+ }
+ var keys = Y.Object.keys(req.query),
+ fileCount = 0, files = [];
+
+ //This is a bug, seems that event and base are not added to the combo'd out list.
+ keys.push('yui-base', 'loader', 'event', 'base');
+
+ YUI({ debug: false, filter: 'min' }).use('loader', 'oop', function(Y) {
+
+ var loader = new Y.Loader({
+ ignoreRegistered: true,
+ require: keys,
+ force: keys.concat("yui-base", "loader", 'oop', 'yui-throttle', 'intl', 'get'),
+ allowRollup: true,
+ filter: filter,
+ loadOptional: false,
+ combine: false
+ });
+ loader.base = Y.config.base;
+ loader.calculate();
+
+ var s = loader.sorted, l = s.length, m, surl, out = [], i;
+ if (l) {
+ for (i=0; i <l; i=i+1) {
+ m = loader.moduleInfo[s[i]];
+ if (s[i].indexOf('nodejs') === -1) {
+ if (m && m.type == 'js') {
+ surl = m.fullpath || loader._url(m.path);
+ out.push(surl);
+ }
+ }
+ }
+ }
+
+ var sendRequest = function() {
+ if (fileCount == out.length) {
+ //console.log('Files are all done..');
+ var body = files.join("\n");
+ var status = 200;
+
+ if (YUI.comboSent[req.url]) {
+ //status = 304;
+ }
+ YUI.comboSent[req.url] = true;
+ res.send(body, {
+ 'Content-Type': 'application/x-javascript',
+ //'Content-Type': 'text/plain',
+ 'Content-Length': body.length,
+ 'Cache-Control': 'max-age=315360000',
+ 'Vary': 'Accept-Encoding',
+ 'Date': new Date(),
+ 'Expires': new Date((new Date()).getTime() + (60 * 60 * 1000 * 365 * 10)),
+ 'Age': '300',
+ 'X-YUI-Combo': req.url
+ }, status);
+ }
+ };
+
+ Y.each(out, function(v, k) {
+ f = v;
+ if (YUI.comboCache[f]) {
+ //console.log('File Loaded from cache (' + k + '): ' + out[k]);
+ fileCount++;
+ files[k] = YUI.comboCache[f];
+ sendRequest();
+ } else {
+ fs.readFile(f, encoding="utf8", Y.rbind(function(err, data, index, fileName) {
+ fileCount++;
+ if (err) {
+ index = data;
+ fileName = index;
+ }
+ //console.log('File Loaded from disk (' + index + '): ' + out[index]);
+ if (err) {
+ //console.log('Throw Error: ', out[index]);
+ //throwError(err, out[index]);
+ } else {
+ files[index] = data;
+ YUI.comboCache[fileName] = data;
+ }
+ sendRequest();
+ }, Y, k, f));
+ }
+ });
+
+
+ });
+
+ };
+
+}, 'NODE');
View
105 lib/io.js
@@ -0,0 +1,105 @@
+/**
+* A NodeJS transport for IO
+* @module io-nodejs
+*/
+YUI.add('io-nodejs', function(Y) {
+ var url = YUI.require('url'),
+ http = YUI.require('http');
+
+ var NodeTransport = {
+ id: 'nodejs',
+ src: {
+ send: function(uri, transactionObject, config) {
+ //Y.log(sys.inspect(transactionObject), 'info', 'nodeio');
+ //Y.log(sys.inspect(config), 'info', 'nodeio');
+
+ Y.io.xdrResponse(transactionObject, config, 'start');
+
+ var urlInfo = url.parse(uri, parseQueryString=false);
+ if (!config.headers) {
+ config.headers = {};
+ }
+ config.headers.host = urlInfo.hostname;
+
+ if (config.data && config.method === 'POST') {
+ config.headers['Content-Length'] = config.data.length;
+ config.headers = Y.merge({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, config.headers);
+ }
+
+ var host = http.createClient(YUI.urlInfoPort(urlInfo), urlInfo.hostname);
+
+ var req_url = urlInfo.pathname;
+ if (urlInfo.search) {
+ req_url += urlInfo.search;
+ }
+ Y.log('Requesting (' + config.method + '): ' + urlInfo.hostname, 'info', 'nodeio');
+ Y.log('URL: ' + req_url, 'info', 'nodeio');
+
+
+ var request = host.request(config.method, req_url, config.headers);
+ request.addListener('response', function (response) {
+ //sys.puts("STATUS: " + response.statusCode);
+ //sys.puts("HEADERS: " + JSON.stringify(response.headers));
+ //response.setBodyEncoding("utf8");
+ var body = '';
+ response.addListener('data', function (chunk) {
+ //sys.puts('chunk: ' + chunk);
+ body += chunk;
+ });
+ response.addListener("end", function() {
+ var statusText, good, status = response.statusCode;
+
+ if (status >= 200 && status < 300) {
+ statusText = 'OK';
+ good = true;
+ } else {
+ statusText = 'Server Error';
+ good = false;
+ }
+
+ transactionObject.c = {
+ status: response.statusCode,
+ statusText: statusText,
+ responseText: body,
+ headers: response.headers,
+ getAllResponseHeaders: function() {
+ return this.headers;
+ },
+ getResponseHeader: function(h) {
+ return this.headers[h];
+ }
+ }
+ //sys.print(sys.inspect(transactionObject.c));
+
+
+ Y.io.xdrResponse(transactionObject, config, 'complete');
+ Y.io.xdrResponse(transactionObject, config, ((good) ? 'success' : 'failure'));
+
+ //TODO
+ //Y.io.xdrResponse(transactionObject, configurationObject, 'timeout');
+ });
+
+ });
+ if (config.method === 'POST') {
+ request.write(config.data);
+ }
+ if (request.end) {
+ request.end();
+ } else {
+ request.close();
+ }
+ },
+ abort: function() {
+ //TODO
+ },
+ isInProgress: function() {
+ //TODO
+ return false;
+ }
+ }
+ };
+
+ Y.io.transport(NodeTransport);
+
+}, 'NODE', { requires: ['io', 'io-xdr'], after: ['io-xdr'] });
+
View
301 lib/node-yui3.js
@@ -3,12 +3,23 @@ var sys = require('sys'),
fs = require('fs'),
path = require('path'),
url = require('url'),
+ //Is gallery installed?
gallery = false,
+ //Is the 2in3 project installed?
twoIn3 = false,
// Extract meaning from stack traces
- STACK_FRAME_RE = /.* \(?(.+:\d+:\d+)\)?$/,
- YUI = require('./yui3/build/yui/yui-debug').YUI;
+ STACK_FRAME_RE = /.* \(?(.+:\d+:\d+)\)?$/;
+try {
+ //Try to load the YUI3-core module
+ var yui3 = require('yui3-core');
+ var YUI = yui3.YUI;
+} catch (e) {
+ console.log('YUI3 Core package was not found; npm install yui3-core');
+ process.exit();
+}
+
+//Does the terminal have color? (for Y.log)
var hasColor = false;
try {
var stdio = require("stdio");
@@ -18,14 +29,17 @@ try {
}
try {
+ //Load Gallery
gallery = require('yui3-gallery').path();
} catch (e) {}
try {
+ //Load 2in3
twoIn3 = require('yui3-2in3').path();
} catch (e) {}
+//Colorize the string
var color = function(str, num) {
if (!hasColor) {
return str;
@@ -40,18 +54,35 @@ var color = function(str, num) {
var YUI_config = {
groups: {},
loaderPath: 'loader/loader-debug.js',
- base: __dirname + '/yui3/build/',
+ domBase: YUI.config.base,
+ base: yui3.path() + '/build/',
injected: true,
modules: {
+ 'express': {
+ after: ['yui-base'],
+ fullpath: __dirname + '/express.js'
+ },
'nodejs-dom': {
+ fullpath: __dirname + '/dom.js',
condition: {
trigger: 'dom',
test: function() {
return true;
}
}
},
+ 'nodejs-node': {
+ fullpath: __dirname + '/node.js',
+ after: ['node'],
+ condition: {
+ trigger: 'node',
+ test: function() {
+ return true;
+ }
+ }
+ },
'io-nodejs': {
+ fullpath: __dirname + '/io.js',
requires: ['io', 'io-xdr', 'nodejs-dom'],
after: ['io-xdr'],
condition: {
@@ -139,89 +170,91 @@ if (twoIn3) {
}
}
-YUI.docTypes = {
- '5': '<!DOCTYPE html>',
- '4-strict': '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">',
- '4-trans': '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
- 'x-strict': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
- 'x-trans': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
+/**
+* This is a pass-thru method that is used inside a YUI module to include "node" modules.
+* This can be modified later to use other "require" methods too.
+* @static
+* @method YUI.require
+*/
+YUI.require = function(str) {
+ return require(str);
};
-YUI.defaultDocType = '5';
-
+/**
+* This is a HACK to apply the "global" YUI_config before applying the
+* users supplied config. Since YUI_config is not truly global in Node
+*/
YUI.prototype.__setup = YUI.prototype._setup;
YUI.prototype._setup = function() {
var self = this;
this.applyConfig(YUI_config);
this.__setup.call(self);
-};
-
-//ExpressJS view support
-YUI.render = function(content, options) {
- var eY, locals = options.locals;
- if (locals.instance) {
- eY = locals.instance;
- } else {
- eY = YUI().use('node');
- };
-
- if (locals.sub) {
- content = eY.Lang.sub(content, locals.sub);
- }
- if (locals.instance) {
- if (!options.isLayout) {
- eY.one('body').prepend(content);
- } else {
- var html = eY.one('body').get('innerHTML');
- eY.one('body').set('innerHTML', content);
- content = html;
+ /**
+ * This is a HACK and should be fixed.. This removes CSS files
+ * From the global _loaded hash, so they can be "reloaded" in other instances.
+ */
+ for (var i in YUI.Env._loaded[this.version]) {
+ if (i.indexOf('skin') > -1 || i.indexOf('css') > -1) {
+ delete YUI.Env._loaded[this.version][i];
}
- } else {
- eY.one('body').set('innerHTML', content);
}
+};
- if (options.isLayout) {
- var docType = YUI.defaultDocType;
- if (locals.docType) {
- if (YUI.docTypes[locals.docType]) {
- docType = locals.docType;
- }
- }
- docType = YUI.docTypes[docType];
- var html = docType + "\n";
- var content = eY.one(locals.content);
- if (content && locals.body) {
- content.set('innerHTML', locals.body);
- }
- if (locals.after) {
- locals.after(eY, options, locals.partial);
- }
- html += eY.config.doc.outerHTML;
- return html;
- } else {
-
- if (locals.yui) {
- locals.yui(eY, options, locals.partial);
- }
- return eY.one('body').get('innerHTML');
- }
+YUI.prototype.fetch = function(url, cb) {
+ if (!url) { return; }
+ var self = this;
+
+ self.use('node', 'io', function() {
+ self.io(url, {
+ xdr: {
+ use: 'nodejs'
+ },
+ on: {
+ success: function(id, o) {
+ self.one('doc').set('innerHTML', o.responseText);
+ if (cb) {
+ cb(o.responseText);
+ }
+ }
+ }
+ });
+ });
+
};
exports.YUI = YUI;
-var urlInfoPort = function(urlInfo) {
+
+/**
+* Attempts to normalize the port number from a given url, defaulting to 80
+* @static
+* @mrthod YUI.urlInfoPort
+*/
+YUI.urlInfoPort = function(urlInfo) {
return urlInfo.port ? urlInfo.port :
urlInfo.protocol === 'http:' ? 80 : 443;
};
+/**
+* Static method to load a YUI module into a specific YUI instance. Since all YUI modules start with YUI.add
+* YUI needs to be present when that code is eval'd. This method will fetch the file (local or remote) and
+* then do some fancy stepping to get the module to compile into the local scope of the YUI instance, still
+* allowing access to the exported YUI global object so the module can be attached.
+* @static
+* @method YUI.include
+*
+*/
YUI.include = function(file, cb) {
var loaderFn = function(err, data) {
if (err) {
cb(err);
} else {
try {
+ /*
+ * This is the fancy stepping required to get the module to eval into the local scope
+ */
var mod = "(function(YUI) { " + data + " return YUI; })",
fn = process.compile(mod, file);
@@ -232,11 +265,12 @@ YUI.include = function(file, cb) {
}
}
};
+ //If the file is remote, fetch it..
if (file.match(/^https?:\/\//)) {
var urlInfo = url.parse(file, parseQueryString=false),
req_url = urlInfo.pathname,
- host = http.createClient(urlInfoPort(urlInfo), urlInfo.hostname);
+ host = http.createClient(YUI.urlInfoPort(urlInfo), urlInfo.hostname);
if (urlInfo.search) {
req_url += urlInfo.search;
@@ -259,10 +293,17 @@ YUI.include = function(file, cb) {
}
} else {
+ //Load the file locally
fs.readFile(file, encoding='utf8', loaderFn);
}
};
+/**
+* Support method for the delayed insertion of CSS elements into a document. Since the document may not exist at the time Get tries to insert it.
+* Called from inside the nodejs-dom module when the document is loaded.
+* @method processCSS
+*/
+
YUI.prototype.processCSS = function() {
var self = this,
urls = [];
@@ -280,29 +321,15 @@ YUI.prototype.processCSS = function() {
//Hack for loadtime Event module.
YUI.config.doc = { documentElement: {} };
-
YUI.Env._ready = YUI.Env.DOMReady = YUI.Env.windowLoaded = true;
-YUI.add('nodejs-dom', function(Y) {
- var jsdom = require('jsdom'),
- browser, dom;
-
- dom = jsdom.defaultLevel;
- browser = jsdom.windowAugmentation(dom, {
- parser: require('htmlparser')
- });
-
- browser.window.eval = eval;
-
- Y.config.doc = browser.window.document;
- Y.config.win = browser.window;
-
- Y.Browser = browser;
-
- Y.processCSS();
-
-}, 'NODE', { requires: ['yui-base'], after: ['yui-base'] });
+/**
+* NodeJS specific Get module used to load remote resources. It contains the same signature as the default Get module so there is no code change needed.
+* Note: There is an added method called Get.domScript, which is the same as Get.script in a browser, it simply loads the script into the dom tree
+* so that you can call outerHTML on the document to print it to the screen.
+* @module get
+*/
YUI.add('get', function(Y) {
var end = function(cb, msg, result) {
@@ -326,6 +353,9 @@ YUI.add('get', function(Y) {
Y.Get = function() {};
+ /**
+ * Override for Get.script for loading local or remote YUI modules.
+ */
Y.Get.script = function(s, cb) {
var A = Y.Array,
urls = A(s), url, i, l = urls.length;
@@ -360,6 +390,9 @@ YUI.add('get', function(Y) {
}
};
+ /**
+ * Additional method for adding script tags to a document for printing.
+ */
Y.Get.domScript = function(s, cb) {
var A = Y.Array,
urls = A(s), url, i, l = urls.length,
@@ -374,7 +407,11 @@ YUI.add('get', function(Y) {
}
};
+ /**
+ * Adds the link tag to the document, if it exists, if it doesn't, the files are added to the _cssLoad hash and loaded from processCSS
+ */
Y.Get.css = function(s, cb) {
+ Y.log('Get.css', 'debug', 'get');
if (!Y.Lang.isArray(s)) {
s = [s];
}
@@ -389,7 +426,9 @@ YUI.add('get', function(Y) {
} else {
Y.log('Real CSS loading', 'debug', 'get');
var head = Y.config.doc.getElementsByTagName('head')[0];
+
s.forEach(function(link) {
+ link = link.replace(Y.config.base, Y.config.domBase);
var l = Y.config.doc.createElement('link');
l.setAttribute('rel', 'stylesheet');
l.setAttribute('type', 'text/css');
@@ -404,106 +443,10 @@ YUI.add('get', function(Y) {
});
-YUI.add('io-nodejs', function(Y) {
-
- var NodeTransport = {
- id: 'nodejs',
- src: {
- send: function(uri, transactionObject, config) {
- //Y.log(sys.inspect(transactionObject), 'info', 'nodeio');
- //Y.log(sys.inspect(config), 'info', 'nodeio');
-
- Y.io.xdrResponse(transactionObject, config, 'start');
-
- var urlInfo = url.parse(uri, parseQueryString=false);
- if (!config.headers) {
- config.headers = {};
- }
- config.headers.host = urlInfo.hostname;
-
- if (config.data && config.method === 'POST') {
- config.headers['Content-Length'] = config.data.length;
- config.headers = Y.merge({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, config.headers);
- }
-
- var host = http.createClient(urlInfoPort(urlInfo), urlInfo.hostname);
-
- var req_url = urlInfo.pathname;
- if (urlInfo.search) {
- req_url += urlInfo.search;
- }
- Y.log('Requesting (' + config.method + '): ' + urlInfo.hostname, 'info', 'nodeio');
- Y.log('URL: ' + req_url, 'info', 'nodeio');
-
-
- var request = host.request(config.method, req_url, config.headers);
- request.addListener('response', function (response) {
- //sys.puts("STATUS: " + response.statusCode);
- //sys.puts("HEADERS: " + JSON.stringify(response.headers));
- //response.setBodyEncoding("utf8");
- var body = '';
- response.addListener('data', function (chunk) {
- //sys.puts('chunk: ' + chunk);
- body += chunk;
- });
- response.addListener("end", function() {
- var statusText, good, status = response.statusCode;
-
- if (status >= 200 && status < 300) {
- statusText = 'OK';
- good = true;
- } else {
- statusText = 'Server Error';
- good = false;
- }
-
- transactionObject.c = {
- status: response.statusCode,
- statusText: statusText,
- responseText: body,
- headers: response.headers,
- getAllResponseHeaders: function() {
- return this.headers;
- },
- getResponseHeader: function(h) {
- return this.headers[h];
- }
- }
- //sys.print(sys.inspect(transactionObject.c));
-
-
- Y.io.xdrResponse(transactionObject, config, 'complete');
- Y.io.xdrResponse(transactionObject, config, ((good) ? 'success' : 'failure'));
-
- //TODO
- //Y.io.xdrResponse(transactionObject, configurationObject, 'timeout');
- });
-
- });
- if (config.method === 'POST') {
- request.write(config.data);
- }
- if (request.end) {
- request.end();
- } else {
- request.close();
- }
- },
- abort: function() {
- //TODO
- },
- isInProgress: function() {
- //TODO
- return false;
- }
- }
- };
-
- Y.io.transport(NodeTransport);
-
-}, 'NODE', { requires: ['io', 'io-xdr'], after: ['io-xdr'] });
+//Helper methods
+//Get the Error Message from the stack
var getErrorMessage = function(e) {
try {
return e.message || e.stack.split('\n')[0].trim();
View
23 lib/node.js
@@ -0,0 +1,23 @@
+/**
+* Adds some helper methods to Node when working on the server.
+* @module nodejs-node
+*/
+YUI.add('nodejs-node', function(Y) {
+
+ /**
+ * Clones a node from one document to another document. Useful when working with a remote document.
+ * @method importNode
+ * @param {Node} node The node to insert into this document.
+ * @param {Boolean} deep Create a deep copy
+ */
+ Y.Node.prototype.importNode = function(node, deep) {
+ node = node.cloneNode(deep);
+ var newDoc = Y.config.doc, n = node._node;
+
+ n._ownerDocument = newDoc;
+ n._attributes._ownerDocument = newDoc
+ n._ownerElement = null;
+
+ return node;
+ };
+});
View
1 package.json
@@ -18,6 +18,7 @@
"main": "./lib/node-yui3",
"bin" : { "yui3docs" : "./cli.js" },
"dependencies": {
+ "yui3-core": ">=3.2.0",
"jsdom": ">=0.1.9",
"htmlparser": ">=1.6.2",
"express": ">=1.0.0rc1",

0 comments on commit cb5da09

Please sign in to comment.