Fixing chat example
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tj Holowaychuk · committed by Tj Holowaychuk · parent a62a5d0 · Browse files · 4 files·+323 added−153 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+323 added−153 removed
- other:+323 added−153 removed
Provenance
- Commit
64b24a9- Tree
1c73685- Author
Tj Holowaychuk <tj@vision-media.ca>- Committer
Tj Holowaychuk <tj@vision-media.ca>- Parent
a62a5d0
4 files changed+323 added−153 removed
deleted:examples/chat/views/style.css.sass-81 removed
1-body2- :font-family "Helvetica Neue", "Lucida Grande", "Arial"3- :font-size 13px4- :text-align center5- =text-stroke 1px rgba(255, 255, 255, 0.1)6- :color #5557- 8-h1, h29- :margin 010- :font-size 22px11- :color #34343412-h113- :text-shadow 1px 2px 2px #ddd14- :font-size 60px15- 16-img.bubble17- :position absolute18- :top -25px19- :left 120px20- 21-#wrapper22- :position relative23- :margin 100px auto24- :width 500px25- :text-align left26- 27-ul28- :margin 029- :padding 030- :max-height 300px31- :overflow-x hidden32- li33- :margin 5px 034- :padding 3px 8px35- :list-style none36- :border 1px solid #eee37- =border-radius 3px38- =border-radius 3px39- li:hover40- :cursor pointer41- :color #2E2E2E42-43-input[type=text]44- :padding 5px45- :border 1px solid #ddd46- :outline none47- =border-radius 2px48-input[type=text]:focus49- :border-color #00C3FF50-51-input[type=submit]52- =border-radius 2px53- =box-shadow 0 1px 2px #ddd54- :padding 6px 10px55- :border solid 1px #99956- :background -webkit-gradient(linear, 0% 0%, 0% 100%, from(#fff), to(#ddd))57- :color #33358- :text-decoration none59- :cursor pointer60- :display inline-block61- :text-align center62- :text-shadow 0px 1px 1px #fff63- :line-height 164-input[type=submit]:hover65- :background -webkit-gradient(linear, 0% 0%, 0% 100%, from(#fff), to(#E6E4E4))66-input[type=submit]:active67- :background -webkit-gradient(linear, 0% 0%, 0% 100%, from(#fff), to(#c7c7c7))68-input[name=name]69- :width 80px70- 71-a72- :color #1ABFF173- =transition-property padding74- =transition-duration 0.15s75-a:hover76- :padding 0 5px77-a:hover:before78- :content 'visit: '79- 80-#online81- :font-size 12pxadded:examples/chat/views/style.sass+81 added
1+body2+ :font-family "Helvetica Neue", "Lucida Grande", "Arial"3+ :font-size 13px4+ :text-align center5+ =text-stroke 1px rgba(255, 255, 255, 0.1)6+ :color #5557+ 8+h1, h29+ :margin 010+ :font-size 22px11+ :color #34343412+h113+ :text-shadow 1px 2px 2px #ddd14+ :font-size 60px15+ 16+img.bubble17+ :position absolute18+ :top -25px19+ :left 120px20+ 21+#wrapper22+ :position relative23+ :margin 100px auto24+ :width 500px25+ :text-align left26+ 27+ul28+ :margin 029+ :padding 030+ :max-height 300px31+ :overflow-x hidden32+ li33+ :margin 5px 034+ :padding 3px 8px35+ :list-style none36+ :border 1px solid #eee37+ =border-radius 3px38+ =border-radius 3px39+ li:hover40+ :cursor pointer41+ :color #2E2E2E42+43+input[type=text]44+ :padding 5px45+ :border 1px solid #ddd46+ :outline none47+ =border-radius 2px48+input[type=text]:focus49+ :border-color #00C3FF50+51+input[type=submit]52+ =border-radius 2px53+ =box-shadow 0 1px 2px #ddd54+ :padding 6px 10px55+ :border solid 1px #99956+ :background -webkit-gradient(linear, 0% 0%, 0% 100%, from(#fff), to(#ddd))57+ :color #33358+ :text-decoration none59+ :cursor pointer60+ :display inline-block61+ :text-align center62+ :text-shadow 0px 1px 1px #fff63+ :line-height 164+input[type=submit]:hover65+ :background -webkit-gradient(linear, 0% 0%, 0% 100%, from(#fff), to(#E6E4E4))66+input[type=submit]:active67+ :background -webkit-gradient(linear, 0% 0%, 0% 100%, from(#fff), to(#c7c7c7))68+input[name=name]69+ :width 80px70+ 71+a72+ :color #1ABFF173+ =transition-property padding74+ =transition-duration 0.15s75+a:hover76+ :padding 0 5px77+a:hover:before78+ :content 'visit: '79+ 80+#online81+ :font-size 12pxmodified:examples/chat/app.js+48 added-72 removed
123423456789101112131415161718196789101112131415212223161718192526272829303132333435363720213940414243444546222348495051525354555657582425262728293031323334353660616237383940414243646566676869707172737475767778798044454647484950515253545556
require.paths.unshift('lib')require('express')require('express/plugins')/** * Module dependencies. */
var messages = [], utils = require('express/utils'), http = require('express/http') configure(function(){ use(Logger) use(MethodOverride) use(ContentLength) use(Cookie) use(Cache, { lifetime: (5).minutes, reapInterval: (1).minute }) use(Session, { lifetime: (15).minutes, reapInterval: (1).minute }) use(Static) set('root', __dirname)})var app = module.exports = require('express').createApplication([ { filter: 'log' }, { filter: 'method-override' }, { filter: 'cookie' }, { filter: 'session' }, { filter: 'body-decoder' }, { provider: 'sass', root: __dirname + '/public' }, { provider: 'static', root: __dirname + '/public' },]);
get('/', function(){ this.pass('/chat')})/** * Chat messages. */
get('/chat', function(){ var self = this Session.store.length(function(err, len){ self.render('chat.html.haml', { locals: { title: 'Chat', messages: messages, name: self.session.name, usersOnline: len } }) })})var messages = [];
post('/chat', function(){ this.session.name = this.param('name') messages .push(utils.escape(this.param('name')) + ': ' + utils.escape(this.param('message')) .replace(/(http:\/\/[^\s]+)/g, '<a href="$1" target="express-chat">$1</a>') .replace(/:\)/g, '<img src="http://icons3.iconfinder.netdna-cdn.com/data/icons/ledicons/emoticon_smile.png">')) this.respond(200)})// Routes
get('/chat/messages', function(){ var self = this, previousLength = messages.length, timer = setInterval(function(){ if (messages.length > previousLength) self.contentType('json'), previousLength = messages.length, self.respond(200, JSON.encode(messages)), clearInterval(timer) }, 100)})app.get('/', function(req, res){ req.sessionStore.length(function(err, len){ res.render('chat.html.haml', { locals: { title: 'Chat', messages: messages, name: self.session.name, usersOnline: len } }) });});
get('/*.css', function(file){ this.render(file + '.css.sass', { layout: false })})app.post('/chat', function(req, res){ var name = req.session.name = req.body.name; messages.push(name + ': ' + req.body.message); res.writeHead(204, {}); res.end();});
get('/error/view', function(){ this.render('does.not.exist')})
get('/error', function(){ throw new Error('oh noes!')})
get('/simple', function(){ return 'Hello :)'})
get('/favicon.ico', function(){ this.notFound()})
run()No newline at end of fileapp.get('/chat/messages', function(req, res){ var previousLength = messages.length; var id = setInterval(function(){ if (messages.length > previousLength) { previousLength = messages.length; res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.encode(messages)); clearInterval(id); } }, 100);});No newline at end of fileadded:lib/express/middleware/view.js+194 added
1+2+// Express - View - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)3+4+/**5+ * Module dependencies.6+ */7+8+var Request = require('./../request').Request,9+ extname = require('path').extname,10+ fs = require('fs')11+12+/**13+ * Cache supported template engine exports.14+ */15+16+var engines = {}17+18+/**19+ * View cache.20+ */21+ 22+var cache = { views: {}, partials: {} }23+24+25+/**26+ * View helpers (merged with locals).27+ */28+29+var helpers = exports.helpers = {}30+31+/**32+ * Cache view files where _type_ is33+ * "partials" or "views".34+ *35+ * @param {string} type36+ * @api public37+ */38+39+function cacheFiles(type) { 40+ (function cacheDir(dir) {41+ try {42+ fs.readdirSync(dir).each(function(file){43+ file = dir + '/' + file44+ var stat = fs.statSync(file)45+ if (stat.isDirectory() && file != set('partials')) 46+ cacheDir(file)47+ else if (stat.isFile())48+ cache[type][file] = fs.readFileSync(file, 'utf8')49+ })50+ } catch (err) {51+ if (err.errno !== process.ENOENT) throw e52+ }53+ })(set(type))54+}55+56+// --- View57+58+exports.View = Plugin.extend({59+ extend: {60+ 61+ /**62+ * Initialize extensions.63+ */64+ 65+ init: function() {66+ 67+ // Settings68+ 69+ if (!set('views'))70+ set('views', function(){ return set('root') + '/views' })71+ 72+ if (!set('partials'))73+ set('partials', function(){ return set('views') + '/partials' })74+ 75+ // Cache views in memory76+ 77+ if (set('cache view contents'))78+ cacheFiles('views')79+ 80+ if (set('cache view partials'))81+ cacheFiles('partials')82+ 83+ // Request84+ 85+ Request.include({86+ 87+ /**88+ * Render _view_ partial with _options_.89+ * View Request#render() for additional options.90+ *91+ * Options:92+ * - as: String name for the id used to which "collection" assign it's current value.93+ * - collection: Array of objects, the name is derived from94+ * the view name itself. For example 'video.haml.html'95+ * will have an object "video" available to it.96+ *97+ * @param {string} view98+ * @param {hash} options99+ * @settings 'partials', 'cache view partials'100+ * @return {string}101+ * @api public102+ */103+ 104+ partial: function(view, options) {105+ var options = options || {}106+ options.partial = true107+ options.layout = false108+ if (options.collection) {109+ var name = options.as || view.split('.').first,110+ len = options.collection.length111+ options.locals = options.locals || {}112+ options.locals.__length__ = len113+ return options.collection.map(function(val, i){114+ options.locals.__isFirst__ = i === 0115+ options.locals.__index__ = i116+ options.locals.__isLast__ = i === len - 1117+ options.locals[name] = val118+ return this.render(view, options)119+ }, this).join('')120+ } else121+ return this.render(view, options)122+ },123+124+ /**125+ * Render _view_ with _options_.126+ *127+ * Views are looked up relative to the'views' path setting. 128+ * View filenames should conform to NAME.TYPE.ENGINE so for example129+ * 'layout.html.ejs', 'ejs' represents the template engine, 'html'130+ * represents the type of content being rendered, which is then passed131+ * to contentType().132+ *133+ * Engines must export a render() method accepting the template string134+ * and a hash of options. Engines can respond to the options listed below135+ * as well as their own arbitrary ones. The "filename" option is always136+ * passed as the path to the given _view_, allowing engines to perform137+ * better error reporting.138+ *139+ * Options:140+ *141+ * - encoding: Passed to Request#respond()142+ * - layout: The layout to use, none when falsey. Defaults to 'layout'143+ * - locals: Most engines support a hash of local variable names / values.144+ * - context: Most engines support an evaluation context (the 'this' keyword). 145+ * Defaults to the current Request instance.146+ *147+ * Optionally you may also pass a _callback_ function which148+ * will be called instead of responding with the 200 status code.149+ *150+ * @param {string} view151+ * @param {object} options152+ * @param {function} callback153+ * @settings 'views', 'cache view contents'154+ * @api public155+ */156+157+ render: function(view, options, callback) {158+ var options = options || {},159+ type = options.partial ? 'partials' : 'views',160+ path = set(type) + '/' + view,161+ parts = view.split('.'),162+ engine = parts.last,163+ contentType = parts.slice(-2)[0],164+ layout = options.layout === undefined165+ ? 'layout'166+ : options.layout167+ options.locals = options.locals || {}168+ Object.merge(options.locals, helpers)169+ options.filename = path170+ if (set('cache view contents'))171+ options.cache = true172+ var content = cache[type][path] || fs.readFileSync(path).toString(options.encoding || 'utf8')173+ options.context = options.context || this174+ content = (engines[engine] = engines[engine] || require(engine)).render(content, options)175+ if (type === 'views') this.contentType(contentType)176+ if (layout) {177+ layout = layout.indexOf('.') !== -1178+ ? layout179+ : [layout, contentType, engine].join('.')180+ this.render(layout, Object.mergeDeep(options, {181+ layout: false,182+ locals: { body: content }183+ }), callback)184+ } else if (type === 'partials')185+ return content186+ else if (callback)187+ callback.call(this, null, content)188+ else189+ this.respond(200, content, options.encoding)190+ }191+ })192+ }193+ }194+})