-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinds_update.js
More file actions
255 lines (221 loc) · 8.15 KB
/
binds_update.js
File metadata and controls
255 lines (221 loc) · 8.15 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
/**
* binds_update.js
* version: 0.2
* author: Akritas Akritidis
* repo: https://github.com/MaanooAk/function-frameworks
*/
/**
* Bind expressions with element properties.
*
* @param {Document | Element | string} [root=document] - Selector string or root element.
* @param {Partial<BindsUpdateOptions>} options - Optional configuration options.
*/
function binds_update(root = document, options = null) {
const default_options = {
attr: "data-bind",
consume: false,
reflect: "data-bond",
implicit: "html",
separator: ";",
binder: ":",
compiler: (expr) => eval(`(self, context) => ${expr}`),
visibility: false,
remember: true,
reset: false,
extensions: {},
}
let remembered_options = {};
function calc_options(options_param) {
const options = Object.assign({}, default_options, remembered_options);
if (options_param) {
Object.assign(options, options_param);
if (options.remember) remembered_options = options_param;
if (options_param.reset) remembered_options = {};
}
return options;
}
function find_root(root) {
if (typeof root === "string") {
const possible = Array.from(document.querySelectorAll(root));
if (possible.length == 0) throw new Error(`Root selects no elements: ${root}`)
if (possible.length >= 2) throw new Error(`Root selects multiple elements: ${root}`)
return possible[0]
} else if (root.querySelectorAll) {
return root;
} else {
throw new TypeError(`Unsupported root type: ${root}`)
}
}
function collect_new_elements(root, options) {
if (typeof root === "string") {
return Array.from(document.querySelectorAll(`${root} [${options.attr}]`));
} else if (root.querySelectorAll) {
return Array.from(root.querySelectorAll(`[${options.attr}]`));
} else {
throw new TypeError(`Unsupported root type: ${root}`)
}
}
const Done = Symbol();
const types = {
"html": (e, v) => e.innerHTML = v ?? "",
"text": (e, v) => e.textContent = v ?? "",
"number": (e, v) => e.textContent = v?.toLocaleString() ?? "",
"value": (e, v) => e.value = v,
"checked": (e, v) => e.checked = !!v,
"context": (e, v) => e.context = v,
"hidden": (e, v) => e.hidden = !!v,
"visible": (e, v) => e.hidden = !v,
"if": (e,v) => {
const cond = !!v
if (e.children[0]) e.children[0].hidden = !cond
if (e.children[1]) e.children[1].hidden = cond
},
// once
"const": (e, v) => {
e.innerHTML = v
return Done
},
"tap": (e, v) => {
const callback = v
e.addEventListener("pointerup", (event) => {
callback(event)
event.stopPropagation()
})
e.classList.add("tap")
return Done
},
"click": (e, v) => {
const callback = v
e.addEventListener("click", (event) => {
callback(event)
event.stopPropagation()
})
e.classList.add("click")
return Done
},
}
const dynamic_types = {
"class-": (e, v, name) => v ? e.classList.add(name) : e.classList.remove(name),
"attr-": (e, v, name) => e.setAttribute(name, v),
"var-": (e, v, name) => e.style.setProperty("--" + name, v)
}
function parse_defs(text, options) {
const def_texts = text.split(options.separator);
const defs = [];
for (const i of def_texts) {
const def = parse_def(i, options);
if (def) defs.push(def);
}
return defs;
}
function parse_def(text, options) {
const trimmed = text.trim();
if (!trimmed) return null;
const index = trimmed.indexOf(options.binder);
if (index == -1) return create_updater(types[options.implicit], null, trimmed, options);
const type = trimmed.substring(0, index).trim();
const expr = trimmed.substring(index + 1).trim();
const types_type = types[type];
if (types_type) return create_updater(types_type, null, expr, options);
const extension_type = options.extensions[type];
if (extension_type) return create_updater(extension_type, null, expr, options);
const type_index = type.indexOf("-");
if (type_index == -1) throw new Error(`Unknown type '${type}' in: ${text}`);
const prefix = type.substring(0, type_index + 1)
const name = type.substring(type_index + 1)
const dynamic_types_type = dynamic_types[prefix];
if (dynamic_types_type) return create_updater(dynamic_types_type, name, expr, options)
const extension_dynamic_type = options.extensions[prefix];
if (extension_dynamic_type) return create_updater(extension_dynamic_type, name, expr, options);
throw new Error(`Unknown dynamic type '${prefix}' in: ${text}`);
}
const UniqNull = Symbol();
function create_updater(handler, name, expr, options) {
const provider = options.compiler(expr);
let last = UniqNull;
let skip = false;
return (ele) => {
if (skip) return false;
if (options.visibility && !ele.parentElement.checkVisibility()) return false;
const value = provider(ele, find_context(ele));
if (value === last) return false;
last = value;
const res = handler(ele, value, name);
if (res === Done) skip = true;
return true;
}
}
function find_context(element, grand = 0) {
while (element) {
const context = element.context;
if (context) {
if (grand === 0) return context
grand -=1
}
element = element.parentElement;
}
}
const elements = [];
let elements_dead = 0;
function update_all() {
for (const i of elements) {
if (i.updaters.length) {
update_element(i)
}
}
}
function update_inside(root_element) {
for (const i of elements) {
if (i.updaters.length && root_element.contains(i.element)) {
update_element(i)
}
}
}
function update_element({ element, updaters }, options) {
if (!element.isConnected) {
updaters.length = 0;
elements_dead += 1;
return false;
}
for (const updater of updaters) {
updater(element);
}
return true;
}
function clean_elements() {
let start = 0;
while (elements[start]?.updaters.length == 0) start++;
const reduced = [];
for (let i = start; i < elements.length; i++) {
if (elements[i].updaters.length == 0) continue;
reduced.push(elements[i]);
}
elements.length = start + reduced.length;
for (let i = 0; i < reduced.length; i++) {
elements[start + i] = reduced[i];
}
elements_dead = 0;
}
binds_update = function binds_update(root = document, options_param) {
const options = calc_options(options_param);
if (!root) return update_all();
const new_elements = collect_new_elements(root, options);
for (const element of new_elements) {
const defs_text = element.getAttribute(options.attr);
const updaters = parse_defs(defs_text, options);
elements.push({ element, updaters })
if (!options.consume) {
element.setAttribute(options.reflect, defs_text);
}
element.removeAttribute(options.attr);
}
if (elements_dead > elements.length / 2) {
clean_elements();
}
const root_element = find_root(root);
return update_inside(root_element);
}
binds_update.Done = Done;
return binds_update(document, options);
}
export default function (...args) { return binds_update(...args); }