Skip to content

Commit

Permalink
feat(hiccup): update derefContext() to only apply to selected keys
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Nov 7, 2018
1 parent d279751 commit 749925f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 14 deletions.
23 changes: 15 additions & 8 deletions packages/hiccup/src/deref.ts
@@ -1,14 +1,21 @@
import { implementsFunction } from "@thi.ng/checks/implements-function";

/**
* Takes an arbitrary `ctx` object and array of `keys`. Attempts to call
* `.deref()` on all given keys' values and stores result values instead
* of original. Returns updated copy of `ctx` or original if `ctx` is
* `null` or no keys were given.
*
* @param ctx
* @param keys
*/
export const derefContext =
(ctx: any) => {
if (ctx == null) return ctx;
const res = {};
for (let k in ctx) {
const v = ctx[k];
res[k] = implementsFunction(v, "deref") ?
v.deref() :
v;
(ctx: any, keys: PropertyKey[]) => {
if (ctx == null || !keys || !keys.length) return ctx;
const res = { ...ctx };
for (let k of keys) {
const v = res[k];
implementsFunction(v, "deref") && (res[k] = v.deref());
}
return res;
};
11 changes: 5 additions & 6 deletions packages/hiccup/src/serialize.ts
Expand Up @@ -11,7 +11,6 @@ import {
VOID_TAGS
} from "./api";
import { css } from "./css";
import { derefContext } from "./deref";
import { escape } from "./escape";

/**
Expand Down Expand Up @@ -70,10 +69,10 @@ import { escape } from "./escape";
* as arguments when that function is called. The return value the
* function MUST be a valid new tree (or `undefined`).
*
* If the `ctx` object is given a shallow copy is passed to component
* fns and any context keys with values implementing the thi.ng/api
* `IDeref` interface, will be automatically deref'd prior to
* serialization.
* If the `ctx` object it'll be passed to each embedded component fns.
* Optionally call `derefContext()` prior to `serialize()` to
* auto-deref context keys with values implementing the thi.ng/api
* `IDeref` interface.
*
* ```js
* const foo = (ctx, a, b) => ["div#" + a, ctx.foo, b];
Expand Down Expand Up @@ -123,7 +122,7 @@ import { escape } from "./escape";
* @param keys attach key attribs
*/
export const serialize = (tree: any, ctx?: any, escape = false, span = false, keys = span, path = [0]) =>
_serialize(tree, derefContext(ctx), escape, span, keys, path);
_serialize(tree, ctx, escape, span, keys, path);

const _serialize = (tree: any, ctx: any, esc: boolean, span: boolean, keys: boolean, path: any[]) => {
if (tree == null) {
Expand Down

0 comments on commit 749925f

Please sign in to comment.