UNPKG

1.99 kBJavaScriptView Raw
1import {select} from "d3-selection";
2import {transition} from "d3-transition";
3
4import {default as attrize} from "./attrize";
5
6/**
7 @function elem
8 @desc Manages the enter/update/exit pattern for a single DOM element.
9 @param {String} selector A D3 selector, which must include the tagname and a class and/or ID.
10 @param {Object} params Additional parameters.
11 @param {Boolean} [params.condition = true] Whether or not the element should be rendered (or removed).
12 @param {Object} [params.enter = {}] A collection of key/value pairs that map to attributes to be given on enter.
13 @param {Object} [params.exit = {}] A collection of key/value pairs that map to attributes to be given on exit.
14 @param {D3Selection} [params.parent = d3.select("body")] The parent element for this new element to be appended to.
15 @param {D3Transition} [params.transition = d3.transition().duration(0)] The transition to use when animated the different life cycle stages.
16 @param {Object} [params.update = {}] A collection of key/value pairs that map to attributes to be given on update.
17*/
18export default function(selector, p) {
19
20 // overrides default params
21 p = Object.assign({}, {
22 condition: true,
23 enter: {},
24 exit: {},
25 parent: select("body"),
26 transition: transition().duration(0),
27 update: {}
28 }, p);
29
30 var className = (/\.([^#]+)/g).exec(selector),
31 id = (/#([^\.]+)/g).exec(selector),
32 tag = (/^([^.^#]+)/g).exec(selector)[1];
33
34 var elem = p.parent.selectAll(selector.includes(":") ? selector.split(":")[1] : selector)
35 .data(p.condition ? [null] : []);
36
37 var enter = elem.enter().append(tag).call(attrize, p.enter);
38
39 if (id) { enter.attr("id", id[1]); }
40 if (className) { enter.attr("class", className[1]); }
41
42 elem.exit().transition(p.transition).call(attrize, p.exit).remove();
43
44 var update = enter.merge(elem);
45 update.transition(p.transition).call(attrize, p.update);
46
47 return update;
48
49}
50
51//# sourceMappingURL=elem.js.map
\No newline at end of file