| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077 |
- ;(function(){
- /**
- * Require the given path.
- *
- * @param {String} path
- * @return {Object} exports
- * @api public
- */
- function require(path, parent, orig) {
- var resolved = require.resolve(path);
- // lookup failed
- if (null == resolved) {
- orig = orig || path;
- parent = parent || 'root';
- var err = new Error('Failed to require "' + orig + '" from "' + parent + '"');
- err.path = orig;
- err.parent = parent;
- err.require = true;
- throw err;
- }
- var module = require.modules[resolved];
- // perform real require()
- // by invoking the module's
- // registered function
- if (!module._resolving && !module.exports) {
- var mod = {};
- mod.exports = {};
- mod.client = mod.component = true;
- module._resolving = true;
- module.call(this, mod.exports, require.relative(resolved), mod);
- delete module._resolving;
- module.exports = mod.exports;
- }
- return module.exports;
- }
- /**
- * Registered modules.
- */
- require.modules = {};
- /**
- * Registered aliases.
- */
- require.aliases = {};
- /**
- * Resolve `path`.
- *
- * Lookup:
- *
- * - PATH/index.js
- * - PATH.js
- * - PATH
- *
- * @param {String} path
- * @return {String} path or null
- * @api private
- */
- require.resolve = function(path) {
- if (path.charAt(0) === '/') path = path.slice(1);
- var paths = [
- path,
- path + '.js',
- path + '.json',
- path + '/index.js',
- path + '/index.json'
- ];
- for (var i = 0; i < paths.length; i++) {
- var path = paths[i];
- if (require.modules.hasOwnProperty(path)) return path;
- if (require.aliases.hasOwnProperty(path)) return require.aliases[path];
- }
- };
- /**
- * Normalize `path` relative to the current path.
- *
- * @param {String} curr
- * @param {String} path
- * @return {String}
- * @api private
- */
- require.normalize = function(curr, path) {
- var segs = [];
- if ('.' != path.charAt(0)) return path;
- curr = curr.split('/');
- path = path.split('/');
- for (var i = 0; i < path.length; ++i) {
- if ('..' == path[i]) {
- curr.pop();
- } else if ('.' != path[i] && '' != path[i]) {
- segs.push(path[i]);
- }
- }
- return curr.concat(segs).join('/');
- };
- /**
- * Register module at `path` with callback `definition`.
- *
- * @param {String} path
- * @param {Function} definition
- * @api private
- */
- require.register = function(path, definition) {
- require.modules[path] = definition;
- };
- /**
- * Alias a module definition.
- *
- * @param {String} from
- * @param {String} to
- * @api private
- */
- require.alias = function(from, to) {
- if (!require.modules.hasOwnProperty(from)) {
- throw new Error('Failed to alias "' + from + '", it does not exist');
- }
- require.aliases[to] = from;
- };
- /**
- * Return a require function relative to the `parent` path.
- *
- * @param {String} parent
- * @return {Function}
- * @api private
- */
- require.relative = function(parent) {
- var p = require.normalize(parent, '..');
- /**
- * lastIndexOf helper.
- */
- function lastIndexOf(arr, obj) {
- var i = arr.length;
- while (i--) {
- if (arr[i] === obj) return i;
- }
- return -1;
- }
- /**
- * The relative require() itself.
- */
- function localRequire(path) {
- var resolved = localRequire.resolve(path);
- return require(resolved, parent, path);
- }
- /**
- * Resolve relative to the parent.
- */
- localRequire.resolve = function(path) {
- var c = path.charAt(0);
- if ('/' == c) return path.slice(1);
- if ('.' == c) return require.normalize(p, path);
- // resolve deps by returning
- // the dep in the nearest "deps"
- // directory
- var segs = parent.split('/');
- var i = lastIndexOf(segs, 'deps') + 1;
- if (!i) i = 0;
- path = segs.slice(0, i + 1).join('/') + '/deps/' + path;
- return path;
- };
- /**
- * Check if module is defined at `path`.
- */
- localRequire.exists = function(path) {
- return require.modules.hasOwnProperty(localRequire.resolve(path));
- };
- return localRequire;
- };
- require.register("component-indexof/index.js", function(exports, require, module){
- module.exports = function(arr, obj){
- if (arr.indexOf) return arr.indexOf(obj);
- for (var i = 0; i < arr.length; ++i) {
- if (arr[i] === obj) return i;
- }
- return -1;
- };
- });
- require.register("component-emitter/index.js", function(exports, require, module){
- /**
- * Module dependencies.
- */
- var index = require('indexof');
- /**
- * Expose `Emitter`.
- */
- module.exports = Emitter;
- /**
- * Initialize a new `Emitter`.
- *
- * @api public
- */
- function Emitter(obj) {
- if (obj) return mixin(obj);
- };
- /**
- * Mixin the emitter properties.
- *
- * @param {Object} obj
- * @return {Object}
- * @api private
- */
- function mixin(obj) {
- for (var key in Emitter.prototype) {
- obj[key] = Emitter.prototype[key];
- }
- return obj;
- }
- /**
- * Listen on the given `event` with `fn`.
- *
- * @param {String} event
- * @param {Function} fn
- * @return {Emitter}
- * @api public
- */
- Emitter.prototype.on = function(event, fn){
- this._callbacks = this._callbacks || {};
- (this._callbacks[event] = this._callbacks[event] || [])
- .push(fn);
- return this;
- };
- /**
- * Adds an `event` listener that will be invoked a single
- * time then automatically removed.
- *
- * @param {String} event
- * @param {Function} fn
- * @return {Emitter}
- * @api public
- */
- Emitter.prototype.once = function(event, fn){
- var self = this;
- this._callbacks = this._callbacks || {};
- function on() {
- self.off(event, on);
- fn.apply(this, arguments);
- }
- fn._off = on;
- this.on(event, on);
- return this;
- };
- /**
- * Remove the given callback for `event` or all
- * registered callbacks.
- *
- * @param {String} event
- * @param {Function} fn
- * @return {Emitter}
- * @api public
- */
- Emitter.prototype.off =
- Emitter.prototype.removeListener =
- Emitter.prototype.removeAllListeners = function(event, fn){
- this._callbacks = this._callbacks || {};
- // all
- if (0 == arguments.length) {
- this._callbacks = {};
- return this;
- }
- // specific event
- var callbacks = this._callbacks[event];
- if (!callbacks) return this;
- // remove all handlers
- if (1 == arguments.length) {
- delete this._callbacks[event];
- return this;
- }
- // remove specific handler
- var i = index(callbacks, fn._off || fn);
- if (~i) callbacks.splice(i, 1);
- return this;
- };
- /**
- * Emit `event` with the given args.
- *
- * @param {String} event
- * @param {Mixed} ...
- * @return {Emitter}
- */
- Emitter.prototype.emit = function(event){
- this._callbacks = this._callbacks || {};
- var args = [].slice.call(arguments, 1)
- , callbacks = this._callbacks[event];
- if (callbacks) {
- callbacks = callbacks.slice(0);
- for (var i = 0, len = callbacks.length; i < len; ++i) {
- callbacks[i].apply(this, args);
- }
- }
- return this;
- };
- /**
- * Return array of callbacks for `event`.
- *
- * @param {String} event
- * @return {Array}
- * @api public
- */
- Emitter.prototype.listeners = function(event){
- this._callbacks = this._callbacks || {};
- return this._callbacks[event] || [];
- };
- /**
- * Check if this emitter has `event` handlers.
- *
- * @param {String} event
- * @return {Boolean}
- * @api public
- */
- Emitter.prototype.hasListeners = function(event){
- return !! this.listeners(event).length;
- };
- });
- require.register("seed/src/main.js", function(exports, require, module){
- var config = require('./config'),
- ViewModel = require('./viewmodel'),
- directives = require('./directives'),
- filters = require('./filters'),
- utils = require('./utils')
- /**
- * Set config options
- */
- ViewModel.config = function (opts) {
- if (opts) {
- utils.extend(config, opts)
- if (opts.prefix) updatePrefix()
- }
- return this
- }
- /**
- * Allows user to register/retrieve a directive definition
- */
- ViewModel.directive = function (id, fn) {
- if (!fn) return directives[id]
- directives[id] = fn
- return this
- }
- /**
- * Allows user to register/retrieve a filter function
- */
- ViewModel.filter = function (id, fn) {
- if (!fn) return filters[id]
- filters[id] = fn
- return this
- }
- /**
- * Allows user to register/retrieve a ViewModel constructor
- */
- ViewModel.component = function (id, Ctor) {
- if (!Ctor) return utils.components[id]
- utils.components[id] = utils.toConstructor(Ctor)
- return this
- }
- /**
- * Allows user to register/retrieve a template partial
- */
- ViewModel.partial = function (id, partial) {
- if (!partial) return utils.partials[id]
- utils.partials[id] = utils.toFragment(partial)
- return this
- }
- /**
- * Allows user to register/retrieve a transition definition object
- */
- ViewModel.transition = function (id, transition) {
- if (!transition) return utils.transitions[id]
- utils.transitions[id] = transition
- return this
- }
- ViewModel.extend = extend
- /**
- * Expose the main ViewModel class
- * and add extend method
- */
- function extend (options) {
- var ParentVM = this
- // inherit options
- options = inheritOptions(options, ParentVM.options, true)
- utils.processOptions(options)
- var ExtendedVM = function (opts) {
- opts = inheritOptions(opts, options, true)
- ParentVM.call(this, opts)
- }
- // inherit prototype props
- var proto = ExtendedVM.prototype = Object.create(ParentVM.prototype)
- utils.defProtected(proto, 'constructor', ExtendedVM)
- // copy prototype props
- var protoMixins = options.proto
- if (protoMixins) {
- for (var key in protoMixins) {
- if (!(key in ViewModel.prototype)) {
- proto[key] = protoMixins[key]
- }
- }
- }
- // allow extended VM to be further extended
- ExtendedVM.extend = extend
- ExtendedVM.super = ParentVM
- ExtendedVM.options = options
- return ExtendedVM
- }
- /**
- * Inherit options
- *
- * For options such as `scope`, `vms`, `directives`, 'partials',
- * they should be further extended. However extending should only
- * be done at top level.
- *
- * `proto` is an exception because it's handled directly on the
- * prototype.
- *
- * `el` is an exception because it's not allowed as an
- * extension option, but only as an instance option.
- */
- function inheritOptions (child, parent, topLevel) {
- child = child || utils.hash()
- if (!parent) return child
- for (var key in parent) {
- if (key === 'el' || key === 'proto') continue
- if (!child[key]) { // child has priority
- child[key] = parent[key]
- } else if (topLevel && utils.typeOf(child[key]) === 'Object') {
- inheritOptions(child[key], parent[key], false)
- }
- }
- return child
- }
- /**
- * Update prefix for some special directives
- * that are used in compilation.
- */
- var specialAttributes = [
- 'id',
- 'pre',
- 'text',
- 'repeat',
- 'partial',
- 'component',
- 'transition'
- ]
- function updatePrefix () {
- specialAttributes.forEach(setPrefix)
- }
- function setPrefix (attr) {
- config.attrs[attr] = config.prefix + '-' + attr
- }
- updatePrefix()
- module.exports = ViewModel
- });
- require.register("seed/src/emitter.js", function(exports, require, module){
- // shiv to make this work for Component, Browserify and Node at the same time.
- var Emitter,
- componentEmitter = 'emitter'
- try {
- // Requiring without a string literal will make browserify
- // unable to parse the dependency, thus preventing it from
- // stopping the compilation after a failed lookup.
- Emitter = require(componentEmitter)
- } catch (e) {}
- module.exports = Emitter || require('events').EventEmitter
- });
- require.register("seed/src/config.js", function(exports, require, module){
- module.exports = {
- prefix : 'sd',
- debug : false,
- silent : false,
- enterClass : 'sd-enter',
- leaveClass : 'sd-leave',
- attrs : {}
-
- }
- });
- require.register("seed/src/utils.js", function(exports, require, module){
- var config = require('./config'),
- attrs = config.attrs,
- toString = Object.prototype.toString,
- join = Array.prototype.join,
- console = window.console,
- ViewModel // late def
- /**
- * Create a prototype-less object
- * which is a better hash/map
- */
- function makeHash () {
- return Object.create(null)
- }
- var utils = module.exports = {
- hash: makeHash,
- // global storage for user-registered
- // vms, partials and transitions
- components : makeHash(),
- partials : makeHash(),
- transitions : makeHash(),
- /**
- * get an attribute and remove it.
- */
- attr: function (el, type, noRemove) {
- var attr = attrs[type],
- val = el.getAttribute(attr)
- if (!noRemove && val !== null) el.removeAttribute(attr)
- return val
- },
- /**
- * Define an ienumerable property
- * This avoids it being included in JSON.stringify
- * or for...in loops.
- */
- defProtected: function (obj, key, val, enumerable, configurable) {
- if (obj.hasOwnProperty(key)) return
- Object.defineProperty(obj, key, {
- value : val,
- enumerable : !!enumerable,
- configurable : !!configurable
- })
- },
- /**
- * Accurate type check
- * internal use only, so no need to check for NaN
- */
- typeOf: function (obj) {
- return toString.call(obj).slice(8, -1)
- },
- /**
- * Most simple bind
- * enough for the usecase and fast than native bind()
- */
- bind: function (fn, ctx) {
- return function () {
- return fn.apply(ctx, arguments)
- }
- },
- /**
- * Make sure only strings and numbers are output to html
- * output empty string is value is not string or number
- */
- toText: function (value) {
- /* jshint eqeqeq: false */
- return (typeof value === 'string' ||
- typeof value === 'boolean' ||
- (typeof value === 'number' && value == value)) // deal with NaN
- ? value
- : ''
- },
- /**
- * simple extend
- */
- extend: function (obj, ext, protective) {
- for (var key in ext) {
- if (protective && obj[key]) continue
- obj[key] = ext[key]
- }
- },
- /**
- * filter an array with duplicates into uniques
- */
- unique: function (arr) {
- var hash = utils.hash(),
- i = arr.length,
- key, res = []
- while (i--) {
- key = arr[i]
- if (hash[key]) continue
- hash[key] = 1
- res.push(key)
- }
- return res
- },
- /**
- * Convert a string template to a dom fragment
- */
- toFragment: function (template) {
- if (typeof template !== 'string') {
- return template
- }
- if (template.charAt(0) === '#') {
- var templateNode = document.getElementById(template.slice(1))
- if (!templateNode) return
- template = templateNode.innerHTML
- }
- var node = document.createElement('div'),
- frag = document.createDocumentFragment(),
- child
- node.innerHTML = template.trim()
- /* jshint boss: true */
- while (child = node.firstChild) {
- frag.appendChild(child)
- }
- return frag
- },
- /**
- * Convert the object to a ViewModel constructor
- * if it is not already one
- */
- toConstructor: function (obj) {
- ViewModel = ViewModel || require('./viewmodel')
- return obj.prototype instanceof ViewModel || obj === ViewModel
- ? obj
- : ViewModel.extend(obj)
- },
- /**
- * convert certain option values to the desired format.
- */
- processOptions: function (options) {
- var components = options.components,
- partials = options.partials,
- template = options.template,
- key
- if (components) {
- for (key in components) {
- components[key] = utils.toConstructor(components[key])
- }
- }
- if (partials) {
- for (key in partials) {
- partials[key] = utils.toFragment(partials[key])
- }
- }
- if (template) {
- options.template = utils.toFragment(template)
- }
- },
- /**
- * log for debugging
- */
- log: function () {
- if (config.debug && console) {
- console.log(join.call(arguments, ' '))
- }
- },
-
- /**
- * warnings, thrown in all cases
- */
- warn: function() {
- if (!config.silent && console) {
- console.warn(join.call(arguments, ' '))
- }
- }
- }
- });
- require.register("seed/src/compiler.js", function(exports, require, module){
- var Emitter = require('./emitter'),
- Observer = require('./observer'),
- config = require('./config'),
- utils = require('./utils'),
- Binding = require('./binding'),
- Directive = require('./directive'),
- TextParser = require('./text-parser'),
- DepsParser = require('./deps-parser'),
- ExpParser = require('./exp-parser'),
- transition = require('./transition'),
- // cache deps ob
- depsOb = DepsParser.observer,
- // cache methods
- slice = Array.prototype.slice,
- log = utils.log,
- makeHash = utils.hash,
- def = utils.defProtected,
- hasOwn = Object.prototype.hasOwnProperty
- /**
- * The DOM compiler
- * scans a DOM node and compile bindings for a ViewModel
- */
- function Compiler (vm, options) {
- var compiler = this
- // indicate that we are intiating this instance
- // so we should not run any transitions
- compiler.init = true
- // extend options
- options = compiler.options = options || makeHash()
- utils.processOptions(options)
- utils.extend(compiler, options.compilerOptions)
- // initialize element
- var el = compiler.setupElement(options)
- log('\nnew VM instance:', el.tagName, '\n')
- // copy scope properties to vm
- var scope = options.scope
- if (scope) utils.extend(vm, scope, true)
- compiler.vm = vm
- def(vm, '$', makeHash())
- def(vm, '$el', el)
- def(vm, '$compiler', compiler)
- // keep track of directives and expressions
- // so they can be unbound during destroy()
- compiler.dirs = []
- compiler.exps = []
- compiler.childCompilers = [] // keep track of child compilers
- compiler.emitter = new Emitter() // the emitter used for nested VM communication
- // Store things during parsing to be processed afterwards,
- // because we want to have created all bindings before
- // observing values / parsing dependencies.
- var observables = compiler.observables = [],
- computed = compiler.computed = []
- // prototypal inheritance of bindings
- var parent = compiler.parentCompiler
- compiler.bindings = parent
- ? Object.create(parent.bindings)
- : makeHash()
- compiler.rootCompiler = parent
- ? getRoot(parent)
- : compiler
- // set parent VM
- // and register child id on parent
- var childId = utils.attr(el, 'id')
- if (parent) {
- def(vm, '$parent', parent.vm)
- if (childId) {
- compiler.childId = childId
- parent.vm.$[childId] = vm
- }
- }
- // setup observer
- compiler.setupObserver()
- // call user init. this will capture some initial values.
- if (options.init) {
- options.init.apply(vm, options.args || [])
- }
- // create bindings for keys set on the vm by the user
- var key, keyPrefix
- for (key in vm) {
- keyPrefix = key.charAt(0)
- if (keyPrefix !== '$' && keyPrefix !== '_') {
- compiler.createBinding(key)
- }
- }
- // for repeated items, create an index binding
- // which should be inenumerable but configurable
- if (compiler.repeat) {
- vm.$index = compiler.repeatIndex
- def(vm, '$collection', compiler.repeatCollection)
- compiler.createBinding('$index')
- }
- // now parse the DOM, during which we will create necessary bindings
- // and bind the parsed directives
- compiler.compile(el, true)
- // observe root values so that they emit events when
- // their nested values change (for an Object)
- // or when they mutate (for an Array)
- var i = observables.length, binding
- while (i--) {
- binding = observables[i]
- Observer.observe(binding.value, binding.key, compiler.observer)
- }
- // extract dependencies for computed properties
- if (computed.length) DepsParser.parse(computed)
- // done!
- compiler.init = false
- }
- var CompilerProto = Compiler.prototype
- /**
- * Initialize the VM/Compiler's element.
- * Fill it in with the template if necessary.
- */
- CompilerProto.setupElement = function (options) {
- // create the node first
- var el = this.el = typeof options.el === 'string'
- ? document.querySelector(options.el)
- : options.el || document.createElement(options.tagName || 'div')
- var template = options.template
- if (template) {
- // replace option: use the first node in
- // the template directly
- if (options.replace && template.childNodes.length === 1) {
- var replacer = template.childNodes[0].cloneNode(true)
- if (el.parentNode) {
- el.parentNode.insertBefore(replacer, el)
- el.parentNode.removeChild(el)
- }
- el = replacer
- } else {
- el.innerHTML = ''
- el.appendChild(template.cloneNode(true))
- }
- }
- // apply element options
- if (options.id) el.id = options.id
- if (options.className) el.className = options.className
- var attrs = options.attributes
- if (attrs) {
- for (var attr in attrs) {
- el.setAttribute(attr, attrs[attr])
- }
- }
- return el
- }
- /**
- * Setup observer.
- * The observer listens for get/set/mutate events on all VM
- * values/objects and trigger corresponding binding updates.
- */
- CompilerProto.setupObserver = function () {
- var compiler = this,
- bindings = compiler.bindings,
- observer = compiler.observer = new Emitter()
- // a hash to hold event proxies for each root level key
- // so they can be referenced and removed later
- observer.proxies = makeHash()
- // add own listeners which trigger binding updates
- observer
- .on('get', function (key) {
- check(key)
- depsOb.emit('get', bindings[key])
- })
- .on('set', function (key, val) {
- observer.emit('change:' + key, val)
- check(key)
- bindings[key].update(val)
- })
- .on('mutate', function (key, val, mutation) {
- observer.emit('change:' + key, val, mutation)
- check(key)
- bindings[key].pub()
- })
- function check (key) {
- if (!bindings[key]) {
- compiler.createBinding(key)
- }
- }
- }
- /**
- * Compile a DOM node (recursive)
- */
- CompilerProto.compile = function (node, root) {
- var compiler = this
- if (node.nodeType === 1) { // a normal node
- // skip anything with sd-pre
- if (utils.attr(node, 'pre') !== null) return
- // special attributes to check
- var repeatExp,
- componentId,
- partialId
- // It is important that we access these attributes
- // procedurally because the order matters.
- //
- // `utils.attr` removes the attribute once it gets the
- // value, so we should not access them all at once.
- // sd-repeat has the highest priority
- // and we need to preserve all other attributes for it.
- /* jshint boss: true */
- if (repeatExp = utils.attr(node, 'repeat')) {
- // repeat block cannot have sd-id at the same time.
- var directive = Directive.parse(config.attrs.repeat, repeatExp, compiler, node)
- if (directive) {
- compiler.bindDirective(directive)
- }
- // sd-component has second highest priority
- // and we preseve all other attributes as well.
- } else if (!root && (componentId = utils.attr(node, 'component'))) {
- var ChildVM = compiler.getOption('components', componentId)
- if (ChildVM) {
- var child = new ChildVM({
- el: node,
- child: true,
- compilerOptions: {
- parentCompiler: compiler
- }
- })
- compiler.childCompilers.push(child.$compiler)
- }
- } else {
- // check transition property
- node.sd_trans = utils.attr(node, 'transition')
-
- // replace innerHTML with partial
- partialId = utils.attr(node, 'partial')
- if (partialId) {
- var partial = compiler.getOption('partials', partialId)
- if (partial) {
- node.innerHTML = ''
- node.appendChild(partial.cloneNode(true))
- }
- }
- // finally, only normal directives left!
- compiler.compileNode(node)
- }
- } else if (node.nodeType === 3) { // text node
- compiler.compileTextNode(node)
- }
- }
- /**
- * Compile a normal node
- */
- CompilerProto.compileNode = function (node) {
- var i, j
- // parse if has attributes
- if (node.attributes && node.attributes.length) {
- var attrs = slice.call(node.attributes),
- attr, valid, exps, exp
- // loop through all attributes
- i = attrs.length
- while (i--) {
- attr = attrs[i]
- valid = false
- exps = Directive.split(attr.value)
- // loop through clauses (separated by ",")
- // inside each attribute
- j = exps.length
- while (j--) {
- exp = exps[j]
- var directive = Directive.parse(attr.name, exp, this, node)
- if (directive) {
- valid = true
- this.bindDirective(directive)
- }
- }
- if (valid) node.removeAttribute(attr.name)
- }
- }
- // recursively compile childNodes
- if (node.childNodes.length) {
- var nodes = slice.call(node.childNodes)
- for (i = 0, j = nodes.length; i < j; i++) {
- this.compile(nodes[i])
- }
- }
- }
- /**
- * Compile a text node
- */
- CompilerProto.compileTextNode = function (node) {
- var tokens = TextParser.parse(node.nodeValue)
- if (!tokens) return
- var dirname = config.attrs.text,
- el, token, directive
- for (var i = 0, l = tokens.length; i < l; i++) {
- token = tokens[i]
- if (token.key) { // a binding
- if (token.key.charAt(0) === '>') { // a partial
- var partialId = token.key.slice(1).trim(),
- partial = this.getOption('partials', partialId)
- if (partial) {
- el = partial.cloneNode(true)
- this.compileNode(el)
- }
- } else { // a binding
- el = document.createTextNode('')
- directive = Directive.parse(dirname, token.key, this, el)
- if (directive) {
- this.bindDirective(directive)
- }
- }
- } else { // a plain string
- el = document.createTextNode(token)
- }
- node.parentNode.insertBefore(el, node)
- }
- node.parentNode.removeChild(node)
- }
- /**
- * Add a directive instance to the correct binding & viewmodel
- */
- CompilerProto.bindDirective = function (directive) {
- // keep track of it so we can unbind() later
- this.dirs.push(directive)
- // for a simple directive, simply call its bind() or _update()
- // and we're done.
- if (directive.isSimple) {
- if (directive.bind) directive.bind()
- return
- }
- // otherwise, we got more work to do...
- var binding,
- compiler = this,
- key = directive.key,
- baseKey = key.split('.')[0],
- ownerCompiler = traceOwnerCompiler(directive, compiler)
- if (directive.isExp) {
- // expression bindings are always created on current compiler
- binding = compiler.createBinding(key, true, directive.isFn)
- } else if (ownerCompiler.vm.hasOwnProperty(baseKey)) {
- // If the directive's owner compiler's VM has the key,
- // it belongs there. Create the binding if it's not already
- // created, and return it.
- binding = hasOwn.call(ownerCompiler.bindings, key)
- ? ownerCompiler.bindings[key]
- : ownerCompiler.createBinding(key)
- } else {
- // due to prototypal inheritance of bindings, if a key doesn't exist
- // on the owner compiler's VM, then it doesn't exist in the whole
- // prototype chain. In this case we create the new binding at the root level.
- binding = ownerCompiler.bindings[key] || compiler.rootCompiler.createBinding(key)
- }
- binding.instances.push(directive)
- directive.binding = binding
- var value = binding.value
- // invoke bind hook if exists
- if (directive.bind) {
- directive.bind(value)
- }
- // set initial value
- if (binding.isComputed) {
- directive.refresh(value)
- } else {
- directive.update(value, true)
- }
- }
- /**
- * Create binding and attach getter/setter for a key to the viewmodel object
- */
- CompilerProto.createBinding = function (key, isExp, isFn) {
- var compiler = this,
- bindings = compiler.bindings,
- binding = new Binding(compiler, key, isExp, isFn)
- if (isExp) {
- // a complex expression binding
- // we need to generate an anonymous computed property for it
- var getter = ExpParser.parse(key, compiler)
- if (getter) {
- log(' created expression binding: ' + key)
- binding.value = isFn
- ? getter
- : { $get: getter }
- compiler.markComputed(binding)
- compiler.exps.push(binding)
- }
- } else {
- log(' created binding: ' + key)
- bindings[key] = binding
- // make sure the key exists in the object so it can be observed
- // by the Observer!
- Observer.ensurePath(compiler.vm, key)
- if (binding.root) {
- // this is a root level binding. we need to define getter/setters for it.
- compiler.define(key, binding)
- } else {
- var parentKey = key.slice(0, key.lastIndexOf('.'))
- if (!hasOwn.call(bindings, parentKey)) {
- // this is a nested value binding, but the binding for its parent
- // has not been created yet. We better create that one too.
- compiler.createBinding(parentKey)
- }
- }
- }
- return binding
- }
- /**
- * Defines the getter/setter for a root-level binding on the VM
- * and observe the initial value
- */
- CompilerProto.define = function (key, binding) {
- log(' defined root binding: ' + key)
- var compiler = this,
- vm = compiler.vm,
- ob = compiler.observer,
- value = binding.value = vm[key], // save the value before redefinening it
- type = utils.typeOf(value)
- if (type === 'Object' && value.$get) {
- // computed property
- compiler.markComputed(binding)
- } else if (type === 'Object' || type === 'Array') {
- // observe objects later, becase there might be more keys
- // to be added to it. we also want to emit all the set events
- // after all values are available.
- compiler.observables.push(binding)
- }
- Object.defineProperty(vm, key, {
- enumerable: true,
- get: function () {
- var value = binding.value
- if (depsOb.active && (!binding.isComputed && (!value || !value.__observer__)) ||
- Array.isArray(value)) {
- // only emit non-computed, non-observed (primitive) values, or Arrays.
- // because these are the cleanest dependencies
- ob.emit('get', key)
- }
- return binding.isComputed
- ? value.$get()
- : value
- },
- set: function (newVal) {
- var value = binding.value
- if (binding.isComputed) {
- if (value.$set) {
- value.$set(newVal)
- }
- } else if (newVal !== value) {
- // unwatch the old value
- Observer.unobserve(value, key, ob)
- // set new value
- binding.value = newVal
- ob.emit('set', key, newVal)
- Observer.ensurePaths(key, newVal, compiler.bindings)
- // now watch the new value, which in turn emits 'set'
- // for all its nested values
- Observer.observe(newVal, key, ob)
- }
- }
- })
- }
- /**
- * Process a computed property binding
- */
- CompilerProto.markComputed = function (binding) {
- var value = binding.value,
- vm = this.vm
- binding.isComputed = true
- // bind the accessors to the vm
- if (binding.isFn) {
- binding.value = utils.bind(value, vm)
- } else {
- value.$get = utils.bind(value.$get, vm)
- if (value.$set) {
- value.$set = utils.bind(value.$set, vm)
- }
- }
- // keep track for dep parsing later
- this.computed.push(binding)
- }
- /**
- * Retrive an option from the compiler
- */
- CompilerProto.getOption = function (type, id) {
- var opts = this.options
- return (opts[type] && opts[type][id]) || (utils[type] && utils[type][id])
- }
- /**
- * Unbind and remove element
- */
- CompilerProto.destroy = function () {
- var compiler = this,
- i, key, dir, instances, binding,
- el = compiler.el,
- directives = compiler.dirs,
- exps = compiler.exps,
- bindings = compiler.bindings,
- teardown = compiler.options.teardown
- // call user teardown first
- if (teardown) teardown()
- // unwatch
- compiler.observer.off()
- compiler.emitter.off()
- // unbind all direcitves
- i = directives.length
- while (i--) {
- dir = directives[i]
- // if this directive is an instance of an external binding
- // e.g. a directive that refers to a variable on the parent VM
- // we need to remove it from that binding's instances
- if (!dir.isSimple && dir.binding.compiler !== compiler) {
- instances = dir.binding.instances
- if (instances) instances.splice(instances.indexOf(dir), 1)
- }
- dir.unbind()
- }
- // unbind all expressions (anonymous bindings)
- i = exps.length
- while (i--) {
- exps[i].unbind()
- }
- // unbind/unobserve all own bindings
- for (key in bindings) {
- if (hasOwn.call(bindings, key)) {
- binding = bindings[key]
- if (binding.root) {
- Observer.unobserve(binding.value, binding.key, compiler.observer)
- }
- binding.unbind()
- }
- }
- // remove self from parentCompiler
- var parent = compiler.parentCompiler,
- childId = compiler.childId
- if (parent) {
- parent.childCompilers.splice(parent.childCompilers.indexOf(compiler), 1)
- if (childId) {
- delete parent.vm.$[childId]
- }
- }
- // finally remove dom element
- if (el === document.body) {
- el.innerHTML = ''
- } else if (el.parentNode) {
- transition(el, -1, function () {
- el.parentNode.removeChild(el)
- }, this)
- }
- }
- // Helpers --------------------------------------------------------------------
- /**
- * determine which viewmodel a key belongs to based on nesting symbols
- */
- function traceOwnerCompiler (key, compiler) {
- if (key.nesting) {
- var levels = key.nesting
- while (compiler.parentCompiler && levels--) {
- compiler = compiler.parentCompiler
- }
- } else if (key.root) {
- while (compiler.parentCompiler) {
- compiler = compiler.parentCompiler
- }
- }
- return compiler
- }
- /**
- * shorthand for getting root compiler
- */
- function getRoot (compiler) {
- return traceOwnerCompiler({ root: true }, compiler)
- }
- module.exports = Compiler
- });
- require.register("seed/src/viewmodel.js", function(exports, require, module){
- var Compiler = require('./compiler'),
- def = require('./utils').defProtected
- /**
- * ViewModel exposed to the user that holds data,
- * computed properties, event handlers
- * and a few reserved methods
- */
- function ViewModel (options) {
- // just compile. options are passed directly to compiler
- new Compiler(this, options)
- }
- // All VM prototype methods are inenumerable
- // so it can be stringified/looped through as raw data
- var VMProto = ViewModel.prototype
- /**
- * Convenience function to set an actual nested value
- * from a flat key string. Used in directives.
- */
- def(VMProto, '$set', function (key, value) {
- var path = key.split('.'),
- obj = getTargetVM(this, path)
- if (!obj) return
- for (var d = 0, l = path.length - 1; d < l; d++) {
- obj = obj[path[d]]
- }
- obj[path[d]] = value
- })
- /**
- * watch a key on the viewmodel for changes
- * fire callback with new value
- */
- def(VMProto, '$watch', function (key, callback) {
- this.$compiler.observer.on('change:' + key, callback)
- })
- /**
- * unwatch a key
- */
- def(VMProto, '$unwatch', function (key, callback) {
- // workaround here
- // since the emitter module checks callback existence
- // by checking the length of arguments
- var args = ['change:' + key],
- ob = this.$compiler.observer
- if (callback) args.push(callback)
- ob.off.apply(ob, args)
- })
- /**
- * unbind everything, remove everything
- */
- def(VMProto, '$destroy', function () {
- this.$compiler.destroy()
- })
- /**
- * broadcast an event to all child VMs recursively.
- */
- def(VMProto, '$broadcast', function () {
- var children = this.$compiler.childCompilers,
- i = children.length,
- child
- while (i--) {
- child = children[i]
- child.emitter.emit.apply(child.emitter, arguments)
- child.vm.$broadcast.apply(child.vm, arguments)
- }
- })
- /**
- * emit an event that propagates all the way up to parent VMs.
- */
- def(VMProto, '$emit', function () {
- var compiler = this.$compiler,
- emitter = compiler.emitter,
- parent = compiler.parentCompiler
- emitter.emit.apply(emitter, arguments)
- if (parent) {
- parent.emitter.emit.apply(parent.emitter, arguments)
- parent.vm.$emit.apply(parent.vm, arguments)
- }
- })
- /**
- * delegate on/off/once to the compiler's emitter
- */
- ;['on', 'off', 'once'].forEach(function (method) {
- def(VMProto, '$' + method, function () {
- var emitter = this.$compiler.emitter
- emitter[method].apply(emitter, arguments)
- })
- })
- /**
- * If a VM doesn't contain a path, go up the prototype chain
- * to locate the ancestor that has it.
- */
- function getTargetVM (vm, path) {
- var baseKey = path[0],
- binding = vm.$compiler.bindings[baseKey]
- return binding
- ? binding.compiler.vm
- : null
- }
- module.exports = ViewModel
- });
- require.register("seed/src/binding.js", function(exports, require, module){
- /**
- * Binding class.
- *
- * each property on the viewmodel has one corresponding Binding object
- * which has multiple directive instances on the DOM
- * and multiple computed property dependents
- */
- function Binding (compiler, key, isExp, isFn) {
- this.value = undefined
- this.isExp = !!isExp
- this.isFn = isFn
- this.root = !this.isExp && key.indexOf('.') === -1
- this.compiler = compiler
- this.key = key
- this.instances = []
- this.subs = []
- this.deps = []
- }
- var BindingProto = Binding.prototype
- /**
- * Process the value, then trigger updates on all dependents
- */
- BindingProto.update = function (value) {
- this.value = value
- var i = this.instances.length
- while (i--) {
- this.instances[i].update(value)
- }
- this.pub()
- }
- /**
- * -- computed property only --
- * Force all instances to re-evaluate themselves
- */
- BindingProto.refresh = function () {
- var i = this.instances.length
- while (i--) {
- this.instances[i].refresh()
- }
- this.pub()
- }
- /**
- * Notify computed properties that depend on this binding
- * to update themselves
- */
- BindingProto.pub = function () {
- var i = this.subs.length
- while (i--) {
- this.subs[i].refresh()
- }
- }
- /**
- * Unbind the binding, remove itself from all of its dependencies
- */
- BindingProto.unbind = function () {
- var i = this.instances.length
- while (i--) {
- this.instances[i].unbind()
- }
- i = this.deps.length
- var subs
- while (i--) {
- subs = this.deps[i].subs
- subs.splice(subs.indexOf(this), 1)
- }
- }
- module.exports = Binding
- });
- require.register("seed/src/observer.js", function(exports, require, module){
- /* jshint proto:true */
- var Emitter = require('./emitter'),
- utils = require('./utils'),
- depsOb = require('./deps-parser').observer,
- // cache methods
- typeOf = utils.typeOf,
- def = utils.defProtected,
- slice = Array.prototype.slice,
- // Array mutation methods to wrap
- methods = ['push','pop','shift','unshift','splice','sort','reverse'],
- // fix for IE + __proto__ problem
- // define methods as inenumerable if __proto__ is present,
- // otherwise enumerable so we can loop through and manually
- // attach to array instances
- hasProto = ({}).__proto__
- // The proxy prototype to replace the __proto__ of
- // an observed array
- var ArrayProxy = Object.create(Array.prototype)
- // Define mutation interceptors so we can emit the mutation info
- methods.forEach(function (method) {
- def(ArrayProxy, method, function () {
- var result = Array.prototype[method].apply(this, arguments)
- this.__observer__.emit('mutate', this.__observer__.path, this, {
- method: method,
- args: slice.call(arguments),
- result: result
- })
- return result
- }, !hasProto)
- })
- // Augment it with several convenience methods
- var extensions = {
- remove: function (index) {
- if (typeof index !== 'number') index = this.indexOf(index)
- return this.splice(index, 1)[0]
- },
- replace: function (index, data) {
- if (typeof index !== 'number') index = this.indexOf(index)
- if (this[index] !== undefined) return this.splice(index, 1, data)[0]
- },
- mutateFilter: function (fn) {
- var i = this.length
- while (i--) {
- if (!fn(this[i])) this.splice(i, 1)
- }
- return this
- }
- }
- for (var method in extensions) {
- def(ArrayProxy, method, extensions[method], !hasProto)
- }
- /**
- * Watch an object based on type
- */
- function watch (obj, path, observer) {
- var type = typeOf(obj)
- if (type === 'Object') {
- watchObject(obj, path, observer)
- } else if (type === 'Array') {
- watchArray(obj, path, observer)
- }
- }
- /**
- * Watch an Object, recursive.
- */
- function watchObject (obj, path, observer) {
- for (var key in obj) {
- var keyPrefix = key.charAt(0)
- if (keyPrefix !== '$' && keyPrefix !== '_') {
- bind(obj, key, path, observer)
- }
- }
- }
- /**
- * Watch an Array, overload mutation methods
- * and add augmentations by intercepting the prototype chain
- */
- function watchArray (arr, path, observer) {
- def(arr, '__observer__', observer)
- observer.path = path
- if (hasProto) {
- arr.__proto__ = ArrayProxy
- } else {
- for (var key in ArrayProxy) {
- def(arr, key, ArrayProxy[key])
- }
- }
- }
- /**
- * Define accessors for a property on an Object
- * so it emits get/set events.
- * Then watch the value itself.
- */
- function bind (obj, key, path, observer) {
- var val = obj[key],
- watchable = isWatchable(val),
- values = observer.values,
- fullKey = (path ? path + '.' : '') + key
- values[fullKey] = val
- // emit set on bind
- // this means when an object is observed it will emit
- // a first batch of set events.
- observer.emit('set', fullKey, val)
- Object.defineProperty(obj, key, {
- enumerable: true,
- get: function () {
- // only emit get on tip values
- if (depsOb.active && !watchable) {
- observer.emit('get', fullKey)
- }
- return values[fullKey]
- },
- set: function (newVal) {
- values[fullKey] = newVal
- ensurePaths(key, newVal, values)
- observer.emit('set', fullKey, newVal)
- watch(newVal, fullKey, observer)
- }
- })
- watch(val, fullKey, observer)
- }
- /**
- * Check if a value is watchable
- */
- function isWatchable (obj) {
- var type = typeOf(obj)
- return type === 'Object' || type === 'Array'
- }
- /**
- * When a value that is already converted is
- * observed again by another observer, we can skip
- * the watch conversion and simply emit set event for
- * all of its properties.
- */
- function emitSet (obj, observer, set) {
- if (typeOf(obj) === 'Array') {
- set('length', obj.length)
- } else {
- var key, val, values = observer.values
- for (key in observer.values) {
- val = values[key]
- set(key, val)
- }
- }
- }
- /**
- * Sometimes when a binding is found in the template, the value might
- * have not been set on the VM yet. To ensure computed properties and
- * dependency extraction can work, we have to create a dummy value for
- * any given path.
- */
- function ensurePaths (key, val, paths) {
- key += '.'
- for (var path in paths) {
- if (!path.indexOf(key)) {
- ensurePath(val, path.replace(key, ''))
- }
- }
- }
- /**
- * walk along a path and make sure it can be accessed
- * and enumerated in that object
- */
- function ensurePath (obj, key) {
- if (typeOf(obj) !== 'Object') return
- var path = key.split('.'), sec
- for (var i = 0, d = path.length - 1; i < d; i++) {
- sec = path[i]
- if (!obj[sec]) obj[sec] = {}
- obj = obj[sec]
- }
- if (typeOf(obj) === 'Object') {
- sec = path[i]
- if (!(sec in obj)) obj[sec] = undefined
- }
- }
- module.exports = {
- // used in sd-repeat
- watchArray: watchArray,
- ensurePath: ensurePath,
- ensurePaths: ensurePaths,
- /**
- * Observe an object with a given path,
- * and proxy get/set/mutate events to the provided observer.
- */
- observe: function (obj, rawPath, observer) {
- if (isWatchable(obj)) {
- var path = rawPath + '.',
- ob, alreadyConverted = !!obj.__observer__
- if (!alreadyConverted) {
- def(obj, '__observer__', new Emitter())
- }
- ob = obj.__observer__
- ob.values = ob.values || utils.hash()
- var proxies = observer.proxies[path] = {
- get: function (key) {
- observer.emit('get', path + key)
- },
- set: function (key, val) {
- observer.emit('set', path + key, val)
- },
- mutate: function (key, val, mutation) {
- // if the Array is a root value
- // the key will be null
- var fixedPath = key ? path + key : rawPath
- observer.emit('mutate', fixedPath, val, mutation)
- // also emit set for Array's length when it mutates
- var m = mutation.method
- if (m !== 'sort' && m !== 'reverse') {
- observer.emit('set', fixedPath + '.length', val.length)
- }
- }
- }
- ob
- .on('get', proxies.get)
- .on('set', proxies.set)
- .on('mutate', proxies.mutate)
- if (alreadyConverted) {
- emitSet(obj, ob, proxies.set)
- } else {
- watch(obj, null, ob)
- }
- }
- },
- /**
- * Cancel observation, turn off the listeners.
- */
- unobserve: function (obj, path, observer) {
- if (!obj || !obj.__observer__) return
- path = path + '.'
- var proxies = observer.proxies[path]
- obj.__observer__
- .off('get', proxies.get)
- .off('set', proxies.set)
- .off('mutate', proxies.mutate)
- observer.proxies[path] = null
- }
- }
- });
- require.register("seed/src/directive.js", function(exports, require, module){
- var config = require('./config'),
- utils = require('./utils'),
- directives = require('./directives'),
- filters = require('./filters'),
- // Regexes!
- // regex to split multiple directive expressions
- SPLIT_RE = /(?:['"](?:\\.|[^'"])*['"]|\\.|[^,])+/g,
- KEY_RE = /^[^\|]+/,
- ARG_RE = /^([\w- ]+):(.+)$/,
- FILTERS_RE = /\|[^\|]+/g,
- FILTER_TOKEN_RE = /[^\s']+|'[^']+'/g,
- NESTING_RE = /^\^+/,
- SINGLE_VAR_RE = /^[\w\.\$]+$/
- /**
- * Directive class
- * represents a single directive instance in the DOM
- */
- function Directive (definition, expression, rawKey, compiler, node) {
- this.compiler = compiler
- this.vm = compiler.vm
- this.el = node
- var isSimple = expression === ''
- // mix in properties from the directive definition
- if (typeof definition === 'function') {
- this[isSimple ? 'bind' : '_update'] = definition
- } else {
- for (var prop in definition) {
- if (prop === 'unbind' || prop === 'update') {
- this['_' + prop] = definition[prop]
- } else {
- this[prop] = definition[prop]
- }
- }
- }
- // empty expression, we're done.
- if (isSimple) {
- this.isSimple = true
- return
- }
- this.expression = expression.trim()
- this.rawKey = rawKey
-
- parseKey(this, rawKey)
- this.isExp = !SINGLE_VAR_RE.test(this.key)
-
- var filterExps = expression.match(FILTERS_RE)
- if (filterExps) {
- this.filters = []
- var i = 0, l = filterExps.length, filter
- for (; i < l; i++) {
- filter = parseFilter(filterExps[i], this.compiler)
- if (filter) this.filters.push(filter)
- }
- if (!this.filters.length) this.filters = null
- } else {
- this.filters = null
- }
- }
- var DirProto = Directive.prototype
- /**
- * parse a key, extract argument and nesting/root info
- */
- function parseKey (dir, rawKey) {
- var argMatch = rawKey.match(ARG_RE)
- var key = argMatch
- ? argMatch[2].trim()
- : rawKey.trim()
- dir.arg = argMatch
- ? argMatch[1].trim()
- : null
- var nesting = key.match(NESTING_RE)
- dir.nesting = nesting
- ? nesting[0].length
- : false
- dir.root = key.charAt(0) === '*'
- if (dir.nesting) {
- key = key.replace(NESTING_RE, '')
- } else if (dir.root) {
- key = key.slice(1)
- }
- dir.key = key
- }
- /**
- * parse a filter expression
- */
- function parseFilter (filter, compiler) {
- var tokens = filter.slice(1).match(FILTER_TOKEN_RE)
- if (!tokens) return
- tokens = tokens.map(function (token) {
- return token.replace(/'/g, '').trim()
- })
- var name = tokens[0],
- apply = compiler.getOption('filters', name) || filters[name]
- if (!apply) {
- utils.warn('Unknown filter: ' + name)
- return
- }
- return {
- name : name,
- apply : apply,
- args : tokens.length > 1
- ? tokens.slice(1)
- : null
- }
- }
- /**
- * called when a new value is set
- * for computed properties, this will only be called once
- * during initialization.
- */
- DirProto.update = function (value, init) {
- if (!init && value === this.value) return
- this.value = value
- this.apply(value)
- }
- /**
- * -- computed property only --
- * called when a dependency has changed
- */
- DirProto.refresh = function (value) {
- // pass element and viewmodel info to the getter
- // enables context-aware bindings
- if (value) this.value = value
- if (this.isFn) {
- value = this.value
- } else {
- value = this.value.$get()
- if (value !== undefined && value === this.computedValue) return
- this.computedValue = value
- }
- this.apply(value)
- }
- /**
- * Actually invoking the _update from the directive's definition
- */
- DirProto.apply = function (value) {
- this._update(
- this.filters
- ? this.applyFilters(value)
- : value
- )
- }
- /**
- * pipe the value through filters
- */
- DirProto.applyFilters = function (value) {
- var filtered = value, filter
- for (var i = 0, l = this.filters.length; i < l; i++) {
- filter = this.filters[i]
- filtered = filter.apply.call(this.vm, filtered, filter.args)
- }
- return filtered
- }
- /**
- * Unbind diretive
- * @ param {Boolean} update
- * Sometimes we call unbind before an update (i.e. not destroy)
- * just to teardown previous stuff, in that case we do not want
- * to null everything.
- */
- DirProto.unbind = function (update) {
- // this can be called before the el is even assigned...
- if (!this.el) return
- if (this._unbind) this._unbind(update)
- if (!update) this.vm = this.el = this.binding = this.compiler = null
- }
- // exposed methods ------------------------------------------------------------
- /**
- * split a unquoted-comma separated expression into
- * multiple clauses
- */
- Directive.split = function (exp) {
- return exp.match(SPLIT_RE) || ['']
- }
- /**
- * make sure the directive and expression is valid
- * before we create an instance
- */
- Directive.parse = function (dirname, expression, compiler, node) {
- var prefix = config.prefix
- if (dirname.indexOf(prefix) === -1) return
- dirname = dirname.slice(prefix.length + 1)
- var dir = compiler.getOption('directives', dirname) || directives[dirname]
- if (!dir) return utils.warn('unknown directive: ' + dirname)
- var keyMatch = expression.match(KEY_RE),
- rawKey = keyMatch && keyMatch[0].trim()
- // have a valid raw key, or be an empty directive
- return (rawKey || expression === '')
- ? new Directive(dir, expression, rawKey, compiler, node)
- : utils.warn('invalid directive expression: ' + expression)
- }
- module.exports = Directive
- });
- require.register("seed/src/exp-parser.js", function(exports, require, module){
- var utils = require('./utils'),
- hasOwn = Object.prototype.hasOwnProperty
- // Variable extraction scooped from https://github.com/RubyLouvre/avalon
- var KEYWORDS =
- // keywords
- 'break,case,catch,continue,debugger,default,delete,do,else,false' +
- ',finally,for,function,if,in,instanceof,new,null,return,switch,this' +
- ',throw,true,try,typeof,var,void,while,with,undefined' +
- // reserved
- ',abstract,boolean,byte,char,class,const,double,enum,export,extends' +
- ',final,float,goto,implements,import,int,interface,long,native' +
- ',package,private,protected,public,short,static,super,synchronized' +
- ',throws,transient,volatile' +
- // ECMA 5 - use strict
- ',arguments,let,yield',
-
- KEYWORDS_RE = new RegExp(["\\b" + KEYWORDS.replace(/,/g, '\\b|\\b') + "\\b"].join('|'), 'g'),
- REMOVE_RE = /\/\*(?:.|\n)*?\*\/|\/\/[^\n]*\n|\/\/[^\n]*$|'[^']*'|"[^"]*"|[\s\t\n]*\.[\s\t\n]*[$\w\.]+/g,
- SPLIT_RE = /[^\w$]+/g,
- NUMBER_RE = /\b\d[^,]*/g,
- BOUNDARY_RE = /^,+|,+$/g
- /**
- * Strip top level variable names from a snippet of JS expression
- */
- function getVariables (code) {
- code = code
- .replace(REMOVE_RE, '')
- .replace(SPLIT_RE, ',')
- .replace(KEYWORDS_RE, '')
- .replace(NUMBER_RE, '')
- .replace(BOUNDARY_RE, '')
- return code
- ? code.split(/,+/)
- : []
- }
- /**
- * A given path could potentially exist not on the
- * current compiler, but up in the parent chain somewhere.
- * This function generates an access relationship string
- * that can be used in the getter function by walking up
- * the parent chain to check for key existence.
- *
- * It stops at top parent if no vm in the chain has the
- * key. It then creates any missing bindings on the
- * final resolved vm.
- */
- function getRel (path, compiler) {
- var rel = '',
- vm = compiler.vm,
- dot = path.indexOf('.'),
- key = dot > -1
- ? path.slice(0, dot)
- : path
- while (true) {
- if (hasOwn.call(vm, key)) {
- break
- } else {
- if (vm.$parent) {
- vm = vm.$parent
- rel += '$parent.'
- } else {
- break
- }
- }
- }
- compiler = vm.$compiler
- if (!hasOwn.call(compiler.bindings, path)) {
- compiler.createBinding(path)
- }
- return rel
- }
- /**
- * Create a function from a string...
- * this looks like evil magic but since all variables are limited
- * to the VM's scope it's actually properly sandboxed
- */
- function makeGetter (exp, raw) {
- /* jshint evil: true */
- var fn
- try {
- fn = new Function(exp)
- } catch (e) {
- utils.warn('Invalid expression: ' + raw)
- }
- return fn
- }
- module.exports = {
- /**
- * Parse and return an anonymous computed property getter function
- * from an arbitrary expression, together with a list of paths to be
- * created as bindings.
- */
- parse: function (exp, compiler) {
- // extract variable names
- var vars = getVariables(exp)
- if (!vars.length) {
- return makeGetter('return ' + exp, exp)
- }
- vars = utils.unique(vars)
- var accessors = '',
- pathRE = new RegExp("\\b(" + vars.join('|') + ")[$\\w\\.]*\\b", 'g'),
- body = 'return ' + exp.replace(pathRE, function (path) {
- var val = 'this.' + getRel(path, compiler) + path
- accessors += val + ';'
- return val
- })
- body = accessors + body
- return makeGetter(body, exp)
- }
- }
- });
- require.register("seed/src/text-parser.js", function(exports, require, module){
- var BINDING_RE = /\{\{(.+?)\}\}/
- module.exports = {
- /**
- * Parse a piece of text, return an array of tokens
- */
- parse: function (text) {
- if (!BINDING_RE.test(text)) return null
- var m, i, tokens = []
- /* jshint boss: true */
- while (m = text.match(BINDING_RE)) {
- i = m.index
- if (i > 0) tokens.push(text.slice(0, i))
- tokens.push({ key: m[1].trim() })
- text = text.slice(i + m[0].length)
- }
- if (text.length) tokens.push(text)
- return tokens
- }
-
- }
- });
- require.register("seed/src/deps-parser.js", function(exports, require, module){
- var Emitter = require('./emitter'),
- utils = require('./utils'),
- observer = new Emitter()
- /**
- * Auto-extract the dependencies of a computed property
- * by recording the getters triggered when evaluating it.
- */
- function catchDeps (binding) {
- if (binding.isFn) return
- utils.log('\n─ ' + binding.key)
- var depsHash = utils.hash()
- observer.on('get', function (dep) {
- if (depsHash[dep.key]) return
- depsHash[dep.key] = 1
- utils.log(' └─ ' + dep.key)
- binding.deps.push(dep)
- dep.subs.push(binding)
- })
- binding.value.$get()
- observer.off('get')
- }
- module.exports = {
- /**
- * the observer that catches events triggered by getters
- */
- observer: observer,
- /**
- * parse a list of computed property bindings
- */
- parse: function (bindings) {
- utils.log('\nparsing dependencies...')
- observer.active = true
- bindings.forEach(catchDeps)
- observer.active = false
- utils.log('\ndone.')
- }
-
- }
- });
- require.register("seed/src/filters.js", function(exports, require, module){
- var keyCodes = {
- enter : 13,
- tab : 9,
- 'delete' : 46,
- up : 38,
- left : 37,
- right : 39,
- down : 40,
- esc : 27
- }
- module.exports = {
- /**
- * 'abc' => 'Abc'
- */
- capitalize: function (value) {
- if (!value && value !== 0) return ''
- value = value.toString()
- return value.charAt(0).toUpperCase() + value.slice(1)
- },
- /**
- * 'abc' => 'ABC'
- */
- uppercase: function (value) {
- return (value || value === 0)
- ? value.toString().toUpperCase()
- : ''
- },
- /**
- * 'AbC' => 'abc'
- */
- lowercase: function (value) {
- return (value || value === 0)
- ? value.toString().toLowerCase()
- : ''
- },
- /**
- * 12345 => $12,345.00
- */
- currency: function (value, args) {
- if (!value && value !== 0) return ''
- var sign = (args && args[0]) || '$',
- s = Math.floor(value).toString(),
- i = s.length % 3,
- h = i > 0 ? (s.slice(0, i) + (s.length > 3 ? ',' : '')) : '',
- f = '.' + value.toFixed(2).slice(-2)
- return sign + h + s.slice(i).replace(/(\d{3})(?=\d)/g, '$1,') + f
- },
- /**
- * args: an array of strings corresponding to
- * the single, double, triple ... forms of the word to
- * be pluralized. When the number to be pluralized
- * exceeds the length of the args, it will use the last
- * entry in the array.
- *
- * e.g. ['single', 'double', 'triple', 'multiple']
- */
- pluralize: function (value, args) {
- return args.length > 1
- ? (args[value - 1] || args[args.length - 1])
- : (args[value - 1] || args[0] + 's')
- },
- /**
- * A special filter that takes a handler function,
- * wraps it so it only gets triggered on specific keypresses.
- */
- key: function (handler, args) {
- if (!handler) return
- var code = keyCodes[args[0]]
- if (!code) {
- code = parseInt(args[0], 10)
- }
- return function (e) {
- if (e.keyCode === code) {
- handler.call(this, e)
- }
- }
- }
- }
- });
- require.register("seed/src/transition.js", function(exports, require, module){
- var endEvent = sniffTransitionEndEvent(),
- config = require('./config'),
- enterClass = config.enterClass,
- leaveClass = config.leaveClass,
- // exit codes for testing
- codes = {
- CSS_E : 1,
- CSS_L : 2,
- JS_E : 3,
- JS_L : 4,
- CSS_SKIP : -1,
- JS_SKIP : -2,
- JS_SKIP_E : -3,
- JS_SKIP_L : -4,
- INIT : -5,
- SKIP : -6
- }
- /**
- * stage:
- * 1 = enter
- * 2 = leave
- */
- var transition = module.exports = function (el, stage, changeState, compiler) {
- if (compiler.init) {
- changeState()
- return codes.INIT
- }
- var transitionId = el.sd_trans
- if (transitionId) {
- return applyTransitionFunctions(
- el,
- stage,
- changeState,
- transitionId,
- compiler
- )
- } else if (transitionId === '') {
- return applyTransitionClass(
- el,
- stage,
- changeState
- )
- } else {
- changeState()
- return codes.SKIP
- }
- }
- transition.codes = codes
- /**
- * Togggle a CSS class to trigger transition
- */
- function applyTransitionClass (el, stage, changeState) {
- if (!endEvent) {
- changeState()
- return codes.CSS_SKIP
- }
- var classList = el.classList,
- lastLeaveCallback = el.sd_trans_cb
- if (stage > 0) { // enter
- // cancel unfinished leave transition
- if (lastLeaveCallback) {
- el.removeEventListener(endEvent, lastLeaveCallback)
- el.sd_trans_cb = null
- }
- // set to hidden state before appending
- classList.add(enterClass)
- // append
- changeState()
- // force a layout so transition can be triggered
- /* jshint unused: false */
- var forceLayout = el.clientHeight
- // trigger transition
- classList.remove(enterClass)
- return codes.CSS_E
- } else { // leave
- // trigger hide transition
- classList.add(leaveClass)
- var onEnd = function (e) {
- if (e.target === el) {
- el.removeEventListener(endEvent, onEnd)
- el.sd_trans_cb = null
- // actually remove node here
- changeState()
- classList.remove(leaveClass)
- }
- }
- // attach transition end listener
- el.addEventListener(endEvent, onEnd)
- el.sd_trans_cb = onEnd
- return codes.CSS_L
-
- }
- }
- function applyTransitionFunctions (el, stage, changeState, functionId, compiler) {
- var funcs = compiler.getOption('transitions', functionId)
- if (!funcs) {
- changeState()
- return codes.JS_SKIP
- }
- var enter = funcs.enter,
- leave = funcs.leave
- if (stage > 0) { // enter
- if (typeof enter !== 'function') {
- changeState()
- return codes.JS_SKIP_E
- }
- enter(el, changeState)
- return codes.JS_E
- } else { // leave
- if (typeof leave !== 'function') {
- changeState()
- return codes.JS_SKIP_L
- }
- leave(el, changeState)
- return codes.JS_L
- }
- }
- /**
- * Sniff proper transition end event name
- */
- function sniffTransitionEndEvent () {
- var el = document.createElement('seed'),
- defaultEvent = 'transitionend',
- events = {
- 'transition' : defaultEvent,
- 'MozTransition' : defaultEvent,
- 'WebkitTransition' : 'webkitTransitionEnd'
- }
- for (var name in events) {
- if (el.style[name] !== undefined) {
- return events[name]
- }
- }
- }
- });
- require.register("seed/src/directives/index.js", function(exports, require, module){
- var utils = require('../utils'),
- transition = require('../transition')
- module.exports = {
- on : require('./on'),
- repeat : require('./repeat'),
- model : require('./model'),
- 'if' : require('./if'),
- attr: function (value) {
- this.el.setAttribute(this.arg, value)
- },
- text: function (value) {
- this.el.textContent = utils.toText(value)
- },
- html: function (value) {
- this.el.innerHTML = utils.toText(value)
- },
- visible: function (value) {
- this.el.style.visibility = value ? '' : 'hidden'
- },
- show: function (value) {
- var el = this.el,
- target = value ? '' : 'none',
- change = function () {
- el.style.display = target
- }
- transition(el, value ? 1 : -1, change, this.compiler)
- },
- 'class': function (value) {
- if (this.arg) {
- this.el.classList[value ? 'add' : 'remove'](this.arg)
- } else {
- if (this.lastVal) {
- this.el.classList.remove(this.lastVal)
- }
- if (value) {
- this.el.classList.add(value)
- this.lastVal = value
- }
- }
- },
- style: {
- bind: function () {
- this.arg = convertCSSProperty(this.arg)
- },
- update: function (value) {
- this.el.style[this.arg] = value
- }
- }
- }
- /**
- * convert hyphen style CSS property to Camel style
- */
- var CONVERT_RE = /-(.)/g
- function convertCSSProperty (prop) {
- if (prop.charAt(0) === '-') prop = prop.slice(1)
- return prop.replace(CONVERT_RE, function (m, char) {
- return char.toUpperCase()
- })
- }
- });
- require.register("seed/src/directives/if.js", function(exports, require, module){
- var transition = require('../transition')
- module.exports = {
- bind: function () {
- this.parent = this.el.parentNode
- this.ref = document.createComment('sd-if-' + this.key)
- this.el.sd_ref = this.ref
- },
- update: function (value) {
- var el = this.el
- if (!this.parent) { // the node was detached when bound
- if (!el.parentNode) {
- return
- } else {
- this.parent = el.parentNode
- }
- }
- // should always have this.parent if we reach here
- var parent = this.parent,
- ref = this.ref,
- compiler = this.compiler
- if (!value) {
- transition(el, -1, remove, compiler)
- } else {
- transition(el, 1, insert, compiler)
- }
- function remove () {
- if (!el.parentNode) return
- // insert the reference node
- var next = el.nextSibling
- if (next) {
- parent.insertBefore(ref, next)
- } else {
- parent.appendChild(ref)
- }
- parent.removeChild(el)
- }
- function insert () {
- if (el.parentNode) return
- parent.insertBefore(el, ref)
- parent.removeChild(ref)
- }
- },
- unbind: function () {
- this.el.sd_ref = null
- }
- }
- });
- require.register("seed/src/directives/repeat.js", function(exports, require, module){
- var Observer = require('../observer'),
- Emitter = require('../emitter'),
- utils = require('../utils'),
- config = require('../config'),
- transition = require('../transition'),
- ViewModel // lazy def to avoid circular dependency
- /**
- * Mathods that perform precise DOM manipulation
- * based on mutator method triggered
- */
- var mutationHandlers = {
- push: function (m) {
- var i, l = m.args.length,
- base = this.collection.length - l
- for (i = 0; i < l; i++) {
- this.buildItem(m.args[i], base + i)
- }
- },
- pop: function () {
- var vm = this.vms.pop()
- if (vm) vm.$destroy()
- },
- unshift: function (m) {
- var i, l = m.args.length
- for (i = 0; i < l; i++) {
- this.buildItem(m.args[i], i)
- }
- },
- shift: function () {
- var vm = this.vms.shift()
- if (vm) vm.$destroy()
- },
- splice: function (m) {
- var i, l,
- index = m.args[0],
- removed = m.args[1],
- added = m.args.length - 2,
- removedVMs = this.vms.splice(index, removed)
- for (i = 0, l = removedVMs.length; i < l; i++) {
- removedVMs[i].$destroy()
- }
- for (i = 0; i < added; i++) {
- this.buildItem(m.args[i + 2], index + i)
- }
- },
- sort: function () {
- var key = this.arg,
- vms = this.vms,
- col = this.collection,
- l = col.length,
- sorted = new Array(l),
- i, j, vm, data
- for (i = 0; i < l; i++) {
- data = col[i]
- for (j = 0; j < l; j++) {
- vm = vms[j]
- if (vm[key] === data) {
- sorted[i] = vm
- break
- }
- }
- }
- for (i = 0; i < l; i++) {
- this.container.insertBefore(sorted[i].$el, this.ref)
- }
- this.vms = sorted
- },
- reverse: function () {
- var vms = this.vms
- vms.reverse()
- for (var i = 0, l = vms.length; i < l; i++) {
- this.container.insertBefore(vms[i].$el, this.ref)
- }
- }
- }
- module.exports = {
- bind: function () {
- var self = this,
- el = self.el,
- ctn = self.container = el.parentNode
- // extract child VM information, if any
- ViewModel = ViewModel || require('../viewmodel')
- var componentId = utils.attr(el, 'component')
- self.ChildVM = self.compiler.getOption('components', componentId) || ViewModel
- // extract transition information
- self.hasTrans = el.hasAttribute(config.attrs.transition)
- // create a comment node as a reference node for DOM insertions
- self.ref = document.createComment('sd-repeat-' + self.arg)
- ctn.insertBefore(self.ref, el)
- ctn.removeChild(el)
- self.initiated = false
- self.collection = null
- self.vms = null
- self.mutationListener = function (path, arr, mutation) {
- self.detach()
- var method = mutation.method
- mutationHandlers[method].call(self, mutation)
- if (method !== 'push' && method !== 'pop') {
- self.updateIndexes()
- }
- self.retach()
- }
- },
- update: function (collection) {
- this.unbind(true)
- // attach an object to container to hold handlers
- this.container.sd_dHandlers = utils.hash()
- // if initiating with an empty collection, we need to
- // force a compile so that we get all the bindings for
- // dependency extraction.
- if (!this.initiated && (!collection || !collection.length)) {
- this.buildItem()
- this.initiated = true
- }
- this.collection = collection || []
- this.vms = []
- // listen for collection mutation events
- // the collection has been augmented during Binding.set()
- if (!collection.__observer__) Observer.watchArray(collection, null, new Emitter())
- collection.__observer__.on('mutate', this.mutationListener)
- // create child-seeds and append to DOM
- if (collection.length) {
- this.detach()
- for (var i = 0, l = collection.length; i < l; i++) {
- this.buildItem(collection[i], i)
- }
- this.retach()
- }
- },
- /**
- * Create a new child VM from a data object
- * passing along compiler options indicating this
- * is a sd-repeat item.
- */
- buildItem: function (data, index) {
- var node = this.el.cloneNode(true),
- ctn = this.container,
- scope = {},
- ref, item
- // append node into DOM first
- // so sd-if can get access to parentNode
- if (data) {
- ref = this.vms.length > index
- ? this.vms[index].$el
- : this.ref
- // make sure it works with sd-if
- if (!ref.parentNode) ref = ref.sd_ref
- // process transition info before appending
- node.sd_trans = utils.attr(node, 'transition', true)
- transition(node, 1, function () {
- ctn.insertBefore(node, ref)
- }, this.compiler)
- }
- // set data on scope and compile
- scope[this.arg] = data || {}
- item = new this.ChildVM({
- el: node,
- scope: scope,
- compilerOptions: {
- repeat: true,
- repeatIndex: index,
- repeatCollection: this.collection,
- repeatPrefix: this.arg,
- parentCompiler: this.compiler,
- delegator: ctn
- }
- })
- if (!data) {
- // this is a forced compile for an empty collection.
- // let's remove it...
- item.$destroy()
- } else {
- this.vms.splice(index, 0, item)
- }
- },
- /**
- * Update index of each item after a mutation
- */
- updateIndexes: function () {
- var i = this.vms.length
- while (i--) {
- this.vms[i].$index = i
- }
- },
- /**
- * Detach/retach the container from the DOM before mutation
- * so that batch DOM updates are done in-memory and faster
- */
- detach: function () {
- if (this.hasTrans) return
- var c = this.container,
- p = this.parent = c.parentNode
- this.next = c.nextSibling
- if (p) p.removeChild(c)
- },
- retach: function () {
- if (this.hasTrans) return
- var n = this.next,
- p = this.parent,
- c = this.container
- if (!p) return
- if (n) {
- p.insertBefore(c, n)
- } else {
- p.appendChild(c)
- }
- },
- unbind: function () {
- if (this.collection) {
- this.collection.__observer__.off('mutate', this.mutationListener)
- var i = this.vms.length
- while (i--) {
- this.vms[i].$destroy()
- }
- }
- var ctn = this.container,
- handlers = ctn.sd_dHandlers
- for (var key in handlers) {
- ctn.removeEventListener(handlers[key].event, handlers[key])
- }
- ctn.sd_dHandlers = null
- }
- }
- });
- require.register("seed/src/directives/on.js", function(exports, require, module){
- var utils = require('../utils')
- function delegateCheck (el, root, identifier) {
- while (el && el !== root) {
- if (el[identifier]) return el
- el = el.parentNode
- }
- }
- module.exports = {
- isFn: true,
- bind: function () {
- if (this.compiler.repeat) {
- // attach an identifier to the el
- // so it can be matched during event delegation
- this.el[this.expression] = true
- // attach the owner viewmodel of this directive
- this.el.sd_viewmodel = this.vm
- }
- },
- update: function (handler) {
- this.unbind(true)
- if (typeof handler !== 'function') {
- return utils.warn('Directive "on" expects a function value.')
- }
- var compiler = this.compiler,
- event = this.arg,
- ownerVM = this.binding.compiler.vm
- if (compiler.repeat &&
- // do not delegate if the repeat is combined with an extended VM
- !this.vm.constructor.super &&
- // blur and focus events do not bubble
- event !== 'blur' && event !== 'focus') {
- // for each blocks, delegate for better performance
- // focus and blur events dont bubble so exclude them
- var delegator = compiler.delegator,
- identifier = this.expression,
- dHandler = delegator.sd_dHandlers[identifier]
- if (dHandler) return
- // the following only gets run once for the entire each block
- dHandler = delegator.sd_dHandlers[identifier] = function (e) {
- var target = delegateCheck(e.target, delegator, identifier)
- if (target) {
- e.el = target
- e.vm = target.sd_viewmodel
- e.item = e.vm[compiler.repeatPrefix]
- handler.call(ownerVM, e)
- }
- }
- dHandler.event = event
- delegator.addEventListener(event, dHandler)
- } else {
- // a normal, single element handler
- var vm = this.vm
- this.handler = function (e) {
- e.el = e.currentTarget
- e.vm = vm
- if (compiler.repeat) {
- e.item = vm[compiler.repeatPrefix]
- }
- handler.call(ownerVM, e)
- }
- this.el.addEventListener(event, this.handler)
- }
- },
- unbind: function (update) {
- this.el.removeEventListener(this.arg, this.handler)
- this.handler = null
- if (!update) this.el.sd_viewmodel = null
- }
- }
- });
- require.register("seed/src/directives/model.js", function(exports, require, module){
- var utils = require('../utils'),
- isIE9 = navigator.userAgent.indexOf('MSIE 9.0') > 0
- module.exports = {
- bind: function () {
- var self = this,
- el = self.el,
- type = el.type
- self.lock = false
- // determine what event to listen to
- self.event =
- (self.compiler.options.lazy ||
- el.tagName === 'SELECT' ||
- type === 'checkbox' ||
- type === 'radio')
- ? 'change'
- : 'input'
- // determin the attribute to change when updating
- var attr = type === 'checkbox'
- ? 'checked'
- : 'value'
- // attach listener
- self.set = self.filters
- ? function () {
- // if this directive has filters
- // we need to let the vm.$set trigger
- // update() so filters are applied.
- // therefore we have to record cursor position
- // so that after vm.$set changes the input
- // value we can put the cursor back at where it is
- var cursorPos
- try {
- cursorPos = el.selectionStart
- } catch (e) {}
- // `input` event has weird updating issue with
- // International (e.g. Chinese) input methods,
- // have to use a Timeout to hack around it...
- setTimeout(function () {
- self.vm.$set(self.key, el[attr])
- if (cursorPos !== undefined) {
- el.setSelectionRange(cursorPos, cursorPos)
- }
- }, 0)
- }
- : function () {
- // no filters, don't let it trigger update()
- self.lock = true
- self.vm.$set(self.key, el[attr])
- self.lock = false
- }
- el.addEventListener(self.event, self.set)
- // fix shit for IE9
- // since it doesn't fire input on backspace / del / cut
- if (isIE9) {
- self.onCut = function () {
- // cut event fires before the value actually changes
- setTimeout(function () {
- self.set()
- }, 0)
- }
- self.onDel = function (e) {
- if (e.keyCode === 46 || e.keyCode === 8) {
- self.set()
- }
- }
- el.addEventListener('cut', self.onCut)
- el.addEventListener('keyup', self.onDel)
- }
- },
- update: function (value) {
- if (this.lock) return
- /* jshint eqeqeq: false */
- var self = this,
- el = self.el
- if (el.tagName === 'SELECT') { // select dropdown
- // setting <select>'s value in IE9 doesn't work
- var o = el.options,
- i = o.length,
- index = -1
- while (i--) {
- if (o[i].value == value) {
- index = i
- break
- }
- }
- o.selectedIndex = index
- } else if (el.type === 'radio') { // radio button
- el.checked = value == el.value
- } else if (el.type === 'checkbox') { // checkbox
- el.checked = !!value
- } else {
- el.value = utils.toText(value)
- }
- },
- unbind: function () {
- this.el.removeEventListener(this.event, this.set)
- if (isIE9) {
- this.el.removeEventListener('cut', this.onCut)
- this.el.removeEventListener('keyup', this.onDel)
- }
- }
- }
- });
- require.alias("component-emitter/index.js", "seed/deps/emitter/index.js");
- require.alias("component-emitter/index.js", "emitter/index.js");
- require.alias("component-indexof/index.js", "component-emitter/deps/indexof/index.js");
- require.alias("seed/src/main.js", "seed/index.js");if (typeof exports == "object") {
- module.exports = require("seed");
- } else if (typeof define == "function" && define.amd) {
- define(function(){ return require("seed"); });
- } else {
- this["Seed"] = require("seed");
- }})();
|