-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathhooks.js
77 lines (62 loc) · 2.19 KB
/
hooks.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
70
71
72
73
74
75
76
77
// Used by workaround for input element value field
// Based on https://github.com/Matt-Esch/virtual-dom/blob/947ecf92b67d25bb693a0f625fa8e90c099887d5/virtual-hyperscript/hooks/soft-set-hook.js
globalThis.SoftSetHook = function(value) {
if (!(this instanceof SoftSetHook)) {
return new SoftSetHook(value);
}
this.value = value;
};
globalThis.SoftSetHook.prototype.hook = function (node, propertyName) {
if (node[propertyName] !== this.value) {
node[propertyName] = this.value;
}
};
var GenericHook = function (init, update, destroy, id, extra) {
if (!(this instanceof GenericHook)) {
return new GenericHook(init, update, destroy, id, extra);
}
this.init = init;
this.update = update;
this.destroy = destroy;
this.id = id;
this.extra = extra;
};
var hook_state_key = "vdom_hook_state_key";
if (this.Symbol) {
hook_state_key = Symbol(hook_state_key);
}
GenericHook.write_state = function (node, propName, state) {
if (!node[hook_state_key]) {
node[hook_state_key] = {};
}
node[hook_state_key][propName] = state;
}
GenericHook.read_state = function (node, propName) {
return node[hook_state_key][propName];
}
GenericHook.remove_state = function (node, propName) {
delete node[hook_state_key][propName];
}
GenericHook.canTransition = function (from, to) {
return from instanceof this && to instanceof this && from.id === to.id && to.update;
};
GenericHook.prototype.hook = function (node, propName, prev) {
if (GenericHook.canTransition(prev, this)) {
var state = GenericHook.read_state(node, propName);
state = this.update(state, node);
GenericHook.write_state(node, propName, state);
} else {
var state = this.init(node);
GenericHook.write_state(node, propName, state);
}
};
GenericHook.prototype.unhook = function (node, propName, next) {
if (GenericHook.canTransition(this, next)) {
// Do nothing, the impending [hook] will handle the call to update.
} else {
var state = GenericHook.read_state(node, propName);
this.destroy(state, node);
GenericHook.remove_state(node, propName);
}
};
globalThis.GenericHook = GenericHook;