Skip to content

Commit

Permalink
feat(hiccup): add support for dynamic user context values
Browse files Browse the repository at this point in the history
- add derefContext() helper to auto-deref any IDeref vals
- update serialize()
  • Loading branch information
postspectacular committed Nov 6, 2018
1 parent 46bf1a7 commit a947873
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
14 changes: 14 additions & 0 deletions packages/hiccup/src/deref.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { implementsFunction } from "@thi.ng/checks/implements-function";

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;
}
return res;
};
1 change: 1 addition & 0 deletions packages/hiccup/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from "./api";
export * from "./css";
export * from "./deref";
export * from "./escape";
export * from "./serialize";
9 changes: 7 additions & 2 deletions packages/hiccup/src/serialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import { isNotStringAndIterable } from "@thi.ng/checks/is-not-string-iterable";
import { isPlainObject } from "@thi.ng/checks/is-plain-object";
import { isString } from "@thi.ng/checks/is-string";
import { illegalArgs } from "@thi.ng/errors/illegal-arguments";

import {
COMMENT,
NO_SPANS,
TAG_REGEXP,
VOID_TAGS
} from "./api";
import { css } from "./css";
import { derefContext } from "./deref";
import { escape } from "./escape";

/**
Expand Down Expand Up @@ -70,6 +70,11 @@ 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.
*
* ```js
* const foo = (ctx, a, b) => ["div#" + a, ctx.foo, b];
*
Expand Down Expand Up @@ -118,7 +123,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, ctx, escape, span, keys, path);
_serialize(tree, derefContext(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 a947873

Please sign in to comment.