From c047d5310fb0efca14b7a9dd72fd57fc385b3fe0 Mon Sep 17 00:00:00 2001 From: ansuz Date: Thu, 24 Mar 2016 12:11:31 +0100 Subject: [PATCH] implement optional filtering in hyperjson Implemented via callback, return falsey if you want to filter an element and all of its children from the serialized result. Conflicts: www/common/convert.js --- www/common/convert.js | 24 +++++++++++++++++++++--- www/common/hyperjson.js | 15 ++++++++++++--- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/www/common/convert.js b/www/common/convert.js index d37e98539..973881c80 100644 --- a/www/common/convert.js +++ b/www/common/convert.js @@ -1,14 +1,16 @@ define([ + '/common/virtual-dom.js', '/common/hyperjson.js', '/common/hyperscript.js' -], function (hyperjson, hyperscript) { +], function (vdom, hyperjson, hyperscript) { // complain if you don't find the required APIs - if (!(hyperjson && hyperscript)) { throw new Error(); } + if (!(vdom && hyperjson && hyperscript)) { throw new Error(); } // Generate a matrix of conversions /* convert.dom.to.hjson, convert.hjson.to.dom, convert.dom.to.vdom, convert.vdom.to.dom, + convert.vdom.to.hjson, convert.hjson.to.vdom and of course, identify functions in case you try to convert a datatype to itself @@ -20,13 +22,28 @@ define([ methods = { dom:{ dom: Self, - hjson: hyperjson.fromDOM + hjson: hyperjson.fromDOM, + vdom: function (D) { + return hyperjson.callOn(hyperjson.fromDOM(D), vdom.h); + } }, hjson:{ hjson: Self, dom: function (H) { // hyperjson.fromDOM, return hyperjson.callOn(H, hyperscript); + }, + vdom: function (H) { + return hyperjson.callOn(H, vdom.h); + } + }, + vdom:{ + vdom: Self, + dom: function (V) { + return vdom.create(V); + }, + hjson: function (V) { + return hyperjson.fromDOM(vdom.create(V)); } } }, @@ -38,6 +55,7 @@ define([ }()); convert.core = { + vdom: vdom, hyperjson: hyperjson, hyperscript: hyperscript }; diff --git a/www/common/hyperjson.js b/www/common/hyperjson.js index 660c62194..31a2caf08 100644 --- a/www/common/hyperjson.js +++ b/www/common/hyperjson.js @@ -47,13 +47,20 @@ define([], function () { return x; }; - var DOM2HyperJSON = function(el){ + var DOM2HyperJSON = function(el, predicate){ if(!el.tagName && el.nodeType === Node.TEXT_NODE){ return el.textContent; } if(!el.attributes){ return; } + + if (predicate) { + if (!predicate(el)) { + // shortcircuit + return; + } + } var attributes = {}; var i = 0; @@ -102,10 +109,12 @@ define([], function () { // js hint complains if we use 'var' here i = 0; + for(; i < el.childNodes.length; i++){ - children.push(DOM2HyperJSON(el.childNodes[i])); + children.push(DOM2HyperJSON(el.childNodes[i], predicate)); } - result.push(children); + + result.push(children.filter(isTruthy)); return result; };