seed.test.js 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540
  1. /**
  2. * Require the given path.
  3. *
  4. * @param {String} path
  5. * @return {Object} exports
  6. * @api public
  7. */
  8. function require(path, parent, orig) {
  9. var resolved = require.resolve(path);
  10. // lookup failed
  11. if (null == resolved) {
  12. orig = orig || path;
  13. parent = parent || 'root';
  14. var err = new Error('Failed to require "' + orig + '" from "' + parent + '"');
  15. err.path = orig;
  16. err.parent = parent;
  17. err.require = true;
  18. throw err;
  19. }
  20. var module = require.modules[resolved];
  21. // perform real require()
  22. // by invoking the module's
  23. // registered function
  24. if (!module._resolving && !module.exports) {
  25. var mod = {};
  26. mod.exports = {};
  27. mod.client = mod.component = true;
  28. module._resolving = true;
  29. module.call(this, mod.exports, require.relative(resolved), mod);
  30. delete module._resolving;
  31. module.exports = mod.exports;
  32. }
  33. return module.exports;
  34. }
  35. /**
  36. * Registered modules.
  37. */
  38. require.modules = {};
  39. /**
  40. * Registered aliases.
  41. */
  42. require.aliases = {};
  43. /**
  44. * Resolve `path`.
  45. *
  46. * Lookup:
  47. *
  48. * - PATH/index.js
  49. * - PATH.js
  50. * - PATH
  51. *
  52. * @param {String} path
  53. * @return {String} path or null
  54. * @api private
  55. */
  56. require.resolve = function(path) {
  57. if (path.charAt(0) === '/') path = path.slice(1);
  58. var paths = [
  59. path,
  60. path + '.js',
  61. path + '.json',
  62. path + '/index.js',
  63. path + '/index.json'
  64. ];
  65. for (var i = 0; i < paths.length; i++) {
  66. var path = paths[i];
  67. if (require.modules.hasOwnProperty(path)) return path;
  68. if (require.aliases.hasOwnProperty(path)) return require.aliases[path];
  69. }
  70. };
  71. /**
  72. * Normalize `path` relative to the current path.
  73. *
  74. * @param {String} curr
  75. * @param {String} path
  76. * @return {String}
  77. * @api private
  78. */
  79. require.normalize = function(curr, path) {
  80. var segs = [];
  81. if ('.' != path.charAt(0)) return path;
  82. curr = curr.split('/');
  83. path = path.split('/');
  84. for (var i = 0; i < path.length; ++i) {
  85. if ('..' == path[i]) {
  86. curr.pop();
  87. } else if ('.' != path[i] && '' != path[i]) {
  88. segs.push(path[i]);
  89. }
  90. }
  91. return curr.concat(segs).join('/');
  92. };
  93. /**
  94. * Register module at `path` with callback `definition`.
  95. *
  96. * @param {String} path
  97. * @param {Function} definition
  98. * @api private
  99. */
  100. require.register = function(path, definition) {
  101. require.modules[path] = definition;
  102. };
  103. /**
  104. * Alias a module definition.
  105. *
  106. * @param {String} from
  107. * @param {String} to
  108. * @api private
  109. */
  110. require.alias = function(from, to) {
  111. if (!require.modules.hasOwnProperty(from)) {
  112. throw new Error('Failed to alias "' + from + '", it does not exist');
  113. }
  114. require.aliases[to] = from;
  115. };
  116. /**
  117. * Return a require function relative to the `parent` path.
  118. *
  119. * @param {String} parent
  120. * @return {Function}
  121. * @api private
  122. */
  123. require.relative = function(parent) {
  124. var p = require.normalize(parent, '..');
  125. /**
  126. * lastIndexOf helper.
  127. */
  128. function lastIndexOf(arr, obj) {
  129. var i = arr.length;
  130. while (i--) {
  131. if (arr[i] === obj) return i;
  132. }
  133. return -1;
  134. }
  135. /**
  136. * The relative require() itself.
  137. */
  138. function localRequire(path) {
  139. var resolved = localRequire.resolve(path);
  140. return require(resolved, parent, path);
  141. }
  142. /**
  143. * Resolve relative to the parent.
  144. */
  145. localRequire.resolve = function(path) {
  146. var c = path.charAt(0);
  147. if ('/' == c) return path.slice(1);
  148. if ('.' == c) return require.normalize(p, path);
  149. // resolve deps by returning
  150. // the dep in the nearest "deps"
  151. // directory
  152. var segs = parent.split('/');
  153. var i = lastIndexOf(segs, 'deps') + 1;
  154. if (!i) i = 0;
  155. path = segs.slice(0, i + 1).join('/') + '/deps/' + path;
  156. return path;
  157. };
  158. /**
  159. * Check if module is defined at `path`.
  160. */
  161. localRequire.exists = function(path) {
  162. return require.modules.hasOwnProperty(localRequire.resolve(path));
  163. };
  164. return localRequire;
  165. };
  166. require.register("component-indexof/index.js", function(exports, require, module){
  167. var indexOf = [].indexOf;
  168. module.exports = function(arr, obj){
  169. if (indexOf) return arr.indexOf(obj);
  170. for (var i = 0; i < arr.length; ++i) {
  171. if (arr[i] === obj) return i;
  172. }
  173. return -1;
  174. };
  175. });
  176. require.register("component-emitter/index.js", function(exports, require, module){
  177. /**
  178. * Module dependencies.
  179. */
  180. var index = require('indexof');
  181. /**
  182. * Expose `Emitter`.
  183. */
  184. module.exports = Emitter;
  185. /**
  186. * Initialize a new `Emitter`.
  187. *
  188. * @api public
  189. */
  190. function Emitter(obj) {
  191. if (obj) return mixin(obj);
  192. };
  193. /**
  194. * Mixin the emitter properties.
  195. *
  196. * @param {Object} obj
  197. * @return {Object}
  198. * @api private
  199. */
  200. function mixin(obj) {
  201. for (var key in Emitter.prototype) {
  202. obj[key] = Emitter.prototype[key];
  203. }
  204. return obj;
  205. }
  206. /**
  207. * Listen on the given `event` with `fn`.
  208. *
  209. * @param {String} event
  210. * @param {Function} fn
  211. * @return {Emitter}
  212. * @api public
  213. */
  214. Emitter.prototype.on = function(event, fn){
  215. this._callbacks = this._callbacks || {};
  216. (this._callbacks[event] = this._callbacks[event] || [])
  217. .push(fn);
  218. return this;
  219. };
  220. /**
  221. * Adds an `event` listener that will be invoked a single
  222. * time then automatically removed.
  223. *
  224. * @param {String} event
  225. * @param {Function} fn
  226. * @return {Emitter}
  227. * @api public
  228. */
  229. Emitter.prototype.once = function(event, fn){
  230. var self = this;
  231. this._callbacks = this._callbacks || {};
  232. function on() {
  233. self.off(event, on);
  234. fn.apply(this, arguments);
  235. }
  236. fn._off = on;
  237. this.on(event, on);
  238. return this;
  239. };
  240. /**
  241. * Remove the given callback for `event` or all
  242. * registered callbacks.
  243. *
  244. * @param {String} event
  245. * @param {Function} fn
  246. * @return {Emitter}
  247. * @api public
  248. */
  249. Emitter.prototype.off =
  250. Emitter.prototype.removeListener =
  251. Emitter.prototype.removeAllListeners = function(event, fn){
  252. this._callbacks = this._callbacks || {};
  253. // all
  254. if (0 == arguments.length) {
  255. this._callbacks = {};
  256. return this;
  257. }
  258. // specific event
  259. var callbacks = this._callbacks[event];
  260. if (!callbacks) return this;
  261. // remove all handlers
  262. if (1 == arguments.length) {
  263. delete this._callbacks[event];
  264. return this;
  265. }
  266. // remove specific handler
  267. var i = index(callbacks, fn._off || fn);
  268. if (~i) callbacks.splice(i, 1);
  269. return this;
  270. };
  271. /**
  272. * Emit `event` with the given args.
  273. *
  274. * @param {String} event
  275. * @param {Mixed} ...
  276. * @return {Emitter}
  277. */
  278. Emitter.prototype.emit = function(event){
  279. this._callbacks = this._callbacks || {};
  280. var args = [].slice.call(arguments, 1)
  281. , callbacks = this._callbacks[event];
  282. if (callbacks) {
  283. callbacks = callbacks.slice(0);
  284. for (var i = 0, len = callbacks.length; i < len; ++i) {
  285. callbacks[i].apply(this, args);
  286. }
  287. }
  288. return this;
  289. };
  290. /**
  291. * Return array of callbacks for `event`.
  292. *
  293. * @param {String} event
  294. * @return {Array}
  295. * @api public
  296. */
  297. Emitter.prototype.listeners = function(event){
  298. this._callbacks = this._callbacks || {};
  299. return this._callbacks[event] || [];
  300. };
  301. /**
  302. * Check if this emitter has `event` handlers.
  303. *
  304. * @param {String} event
  305. * @return {Boolean}
  306. * @api public
  307. */
  308. Emitter.prototype.hasListeners = function(event){
  309. return !! this.listeners(event).length;
  310. };
  311. });
  312. require.register("seed/src/main.js", function(exports, require, module){
  313. var config = require('./config'),
  314. ViewModel = require('./viewmodel'),
  315. directives = require('./directives'),
  316. filters = require('./filters'),
  317. utils = require('./utils')
  318. /*
  319. * Set config options
  320. */
  321. ViewModel.config = function (opts) {
  322. if (opts) {
  323. utils.extend(config, opts)
  324. }
  325. }
  326. /*
  327. * Allows user to register/retrieve a directive definition
  328. */
  329. ViewModel.directive = function (id, fn) {
  330. if (!fn) return directives[id]
  331. directives[id] = fn
  332. }
  333. /*
  334. * Allows user to register/retrieve a filter function
  335. */
  336. ViewModel.filter = function (id, fn) {
  337. if (!fn) return filters[id]
  338. filters[id] = fn
  339. }
  340. /*
  341. * Allows user to register/retrieve a ViewModel constructor
  342. */
  343. ViewModel.vm = function (id, Ctor) {
  344. if (!Ctor) return utils.vms[id]
  345. utils.vms[id] = Ctor
  346. }
  347. /*
  348. * Allows user to register/retrieve a template partial
  349. */
  350. ViewModel.partial = function (id, partial) {
  351. if (!partial) return utils.partials[id]
  352. utils.partials[id] = templateToFragment(partial)
  353. }
  354. /*
  355. * Allows user to register/retrieve a transition definition object
  356. */
  357. ViewModel.transition = function (id, transition) {
  358. if (!transition) return utils.transitions[id]
  359. utils.transitions[id] = transition
  360. }
  361. ViewModel.extend = extend
  362. /*
  363. * Expose the main ViewModel class
  364. * and add extend method
  365. */
  366. function extend (options) {
  367. var ParentVM = this
  368. // inherit options
  369. options = inheritOptions(options, ParentVM.options, true)
  370. var ExtendedVM = function (opts) {
  371. opts = inheritOptions(opts, options, true)
  372. ParentVM.call(this, opts)
  373. }
  374. // inherit prototype props
  375. var proto = ExtendedVM.prototype = Object.create(ParentVM.prototype)
  376. utils.defProtected(proto, 'constructor', ExtendedVM)
  377. // copy prototype props
  378. var protoMixins = options.proto
  379. if (protoMixins) {
  380. for (var key in protoMixins) {
  381. if (!(key in ViewModel.prototype)) {
  382. proto[key] = protoMixins[key]
  383. }
  384. }
  385. }
  386. // convert template to documentFragment
  387. if (options.template) {
  388. options.templateFragment = templateToFragment(options.template)
  389. }
  390. // allow extended VM to be further extended
  391. ExtendedVM.extend = extend
  392. ExtendedVM.super = ParentVM
  393. ExtendedVM.options = options
  394. return ExtendedVM
  395. }
  396. /*
  397. * Inherit options
  398. *
  399. * For options such as `scope`, `vms`, `directives`, 'partials',
  400. * they should be further extended. However extending should only
  401. * be done at top level.
  402. *
  403. * `proto` is an exception because it's handled directly on the
  404. * prototype.
  405. *
  406. * `el` is an exception because it's not allowed as an
  407. * extension option, but only as an instance option.
  408. */
  409. function inheritOptions (child, parent, topLevel) {
  410. child = child || {}
  411. convertPartials(child.partials)
  412. if (!parent) return child
  413. for (var key in parent) {
  414. if (key === 'el' || key === 'proto') continue
  415. if (!child[key]) { // child has priority
  416. child[key] = parent[key]
  417. } else if (topLevel && utils.typeOf(child[key]) === 'Object') {
  418. inheritOptions(child[key], parent[key], false)
  419. }
  420. }
  421. return child
  422. }
  423. /*
  424. * Convert an object of partials to dom fragments
  425. */
  426. function convertPartials (partials) {
  427. if (!partials) return
  428. for (var key in partials) {
  429. if (typeof partials[key] === 'string') {
  430. partials[key] = templateToFragment(partials[key])
  431. }
  432. }
  433. }
  434. /*
  435. * Convert a string template to a dom fragment
  436. */
  437. function templateToFragment (template) {
  438. if (template.charAt(0) === '#') {
  439. var templateNode = document.querySelector(template)
  440. if (!templateNode) return
  441. template = templateNode.innerHTML
  442. }
  443. var node = document.createElement('div'),
  444. frag = document.createDocumentFragment(),
  445. child
  446. node.innerHTML = template.trim()
  447. /* jshint boss: true */
  448. while (child = node.firstChild) {
  449. frag.appendChild(child)
  450. }
  451. return frag
  452. }
  453. module.exports = ViewModel
  454. });
  455. require.register("seed/src/emitter.js", function(exports, require, module){
  456. // shiv to make this work for Component, Browserify and Node at the same time.
  457. var Emitter,
  458. componentEmitter = 'emitter'
  459. try {
  460. // Requiring without a string literal will make browserify
  461. // unable to parse the dependency, thus preventing it from
  462. // stopping the compilation after a failed lookup.
  463. Emitter = require(componentEmitter)
  464. } catch (e) {}
  465. module.exports = Emitter || require('events').EventEmitter
  466. });
  467. require.register("seed/src/config.js", function(exports, require, module){
  468. module.exports = {
  469. prefix : 'sd',
  470. debug : false
  471. }
  472. });
  473. require.register("seed/src/utils.js", function(exports, require, module){
  474. var config = require('./config'),
  475. toString = Object.prototype.toString,
  476. join = Array.prototype.join,
  477. console = window.console
  478. module.exports = {
  479. // global storage for user-registered
  480. // vms, partials and transitions
  481. vms : {},
  482. partials : {},
  483. transitions : {},
  484. /*
  485. * Define an ienumerable property
  486. * This avoids it being included in JSON.stringify
  487. * or for...in loops.
  488. */
  489. defProtected: function (obj, key, val, enumerable) {
  490. if (obj.hasOwnProperty(key)) return
  491. Object.defineProperty(obj, key, {
  492. enumerable: !!enumerable,
  493. configurable: false,
  494. value: val
  495. })
  496. },
  497. /*
  498. * Accurate type check
  499. */
  500. typeOf: function (obj) {
  501. return toString.call(obj).slice(8, -1)
  502. },
  503. /*
  504. * Make sure only strings and numbers are output to html
  505. * output empty string is value is not string or number
  506. */
  507. toText: function (value) {
  508. /* jshint eqeqeq: false */
  509. return (typeof value === 'string' ||
  510. (typeof value === 'number' && value == value)) // deal with NaN
  511. ? value
  512. : ''
  513. },
  514. /*
  515. * simple extend
  516. */
  517. extend: function (obj, ext, protective) {
  518. if (!ext) return
  519. for (var key in ext) {
  520. if (protective && obj[key]) continue
  521. obj[key] = ext[key]
  522. }
  523. },
  524. /*
  525. * log for debugging
  526. */
  527. log: function () {
  528. if (config.debug && console) {
  529. console.log(join.call(arguments, ' '))
  530. }
  531. },
  532. /*
  533. * warn for debugging
  534. */
  535. warn: function() {
  536. if (config.debug && console) {
  537. console.warn(join.call(arguments, ' '))
  538. }
  539. }
  540. }
  541. });
  542. require.register("seed/src/compiler.js", function(exports, require, module){
  543. var Emitter = require('./emitter'),
  544. Observer = require('./observer'),
  545. config = require('./config'),
  546. utils = require('./utils'),
  547. Binding = require('./binding'),
  548. Directive = require('./directive'),
  549. TextParser = require('./text-parser'),
  550. DepsParser = require('./deps-parser'),
  551. ExpParser = require('./exp-parser'),
  552. slice = Array.prototype.slice,
  553. log = utils.log,
  554. vmAttr,
  555. repeatAttr,
  556. partialAttr,
  557. transitionAttr,
  558. preAttr
  559. /*
  560. * The DOM compiler
  561. * scans a DOM node and compile bindings for a ViewModel
  562. */
  563. function Compiler (vm, options) {
  564. refreshPrefix()
  565. var compiler = this
  566. // extend options
  567. options = compiler.options = options || {}
  568. utils.extend(compiler, options.compilerOptions)
  569. // initialize element
  570. compiler.setupElement(options)
  571. log('\nnew VM instance:', compiler.el.tagName, '\n')
  572. // copy scope properties to vm
  573. var scope = options.scope
  574. if (scope) utils.extend(vm, scope, true)
  575. compiler.vm = vm
  576. vm.$compiler = compiler
  577. vm.$el = compiler.el
  578. // keep track of directives and expressions
  579. // so they can be unbound during destroy()
  580. compiler.dirs = []
  581. compiler.exps = []
  582. compiler.childCompilers = [] // keep track of child compilers
  583. compiler.emitter = new Emitter() // the emitter used for nested VM communication
  584. // Store things during parsing to be processed afterwards,
  585. // because we want to have created all bindings before
  586. // observing values / parsing dependencies.
  587. var observables = compiler.observables = [],
  588. computed = compiler.computed = []
  589. // prototypal inheritance of bindings
  590. var parent = compiler.parentCompiler
  591. compiler.bindings = parent
  592. ? Object.create(parent.bindings)
  593. : {}
  594. compiler.rootCompiler = parent
  595. ? getRoot(parent)
  596. : compiler
  597. // setup observer
  598. compiler.setupObserver()
  599. // call user init. this will capture some initial values.
  600. if (options.init) {
  601. options.init.apply(vm, options.args || [])
  602. }
  603. // create bindings for keys set on the vm by the user
  604. var key, keyPrefix
  605. for (key in vm) {
  606. keyPrefix = key.charAt(0)
  607. if (keyPrefix !== '$' && keyPrefix !== '_') {
  608. compiler.createBinding(key)
  609. }
  610. }
  611. // for repeated items, create an index binding
  612. if (compiler.repeat) {
  613. vm[compiler.repeatPrefix].$index = compiler.repeatIndex
  614. }
  615. // now parse the DOM, during which we will create necessary bindings
  616. // and bind the parsed directives
  617. compiler.compile(compiler.el, true)
  618. // observe root values so that they emit events when
  619. // their nested values change (for an Object)
  620. // or when they mutate (for an Array)
  621. var i = observables.length, binding
  622. while (i--) {
  623. binding = observables[i]
  624. Observer.observe(binding.value, binding.key, compiler.observer)
  625. }
  626. // extract dependencies for computed properties
  627. if (computed.length) DepsParser.parse(computed)
  628. // unset these no longer needed stuff
  629. compiler.observables = compiler.computed = compiler.arrays = null
  630. }
  631. var CompilerProto = Compiler.prototype
  632. /*
  633. * Initialize the VM/Compiler's element.
  634. * Fill it in with the template if necessary.
  635. */
  636. CompilerProto.setupElement = function (options) {
  637. // create the node first
  638. var el = this.el = typeof options.el === 'string'
  639. ? document.querySelector(options.el)
  640. : options.el || document.createElement(options.tagName || 'div')
  641. // apply element options
  642. if (options.id) el.id = options.id
  643. if (options.className) el.className = options.className
  644. var attrs = options.attributes
  645. if (attrs) {
  646. for (var attr in attrs) {
  647. el.setAttribute(attr, attrs[attr])
  648. }
  649. }
  650. // initialize template
  651. var template = options.template
  652. if (typeof template === 'string') {
  653. if (template.charAt(0) === '#') {
  654. var templateNode = document.querySelector(template)
  655. if (templateNode) {
  656. el.innerHTML = templateNode.innerHTML
  657. }
  658. } else {
  659. el.innerHTML = template
  660. }
  661. } else if (options.templateFragment) {
  662. el.innerHTML = ''
  663. el.appendChild(options.templateFragment.cloneNode(true))
  664. }
  665. }
  666. /*
  667. * Setup observer.
  668. * The observer listens for get/set/mutate events on all VM
  669. * values/objects and trigger corresponding binding updates.
  670. */
  671. CompilerProto.setupObserver = function () {
  672. var bindings = this.bindings,
  673. observer = this.observer = new Emitter(),
  674. depsOb = DepsParser.observer
  675. // a hash to hold event proxies for each root level key
  676. // so they can be referenced and removed later
  677. observer.proxies = {}
  678. // add own listeners which trigger binding updates
  679. observer
  680. .on('get', function (key) {
  681. if (bindings[key] && depsOb.isObserving) {
  682. depsOb.emit('get', bindings[key])
  683. }
  684. })
  685. .on('set', function (key, val) {
  686. observer.emit('change:' + key, val)
  687. if (bindings[key]) bindings[key].update(val)
  688. })
  689. .on('mutate', function (key, val, mutation) {
  690. observer.emit('change:' + key, val, mutation)
  691. if (bindings[key]) bindings[key].pub()
  692. })
  693. }
  694. /*
  695. * Compile a DOM node (recursive)
  696. */
  697. CompilerProto.compile = function (node, root) {
  698. var compiler = this
  699. if (node.nodeType === 1) {
  700. // a normal node
  701. if (node.hasAttribute(preAttr)) return
  702. var repeatExp = node.getAttribute(repeatAttr),
  703. vmId = node.getAttribute(vmAttr),
  704. partialId = node.getAttribute(partialAttr)
  705. // we need to check for any possbile special directives
  706. // e.g. sd-repeat, sd-viewmodel & sd-partial
  707. if (repeatExp) { // repeat block
  708. var directive = Directive.parse(repeatAttr, repeatExp, compiler, node)
  709. if (directive) {
  710. compiler.bindDirective(directive)
  711. }
  712. } else if (vmId && !root) { // child ViewModels
  713. node.removeAttribute(vmAttr)
  714. var ChildVM = compiler.getOption('vms', vmId)
  715. if (ChildVM) {
  716. var child = new ChildVM({
  717. el: node,
  718. child: true,
  719. compilerOptions: {
  720. parentCompiler: compiler
  721. }
  722. })
  723. compiler.childCompilers.push(child.$compiler)
  724. }
  725. } else {
  726. if (partialId) { // replace innerHTML with partial
  727. node.removeAttribute(partialAttr)
  728. var partial = compiler.getOption('partials', partialId)
  729. if (partial) {
  730. node.innerHTML = ''
  731. node.appendChild(partial.cloneNode(true))
  732. }
  733. }
  734. // finally, only normal directives left!
  735. compiler.compileNode(node)
  736. }
  737. } else if (node.nodeType === 3) { // text node
  738. compiler.compileTextNode(node)
  739. }
  740. }
  741. /*
  742. * Compile a normal node
  743. */
  744. CompilerProto.compileNode = function (node) {
  745. var i, j
  746. // parse if has attributes
  747. if (node.attributes && node.attributes.length) {
  748. var attrs = slice.call(node.attributes),
  749. attr, valid, exps, exp
  750. // loop through all attributes
  751. i = attrs.length
  752. while (i--) {
  753. attr = attrs[i]
  754. valid = false
  755. exps = attr.value.split(',')
  756. // loop through clauses (separated by ",")
  757. // inside each attribute
  758. j = exps.length
  759. while (j--) {
  760. exp = exps[j]
  761. var directive = Directive.parse(attr.name, exp, this, node)
  762. if (directive) {
  763. valid = true
  764. this.bindDirective(directive)
  765. }
  766. }
  767. if (valid) node.removeAttribute(attr.name)
  768. }
  769. }
  770. // recursively compile childNodes
  771. if (node.childNodes.length) {
  772. var nodes = slice.call(node.childNodes)
  773. for (i = 0, j = nodes.length; i < j; i++) {
  774. this.compile(nodes[i])
  775. }
  776. }
  777. }
  778. /*
  779. * Compile a text node
  780. */
  781. CompilerProto.compileTextNode = function (node) {
  782. var tokens = TextParser.parse(node.nodeValue)
  783. if (!tokens) return
  784. var dirname = config.prefix + '-text',
  785. el, token, directive
  786. for (var i = 0, l = tokens.length; i < l; i++) {
  787. token = tokens[i]
  788. if (token.key) { // a binding
  789. if (token.key.charAt(0) === '>') { // a partial
  790. var partialId = token.key.slice(1).trim(),
  791. partial = this.getOption('partials', partialId)
  792. if (partial) {
  793. el = partial.cloneNode(true)
  794. this.compileNode(el)
  795. }
  796. } else { // a binding
  797. el = document.createTextNode('')
  798. directive = Directive.parse(dirname, token.key, this, el)
  799. if (directive) {
  800. this.bindDirective(directive)
  801. }
  802. }
  803. } else { // a plain string
  804. el = document.createTextNode(token)
  805. }
  806. node.parentNode.insertBefore(el, node)
  807. }
  808. node.parentNode.removeChild(node)
  809. }
  810. /*
  811. * Add a directive instance to the correct binding & viewmodel
  812. */
  813. CompilerProto.bindDirective = function (directive) {
  814. var binding,
  815. compiler = this,
  816. key = directive.key,
  817. baseKey = key.split('.')[0],
  818. ownerCompiler = traceOwnerCompiler(directive, compiler)
  819. compiler.dirs.push(directive)
  820. if (directive.isExp) {
  821. binding = compiler.createBinding(key, true)
  822. } else if (ownerCompiler.vm.hasOwnProperty(baseKey)) {
  823. // if the value is present in the target VM, we create the binding on its compiler
  824. binding = ownerCompiler.bindings.hasOwnProperty(key)
  825. ? ownerCompiler.bindings[key]
  826. : ownerCompiler.createBinding(key)
  827. } else {
  828. // due to prototypal inheritance of bindings, if a key doesn't exist here,
  829. // it doesn't exist in the whole prototype chain. Therefore in that case
  830. // we create the new binding at the root level.
  831. binding = ownerCompiler.bindings[key] || compiler.rootCompiler.createBinding(key)
  832. }
  833. binding.instances.push(directive)
  834. directive.binding = binding
  835. // for newly inserted sub-VMs (repeat items), need to bind deps
  836. // because they didn't get processed when the parent compiler
  837. // was binding dependencies.
  838. var i, dep, deps = binding.contextDeps
  839. if (deps) {
  840. i = deps.length
  841. while (i--) {
  842. dep = compiler.bindings[deps[i]]
  843. dep.subs.push(directive)
  844. }
  845. }
  846. var value = binding.value
  847. // invoke bind hook if exists
  848. if (directive.bind) {
  849. directive.bind(value)
  850. }
  851. // set initial value
  852. if (binding.isComputed) {
  853. directive.refresh(value)
  854. } else {
  855. directive.update(value, true)
  856. }
  857. }
  858. /*
  859. * Create binding and attach getter/setter for a key to the viewmodel object
  860. */
  861. CompilerProto.createBinding = function (key, isExp) {
  862. var compiler = this,
  863. bindings = compiler.bindings,
  864. binding = new Binding(compiler, key, isExp)
  865. if (isExp) {
  866. // a complex expression binding
  867. // we need to generate an anonymous computed property for it
  868. var result = ExpParser.parse(key)
  869. if (result) {
  870. log(' created anonymous binding: ' + key)
  871. binding.value = { get: result.getter }
  872. compiler.markComputed(binding)
  873. compiler.exps.push(binding)
  874. // need to create the bindings for keys
  875. // that do not exist yet
  876. var i = result.vars.length, v
  877. while (i--) {
  878. v = result.vars[i]
  879. if (!bindings[v]) {
  880. compiler.rootCompiler.createBinding(v)
  881. }
  882. }
  883. } else {
  884. utils.warn(' invalid expression: ' + key)
  885. }
  886. } else {
  887. log(' created binding: ' + key)
  888. bindings[key] = binding
  889. // make sure the key exists in the object so it can be observed
  890. // by the Observer!
  891. compiler.ensurePath(key)
  892. if (binding.root) {
  893. // this is a root level binding. we need to define getter/setters for it.
  894. compiler.define(key, binding)
  895. } else {
  896. var parentKey = key.slice(0, key.lastIndexOf('.'))
  897. if (!bindings.hasOwnProperty(parentKey)) {
  898. // this is a nested value binding, but the binding for its parent
  899. // has not been created yet. We better create that one too.
  900. compiler.createBinding(parentKey)
  901. }
  902. }
  903. }
  904. return binding
  905. }
  906. /*
  907. * Sometimes when a binding is found in the template, the value might
  908. * have not been set on the VM yet. To ensure computed properties and
  909. * dependency extraction can work, we have to create a dummy value for
  910. * any given path.
  911. */
  912. CompilerProto.ensurePath = function (key) {
  913. var path = key.split('.'), sec, obj = this.vm
  914. for (var i = 0, d = path.length - 1; i < d; i++) {
  915. sec = path[i]
  916. if (!obj[sec]) obj[sec] = {}
  917. obj = obj[sec]
  918. }
  919. if (utils.typeOf(obj) === 'Object') {
  920. sec = path[i]
  921. if (!(sec in obj)) obj[sec] = undefined
  922. }
  923. }
  924. /*
  925. * Defines the getter/setter for a root-level binding on the VM
  926. * and observe the initial value
  927. */
  928. CompilerProto.define = function (key, binding) {
  929. log(' defined root binding: ' + key)
  930. var compiler = this,
  931. vm = compiler.vm,
  932. ob = compiler.observer,
  933. value = binding.value = vm[key], // save the value before redefinening it
  934. type = utils.typeOf(value)
  935. if (type === 'Object' && value.get) {
  936. // computed property
  937. compiler.markComputed(binding)
  938. } else if (type === 'Object' || type === 'Array') {
  939. // observe objects later, becase there might be more keys
  940. // to be added to it. we also want to emit all the set events
  941. // after all values are available.
  942. compiler.observables.push(binding)
  943. }
  944. Object.defineProperty(vm, key, {
  945. enumerable: true,
  946. get: function () {
  947. var value = binding.value
  948. if ((!binding.isComputed && (!value || !value.__observer__)) ||
  949. Array.isArray(value)) {
  950. // only emit non-computed, non-observed (primitive) values, or Arrays.
  951. // because these are the cleanest dependencies
  952. ob.emit('get', key)
  953. }
  954. return binding.isComputed
  955. ? value.get()
  956. : value
  957. },
  958. set: function (newVal) {
  959. var value = binding.value
  960. if (binding.isComputed) {
  961. if (value.set) {
  962. value.set(newVal)
  963. }
  964. } else if (newVal !== value) {
  965. // unwatch the old value
  966. Observer.unobserve(value, key, ob)
  967. // set new value
  968. binding.value = newVal
  969. ob.emit('set', key, newVal)
  970. // now watch the new value, which in turn emits 'set'
  971. // for all its nested values
  972. Observer.observe(newVal, key, ob)
  973. }
  974. }
  975. })
  976. }
  977. /*
  978. * Process a computed property binding
  979. */
  980. CompilerProto.markComputed = function (binding) {
  981. var value = binding.value,
  982. vm = this.vm
  983. binding.isComputed = true
  984. // bind the accessors to the vm
  985. value.get = value.get.bind(vm)
  986. if (value.set) value.set = value.set.bind(vm)
  987. // keep track for dep parsing later
  988. this.computed.push(binding)
  989. }
  990. /*
  991. * Process subscriptions for computed properties that has
  992. * dynamic context dependencies
  993. */
  994. CompilerProto.bindContexts = function (bindings) {
  995. var i = bindings.length, j, k, binding, depKey, dep, ins
  996. while (i--) {
  997. binding = bindings[i]
  998. j = binding.contextDeps.length
  999. while (j--) {
  1000. depKey = binding.contextDeps[j]
  1001. k = binding.instances.length
  1002. while (k--) {
  1003. ins = binding.instances[k]
  1004. dep = ins.compiler.bindings[depKey]
  1005. dep.subs.push(ins)
  1006. }
  1007. }
  1008. }
  1009. }
  1010. /*
  1011. * Retrive an option from the compiler
  1012. */
  1013. CompilerProto.getOption = function (type, id) {
  1014. var opts = this.options
  1015. return (opts[type] && opts[type][id]) || (utils[type] && utils[type][id])
  1016. }
  1017. /*
  1018. * Unbind and remove element
  1019. */
  1020. CompilerProto.destroy = function () {
  1021. var compiler = this
  1022. log('compiler destroyed: ', compiler.vm.$el)
  1023. // unwatch
  1024. compiler.observer.off()
  1025. compiler.emitter.off()
  1026. var i, key, dir, inss, binding,
  1027. el = compiler.el,
  1028. directives = compiler.dirs,
  1029. exps = compiler.exps,
  1030. bindings = compiler.bindings
  1031. // remove all directives that are instances of external bindings
  1032. i = directives.length
  1033. while (i--) {
  1034. dir = directives[i]
  1035. if (dir.binding.compiler !== compiler) {
  1036. inss = dir.binding.instances
  1037. if (inss) inss.splice(inss.indexOf(dir), 1)
  1038. }
  1039. dir.unbind()
  1040. }
  1041. // unbind all expressions (anonymous bindings)
  1042. i = exps.length
  1043. while (i--) {
  1044. exps[i].unbind()
  1045. }
  1046. // unbind/unobserve all own bindings
  1047. for (key in bindings) {
  1048. if (bindings.hasOwnProperty(key)) {
  1049. binding = bindings[key]
  1050. if (binding.root) {
  1051. Observer.unobserve(binding.value, binding.key, compiler.observer)
  1052. }
  1053. binding.unbind()
  1054. }
  1055. }
  1056. // remove self from parentCompiler
  1057. var parent = compiler.parentCompiler
  1058. if (parent) {
  1059. parent.childCompilers.splice(parent.childCompilers.indexOf(compiler), 1)
  1060. }
  1061. // remove el
  1062. if (el === document.body) {
  1063. el.innerHTML = ''
  1064. } else if (el.parentNode) {
  1065. el.parentNode.removeChild(el)
  1066. }
  1067. }
  1068. // Helpers --------------------------------------------------------------------
  1069. /*
  1070. * Refresh prefix in case it has been changed
  1071. * during compilations
  1072. */
  1073. function refreshPrefix () {
  1074. var prefix = config.prefix
  1075. repeatAttr = prefix + '-repeat'
  1076. vmAttr = prefix + '-viewmodel'
  1077. partialAttr = prefix + '-partial'
  1078. transitionAttr = prefix + '-transition'
  1079. preAttr = prefix + '-pre'
  1080. }
  1081. /*
  1082. * determine which viewmodel a key belongs to based on nesting symbols
  1083. */
  1084. function traceOwnerCompiler (key, compiler) {
  1085. if (key.nesting) {
  1086. var levels = key.nesting
  1087. while (compiler.parentCompiler && levels--) {
  1088. compiler = compiler.parentCompiler
  1089. }
  1090. } else if (key.root) {
  1091. while (compiler.parentCompiler) {
  1092. compiler = compiler.parentCompiler
  1093. }
  1094. }
  1095. return compiler
  1096. }
  1097. /*
  1098. * shorthand for getting root compiler
  1099. */
  1100. function getRoot (compiler) {
  1101. return traceOwnerCompiler({ root: true }, compiler)
  1102. }
  1103. module.exports = Compiler
  1104. });
  1105. require.register("seed/src/viewmodel.js", function(exports, require, module){
  1106. var Compiler = require('./compiler')
  1107. /*
  1108. * ViewModel exposed to the user that holds data,
  1109. * computed properties, event handlers
  1110. * and a few reserved methods
  1111. */
  1112. function ViewModel (options) {
  1113. // just compile. options are passed directly to compiler
  1114. new Compiler(this, options)
  1115. }
  1116. var VMProto = ViewModel.prototype
  1117. /*
  1118. * Convenience function to set an actual nested value
  1119. * from a flat key string. Used in directives.
  1120. */
  1121. VMProto.$set = function (key, value) {
  1122. var path = key.split('.'),
  1123. obj = getTargetVM(this, path)
  1124. if (!obj) return
  1125. for (var d = 0, l = path.length - 1; d < l; d++) {
  1126. obj = obj[path[d]]
  1127. }
  1128. obj[path[d]] = value
  1129. }
  1130. /*
  1131. * The function for getting a key
  1132. * which will go up along the prototype chain of the bindings
  1133. * Used in exp-parser.
  1134. */
  1135. VMProto.$get = function (key) {
  1136. var path = key.split('.'),
  1137. obj = getTargetVM(this, path),
  1138. vm = obj
  1139. if (!obj) return
  1140. for (var d = 0, l = path.length; d < l; d++) {
  1141. obj = obj[path[d]]
  1142. }
  1143. if (typeof obj === 'function') obj = obj.bind(vm)
  1144. return obj
  1145. }
  1146. /*
  1147. * watch a key on the viewmodel for changes
  1148. * fire callback with new value
  1149. */
  1150. VMProto.$watch = function (key, callback) {
  1151. this.$compiler.observer.on('change:' + key, callback)
  1152. }
  1153. /*
  1154. * unwatch a key
  1155. */
  1156. VMProto.$unwatch = function (key, callback) {
  1157. // workaround here
  1158. // since the emitter module checks callback existence
  1159. // by checking the length of arguments
  1160. var args = ['change:' + key],
  1161. ob = this.$compiler.observer
  1162. if (callback) args.push(callback)
  1163. ob.off.apply(ob, args)
  1164. }
  1165. /*
  1166. * unbind everything, remove everything
  1167. */
  1168. VMProto.$destroy = function () {
  1169. this.$compiler.destroy()
  1170. this.$compiler = null
  1171. }
  1172. /*
  1173. * broadcast an event to all child VMs recursively.
  1174. */
  1175. VMProto.$broadcast = function () {
  1176. var children = this.$compiler.childCompilers,
  1177. i = children.length,
  1178. child
  1179. while (i--) {
  1180. child = children[i]
  1181. child.emitter.emit.apply(child.emitter, arguments)
  1182. child.vm.$broadcast.apply(child.vm, arguments)
  1183. }
  1184. }
  1185. /*
  1186. * emit an event that propagates all the way up to parent VMs.
  1187. */
  1188. VMProto.$emit = function () {
  1189. var parent = this.$compiler.parentCompiler
  1190. if (parent) {
  1191. parent.emitter.emit.apply(parent.emitter, arguments)
  1192. parent.vm.$emit.apply(parent.vm, arguments)
  1193. }
  1194. }
  1195. /*
  1196. * delegate on/off/once to the compiler's emitter
  1197. */
  1198. ;['on', 'off', 'once'].forEach(function (method) {
  1199. VMProto['$' + method] = function () {
  1200. var emitter = this.$compiler.emitter
  1201. emitter[method].apply(emitter, arguments)
  1202. }
  1203. })
  1204. /*
  1205. * If a VM doesn't contain a path, go up the prototype chain
  1206. * to locate the ancestor that has it.
  1207. */
  1208. function getTargetVM (vm, path) {
  1209. var baseKey = path[0],
  1210. binding = vm.$compiler.bindings[baseKey]
  1211. return binding
  1212. ? binding.compiler.vm
  1213. : null
  1214. }
  1215. module.exports = ViewModel
  1216. });
  1217. require.register("seed/src/binding.js", function(exports, require, module){
  1218. /*
  1219. * Binding class.
  1220. *
  1221. * each property on the viewmodel has one corresponding Binding object
  1222. * which has multiple directive instances on the DOM
  1223. * and multiple computed property dependents
  1224. */
  1225. function Binding (compiler, key, isExp) {
  1226. this.value = undefined
  1227. this.isExp = !!isExp
  1228. this.root = !this.isExp && key.indexOf('.') === -1
  1229. this.compiler = compiler
  1230. this.key = key
  1231. this.instances = []
  1232. this.subs = []
  1233. this.deps = []
  1234. }
  1235. var BindingProto = Binding.prototype
  1236. /*
  1237. * Process the value, then trigger updates on all dependents
  1238. */
  1239. BindingProto.update = function (value) {
  1240. this.value = value
  1241. var i = this.instances.length
  1242. while (i--) {
  1243. this.instances[i].update(value)
  1244. }
  1245. this.pub()
  1246. }
  1247. /*
  1248. * -- computed property only --
  1249. * Force all instances to re-evaluate themselves
  1250. */
  1251. BindingProto.refresh = function () {
  1252. var i = this.instances.length
  1253. while (i--) {
  1254. this.instances[i].refresh()
  1255. }
  1256. this.pub()
  1257. }
  1258. /*
  1259. * Notify computed properties that depend on this binding
  1260. * to update themselves
  1261. */
  1262. BindingProto.pub = function () {
  1263. var i = this.subs.length
  1264. while (i--) {
  1265. this.subs[i].refresh()
  1266. }
  1267. }
  1268. /*
  1269. * Unbind the binding, remove itself from all of its dependencies
  1270. */
  1271. BindingProto.unbind = function () {
  1272. var i = this.instances.length
  1273. while (i--) {
  1274. this.instances[i].unbind()
  1275. }
  1276. i = this.deps.length
  1277. var subs
  1278. while (i--) {
  1279. subs = this.deps[i].subs
  1280. subs.splice(subs.indexOf(this), 1)
  1281. }
  1282. this.compiler = this.pubs = this.subs = this.instances = this.deps = null
  1283. }
  1284. module.exports = Binding
  1285. });
  1286. require.register("seed/src/observer.js", function(exports, require, module){
  1287. /* jshint proto:true */
  1288. var Emitter = require('./emitter'),
  1289. utils = require('./utils'),
  1290. typeOf = utils.typeOf,
  1291. def = utils.defProtected,
  1292. slice = Array.prototype.slice,
  1293. methods = ['push','pop','shift','unshift','splice','sort','reverse'],
  1294. hasProto = ({}).__proto__ // fix for IE9
  1295. // The proxy prototype to replace the __proto__ of
  1296. // an observed array
  1297. var ArrayProxy = Object.create(Array.prototype)
  1298. // Define mutation interceptors so we can emit the mutation info
  1299. methods.forEach(function (method) {
  1300. def(ArrayProxy, method, function () {
  1301. var result = Array.prototype[method].apply(this, arguments)
  1302. this.__observer__.emit('mutate', this.__observer__.path, this, {
  1303. method: method,
  1304. args: slice.call(arguments),
  1305. result: result
  1306. })
  1307. return result
  1308. }, !hasProto)
  1309. })
  1310. // Augment it with several convenience methods
  1311. var extensions = {
  1312. remove: function (index) {
  1313. if (typeof index !== 'number') index = this.indexOf(index)
  1314. return this.splice(index, 1)[0]
  1315. },
  1316. replace: function (index, data) {
  1317. if (typeof index !== 'number') index = this.indexOf(index)
  1318. if (this[index] !== undefined) return this.splice(index, 1, data)[0]
  1319. },
  1320. mutateFilter: function (fn) {
  1321. var i = this.length
  1322. while (i--) {
  1323. if (!fn(this[i])) this.splice(i, 1)
  1324. }
  1325. return this
  1326. }
  1327. }
  1328. for (var method in extensions) {
  1329. def(ArrayProxy, method, extensions[method], !hasProto)
  1330. }
  1331. /*
  1332. * Watch an object based on type
  1333. */
  1334. function watch (obj, path, observer) {
  1335. var type = typeOf(obj)
  1336. if (type === 'Object') {
  1337. watchObject(obj, path, observer)
  1338. } else if (type === 'Array') {
  1339. watchArray(obj, path, observer)
  1340. }
  1341. }
  1342. /*
  1343. * Watch an Object, recursive.
  1344. */
  1345. function watchObject (obj, path, observer) {
  1346. for (var key in obj) {
  1347. bind(obj, key, path, observer)
  1348. }
  1349. }
  1350. /*
  1351. * Watch an Array, overload mutation methods
  1352. * and add augmentations by intercepting the prototype chain
  1353. */
  1354. function watchArray (arr, path, observer) {
  1355. def(arr, '__observer__', observer)
  1356. observer.path = path
  1357. if (hasProto) {
  1358. arr.__proto__ = ArrayProxy
  1359. } else {
  1360. for (var key in ArrayProxy) {
  1361. def(arr, key, ArrayProxy[key])
  1362. }
  1363. }
  1364. }
  1365. /*
  1366. * Define accessors for a property on an Object
  1367. * so it emits get/set events.
  1368. * Then watch the value itself.
  1369. */
  1370. function bind (obj, key, path, observer) {
  1371. var val = obj[key],
  1372. watchable = isWatchable(val),
  1373. values = observer.values,
  1374. fullKey = (path ? path + '.' : '') + key
  1375. values[fullKey] = val
  1376. // emit set on bind
  1377. // this means when an object is observed it will emit
  1378. // a first batch of set events.
  1379. observer.emit('set', fullKey, val)
  1380. Object.defineProperty(obj, key, {
  1381. enumerable: true,
  1382. get: function () {
  1383. // only emit get on tip values
  1384. if (!watchable) observer.emit('get', fullKey)
  1385. return values[fullKey]
  1386. },
  1387. set: function (newVal) {
  1388. values[fullKey] = newVal
  1389. observer.emit('set', fullKey, newVal)
  1390. watch(newVal, fullKey, observer)
  1391. }
  1392. })
  1393. watch(val, fullKey, observer)
  1394. }
  1395. /*
  1396. * Check if a value is watchable
  1397. */
  1398. function isWatchable (obj) {
  1399. var type = typeOf(obj)
  1400. return type === 'Object' || type === 'Array'
  1401. }
  1402. /*
  1403. * When a value that is already converted is
  1404. * observed again by another observer, we can skip
  1405. * the watch conversion and simply emit set event for
  1406. * all of its properties.
  1407. */
  1408. function emitSet (obj, observer) {
  1409. if (typeOf(obj) === 'Array') {
  1410. observer.emit('set', 'length', obj.length)
  1411. } else {
  1412. var key, val, values = observer.values
  1413. for (key in observer.values) {
  1414. val = values[key]
  1415. observer.emit('set', key, val)
  1416. }
  1417. }
  1418. }
  1419. module.exports = {
  1420. // used in sd-repeat
  1421. watchArray: watchArray,
  1422. /*
  1423. * Observe an object with a given path,
  1424. * and proxy get/set/mutate events to the provided observer.
  1425. */
  1426. observe: function (obj, rawPath, observer) {
  1427. if (isWatchable(obj)) {
  1428. var path = rawPath + '.',
  1429. ob, alreadyConverted = !!obj.__observer__
  1430. if (!alreadyConverted) {
  1431. def(obj, '__observer__', new Emitter())
  1432. }
  1433. ob = obj.__observer__
  1434. ob.values = ob.values || {}
  1435. var proxies = observer.proxies[path] = {
  1436. get: function (key) {
  1437. observer.emit('get', path + key)
  1438. },
  1439. set: function (key, val) {
  1440. observer.emit('set', path + key, val)
  1441. },
  1442. mutate: function (key, val, mutation) {
  1443. // if the Array is a root value
  1444. // the key will be null
  1445. var fixedPath = key ? path + key : rawPath
  1446. observer.emit('mutate', fixedPath, val, mutation)
  1447. // also emit set for Array's length when it mutates
  1448. var m = mutation.method
  1449. if (m !== 'sort' && m !== 'reverse') {
  1450. observer.emit('set', fixedPath + '.length', val.length)
  1451. }
  1452. }
  1453. }
  1454. ob
  1455. .on('get', proxies.get)
  1456. .on('set', proxies.set)
  1457. .on('mutate', proxies.mutate)
  1458. if (alreadyConverted) {
  1459. emitSet(obj, ob, rawPath)
  1460. } else {
  1461. watch(obj, null, ob)
  1462. }
  1463. }
  1464. },
  1465. /*
  1466. * Cancel observation, turn off the listeners.
  1467. */
  1468. unobserve: function (obj, path, observer) {
  1469. if (!obj || !obj.__observer__) return
  1470. path = path + '.'
  1471. var proxies = observer.proxies[path]
  1472. obj.__observer__
  1473. .off('get', proxies.get)
  1474. .off('set', proxies.set)
  1475. .off('mutate', proxies.mutate)
  1476. observer.proxies[path] = null
  1477. }
  1478. }
  1479. });
  1480. require.register("seed/src/directive.js", function(exports, require, module){
  1481. var config = require('./config'),
  1482. utils = require('./utils'),
  1483. directives = require('./directives'),
  1484. filters = require('./filters')
  1485. var KEY_RE = /^[^\|]+/,
  1486. ARG_RE = /([^:]+):(.+)$/,
  1487. FILTERS_RE = /\|[^\|]+/g,
  1488. FILTER_TOKEN_RE = /[^\s']+|'[^']+'/g,
  1489. NESTING_RE = /^\^+/,
  1490. SINGLE_VAR_RE = /^[\w\.\$]+$/
  1491. /*
  1492. * Directive class
  1493. * represents a single directive instance in the DOM
  1494. */
  1495. function Directive (definition, directiveName, expression, rawKey, compiler, node) {
  1496. this.compiler = compiler
  1497. this.vm = compiler.vm
  1498. this.el = node
  1499. // mix in properties from the directive definition
  1500. if (typeof definition === 'function') {
  1501. this._update = definition
  1502. } else {
  1503. for (var prop in definition) {
  1504. if (prop === 'unbind' || prop === 'update') {
  1505. this['_' + prop] = definition[prop]
  1506. } else {
  1507. this[prop] = definition[prop]
  1508. }
  1509. }
  1510. }
  1511. this.name = directiveName
  1512. this.expression = expression.trim()
  1513. this.rawKey = rawKey
  1514. parseKey(this, rawKey)
  1515. this.isExp = !SINGLE_VAR_RE.test(this.key)
  1516. var filterExps = expression.match(FILTERS_RE)
  1517. if (filterExps) {
  1518. this.filters = []
  1519. var i = 0, l = filterExps.length, filter
  1520. for (; i < l; i++) {
  1521. filter = parseFilter(filterExps[i], this.compiler)
  1522. if (filter) this.filters.push(filter)
  1523. }
  1524. if (!this.filters.length) this.filters = null
  1525. } else {
  1526. this.filters = null
  1527. }
  1528. }
  1529. var DirProto = Directive.prototype
  1530. /*
  1531. * parse a key, extract argument and nesting/root info
  1532. */
  1533. function parseKey (dir, rawKey) {
  1534. var argMatch = rawKey.match(ARG_RE)
  1535. var key = argMatch
  1536. ? argMatch[2].trim()
  1537. : rawKey.trim()
  1538. dir.arg = argMatch
  1539. ? argMatch[1].trim()
  1540. : null
  1541. var nesting = key.match(NESTING_RE)
  1542. dir.nesting = nesting
  1543. ? nesting[0].length
  1544. : false
  1545. dir.root = key.charAt(0) === '$'
  1546. if (dir.nesting) {
  1547. key = key.replace(NESTING_RE, '')
  1548. } else if (dir.root) {
  1549. key = key.slice(1)
  1550. }
  1551. dir.key = key
  1552. }
  1553. /*
  1554. * parse a filter expression
  1555. */
  1556. function parseFilter (filter, compiler) {
  1557. var tokens = filter.slice(1).match(FILTER_TOKEN_RE)
  1558. if (!tokens) return
  1559. tokens = tokens.map(function (token) {
  1560. return token.replace(/'/g, '').trim()
  1561. })
  1562. var name = tokens[0],
  1563. apply = compiler.getOption('filters', name) || filters[name]
  1564. if (!apply) {
  1565. utils.warn('Unknown filter: ' + name)
  1566. return
  1567. }
  1568. return {
  1569. name : name,
  1570. apply : apply,
  1571. args : tokens.length > 1
  1572. ? tokens.slice(1)
  1573. : null
  1574. }
  1575. }
  1576. /*
  1577. * called when a new value is set
  1578. * for computed properties, this will only be called once
  1579. * during initialization.
  1580. */
  1581. DirProto.update = function (value, init) {
  1582. if (!init && value === this.value) return
  1583. this.value = value
  1584. this.apply(value)
  1585. }
  1586. /*
  1587. * -- computed property only --
  1588. * called when a dependency has changed
  1589. */
  1590. DirProto.refresh = function (value) {
  1591. // pass element and viewmodel info to the getter
  1592. // enables context-aware bindings
  1593. if (value) this.value = value
  1594. value = this.value.get({
  1595. el: this.el,
  1596. vm: this.vm
  1597. })
  1598. if (value && value === this.computedValue) return
  1599. this.computedValue = value
  1600. this.apply(value)
  1601. }
  1602. /*
  1603. * Actually invoking the _update from the directive's definition
  1604. */
  1605. DirProto.apply = function (value) {
  1606. this._update(
  1607. this.filters
  1608. ? this.applyFilters(value)
  1609. : value
  1610. )
  1611. }
  1612. /*
  1613. * pipe the value through filters
  1614. */
  1615. DirProto.applyFilters = function (value) {
  1616. var filtered = value, filter
  1617. for (var i = 0, l = this.filters.length; i < l; i++) {
  1618. filter = this.filters[i]
  1619. filtered = filter.apply(filtered, filter.args)
  1620. }
  1621. return filtered
  1622. }
  1623. /*
  1624. * Unbind diretive
  1625. * @ param {Boolean} update
  1626. * Sometimes we call unbind before an update (i.e. not destroy)
  1627. * just to teardown previousstuff, in that case we do not want
  1628. * to null everything.
  1629. */
  1630. DirProto.unbind = function (update) {
  1631. // this can be called before the el is even assigned...
  1632. if (!this.el) return
  1633. if (this._unbind) this._unbind(update)
  1634. if (!update) this.vm = this.el = this.binding = this.compiler = null
  1635. }
  1636. /*
  1637. * make sure the directive and expression is valid
  1638. * before we create an instance
  1639. */
  1640. Directive.parse = function (dirname, expression, compiler, node) {
  1641. var prefix = config.prefix
  1642. if (dirname.indexOf(prefix) === -1) return null
  1643. dirname = dirname.slice(prefix.length + 1)
  1644. var dir = compiler.getOption('directives', dirname) || directives[dirname],
  1645. keyMatch = expression.match(KEY_RE),
  1646. rawKey = keyMatch && keyMatch[0].trim()
  1647. if (!dir) utils.warn('unknown directive: ' + dirname)
  1648. if (!rawKey) utils.warn('invalid directive expression: ' + expression)
  1649. return dir && rawKey
  1650. ? new Directive(dir, dirname, expression, rawKey, compiler, node)
  1651. : null
  1652. }
  1653. module.exports = Directive
  1654. });
  1655. require.register("seed/src/exp-parser.js", function(exports, require, module){
  1656. // Variable extraction scooped from https://github.com/RubyLouvre/avalon
  1657. var KEYWORDS =
  1658. // keywords
  1659. 'break,case,catch,continue,debugger,default,delete,do,else,false'
  1660. + ',finally,for,function,if,in,instanceof,new,null,return,switch,this'
  1661. + ',throw,true,try,typeof,var,void,while,with'
  1662. // reserved
  1663. + ',abstract,boolean,byte,char,class,const,double,enum,export,extends'
  1664. + ',final,float,goto,implements,import,int,interface,long,native'
  1665. + ',package,private,protected,public,short,static,super,synchronized'
  1666. + ',throws,transient,volatile'
  1667. // ECMA 5 - use strict
  1668. + ',arguments,let,yield'
  1669. + ',undefined',
  1670. KEYWORDS_RE = new RegExp(["\\b" + KEYWORDS.replace(/,/g, '\\b|\\b') + "\\b"].join('|'), 'g'),
  1671. REMOVE_RE = /\/\*(?:.|\n)*?\*\/|\/\/[^\n]*\n|\/\/[^\n]*$|'[^']*'|"[^"]*"|[\s\t\n]*\.[\s\t\n]*[$\w\.]+/g,
  1672. SPLIT_RE = /[^\w$]+/g,
  1673. NUMBER_RE = /\b\d[^,]*/g,
  1674. BOUNDARY_RE = /^,+|,+$/g
  1675. function getVariables (code) {
  1676. code = code
  1677. .replace(REMOVE_RE, '')
  1678. .replace(SPLIT_RE, ',')
  1679. .replace(KEYWORDS_RE, '')
  1680. .replace(NUMBER_RE, '')
  1681. .replace(BOUNDARY_RE, '')
  1682. return code
  1683. ? code.split(/,+/)
  1684. : []
  1685. }
  1686. module.exports = {
  1687. /*
  1688. * Parse and create an anonymous computed property getter function
  1689. * from an arbitrary expression.
  1690. */
  1691. parse: function (exp) {
  1692. // extract variable names
  1693. var vars = getVariables(exp)
  1694. if (!vars.length) return null
  1695. var args = [],
  1696. v, i, keyPrefix,
  1697. l = vars.length,
  1698. hash = {}
  1699. for (i = 0; i < l; i++) {
  1700. v = vars[i]
  1701. // avoid duplicate keys
  1702. if (hash[v]) continue
  1703. hash[v] = v
  1704. // push assignment
  1705. keyPrefix = v.charAt(0)
  1706. args.push(v + (
  1707. (keyPrefix === '$' || keyPrefix === '_')
  1708. ? '=this.' + v
  1709. : '=this.$get("' + v + '")'
  1710. ))
  1711. }
  1712. args = 'var ' + args.join(',') + ';return ' + exp
  1713. /* jshint evil: true */
  1714. return {
  1715. getter: new Function(args),
  1716. vars: Object.keys(hash)
  1717. }
  1718. }
  1719. }
  1720. });
  1721. require.register("seed/src/text-parser.js", function(exports, require, module){
  1722. var BINDING_RE = /\{\{(.+?)\}\}/
  1723. module.exports = {
  1724. /*
  1725. * Parse a piece of text, return an array of tokens
  1726. */
  1727. parse: function (text) {
  1728. if (!BINDING_RE.test(text)) return null
  1729. var m, i, tokens = []
  1730. do {
  1731. m = text.match(BINDING_RE)
  1732. if (!m) break
  1733. i = m.index
  1734. if (i > 0) tokens.push(text.slice(0, i))
  1735. tokens.push({ key: m[1].trim() })
  1736. text = text.slice(i + m[0].length)
  1737. } while (true)
  1738. if (text.length) tokens.push(text)
  1739. return tokens
  1740. }
  1741. }
  1742. });
  1743. require.register("seed/src/deps-parser.js", function(exports, require, module){
  1744. var Emitter = require('./emitter'),
  1745. utils = require('./utils'),
  1746. observer = new Emitter()
  1747. /*
  1748. * Auto-extract the dependencies of a computed property
  1749. * by recording the getters triggered when evaluating it.
  1750. */
  1751. function catchDeps (binding) {
  1752. utils.log('\n─ ' + binding.key)
  1753. var depsHash = {}
  1754. observer.on('get', function (dep) {
  1755. if (depsHash[dep.key]) return
  1756. depsHash[dep.key] = 1
  1757. utils.log(' └─ ' + dep.key)
  1758. binding.deps.push(dep)
  1759. dep.subs.push(binding)
  1760. })
  1761. binding.value.get()
  1762. observer.off('get')
  1763. }
  1764. module.exports = {
  1765. /*
  1766. * the observer that catches events triggered by getters
  1767. */
  1768. observer: observer,
  1769. /*
  1770. * parse a list of computed property bindings
  1771. */
  1772. parse: function (bindings) {
  1773. utils.log('\nparsing dependencies...')
  1774. observer.isObserving = true
  1775. bindings.forEach(catchDeps)
  1776. observer.isObserving = false
  1777. utils.log('\ndone.')
  1778. }
  1779. }
  1780. });
  1781. require.register("seed/src/filters.js", function(exports, require, module){
  1782. var keyCodes = {
  1783. enter : 13,
  1784. tab : 9,
  1785. 'delete' : 46,
  1786. up : 38,
  1787. left : 37,
  1788. right : 39,
  1789. down : 40,
  1790. esc : 27
  1791. }
  1792. module.exports = {
  1793. capitalize: function (value) {
  1794. if (!value && value !== 0) return ''
  1795. value = value.toString()
  1796. return value.charAt(0).toUpperCase() + value.slice(1)
  1797. },
  1798. uppercase: function (value) {
  1799. return (value || value === 0)
  1800. ? value.toString().toUpperCase()
  1801. : ''
  1802. },
  1803. lowercase: function (value) {
  1804. return (value || value === 0)
  1805. ? value.toString().toLowerCase()
  1806. : ''
  1807. },
  1808. /*
  1809. * args: an array of strings corresponding to
  1810. * the single, double, triple ... forms of the word to
  1811. * be pluralized. When the number to be pluralized
  1812. * exceeds the length of the args, it will use the last
  1813. * entry in the array.
  1814. *
  1815. * e.g. ['single', 'double', 'triple', 'multiple']
  1816. */
  1817. pluralize: function (value, args) {
  1818. return args.length > 1
  1819. ? (args[value - 1] || args[args.length - 1])
  1820. : (args[value - 1] || args[0] + 's')
  1821. },
  1822. currency: function (value, args) {
  1823. if (!value && value !== 0) return ''
  1824. var sign = (args && args[0]) || '$',
  1825. s = Math.floor(value).toString(),
  1826. i = s.length % 3,
  1827. h = i > 0 ? (s.slice(0, i) + (s.length > 3 ? ',' : '')) : '',
  1828. f = '.' + value.toFixed(2).slice(-2)
  1829. return sign + h + s.slice(i).replace(/(\d{3})(?=\d)/g, '$1,') + f
  1830. },
  1831. key: function (handler, args) {
  1832. if (!handler) return
  1833. var code = keyCodes[args[0]]
  1834. if (!code) {
  1835. code = parseInt(args[0], 10)
  1836. }
  1837. return function (e) {
  1838. if (e.keyCode === code) {
  1839. handler.call(this, e)
  1840. }
  1841. }
  1842. }
  1843. }
  1844. });
  1845. require.register("seed/src/directives/index.js", function(exports, require, module){
  1846. var utils = require('../utils')
  1847. module.exports = {
  1848. on : require('./on'),
  1849. repeat : require('./repeat'),
  1850. model : require('./model'),
  1851. attr: function (value) {
  1852. this.el.setAttribute(this.arg, value)
  1853. },
  1854. text: function (value) {
  1855. this.el.textContent = utils.toText(value)
  1856. },
  1857. html: function (value) {
  1858. this.el.innerHTML = utils.toText(value)
  1859. },
  1860. style: {
  1861. bind: function () {
  1862. this.arg = convertCSSProperty(this.arg)
  1863. },
  1864. update: function (value) {
  1865. this.el.style[this.arg] = value
  1866. }
  1867. },
  1868. show: function (value) {
  1869. this.el.style.display = value ? '' : 'none'
  1870. },
  1871. visible: function (value) {
  1872. this.el.style.visibility = value ? '' : 'hidden'
  1873. },
  1874. class: function (value) {
  1875. if (this.arg) {
  1876. this.el.classList[value ? 'add' : 'remove'](this.arg)
  1877. } else {
  1878. if (this.lastVal) {
  1879. this.el.classList.remove(this.lastVal)
  1880. }
  1881. this.el.classList.add(value)
  1882. this.lastVal = value
  1883. }
  1884. },
  1885. 'if': {
  1886. bind: function () {
  1887. this.parent = this.el.parentNode
  1888. this.ref = document.createComment('sd-if-' + this.key)
  1889. },
  1890. update: function (value) {
  1891. var attached = !!this.el.parentNode
  1892. if (!this.parent) { // the node was detached when bound
  1893. if (!attached) {
  1894. return
  1895. } else {
  1896. this.parent = this.el.parentNode
  1897. }
  1898. }
  1899. // should always have this.parent if we reach here
  1900. if (!value) {
  1901. if (attached) {
  1902. // insert the reference node
  1903. var next = this.el.nextSibling
  1904. if (next) {
  1905. this.parent.insertBefore(this.ref, next)
  1906. } else {
  1907. this.parent.appendChild(this.ref)
  1908. }
  1909. this.parent.removeChild(this.el)
  1910. }
  1911. } else if (!attached) {
  1912. this.parent.insertBefore(this.el, this.ref)
  1913. this.parent.removeChild(this.ref)
  1914. }
  1915. }
  1916. }
  1917. }
  1918. /*
  1919. * convert hyphen style CSS property to Camel style
  1920. */
  1921. var CONVERT_RE = /-(.)/g
  1922. function convertCSSProperty (prop) {
  1923. if (prop.charAt(0) === '-') prop = prop.slice(1)
  1924. return prop.replace(CONVERT_RE, function (m, char) {
  1925. return char.toUpperCase()
  1926. })
  1927. }
  1928. });
  1929. require.register("seed/src/directives/repeat.js", function(exports, require, module){
  1930. var config = require('../config'),
  1931. Observer = require('../observer'),
  1932. Emitter = require('../emitter'),
  1933. ViewModel // lazy def to avoid circular dependency
  1934. /*
  1935. * Mathods that perform precise DOM manipulation
  1936. * based on mutator method triggered
  1937. */
  1938. var mutationHandlers = {
  1939. push: function (m) {
  1940. var i, l = m.args.length,
  1941. base = this.collection.length - l
  1942. for (i = 0; i < l; i++) {
  1943. this.buildItem(m.args[i], base + i)
  1944. }
  1945. },
  1946. pop: function () {
  1947. var vm = this.vms.pop()
  1948. if (vm) vm.$destroy()
  1949. },
  1950. unshift: function (m) {
  1951. var i, l = m.args.length
  1952. for (i = 0; i < l; i++) {
  1953. this.buildItem(m.args[i], i)
  1954. }
  1955. },
  1956. shift: function () {
  1957. var vm = this.vms.shift()
  1958. if (vm) vm.$destroy()
  1959. },
  1960. splice: function (m) {
  1961. var i, l,
  1962. index = m.args[0],
  1963. removed = m.args[1],
  1964. added = m.args.length - 2,
  1965. removedVMs = this.vms.splice(index, removed)
  1966. for (i = 0, l = removedVMs.length; i < l; i++) {
  1967. removedVMs[i].$destroy()
  1968. }
  1969. for (i = 0; i < added; i++) {
  1970. this.buildItem(m.args[i + 2], index + i)
  1971. }
  1972. },
  1973. sort: function () {
  1974. var key = this.arg,
  1975. vms = this.vms,
  1976. col = this.collection,
  1977. l = col.length,
  1978. sorted = new Array(l),
  1979. i, j, vm, data
  1980. for (i = 0; i < l; i++) {
  1981. data = col[i]
  1982. for (j = 0; j < l; j++) {
  1983. vm = vms[j]
  1984. if (vm[key] === data) {
  1985. sorted[i] = vm
  1986. break
  1987. }
  1988. }
  1989. }
  1990. for (i = 0; i < l; i++) {
  1991. this.container.insertBefore(sorted[i].$el, this.ref)
  1992. }
  1993. this.vms = sorted
  1994. },
  1995. reverse: function () {
  1996. var vms = this.vms
  1997. vms.reverse()
  1998. for (var i = 0, l = vms.length; i < l; i++) {
  1999. this.container.insertBefore(vms[i].$el, this.ref)
  2000. }
  2001. }
  2002. }
  2003. module.exports = {
  2004. bind: function () {
  2005. this.el.removeAttribute(config.prefix + '-repeat')
  2006. var ctn = this.container = this.el.parentNode
  2007. // create a comment node as a reference node for DOM insertions
  2008. this.ref = document.createComment('sd-repeat-' + this.arg)
  2009. ctn.insertBefore(this.ref, this.el)
  2010. ctn.removeChild(this.el)
  2011. this.collection = null
  2012. this.vms = null
  2013. var self = this
  2014. this.mutationListener = function (path, arr, mutation) {
  2015. self.detach()
  2016. var method = mutation.method
  2017. mutationHandlers[method].call(self, mutation)
  2018. if (method !== 'push' && method !== 'pop') {
  2019. self.updateIndexes()
  2020. }
  2021. self.retach()
  2022. }
  2023. },
  2024. update: function (collection) {
  2025. this.unbind(true)
  2026. // attach an object to container to hold handlers
  2027. this.container.sd_dHandlers = {}
  2028. // if initiating with an empty collection, we need to
  2029. // force a compile so that we get all the bindings for
  2030. // dependency extraction.
  2031. if (!this.collection && !collection.length) {
  2032. this.buildItem()
  2033. }
  2034. this.collection = collection
  2035. this.vms = []
  2036. // listen for collection mutation events
  2037. // the collection has been augmented during Binding.set()
  2038. if (!collection.__observer__) Observer.watchArray(collection, null, new Emitter())
  2039. collection.__observer__.on('mutate', this.mutationListener)
  2040. // create child-seeds and append to DOM
  2041. this.detach()
  2042. for (var i = 0, l = collection.length; i < l; i++) {
  2043. this.buildItem(collection[i], i)
  2044. }
  2045. this.retach()
  2046. },
  2047. /*
  2048. * Create a new child VM from a data object
  2049. * passing along compiler options indicating this
  2050. * is a sd-repeat item.
  2051. */
  2052. buildItem: function (data, index) {
  2053. ViewModel = ViewModel || require('../viewmodel')
  2054. var node = this.el.cloneNode(true),
  2055. ctn = this.container,
  2056. vmID = node.getAttribute(config.prefix + '-viewmodel'),
  2057. ChildVM = this.compiler.getOption('vms', vmID) || ViewModel,
  2058. scope = {}
  2059. scope[this.arg] = data || {}
  2060. var item = new ChildVM({
  2061. el: node,
  2062. scope: scope,
  2063. compilerOptions: {
  2064. repeat: true,
  2065. repeatIndex: index,
  2066. repeatPrefix: this.arg,
  2067. parentCompiler: this.compiler,
  2068. delegator: ctn
  2069. }
  2070. })
  2071. if (!data) {
  2072. item.$destroy()
  2073. } else {
  2074. var ref = this.vms.length > index
  2075. ? this.vms[index].$el
  2076. : this.ref
  2077. ctn.insertBefore(node, ref)
  2078. this.vms.splice(index, 0, item)
  2079. }
  2080. },
  2081. /*
  2082. * Update index of each item after a mutation
  2083. */
  2084. updateIndexes: function () {
  2085. var i = this.vms.length
  2086. while (i--) {
  2087. this.vms[i][this.arg].$index = i
  2088. }
  2089. },
  2090. /*
  2091. * Detach/ the container from the DOM before mutation
  2092. * so that batch DOM updates are done in-memory and faster
  2093. */
  2094. detach: function () {
  2095. var c = this.container,
  2096. p = this.parent = c.parentNode
  2097. this.next = c.nextSibling
  2098. if (p) p.removeChild(c)
  2099. },
  2100. retach: function () {
  2101. var n = this.next,
  2102. p = this.parent,
  2103. c = this.container
  2104. if (!p) return
  2105. if (n) {
  2106. p.insertBefore(c, n)
  2107. } else {
  2108. p.appendChild(c)
  2109. }
  2110. },
  2111. unbind: function () {
  2112. if (this.collection) {
  2113. this.collection.__observer__.off('mutate', this.mutationListener)
  2114. var i = this.vms.length
  2115. while (i--) {
  2116. this.vms[i].$destroy()
  2117. }
  2118. }
  2119. var ctn = this.container,
  2120. handlers = ctn.sd_dHandlers
  2121. for (var key in handlers) {
  2122. ctn.removeEventListener(handlers[key].event, handlers[key])
  2123. }
  2124. ctn.sd_dHandlers = null
  2125. }
  2126. }
  2127. });
  2128. require.register("seed/src/directives/on.js", function(exports, require, module){
  2129. var utils = require('../utils')
  2130. function delegateCheck (current, top, identifier) {
  2131. if (current[identifier]) {
  2132. return current
  2133. } else if (current === top) {
  2134. return false
  2135. } else {
  2136. return delegateCheck(current.parentNode, top, identifier)
  2137. }
  2138. }
  2139. module.exports = {
  2140. bind: function () {
  2141. if (this.compiler.repeat) {
  2142. // attach an identifier to the el
  2143. // so it can be matched during event delegation
  2144. this.el[this.expression] = true
  2145. // attach the owner viewmodel of this directive
  2146. this.el.sd_viewmodel = this.vm
  2147. }
  2148. },
  2149. update: function (handler) {
  2150. this.unbind(true)
  2151. if (typeof handler !== 'function') {
  2152. return utils.warn('Directive "on" expects a function value.')
  2153. }
  2154. var compiler = this.compiler,
  2155. event = this.arg,
  2156. ownerVM = this.binding.compiler.vm
  2157. if (compiler.repeat && event !== 'blur' && event !== 'focus') {
  2158. // for each blocks, delegate for better performance
  2159. // focus and blur events dont bubble so exclude them
  2160. var delegator = compiler.delegator,
  2161. identifier = this.expression,
  2162. dHandler = delegator.sd_dHandlers[identifier]
  2163. if (dHandler) return
  2164. // the following only gets run once for the entire each block
  2165. dHandler = delegator.sd_dHandlers[identifier] = function (e) {
  2166. var target = delegateCheck(e.target, delegator, identifier)
  2167. if (target) {
  2168. e.el = target
  2169. e.vm = target.sd_viewmodel
  2170. e.item = e.vm[compiler.repeatPrefix]
  2171. handler.call(ownerVM, e)
  2172. }
  2173. }
  2174. dHandler.event = event
  2175. delegator.addEventListener(event, dHandler)
  2176. } else {
  2177. // a normal, single element handler
  2178. var vm = this.vm
  2179. this.handler = function (e) {
  2180. e.el = e.currentTarget
  2181. e.vm = vm
  2182. if (compiler.repeat) {
  2183. e.item = vm[compiler.repeatPrefix]
  2184. }
  2185. handler.call(ownerVM, e)
  2186. }
  2187. this.el.addEventListener(event, this.handler)
  2188. }
  2189. },
  2190. unbind: function (update) {
  2191. this.el.removeEventListener(this.arg, this.handler)
  2192. this.handler = null
  2193. if (!update) this.el.sd_viewmodel = null
  2194. }
  2195. }
  2196. });
  2197. require.register("seed/src/directives/model.js", function(exports, require, module){
  2198. var utils = require('../utils')
  2199. module.exports = {
  2200. bind: function () {
  2201. var self = this,
  2202. el = self.el,
  2203. type = el.type
  2204. self.lock = false
  2205. // determine what event to listen to
  2206. self.event =
  2207. (self.compiler.options.lazy ||
  2208. el.tagName === 'SELECT' ||
  2209. type === 'checkbox' ||
  2210. type === 'radio')
  2211. ? 'change'
  2212. : 'keyup'
  2213. // determin the attribute to change when updating
  2214. var attr = type === 'checkbox'
  2215. ? 'checked'
  2216. : 'value'
  2217. // attach listener
  2218. self.set = function () {
  2219. self.lock = true
  2220. self.vm.$set(self.key, el[attr])
  2221. self.lock = false
  2222. }
  2223. el.addEventListener(self.event, self.set)
  2224. },
  2225. update: function (value) {
  2226. /* jshint eqeqeq: false */
  2227. var self = this,
  2228. el = self.el
  2229. if (self.lock) return
  2230. if (el.tagName === 'SELECT') { // select dropdown
  2231. // setting <select>'s value in IE9 doesn't work
  2232. var o = el.options,
  2233. i = o.length,
  2234. index = -1
  2235. while (i--) {
  2236. if (o[i].value == value) {
  2237. index = i
  2238. break
  2239. }
  2240. }
  2241. o.selectedIndex = index
  2242. } else if (el.type === 'radio') { // radio button
  2243. el.checked = value == el.value
  2244. } else if (el.type === 'checkbox') { // checkbox
  2245. el.checked = !!value
  2246. } else {
  2247. el.value = utils.toText(value)
  2248. }
  2249. },
  2250. unbind: function () {
  2251. this.el.removeEventListener(this.event, this.set)
  2252. }
  2253. }
  2254. });
  2255. require.alias("component-emitter/index.js", "seed/deps/emitter/index.js");
  2256. require.alias("component-emitter/index.js", "emitter/index.js");
  2257. require.alias("component-indexof/index.js", "component-emitter/deps/indexof/index.js");
  2258. require.alias("seed/src/main.js", "seed/index.js");