-
Notifications
You must be signed in to change notification settings - Fork 4
/
imperative.js
268 lines (249 loc) · 8.13 KB
/
imperative.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
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
256
257
258
259
260
261
262
263
264
265
266
267
268
async function run(main, container=document.body) {
let cleanup = [], output = {v: null};
while(true) {
let value, done;
({value, done} = ('v' in output) ? main.next(output.v) : main.throw(output.e));
if(done) {
await Promise.all(cleanup.slice(0).reverse().map(k => k()));
console.log("Completed with value", value);
return value;
}
try {
output = {v: await value({
H: (felem) => {
let elem = felem( container, () => {
container.removeChild(elem);
});
if(elem) {
container.appendChild(elem);
}
},
cleanup: (k) => cleanup.push(k)
})};
} catch(e) {
output = {e};
}
await Promise.all(cleanup.slice(0).reverse().map(k => k()));
cleanup = [];
}
}
function never() {
return new Promise(resolve => {});
}
function* T(str) {
yield ({H, cleanup}) => {
H((_,remover) => { cleanup(remover); return document.createTextNode(str) });
return never();
};
}
function* A(name, val) {
yield ({H, cleanup}) => {
H((elem) => {
elem[ name ] = val;
cleanup(() => { elem[ name ] = null; });
});
return never();
};
}
function* globalStyle(css) {
yield ({cleanup}) => {
let ss = document.createElement("style");
document.head.appendChild(ss);
ss.innerText = css;
cleanup(() => document.head.removeChild(ss));
return never();
}
}
function* S(name, val) {
let obj = typeof name === 'object' ? name : {[name]: val};
yield ({H, cleanup}) => {
H((elem) => {
for(let [name, val] of Object.entries(obj)) {
elem.style[ name ] = val;
}
cleanup(() => {
for(let [name, val] of Object.entries(obj)) {
elem.style[ name ] = null;
}
});
});
return never();
};
}
function* E(name) {
return yield ({H, cleanup}) => new Promise(resolve => {
H((elem) => {
let fn = (ev) => resolve(ev);
elem.addEventListener(name, fn);
cleanup(() => { elem.removeEventListener( name, fn ) });
});
});
}
function* H(name, ...children) {
children = children.flat(1).map(child => typeof child === 'string' ? function*() { yield* T(child) } : child);
let childElems = children.map(() => []);
let parentElem = document.createElement(name);
return yield* multi(
function*() {
yield ({H, cleanup}) => {
H((_,remover) => { cleanup(remover); return parentElem });
return never();
}
},
children.map((child, ii) =>
local(({H, ...args}) => ({
H: (fel) => {
let el = fel(parentElem, () => {
childElems[ii] = childElems[ii].filter(cel => cel !== el);
parentElem.removeChild(el);
});
if(el) {
let nextChild = childElems.slice(ii+1).flat().find(Boolean);
if(nextChild) parentElem.insertBefore(el, nextChild);
else parentElem.appendChild(el);
childElems[ii].push(el);
}
},
...args
}), child)
)
);
}
function toGen(gen) {
if(typeof gen === 'string') return T(gen);
return gen.next ? gen : gen();
}
function* local(fn, ...gens) {
gens = gens.flat(1).map(toGen);
const gen = gens.length === 1 ? gens[0] : multi(gens);
let output = {v: null};
while(true) {
let {value, done} = ('v' in output) ? gen.next(output.v) : gen.throw(output.e);
if(done) return value;
try {
output = {v: yield (args) => value(fn(args))};
} catch(e) {
output = {e};
}
}
}
function* multi(...gens) {
gens = gens.flat(1).map(toGen);
let cleanups = gens.map(() => []);
return yield (args) => {
return new Promise((resolve, reject) => {
let resolved = false;
args.cleanup(() => {
resolved = true;
cleanups.flat(1).reverse().map(k => k())
});
gens.map(async (gen, ii) => {
let output = {v: null};
while(true) {
if(resolved) {
return;
}
let value, done;
try {
({value, done} = ('v' in output) ? gen.next(output.v) : gen.throw(output.e));
} catch(e) {
if(!resolved) {
resolved = true;
reject(e);
}
return;
}
if(done) {
if(!resolved) {
resolved = true;
resolve(value);
}
return;
}
try {
output = {v: await value({...args, cleanup: (k) => cleanups[ii].push(k)})};
} catch(e) {
output = {e};
}
await Promise.all(cleanups[ii].slice(0).reverse().map(k => k()));
cleanups[ii] = [];
}
});
});
}
}
function AsyncVar(init) {
let value = init;
const listeners = new Set();
return {
get: () => value,
next: function(cleanup) {
return new Promise(resolve => {
listeners.add(resolve);
cleanup(() => {
listeners.delete(resolve)
});
});
},
set: (v) => {
value = v;
listeners.forEach(cb => cb(value));
}
}
}
function wrapAsyncVar(asyncVar) {
return {
get: asyncVar.get,
next: function*() {
return yield ({cleanup}) => asyncVar.next(cleanup);
},
set: asyncVar.set,
fmap: function*(fn) {
let self = this;
while(true) {
let res = yield* multi(function*() { yield* self.next(); return null; }, function*() { return [yield* fn(self.get())] });
if(res) return res[0];
}
}
}
}
function Var(init) {
if(Object.prototype.toString.call(init) === '[object AsyncGenerator]') {
let ret = Var(undefined);
(async () => {
for await(val of init) {
ret.set(val);
}
})();
return ret;
}
return wrapAsyncVar( AsyncVar(init) );
}
function* openPortal(fn) {
let portalArgs;
let resolvePortal;
let portalReady = new Promise(resolve => { resolvePortal = resolve; });
return yield* fn(
function* () { yield ({cleanup, ...args}) => { portalArgs = args; resolvePortal(); return new Promise(resolve => {}) } },
function* (portalChild) { yield () => portalReady; return yield* local(({cleanup, ...args}) => ({cleanup, ...portalArgs}), portalChild); });
}
function* Fetch(url, opts={}) {
return yield ({cleanup}) => {
let ac = new AbortController();
cleanup(() => ac.abort());
return fetch(url, {...opts, signal: ac.signal}).then(fetchResult => {
let json = fetchResult.json.bind(fetchResult);
let text = fetchResult.text.bind(fetchResult);
fetchResult.json = function*() { yield () => json() };
fetchResult.text = function*() { yield () => text() };
return fetchResult;
});
}
}
function* wait(n) {
yield () => new Promise(resolve => setTimeout(resolve, n));
}
function* waitFrame(n) {
yield () => new Promise(resolve => requestAnimationFrame(resolve));
}
module.exports = { run, multi, local, H, A, S, T, E, globalStyle, Var, openPortal, never, Fetch, wait, waitFrame };