UNPKG

chocolate

Version:

A full stack Node.js web framework built using Coffeescript

593 lines (502 loc) 23.2 kB
# **CoffeeKup** lets you to write HTML templates in 100% pure # [CoffeeScript](http://coffeescript.org). # # You can run it on [node.js](http://nodejs.org) or the browser, or compile your # templates down to self-contained javascript functions, that will take in data # and options and return generated HTML on any JS runtime. # # The concept is directly stolen from the amazing # [Markaby](http://markaby.rubyforge.org/) by Tim Fletcher and why the lucky stiff. if window? coffeekup = window[if window.exports? then "exports" else "Coffeekup"] = {} coffee = if CoffeeScript? then CoffeeScript else null else coffeekup = exports coffee = require('coffee-script') coffeekup.version = '0.3.1edge' # Values available to the `doctype` function inside a template. # Ex.: `doctype 'strict'` coffeekup.doctypes = 'default': '<!DOCTYPE html>' '5': '<!DOCTYPE html>' 'xml': '<?xml version="1.0" encoding="utf-8" ?>' 'transitional': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' 'strict': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' 'frameset': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">' '1.1': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">', 'basic': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">' 'mobile': '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">' 'ce': '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "ce-html-1.0-transitional.dtd">' # CoffeeScript-generated JavaScript may contain anyone of these; but when we # take a function to string form to manipulate it, and then recreate it through # the `Function()` constructor, it loses access to its parent scope and # consequently to any helpers it might need. So we need to reintroduce these # inside any "rewritten" function. coffeescript_helpers = """ var __slice = slice = Array.prototype.slice; var __hasProp = hasProp = Object.prototype.hasOwnProperty; var __bind = bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; var __extends = extend = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }; var __indexOf = indexOf = Array.prototype.indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (this[i] === item) return i; } return -1; }; """.replace /\n/g, '' # Private HTML element reference. # Please mind the gap (1 space at the beginning of each subsequent line). elements = # Valid HTML 5 elements requiring a closing tag. # Note: the `var` element is out for obvious reasons, please use `tag 'var'`. regular: 'a abbr address article aside audio b bdi bdo blockquote body button canvas caption cite code colgroup datalist dd del details dfn div dl dt em fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hgroup html i iframe ins kbd label legend li main map mark menu meter nav noscript object ol optgroup option output p pre progress q rp rt ruby s samp script section select small span strong style sub summary sup table tbody td textarea tfoot th thead time title tr u ul video' # Valid self-closing HTML 5 elements. void: 'area base br col command embed hr img input keygen link meta param source track wbr' obsolete: 'applet acronym bgsound dir frameset noframes isindex listing nextid noembed plaintext rb strike xmp big blink center font marquee multicol nobr spacer tt' obsolete_void: 'basefont frame' # Create a unique list of element names merging the desired groups. merge_elements = (args...) -> result = [] for a in args for element in elements[a].split ' ' result.push element unless element in result result # Public/customizable list of possible elements. # For each name in this list that is also present in the input template code, # a function with the same name will be added to the compiled template. coffeekup.tags = merge_elements 'regular', 'obsolete', 'void', 'obsolete_void' # Public/customizable list of elements that should be rendered self-closed. coffeekup.self_closing = merge_elements 'void', 'obsolete_void' # This is the basic material from which compiled templates will be formed. # It will be manipulated in its string form at the `coffeekup.compile` function # to generate the final template function. skeleton = (__data = {}) -> # Whether to generate formatted HTML with indentation and line breaks, or # just the natural "faux-minified" output. __data.format ?= off # Whether to autoescape all content or let you handle it on a case by case # basis with the `h` function. __data.autoescape ?= off # Used to generate DOM ids scoped to a global, module or local space __data.module_path ?= 'global' __data.local_ids ?= {} # Internal CoffeeKup stuff. __ck = buffer: [] ids: null esc: (txt) -> if __data.autoescape then h(txt) else String(txt) tabs: 0 repeat: (string, count) -> Array(count + 1).join string indent: -> text @repeat(' ', @tabs) if __data.format # Adapter to keep the builtin tag functions DRY. tag: (name, args) -> combo = [name] combo.push i for i in args tag.apply __data, combo render_idclass: (str) -> classes = [] for i in str.split '.' if '#' in i id = i.replace '#', '' else classes.push i unless i is '' text " id=\"#{id}\"" if id if classes.length > 0 text " class=\"" for c in classes text ' ' unless c is classes[0] text c text '"' render_attrs: (obj, prefix = '') -> for k, v of obj # `true` is rendered as `selected="selected"`. v = k if typeof v is 'boolean' and v # Functions are rendered in an executable form. v = "(#{v}).call(this);" if typeof v is 'function' # Prefixed attribute. if v? and typeof v is 'object' and v not instanceof Array # `data: {icon: 'foo'}` is rendered as `data-icon="foo"`. @render_attrs(v, prefix + k + '-') # `undefined`, `false` and `null` result in the attribute not being rendered. else if v? and v isnt false # strings, numbers, arrays and functions are rendered "as is". text " #{prefix + k}=\"#{@esc(v)}\"" render_contents: (contents) -> switch typeof contents when 'string', 'number', 'boolean' text @esc(contents) when 'function' text '\n' if __data.format @tabs++ result = contents.call __data if typeof result is 'string' @indent() text @esc(result) text '\n' if __data.format @tabs-- @indent() render_tag: (name, idclass, attrs, contents) -> @indent() if __ck.buffer[__ck.buffer.length-1] is "\n" text "<#{name}" @render_idclass(idclass) if idclass @render_attrs(attrs) if attrs if name in @self_closing text ' />' text '\n' if __data.format else text '>' @render_contents(contents) text "</#{name}>" text '\n' if __data.format null tag = (name, args...) -> for a in args switch typeof a when 'function' contents = a when 'object' attrs = a when 'number', 'boolean' contents = a when 'string' if args.length is 1 if args[0][0] isnt '.' or args[0].indexOf(' ') >= 0 then contents = a else idclass = a ; contents = null else if a is args[0] idclass = a else contents = a __ck.render_tag(name, idclass, attrs, contents) _global_ids = {} _modules_ids = {} _coffeescript_ids_done = global: null, module: {} id = (db, value) -> if typeof db is 'string' then value = db ; db = null if typeof value is 'string' ids = db ? __data.local_ids ? {} prefix = if value then value.replace(/[\.\#]/g, '-') else '' for key in arguments when key isnt db then ids[key] ?= prefix + id() return if arguments.length <= 2 then ids[value] ?= prefix + id() else ids __data.id(parseInt value) if value? and typeof value is "number" '_' + __data.id() id.local = (value) -> id __data.local_ids, value id.module = (value) -> id (_modules_ids[__data.module_path] ?= {}), value id.global = (value) -> id _global_ids, value id.ids = (db) -> _ids = db ? __data.local_ids ? {} ids = (value) -> unless value? then return _ids _ids[value] ? _ids[value] = id(value) ids.toJSONString = (var_name) -> func = """ (function (key) { """ func += "var _id = " + switch var_name when 'id.module' then """ document.querySelector("script[data-coffeekup-ids-module-#{__data.hash(__data.module_path)}-" + key.replace(/[\.\#]/g, '-') + "]" ).getAttribute("data-coffeekup-ids-module-#{__data.hash(__data.module_path)}-" + key.replace(/[\.\#]/g, '-')); """ when 'id.general' then """ document.querySelector("script[data-coffeekup-ids-general-" + key.replace(/[\.\#]/g, '-') + "]").getAttribute("data-coffeekup-ids-general-" + key.replace(/[\.\#]/g, '-')); """ else "(#{JSON.stringify _ids})[key];" if var_name is 'id' func += """ if (_id == null && id.module != null) _id = id.module(key); """ if var_name in ['id', 'id.module'] func += """ if (_id == null && id.global != null) _id = id.global(key); """ func += """ return (_id != null ? _id : ''); }) """ """ #{func}#{(for own k, v of @ when k isnt 'toJSONString' then ";#{var_name}.#{k}=#{if v.toJSONString then v.toJSONString(var_name + '.' + k) else v.toString()}").join('')} """ ids id.ids.local = -> id.ids __data.local_ids id.ids.module = -> id.ids (_modules_ids[__data.module_path] ?= {}) id.ids.global = -> id.ids _global_ids id.classes = id.ids totext = (func) -> temp_buffer = [] old_buffer = __ck.buffer __ck.buffer = temp_buffer func() __ck.buffer = old_buffer temp_buffer.join '' h = (txt) -> String(txt).replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') doctype = (type = 'default') -> text __ck.doctypes[type] text '\n' if __data.format text = (txt) -> __ck.buffer.push String(txt) null comment = (cmt) -> text "<!--#{cmt}-->" text '\n' if __data.format coffeescript = (param, func) -> has_local = no; for k of __data.local_ids then has_local = yes; break has_module = _modules_ids[__data.module_path]? if (has_local or has_module) unless func? then func = param; param = null func = func?.toString() unless param?.id? or not func? if (idx = func.indexOf('id')) >= 0 then (param ?= {}).id = id.ids.local() ? {} if idx > 0 ids_module = id.ids.module() if func.indexOf('module') >= 0 then param.id.module = ids_module ? {} else if ids_module? then param.id.module = ids_module ids_global = id.ids.global() if func.indexOf('global') >= 0 then param.id.global = ids_global ? {} else if ids_global? then param.id.global = ids_global script_data = null if param.id?.module? and _coffeescript_ids_done.module[__data.module_path] isnt yes module_hash = __data.hash(__data.module_path) for key, value of _modules_ids[__data.module_path] script_data ?= data:{coffeekup:ids:module:{}} script_data.data.coffeekup.ids.module[module_hash] ?= {} script_data.data.coffeekup.ids.module[module_hash][key.replace(/[\.\#]/g, '-')] = value _coffeescript_ids_done.module[__data.module_path] = yes if param.id?.global? and _coffeescript_ids_done.global isnt yes for key, value of _global_ids script_data ?= data:{coffeekup:ids:{}} script_data.data.coffeekup.ids.global ?= {} script_data.data.coffeekup.ids.global[key.replace(/[\.\#]/g, '-')] = value _coffeescript_ids_done.global = yes if (func) # `coffeescript {value:"sample"} -> alert value'` becomes: # `<script>var value="sample";(function () {return alert(value);})();</script>` script script_data, "#{__ck.coffeescript_helpers}" + (if param? then "\n(function() {var " + ("#{k}=" + (if typeof v is 'function' then (if v.toJSONString? then v.toJSONString(k) else "#{v.toString()}") else JSON.stringify(v)) for k,v of param).join(',') + ";\n" else '') + "(#{func}).call(this)" + if param? then "}).call(this);" else ";" __ck.coffeescript_helpers = "" # needed only once in a `render` else switch typeof param # `coffeescript -> alert 'hi'` becomes: # `<script>;(function () {return alert('hi');})();</script>` when 'function' script "#{__ck.coffeescript_helpers}(#{param}).call(this);" __ck.coffeescript_helpers = "" # needed only once in a `render` # `coffeescript "alert 'hi'"` becomes: # `<script type="text/coffeescript">alert 'hi'</script>` when 'string' script type: 'text/coffeescript', -> param # `coffeescript src: 'script.coffee'` becomes: # `<script type="text/coffeescript" src="script.coffee"></script>` when 'object' (param ?= {}).type = 'text/coffeescript' script param # Conditional IE comments. ie = (condition, contents) -> __ck.indent() text "<!--[if #{condition}]>" __ck.render_contents(contents) text "<![endif]-->" text '\n' if __data.format null # Stringify the skeleton and unwrap it from its enclosing `function(){}`, then # add the CoffeeScript helpers. skeleton = String(skeleton) .replace(/function\s*\(.*\)\s*\{/, '') .replace(/return null;\s*\}$/, '') skeleton = coffeescript_helpers + skeleton stringify = -> doit = (o) -> result = [] result.push switch Object.prototype.toString.apply o when '[object Object]' then "{#{("'"+ k + "':" + doit(v) for own k,v of o).join(',')}}" when '[object Array]' then "function () {var a = []; var o = {#{(k + ':' + doit(v) for own k,v of o).join(',')}};for (var k in o) {a[k] = o[k];} return a; }()" when '[object Boolean]' then o when '[object Number]' then o when '[object Date]' then "new Date(#{o.valueOf()})" when '[object Function]' then "function(){return (#{o.toString()}).apply(__data, arguments);}"# Make sure these functions have access to `__data` as `@/this`. when '[object Math]' then 'Math' when '[object String]' then "'#{o.replace /\'/g, '\\\''}'" when '[object Undefined]' then 'void 0' when '[object Null]' then 'null' result doit(arguments[0]).join(', ') # Compiles a template into a standalone JavaScript function. coffeekup.compile = (template, options = {}) -> # The template can be provided as either a function or a CoffeeScript string # (in the latter case, the CoffeeScript compiler must be available). if typeof template is 'function' then template = String(template) else if typeof template is 'string' and coffee? template = coffee.compile template, bare: yes template = "function(){#{template}}" # If an object `hardcode` is provided, insert the stringified value # of each variable directly in the function body. This is a less flexible but # faster alternative to the standard method of using `with` (see below). hardcoded_locals = '' if options.hardcode for k, v of options.hardcode unless options.document and typeof v is 'function' hardcoded_locals += "var #{k} = #{stringify v};" else hardcoded_locals += "var #{k} = function() { return (#{stringify v}).apply(this.bin ? this : __data.document, arguments) };" # Add a function for each tag this template references. We don't want to have # all hundred-odd tags wasting space in the compiled function. tag_functions = '' tags_used = [] for t in coffeekup.tags if options.all_tags or template.indexOf(t) > -1 or hardcoded_locals.indexOf(t) > -1 tags_used.push t tag_functions += "var #{tags_used.join ','};" for t in tags_used tag_functions += "#{t} = function(){return __ck.tag('#{t}', arguments);};" # Main function assembly. code = tag_functions + hardcoded_locals + skeleton code += "__ck.doctypes = #{JSON.stringify coffeekup.doctypes};" code += "__ck.coffeescript_helpers = #{JSON.stringify coffeescript_helpers};" code += "__ck.self_closing = #{JSON.stringify coffeekup.self_closing};" # If `locals` is set, wrap the template inside a `with` block. This is the # most flexible but slower approach to specifying local variables. code += 'with(__data.locals){' if options.locals code += "(#{template}).call(__data" + (if options.bin? then ", __data.bin" else '') + ");" code += '}' if options.locals code += "return __ck.buffer.join('');" new Function('__data', code) cache = {} # Template in, HTML out. Accepts functions or strings as does `coffeekup.compile`. # # Accepts an option `cache`, by default `false`. If set to `false` templates will # be recompiled each time. # # `options` is just a convenience parameter to pass options separately from the # data, but the two will be merged and passed down to the compiler (which uses # `locals` and `hardcode`), and the template (which understands `locals`, `format` # and `autoescape`). coffeekup.render = (template, data = {}, options = {}) -> data[k] = v for k, v of options data.cache ?= off data.hash = (b) -> c = (a, b) -> a >>> b | a << 32 - b d = undefined; e = undefined f = Math.pow; g = f(2, 32); h = 'length'; i = ''; j = []; k = 8 * b[h]; l = []; m = []; n = m[h]; o = {}; p = 2 while 64 > n if !o[p] d = 0 while 313 > d o[d] = p d += p l[n] = f(p, .5) * g | 0 m[n++] = f(p, 1 / 3) * g | 0 p++ b += '\x80' while b[h] % 64 - 56 b += '\x00' d = 0 while d < b[h] if (e = b.charCodeAt(d); e >> 8) return j[d >> 2] |= e << (3 - d) % 4 * 8 d++ j[j[h]] = k / g | 0 j[j[h]] = k e = 0 while e < j[h] q = j.slice(e, e += 16) r = l l = l.slice(0, 8) d = 0 while 64 > d s = q[d - 15] t = q[d - 2] u = l[0] v = l[4] w = l[7] + (c(v, 6) ^ c(v, 11) ^ c(v, 25)) + (v & l[5] ^ ~v & l[6]) + m[d] + (q[d] = if 16 > d then q[d] else q[d - 16] + (c(s, 7) ^ c(s, 18) ^ s >>> 3) + q[d - 7] + (c(t, 17) ^ c(t, 19) ^ t >>> 10) | 0) x = (c(u, 2) ^ c(u, 13) ^ c(u, 22)) + (u & l[1] ^ u & l[2] ^ l[1] & l[2]) l = [ w + x | 0 ].concat(l) l[4] = l[4] + w | 0 d++ d = 0 while 8 > d l[d] = l[d] + r[d] | 0 d++ d = 0 while 8 > d e = 3 while e + 1 y = l[d] >> 8 * e & 255 i += (if 16 > y then 0 else '') + y.toString(16) e-- d++ i data.id = do -> c = 0 ; blockSize = 4 ; base = 36 ; discreteValues = Math.pow base, blockSize pad = (num, size) -> s = '000000000' + num ; s.substr s.length - size randomBlock = -> pad (Math.random() * discreteValues << 0).toString(base), blockSize safeCounter = -> (c = if c < discreteValues then c else 0) ; c++ ; c - 1 api = -> letter = 'c' timestamp = (new Date).getTime().toString(base) counter = undefined fingerprint = api.fingerprint() random = randomBlock() + randomBlock() counter = pad(safeCounter().toString(base), blockSize) letter + timestamp + counter + fingerprint + random api.slug = -> date = (new Date).getTime().toString(36) counter = undefined print = api.fingerprint().slice(0, 1) + api.fingerprint().slice(-1) random = randomBlock().slice(-2) counter = safeCounter().toString(36).slice(-4) date.slice(-2) + counter + print + random api.globalCount = unless window? then undefined else -> cache = (-> i = undefined ; count = 0 ; (for i of window then count++) ; count)() api.globalCount = -> cache cache api.fingerprint = if window? -> pad (navigator.mimeTypes.length + navigator.userAgent.length).toString(36) + api.globalCount().toString(36), 4 else -> os = require('os') ; padding = 2 pid = pad(process.pid.toString(36), padding) hostname = os.hostname() ; length = hostname.length hostId = pad(hostname.split('').reduce(((prev, char) -> +prev + char.charCodeAt(0) ), +length + 36).toString(36), padding) pid + hostId api if data.cache and cache[template]? then tpl = cache[template] else if data.cache then tpl = cache[template] = coffeekup.compile(template, data) else tpl = coffeekup.compile(template, data) tpl(data) unless window? coffeekup.adapters = # Legacy adapters for when CoffeeKup expected data in the `context` attribute. simple: coffeekup.render meryl: coffeekup.render express: TemplateError: class extends Error constructor: (@message) -> Error.call this, @message Error.captureStackTrace this, arguments.callee name: 'TemplateError' compile: (template, data) -> # Allows `partial 'foo'` instead of `text @partial 'foo'`. data.hardcode ?= {} data.hardcode.partial = -> text @partial.apply @, arguments TemplateError = @TemplateError try tpl = coffeekup.compile(template, data) catch e then throw new TemplateError "Error compiling #{data.filename}: #{e.message}" return -> try tpl arguments... catch e then throw new TemplateError "Error rendering #{data.filename}: #{e.message}"