cell.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. /*
  2. * {cell}
  3. *
  4. * - Membrane: "The cell membrane (also known as the plasma membrane or cytoplasmic membrane) is a biological membrane that separates the interior of all cells from the outside environment"
  5. * - Gene: "The transmission of genes to an organism's offspring is the basis of the inheritance of phenotypic traits. These genes make up different DNA sequences called genotypes. Genotypes along with environmental and developmental factors determine what the phenotypes will be."
  6. * - Genotype: "Genotype is an organism's full hereditary information."
  7. * - Phenotype: "Phenotype is an organism's actual observed properties, such as morphology, development, or behavior."
  8. * - Nucleus: "The nucleus maintains the integrity of genes and controls the activities of the cell by regulating gene expression—the nucleus is, therefore, the control center of the cell."
  9. */
  10. (function($root) {
  11. var Membrane = {
  12. /*
  13. * [Membrane] The Shell
  14. *
  15. * "The cell membrane (also known as the plasma membrane or cytoplasmic membrane) is a biological membrane that separates the interior of all cells from the outside environment"
  16. * - https://en.wikipedia.org/wiki/Cell_membrane
  17. *
  18. * The Membrane module determines how a cell is inserted into the DOM. There are two ways: Replacing an existing node with cell (inject), or Creating an additional cell node (add).
  19. * - inject(): attempts to inject cell into an existing host node
  20. * - add(): creates a new cell node and adds it to the DOM without touching other nodes
  21. */
  22. inject: function($host, gene, namespace, replace) {
  23. /*
  24. * Membrane.inject() : Inject cell into an existing node
  25. *
  26. * @param {Object} $host - existing host node to inject into
  27. * @param {Object} gene - gene object
  28. * @param {String} namespace - for handling namespaced elements such as SVG https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS
  29. * @param {Boolean} replace - if true, create a node and replace it with the host node. Used for manual instantiation
  30. */
  31. var $node = null;
  32. var $replacement;
  33. if (replace && $host) {
  34. // 1. Inject into an existing node ($host) by explicit instantiation
  35. $replacement = Phenotype.$type(gene, namespace);
  36. if (gene.hasOwnProperty('$cell')) {
  37. $node = $host;
  38. if ($node.parentNode) $node.parentNode.replaceChild($replacement, $node);
  39. }
  40. $node = $replacement;
  41. } else if (gene.$type && (gene.$type === 'head' || gene.$type === 'body') && $root.document.getElementsByTagName(gene.$type)) {
  42. // 2. Inject into existing 'head' or 'body' nodes
  43. $node = $root.document.getElementsByTagName(gene.$type)[0];
  44. } else if (gene.id && $root.document.getElementById(gene.id)) {
  45. // 3. Inject into an existing nodes by ID
  46. $node = $root.document.getElementById(gene.id);
  47. if ($node.nodeName.toLowerCase() !== (gene.$type || 'div')) {
  48. $replacement = Phenotype.$type(gene, namespace);
  49. $node.parentNode.replaceChild($replacement, $node);
  50. $node = $replacement;
  51. }
  52. }
  53. if ($node && !$node.Meta) $node.Meta = {};
  54. return $node;
  55. },
  56. add: function($parent, gene, index, namespace) {
  57. /*
  58. * Membrane.add() : Adds a new cell node into the DOM tree
  59. *
  60. * @param $parent - The parent node to which the new cell node will be added
  61. * @param gene - gene object
  62. * @param index - the position within the parent's childNodes array to which this cell node will be added. Not used in the initial render but used for subsequent renders based on the diff logic
  63. * @param namespace - namespace URL for namespaced elements such as SVG
  64. */
  65. var $node = Phenotype.$type(gene, namespace);
  66. if (index !== null && index !== undefined && $parent.childNodes && $parent.childNodes[index]) {
  67. // Index is specified, so insert into that position
  68. $parent.insertBefore($node, $parent.childNodes[index]);
  69. } else {
  70. // No index, simply apppend to the end
  71. $parent.appendChild($node);
  72. }
  73. return $node;
  74. },
  75. build: function($parent, gene, index, namespace, replace) {
  76. /*
  77. * Membrane.build() : The main builder function that interfaces with Membrane.inject() and Membrane.add().
  78. */
  79. // 1. Attempt to inject into an existing node
  80. var $existing = Membrane.inject($parent, gene, namespace, replace);
  81. if ($existing) return $existing;
  82. // 2. If it's not an injection into an existing node, we create a node
  83. else return Membrane.add($parent, gene, index, namespace);
  84. },
  85. };
  86. var Genotype = {
  87. /*
  88. * [Genotype] Internal Storage of Genes
  89. *
  90. * "Genotype is an organism's full hereditary information."
  91. * - https://en.wikipedia.org/wiki/Genotype
  92. *
  93. * The Genotype module is an internal storage for all the variables required to construct a cell node (attributes, $variables, and _variables)
  94. * When you set a variable on a cell (for example: this._index=1), it's actually stored under the node's Genotype instead of directly on the node itself.
  95. *
  96. * - set(): a low-level function to simply set a key/value pair on the Genotype object, used by update() and build()
  97. * - update(): updates a key/value pair from the genotype and schedules a phenotype (view) update event to be processed on the next tick
  98. * - build(): builds a fresh genotype object from a gene object
  99. */
  100. set: function($node, key, val) {
  101. if (['$init'].indexOf(key) === -1) {
  102. $node.Genotype[key] = Nucleus.bind($node, val);
  103. } else {
  104. val.snapshot = val; // snapshot of $init
  105. $node.Genotype[key] = val;
  106. }
  107. },
  108. update: function($node, key, val) {
  109. Nucleus.queue($node, key, 'w');
  110. Genotype.set($node, key, val);
  111. },
  112. build: function($node, gene, inheritance) {
  113. $node.Genotype = {};
  114. $node.Inheritance = inheritance;
  115. for (var key in gene) {
  116. Genotype.set($node, key, gene[key]);
  117. }
  118. },
  119. };
  120. var Gene = {
  121. /*
  122. * [Gene] Gene manipulation/diff functions
  123. *
  124. * "The transmission of genes to an organism's offspring is the basis of the inheritance of phenotypic traits. These genes make up different DNA sequences called genotypes. Genotypes along with environmental and developmental factors determine what the phenotypes will be."
  125. * - https://en.wikipedia.org/wiki/Gene
  126. *
  127. * The Gene module is a collection of utility functions used for comparing gene objects to determine if a node needs to be replaced or left alone when there's an update.
  128. * - freeze(): stringifies a Javascript object snapshot for comparison
  129. * - LCS(): Longest Common Subsequence algorithm https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
  130. * - diff(): A diff algorithm that returns what have been added (+), and removed (-)
  131. */
  132. freeze: function(gene) {
  133. var cache = [];
  134. var res = JSON.stringify(gene, function(key, val) {
  135. if (typeof val === 'function') { return val.toString(); }
  136. if (typeof val === 'object' && val !== null) {
  137. if (cache.indexOf(val) !== -1) { return '[Circular]'; }
  138. cache.push(val);
  139. }
  140. return val;
  141. });
  142. cache = null;
  143. return res;
  144. },
  145. LCS: function(a, b) {
  146. var m = a.length, n = b.length, C = [], i, j, af = [], bf = [];
  147. for (i = 0; i < m; i++) af.push(Gene.freeze(a[i]));
  148. for (j = 0; j < n; j++) bf.push(Gene.freeze(b[j]));
  149. for (i = 0; i <= m; i++) C.push([0]);
  150. for (j = 0; j < n; j++) C[0].push(0);
  151. for (i = 0; i < m; i++) for (j = 0; j < n; j++) C[i+1][j+1] = af[i] === bf[j] ? C[i][j]+1 : Math.max(C[i+1][j], C[i][j+1]);
  152. return (function bt(i, j) {
  153. if (i*j === 0) { return []; }
  154. if (af[i-1] === bf[j-1]) { return bt(i-1, j-1).concat([{ item: a[i-1], _old: i-1, _new: j-1 }]); }
  155. return C[i][j-1] > C[i-1][j] ? bt(i, j-1) : bt(i-1, j);
  156. }(m, n));
  157. },
  158. diff: function(_old, _new) {
  159. var lcs = Gene.LCS(_old, _new);
  160. var old_common = lcs.map(function(i) { return i._old; });
  161. var minus = _old.map(function(item, index) {
  162. return { item: item, index: index };
  163. }).filter(function(item, index) {
  164. return old_common.indexOf(index) === -1;
  165. });
  166. var new_common = lcs.map(function(i) { return i._new; });
  167. var plus = _new.map(function(item, index) {
  168. return { item: item, index: index };
  169. }).filter(function(item, index) {
  170. return new_common.indexOf(index) === -1;
  171. });
  172. return { '-': minus, '+': plus };
  173. },
  174. };
  175. var Phenotype = {
  176. /*
  177. * [Phenotype] Actual observed properties of a cell
  178. *
  179. * "Phenotype is an organism's actual observed properties, such as morphology, development, or behavior."
  180. * - https://en.wikipedia.org/wiki/Phenotype
  181. *
  182. * The Phenotype module manages a cell's actual observed properties, such as textContent ($text), nodeType ($type), innerHTML ($html), childNodes ($components), and DOM attributes
  183. *
  184. * - build(): Build phenotype from genotype
  185. * - set(): Sets a key/value pair of phenotype
  186. * - $type(): translates the "$type" attribute to nodeType
  187. * - $text(): translates the "$type" attribute to textContent
  188. * - $html(): translates the "$type" attribute to innerHTML
  189. * - $components(): translates the "$components" attribute to childNodes
  190. * - $init(): executes the "$init" callback function after the element has been rendered
  191. * - $update(): executes the "$update" callback function when needed (called by Nucleus on every tick)
  192. */
  193. build: function($node, genotype) {
  194. Phenotype.$init($node);
  195. for (var key in genotype) {
  196. if (genotype[key] !== null && genotype[key] !== undefined) {
  197. Phenotype.set($node, key, genotype[key]);
  198. }
  199. }
  200. },
  201. multiline: function(fn) { return /\/\*!?(?:@preserve)?[ \t]*(?:\r\n|\n)([\s\S]*?)(?:\r\n|\n)[ \t]*\*\//.exec(fn.toString())[1]; },
  202. get: function(key) {
  203. return Object.getOwnPropertyDescriptor($root.HTMLElement.prototype, key) || Object.getOwnPropertyDescriptor($root.Element.prototype, key);
  204. },
  205. set: function($node, key, val) {
  206. if (key[0] === '$') {
  207. if (key === '$type') {
  208. // recreate and rebind the node if it's different from the old one
  209. var tag = $node.tagName ? $node.tagName.toLowerCase() : 'text';
  210. if (val.toLowerCase() !== tag) {
  211. var fragment = Phenotype.$type({ $type: 'fragment' });
  212. var replacement = fragment.$build($node.Genotype, $node.Inheritance, null, $node.Meta.namespace);
  213. $node.parentNode.replaceChild(replacement, $node);
  214. $node = replacement;
  215. }
  216. } else if (key === '$text') {
  217. if (typeof val === 'function') val = Phenotype.multiline(val);
  218. $node.textContent = val;
  219. } else if (key === '$html') {
  220. if (typeof val === 'function') val = Phenotype.multiline(val);
  221. $node.innerHTML = val;
  222. } else if (key === '$components') {
  223. Phenotype.$components($node, val);
  224. }
  225. } else if (key[0] === '_') {
  226. // "_" variables don't directly alter the phenotype, so do nothing
  227. } else if (key === 'value') {
  228. $node[key] = val;
  229. } else if (key === 'style' && typeof val === 'object') {
  230. var CSSStyleDeclaration = Phenotype.get(key).get.call($node);
  231. for (var attr in val) { CSSStyleDeclaration[attr] = val[attr]; }
  232. } else if (typeof val === 'number' || typeof val === 'string' || typeof val === 'boolean') {
  233. if ($node.setAttribute) $node.setAttribute(key, val);
  234. } else if (typeof val === 'function') {
  235. // For natively supported HTMLElement.prototype methods such as onclick()
  236. var prop = Phenotype.get(key);
  237. if (prop) prop.set.call($node, val);
  238. }
  239. },
  240. $type: function(model, namespace) {
  241. var meta = {};
  242. var $node;
  243. if (model.$type === 'text') {
  244. if (model.$text && typeof model.$text === 'function') model.$text = Phenotype.multiline(model.$text);
  245. $node = $root.document.createTextNode(model.$text);
  246. } else if (model.$type === 'svg') {
  247. $node = $root.document.createElementNS('http://www.w3.org/2000/svg', model.$type);
  248. meta.namespace = $node.namespaceURI;
  249. } else if (namespace) {
  250. $node = $root.document.createElementNS(namespace, model.$type);
  251. meta.namespace = $node.namespaceURI;
  252. } else if (model.$type === 'fragment') {
  253. $node = $root.document.createDocumentFragment();
  254. } else {
  255. $node = $root.document.createElement(model.$type || 'div');
  256. }
  257. $node.Meta = meta;
  258. return $node;
  259. },
  260. $components: function($parent, components) {
  261. if (!components) components = [];
  262. var old = [].map.call($parent.childNodes, function($node) {
  263. return $node.Genotype;
  264. }).filter(function(item) {
  265. return item; // only compare with Cells (that have Genotype), not additional elements created by another javascript library
  266. });
  267. if (old.length > 0) {
  268. // If childNodes already exist, try to insert into a correct position.
  269. var diff = Gene.diff(old, components);
  270. diff['-'].forEach(function(item) { $parent.childNodes[item.index].Kill = true; });
  271. [].filter.call($parent.childNodes, function($node) {
  272. return $node.Kill;
  273. }).forEach(function($node) {
  274. $parent.removeChild($node);
  275. });
  276. diff['+'].forEach(function(item) {
  277. var inheritance = $parent.Inheritance;
  278. for (var key in $parent.Genotype) {
  279. if (key[0] === '_') inheritance = inheritance.concat([key]);
  280. }
  281. $parent.$build(item.item, inheritance, item.index, $parent.Meta.namespace);
  282. $parent.$components[item.index] = $parent.childNodes[item.index].Genotype;
  283. });
  284. } else {
  285. // first time construction => no childNodes => build a fragment and insert at once
  286. var $fragment = Phenotype.$type({ $type: 'fragment' });
  287. var inheritance = $parent.Inheritance;
  288. for (var key in $parent.Genotype) {
  289. if (key[0] === '_') inheritance = inheritance.concat([key]);
  290. }
  291. while ($parent.firstChild) { $parent.removeChild($parent.firstChild); } // remove empty text nodes
  292. components.forEach(function(component) {
  293. $fragment.$build(component, inheritance, null, $parent.Meta.namespace);
  294. });
  295. $parent.appendChild($fragment);
  296. $parent.$components = [].map.call($parent.childNodes, function($node) { return $node.Genotype; });
  297. }
  298. },
  299. $init: function($node) {
  300. Nucleus.tick.call($root, function() {
  301. if ($node.Genotype && $node.Genotype.$init) Nucleus.bind($node, $node.Genotype.$init)();
  302. });
  303. },
  304. $update: function($node) {
  305. if ($node.parentNode && !$node.Meta.$updated && $node.$update) {
  306. $node.Meta.$updated = true;
  307. $node.$update();
  308. for (var key in $node.Dirty) { Phenotype.set($node, key, $node.Genotype[key]); }
  309. $node.Meta.$updated = false;
  310. $node.Dirty = null;
  311. }
  312. },
  313. };
  314. var Nucleus = {
  315. /*
  316. * [Nucleus] Handles the cell cycle
  317. *
  318. * "The nucleus maintains the integrity of genes and controls the activities of the cell by regulating gene expression—the nucleus is, therefore, the control center of the cell."
  319. * - https://en.wikipedia.org/wiki/Cell_nucleus
  320. *
  321. * The Nucleus module creates a proxy that lets Cell interface with the outside world. Its main job is to automatically trigger phenotype updates based on genotype updates
  322. *
  323. * - set(): Starts listening to a single attribute.
  324. * - build(): Starts listening to all attributes defined on the gene
  325. * - bind(): Creates a wrapper function that executes the original function, and then automatically updates the Phenotype if necessary.
  326. * - queue(): A function that queues up all potential genotype mutation events so that they can be batch-processed in a single tick.
  327. */
  328. tick: $root.requestAnimationFrame || $root.webkitRequestAnimationFrame || $root.mozRequestAnimationFrame || $root.msRequestAnimationFrame || function(cb) { return $root.setTimeout(cb, 1000/60); },
  329. set: function($node, key) {
  330. // Object.defineProperty is used for overriding the default getter and setter behaviors.
  331. try {
  332. Object.defineProperty($node, key, {
  333. configurable: true,
  334. get: function() {
  335. // 1. get() overrides the node's getter to create an illusion that users are directly accessing the attribute on the node (In reality they are accessing the genotype via nucleus)
  336. // 2. get() also queues up the accessed variable so it can potentially trigger a phenotype update in case there's been a mutation
  337. if (key[0] === '$' || key[0] === '_') {
  338. if (key in $node.Genotype) {
  339. Nucleus.queue($node, key, 'r');
  340. return $node.Genotype[key];
  341. } else if (key[0] === '_') {
  342. // Context Inheritance: If a _variable cannot be found on the current node, propagate upwards until we find a node with the attribute.
  343. var $current = $node;
  344. while ($current = $current.parentNode) { // eslint-disable-line no-cond-assign
  345. if ($current && $current.Genotype && (key in $current.Genotype)) {
  346. Nucleus.queue($current, key, 'r');
  347. return $current.Genotype[key];
  348. }
  349. }
  350. } else {
  351. return null;
  352. }
  353. } else {
  354. // DOM Attributes.
  355. if (key === 'value') {
  356. // The "value" attribute needs a special treatment.
  357. return Object.getOwnPropertyDescriptor(Object.getPrototypeOf($node), key).get.call($node);
  358. } else if (key === 'style') {
  359. return Phenotype.get(key).get.call($node);
  360. } else if (key in $node.Genotype) {
  361. // Otherwise utilize Genotype
  362. return $node.Genotype[key];
  363. } else {
  364. // If the key doesn't exist on the Genotype, it means we're dealing with native DOM attributes we didn't explicitly define on the gene.
  365. // For example, there are many DOM attributes such as "tagName" that come with the node by default.
  366. // These are not something we directly define on a gene object, but we still need to be able to access them..
  367. // In this case we just use the native HTMLElement.prototype accessor
  368. return Phenotype.get(key).get.call($node);
  369. }
  370. }
  371. },
  372. set: function(val) {
  373. // set() overrides the node's setter to create an illusion that users are directly setting an attribute on the node (In reality it's proxied to set the genotype value instead)
  374. // set() also queues up the mutated variable so it can trigger a phenotype update once the current call stack becomes empty
  375. // 0. Context Inheritance: If a _variable cannot be found on the current node, cell propagates upwards until it finds a node with the attribute.
  376. var $current = $node;
  377. if (!(key in $node.Genotype) && key[0] === '_') {
  378. while ($current = $current.parentNode) { // eslint-disable-line no-cond-assign
  379. if ($current && $current.Genotype && (key in $current.Genotype)) {
  380. break;
  381. }
  382. }
  383. }
  384. // 1. Set genotype by default
  385. Genotype.update($current, key, val);
  386. // 2. DOM attribute handling (anything that doesn't start with $ or _)
  387. if (key[0] !== '$' && key[0] !== '_') {
  388. if (key === 'value') {
  389. return Object.getOwnPropertyDescriptor(Object.getPrototypeOf($node), key).set.call($node, val);
  390. } else if (key === 'style' && typeof val === 'object') {
  391. Phenotype.get(key).set.call($node, val);
  392. } else if (typeof val === 'number' || typeof val === 'string' || typeof val === 'boolean') {
  393. $node.setAttribute(key, val);
  394. } else if (typeof val === 'function') {
  395. Phenotype.get(key).set.call($node, val);
  396. }
  397. }
  398. },
  399. });
  400. } catch (e) { /** native element edge case handling for electron **/ }
  401. },
  402. build: function($node) {
  403. // 1. The special attributes "$type", "$text", "$html", "$components" are tracked by default even if not manually defined
  404. ['$type', '$text', '$html', '$components'].forEach(function(key) {
  405. if (!(key in $node.Genotype)) Nucleus.set($node, key);
  406. });
  407. // 2. Used for context inheritance. We want to track not just the attributes directly defined on the current node but all the attributes inherited from ancestors.
  408. if ($node.Inheritance) {
  409. $node.Inheritance.forEach(function(key) {
  410. Nucleus.set($node, key);
  411. });
  412. }
  413. // 3. Track all keys defined on the gene object
  414. for (var key in $node.Genotype) {
  415. Nucleus.set($node, key);
  416. }
  417. },
  418. _queue: [],
  419. bind: function($node, v) {
  420. // Binding an attribute to the nucleus.
  421. // 1. No difference if the attribute is just a regular variable
  422. // 2. If the attribute is a function, we create a wrapper function that first executes the original function, and then triggers a phenotype update depending on the queue condition
  423. if (typeof v === 'function') {
  424. var fun = function() {
  425. // In the following code, everything inside Nucleus.tick.call is executed AFTER the last line--v.apply($node, arguments)--because it gets added to the event loop and waits until the next render cycle.
  426. // 1. Schedule phenotype update by wrapping them in a single tick (requestAnimationFrame)
  427. Nucleus.tick.call($root, function() {
  428. // At this point, Nucleus._queue contains all the nodes that have been touched since the last tick.
  429. // We process each node one by one to determine whether to update phenotype and whether to auto-trigger $update().
  430. // Note: If we're in a middle of multiple nested function calls (fnA calls fnB calls fnC), the queue will be processed from the first function (fnA) only,
  431. // This is because the Nucleus._queue will have been drained empty by the time the second function (fnB)'s Nucleus.tick.call reaches this point.
  432. Nucleus._queue.forEach(function($node) {
  433. var needs_update = false;
  434. /*
  435. * At this point, $node.Dirty looks something like this:
  436. * { "_index": 1, "_items": [0,1,2] }
  437. *
  438. * We go through each and compare with the latest version of the Genotype.
  439. * If there's been a change we set the Phenotype and mark it as "needs_update"
  440. */
  441. for (var key in $node.Dirty) {
  442. if (Gene.freeze($node.Genotype[key]) !== $node.Dirty[key]) { // Update phenotype if the new value is different from old (Dirty)
  443. Phenotype.set($node, key, $node.Genotype[key]);
  444. if (key[0] === '_') { needs_update = true; } // If any of the _ variables have changed, need to call $update
  445. }
  446. }
  447. if (needs_update && '$update' in $node.Genotype && (typeof $node.Genotype.$update === 'function')) {
  448. Phenotype.$update($node);
  449. } else { $node.Dirty = null; }
  450. });
  451. // Remove the $node from the queue
  452. var index = Nucleus._queue.indexOf($node);
  453. if (index !== -1) Nucleus._queue.splice(index, 1);
  454. });
  455. // 2. Run the actual function, which will modify the queue
  456. return v.apply($node, arguments);
  457. };
  458. fun.snapshot = v;
  459. return fun;
  460. } else {
  461. return v;
  462. }
  463. },
  464. queue: function($node, key, mode) {
  465. var val = $node.Genotype[key];
  466. if (mode === 'r') {
  467. /*
  468. * Read mode access => the key was queued as a result of a "get()", which doesn't normally mutate the variable.
  469. *
  470. * But we still need to take into account the cases where its descendants get mutated, which happens when we're dealing with an array or an object. For example:
  471. * - this._items.push(item);
  472. * - this._module.name="cell";
  473. *
  474. * In these cases we didn't directly mutate the variables (Direct mutations would have been something like: this._items=[1,2]; or this._module={name: "cell"};)
  475. * but each variable's value *did* change as a result of each expression. To make sure we don't miss these types, we queue them up with a "r" (read) type.
  476. * But we only need to do this for objects and arrays. (not string, number, etc. because they can't have descendants)
  477. */
  478. if (typeof val !== 'object' && !Array.isArray(val)) return;
  479. }
  480. if (Nucleus._queue.indexOf($node) === -1) { Nucleus._queue.push($node); }
  481. if (!$node.Dirty) $node.Dirty = {};
  482. if (!(key in $node.Dirty)) {
  483. /*
  484. * Caches the original gene under $node.Dirty when a key is touched.
  485. *
  486. * {
  487. * Dirty: {
  488. * "_index": 1,
  489. * "_items": [0,1,2]
  490. * }
  491. * }
  492. *
  493. */
  494. $node.Dirty[key] = Gene.freeze($node.Genotype[key]); // stores the original value under "Dirty"
  495. }
  496. },
  497. };
  498. var God = {
  499. /*
  500. * The Creator
  501. * The only purpose of this module is to create cells and get out of the way.
  502. */
  503. detect: function($context) {
  504. // takes a context, returns all the objects containing thew '$cell' key
  505. if ($context === undefined) $context = this;
  506. return Object.keys($context).filter(function(k) {
  507. try {
  508. if (/webkitStorageInfo|webkitIndexedDB/.test(k) || $context[k] instanceof $root.Element) return false; // Only look for plain javascript object
  509. return $context[k] && Object.prototype.hasOwnProperty.call($context[k], '$cell');
  510. } catch (e) { return false; }
  511. }).map(function(k) {
  512. return $context[k];
  513. });
  514. },
  515. plan: function($context) {
  516. // Prepare the DOM for cell creation by adding prototype methods to nodes.
  517. // As a result, all HTML elements become autonomous.
  518. if ($context === undefined) $context = $root;
  519. else $root = $context;
  520. $context.DocumentFragment.prototype.$build = $context.Element.prototype.$build = function(gene, inheritance, index, namespace, replace) {
  521. var $node = Membrane.build(this, gene, index, namespace, replace);
  522. Genotype.build($node, gene, inheritance || [], index);
  523. Nucleus.build($node);
  524. Phenotype.build($node, $node.Genotype);
  525. return $node;
  526. };
  527. $context.DocumentFragment.prototype.$cell = $context.Element.prototype.$cell = function(gene, options) {
  528. return this.$build(gene, [], null, (options && options.namespace) || null, true);
  529. };
  530. $context.DocumentFragment.prototype.$snapshot = $context.Element.prototype.$snapshot = function() {
  531. var json = JSON.stringify(this.Genotype, function(k, v) {
  532. if (typeof v === 'function' && v.snapshot) { return '(' + v.snapshot.toString() + ')'; }
  533. return v;
  534. });
  535. return JSON.parse(json, function(k, v) {
  536. if (typeof v === 'string' && v.indexOf('function') >= 0) { return eval(v); }
  537. return v;
  538. });
  539. };
  540. if ($root.NodeList && !$root.NodeList.prototype.forEach) $root.NodeList.prototype.forEach = Array.prototype.forEach; // NodeList.forEach override polyfill
  541. },
  542. create: function($context) {
  543. // Automatic cell generation based on declarative rules
  544. return God.detect($context).map(function(gene) {
  545. return $context.document.body.$build(gene, []);
  546. });
  547. },
  548. };
  549. // For testing
  550. if (typeof exports !== 'undefined') {
  551. var x = {
  552. Phenotype: Phenotype,
  553. Genotype: Genotype,
  554. Nucleus: Nucleus,
  555. Gene: Gene,
  556. Membrane: Membrane,
  557. God: God,
  558. plan: God.plan.bind(God),
  559. create: God.create.bind(God),
  560. };
  561. if (typeof module !== 'undefined' && module.exports) { exports = module.exports = x; }
  562. exports = x;
  563. } else {
  564. God.plan(this);
  565. if (this.addEventListener) {
  566. // Let there be Cell
  567. this.addEventListener('load', function() {
  568. God.create(this);
  569. });
  570. }
  571. }
  572. }(this));