Repository navigation
Expand file tree
/
Copy pathpluton.js
More file actions
77 lines (60 loc) · 2.17 KB
/
Copy pathpluton.js
File metadata and controls
77 lines (60 loc) · 2.17 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
export default class Pluton {
constructor(modules) {
this.modules = modules;
this.classes = {};
this.instances = {};
this.ready = this.loadModules().then(classes => {
this.classes = classes;
this.setup();
return this;
});
}
async loadModules() {
// IMPORTANT: `{ eager: true }` must stay a literal `true`. Vite's production
// glob transform (Rolldown) only recognises static literals and silently
// falls back to lazy imports for anything else (e.g. a minifier's `!0`).
// This file is therefore shipped unminified on purpose.
const modules = this.modules ?? import.meta.glob('/resources/js/parts/*.js', { eager: true });
const entries = await Promise.all(
Object.entries(modules).map(async ([path, mod]) => [
path,
typeof mod === 'function' ? await mod() : mod,
])
);
const classes = {};
for (const [path, mod] of entries) {
const component = mod?.default;
if (!component?.selector) {
console.warn(`[Pluton] "${path}" has no default export with a static "selector" and was skipped.`);
continue;
}
classes[component.selector] = component;
}
return classes;
}
clear() {
this.instances = {};
}
setup(root) {
for (const className in this.classes) {
this.setupComponent(className, this.classes[className], root);
}
}
setupComponent(className, component, root) {
if (!component.selector) {
return;
}
(root || document).querySelectorAll(component.selector).forEach(el => {
if (!this.instances[className]) {
this.instances[className] = [];
}
this.instances[className].push(new component(el));
});
}
call(className, fn, parameters) {
if (!this.instances[className]) return;
for (let i = this.instances[className].length - 1; i >= 0; i--) {
this.instances[className][i][fn](parameters);
}
}
}