-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathindex.js
69 lines (65 loc) · 2.54 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import dispatch from "./dispatch.js";
import {inspect} from "./inspect.js";
import inspectName from "./inspectName.js";
const LOCATION_MATCH = /\s+\(\d+:\d+\)$/m;
export class Inspector {
constructor(node) {
if (!node) throw new Error("invalid node");
this._node = node;
node.classList.add("observablehq");
}
pending() {
const {_node} = this;
_node.classList.remove("observablehq--error");
_node.classList.add("observablehq--running");
}
fulfilled(value, name) {
const {_node} = this;
if (!isnode(value) || (value.parentNode && value.parentNode !== _node)) {
value = inspect(value, false, _node.firstChild // TODO Do this better.
&& _node.firstChild.classList
&& _node.firstChild.classList.contains("observablehq--expanded"), name);
value.classList.add("observablehq--inspect");
}
_node.classList.remove("observablehq--running", "observablehq--error");
if (_node.firstChild !== value) {
if (_node.firstChild) {
while (_node.lastChild !== _node.firstChild) _node.removeChild(_node.lastChild);
_node.replaceChild(value, _node.firstChild);
} else {
_node.appendChild(value);
}
}
dispatch(_node, "update");
}
rejected(error, name) {
const {_node} = this;
_node.classList.remove("observablehq--running");
_node.classList.add("observablehq--error");
while (_node.lastChild) _node.removeChild(_node.lastChild);
var div = document.createElement("div");
div.className = "observablehq--inspect";
if (name) div.appendChild(inspectName(name));
div.appendChild(document.createTextNode((error + "").replace(LOCATION_MATCH, "")));
_node.appendChild(div);
dispatch(_node, "error", {error: error});
}
}
Inspector.into = function(container) {
if (typeof container === "string") {
container = document.querySelector(container);
if (container == null) throw new Error("container not found");
}
return function() {
return new Inspector(container.appendChild(document.createElement("div")));
};
};
// Returns true if the given value is something that should be added to the DOM
// by the inspector, rather than being inspected. This deliberately excludes
// DocumentFragment since appending a fragment “dissolves” (mutates) the
// fragment, and we wish for the inspector to not have side-effects. Also,
// HTMLElement.prototype is an instanceof Element, but not an element!
function isnode(value) {
return (value instanceof Element || value instanceof Text)
&& (value instanceof value.constructor);
}