/
index.ts
394 lines (368 loc) · 12.1 KB
/
index.ts
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import UrlPattern from 'url-pattern';
import assertNever from './assert-never';
import { ElementLifecycle } from './element-lifecycle';
import { GateKeeper } from './gate-keeper';
import Telemetry, { TelemetryLevel, TelemetryHandler, consoleTelemetryHandler } from './telemetry';
/** The name of the vacancy attribute. */
export const VACANCY_ATTRIBUTE = 'data-vacancy';
const DEFAULT_OPTIONS = {
telemetryLevel: 'warn',
telemetryHandler: consoleTelemetryHandler,
} as const;
/**
* A promise that resolves when all vacancies matching
* a given pattern have disappeared from the DOM.
*/
export type ExitPromise = Promise<void>;
/**
* Key/value pairs representing a match against a vacancy.
* For example, the vacancy `"users/123"` matches the pattern `"users/:id"`.
* The corresponding match object would look like this: `{ id: '123' }`.
*/
export interface PatternMatch {
[key: string]: string;
}
/**
* Options used when creating a Motel instance.
*/
export interface MotelOptions {
/**
* Higher levels generate less telemetry.
* For example, use `"warn"` in prod, `"debug"` in dev.
* The default is `"warn"`.
*/
telemetryLevel?: TelemetryLevel;
/**
* Supplying this overrides the default behavior of logging to console.
*/
telemetryHandler?: TelemetryHandler;
}
/**
* Callback that executes when a vacancy matches a string pattern.
*
* @typeparam A The type of object that you'll dispatch to your app.
* @param matchObject The result of matching the vacancy with the string pattern.
* @param dispatch Dispatches data to your app.
* @param exit Called when all matching vacancies have left the DOM.
*/
export interface PatternCallback<A> {
(
matchObject: PatternMatch,
dispatch: Dispatcher<A>,
exit: ExitPromise,
): void | Promise<void>;
}
/**
* Callback that executes when a vacancy matches a regex pattern.
*
* @typeparam A The type of object that you'll dispatch to your app.
* @param matchArray The result of matching the vacancy with the regex.
* @param dispatch Dispatches data to your app.
* @param exit Called when all matching vacancies have left the DOM.
*/
export interface RegExpCallback<A> {
(
matchArray: RegExpMatchArray,
dispatch: Dispatcher<A>,
exit: ExitPromise,
): void | Promise<void>;
}
/**
* Callback that executes when any vacancy is found.
*
* @typeparam A The type of object that you'll dispatch to your app.
* @param vacancy The vacancy that was found.
* @param dispatch Dispatches data to your app.
* @param exit Called when all matching vacancies have left the DOM.
*/
export interface WildcardCallback<A> {
(
vacancy: string,
dispatch: Dispatcher<A>,
exit: ExitPromise,
): void | Promise<void>;
}
/**
* Used to dispatch an object of type `<A>` to any subscribers.
*
* @typeparam A The type of object to be dispatched.
*/
export interface Dispatcher<A> {
(action: A): void;
}
type Observer<T>
= PatternObserver<T>
| RegExpObserver<T>
| WildcardObserver<T>;
interface PatternObserver<T> {
is: 'pattern';
pattern: UrlPattern;
handler: PatternCallback<T>;
cleanup?: () => void;
}
interface RegExpObserver<T> {
is: 'regex';
regex: RegExp;
handler: RegExpCallback<T>;
cleanup?: () => void;
}
interface WildcardObserver<T> {
is: 'wildcard';
handler: WildcardCallback<T>;
cleanup?: () => void;
}
/**
* This is your main API entry point to this library.
*
* An instance of this class manages your vacancy observers,
* including methods for adding observers and listening on a
* DOM element. Typically the instance would be created at
* application startup time and would last for the duration
* of the app.
*
* Internally, it creates a `MutationObserver` which does
* the actual work of detecting vacancies.
*
* For convenience, methods on this class are chainable,
* allowing patterns like this:
*
* ```js
* const vacancies = Motel.create()
* .observe(...observer callback...)
* .observe(...observer callback...)
* .observe(...observer callback...)
* .subscribe(action => store.dipatch(action))
* .connect(document.querySelector('#root'));
* ```
*
* ...however note that it may be better to break these
* calls across different modules.
*
* @typeparam A The output type of this Motel instance.
* That is, the type of object you'll dispatch from your
* observer callbacks. For example, in a Redux app this
* would probably be your Redux action type.
*/
export default class Motel<A = any> {
/**
* Create a new instance with the given options.
*
* @typeparam A The type of object that you'll dispatch to
* your app from your vacancy observers.
*/
public static create<AA = any>(opts: MotelOptions = DEFAULT_OPTIONS) {
return new Motel<AA>(opts);
}
private readonly telemetry: Telemetry;
private readonly send: Dispatcher<A>;
private readonly observers: Observer<A>[];
private readonly subscriptions: Dispatcher<A>[];
private lifecycle?: ElementLifecycle;
private constructor(opts: MotelOptions) {
const allOpts = { ...DEFAULT_OPTIONS, ...opts };
this.telemetry = new Telemetry(
allOpts.telemetryLevel,
allOpts.telemetryHandler,
);
const observers: Observer<A>[] = [];
const subscriptions: Dispatcher<A>[] = [];
const send = createPublishFunc(subscriptions, this.telemetry);
this.send = send;
this.observers = observers;
this.subscriptions = subscriptions;
this.telemetry.send('debug', 'instance created');
}
/**
* Create a wildcard observer that sees every vacancy.
*
* @param wildcard The special `"*"` string, which represents
* a pattern that matches everything.
*/
public observe(wildcard: '*', handler: WildcardCallback<A>): Motel<A>
/**
* Create an observer that matches vacancies based on the
* given string pattern. Pattern matching follows the rules of
* a [UrlPattern](https://www.npmjs.com/package/url-pattern)
* object.
*
* @param stringPattern A pattern string as described
* [here](https://www.npmjs.com/package/url-pattern).
*/
public observe(stringPattern: string, handler: PatternCallback<A>): Motel<A>
/**
* Create an observer that matches vacancies based on a regex.
*
* @param regex A pattern string as described
* [here](https://www.npmjs.com/package/url-pattern).
*/
public observe(regex: RegExp, handler: RegExpCallback<A>): Motel<A>
/**
* @param handler A callback function that runs whenever
* a vacancy is found.
*/
public observe(matcher: string | RegExp, handler: any): Motel<A> {
const { observers } = this;
if (matcher === '*') {
this.telemetry.send('debug', 'adding wildcard observer');
observers.push({ is: 'wildcard', handler });
} else if (typeof matcher === 'string') {
const pattern = new UrlPattern(matcher);
this.telemetry.send('debug', `adding string pattern observer: ${matcher}`);
observers.push({ is: 'pattern', pattern, handler });
} else {
const regex = matcher;
this.telemetry.send('debug', `adding regex observer: ${regex}`);
observers.push({ is: 'regex', regex, handler });
}
return this;
}
/**
* Connect a `MutationObserver` to the given root DOM element and begin watchng for vacancies.
* It also synchronously finds pre-existing vacancies in the root's subtree and reports them to observers.
* Observers should thus be attached before calling this method, or some vacancies may go undetected.
* This is especially relevant if you're using SSR.
*
* @param root Vacancies occurring on or anywhere below
* this element will be observed.
*/
public connect(root: Element): Motel<A> {
if (this.lifecycle) {
this.telemetry.send('error', 'instance is already connected');
return this;
}
const id = root.id ? `#${root.id}` : '';
const className = root.className ? `.${root.className}` : '';
const nodeDescriptor = `${root.nodeName.toLowerCase()}${id}${className}`;
this.telemetry.send('debug', `connecting instance to DOM node: ${nodeDescriptor}`);
const gateKeeper = new GateKeeper();
this.lifecycle = ElementLifecycle.of(root, VACANCY_ATTRIBUTE)
.on('enter', async(el, vacancy) => {
this.telemetry.send('silly', `incrementing vacancy: ${vacancy}`);
const exitProm = gateKeeper.incr(vacancy);
if (exitProm) {
// exits proceed async
// so entrances should too
await tick();
this._publish(vacancy, exitProm);
}
})
.on('exit', (el, vacancy) => {
this.telemetry.send('silly', `decrementing vacancy: ${vacancy}`);
gateKeeper.decr(vacancy);
})
.start();
return this;
}
/**
* Stop listening for vacancies.
*/
public disconnect(): Motel<A> {
if (!this.lifecycle) {
this.telemetry.send('error', 'instance is not connected');
return this;
}
this.telemetry.send('debug', 'disconnecting instance');
this.lifecycle.stop();
delete this.lifecycle;
return this;
}
/**
* Subscribe to the output of this instance. That is, a stream
* of objects of type `<A>`. Every dispatched object will be
* seen by the subscriber.
*
* @param subscriber A callback function which receives
* objects of type `A` dispatched from your vacancy
* observers.
*/
public subscribe(subscriber: Dispatcher<A>): Motel<A> {
this.telemetry.send('debug', 'adding subscriber');
const { subscriptions } = this;
subscriptions.push(subscriber);
return this;
}
/** @hidden */
_publish(vacancy: string, exitProm: Promise<void>): void {
this.telemetry.send('debug', `entering vacancy: ${vacancy}`);
exitProm.then(() =>
this.telemetry.send('debug', `exiting vacancy: ${vacancy}`));
const { observers, send } = this;
const proms: Array<Promise<void> | void> = [];
for (let observer of observers) {
switch (observer.is) {
case 'wildcard': {
const { handler } = observer;
this.telemetry.send('debug', `handling wildcard vacancy: ${vacancy}`);
try { proms.push(handler(vacancy, send, exitProm)); }
catch(ex) { proms.push(Promise.reject(ex)); }
break;
}
case 'pattern': {
const { pattern, handler } = observer;
const match = processMatch(pattern.match(vacancy));
if (match) {
this.telemetry.send('debug', `handling string pattern vacancy: ${vacancy}`, match);
try { proms.push(handler(match, send, exitProm)); }
catch(ex) { proms.push(Promise.reject(ex)); }
}
break;
}
case 'regex': {
const { regex, handler } = observer;
const match = vacancy.match(regex);
if (match) {
this.telemetry.send('debug', `handling regex vacancy: ${vacancy}`, match);
try { proms.push(handler(match, send, exitProm)); }
catch(ex) { proms.push(Promise.reject(ex)); }
}
break;
}
default: {
this.telemetry.send('critical', 'untyped observer', observer);
assertNever(observer);
}
}
}
if (proms.length === 0) {
this.telemetry.send('warn', `unobserved vacancy: ${vacancy}`);
}
Promise.all(proms).catch(err =>
this.telemetry.send('error', `error while handling vacancy: ${vacancy}`, err));
}
}
function createPublishFunc<T>(
subscriptions: Dispatcher<T>[],
telemetry: Telemetry,
): Dispatcher<T> {
return (action: T) => {
for (let sub of subscriptions) {
try {
telemetry.send('debug', 'publishing action', action);
sub(action);
} catch(ex) {
telemetry.send('error', 'error while publishing action', ex);
}
}
};
}
function processMatch(match: any): PatternMatch | null {
if (match) {
const result: PatternMatch = {};
for (let [key, val] of Object.entries(match)) {
if (Array.isArray(val)) {
val = val[0];
}
if (typeof val === 'string') {
result[key] = val;
} else {
result[key] = `${val}`;
}
}
return result;
} else {
return null;
}
}
function tick(): Promise<void> {
return new Promise(r => setImmediate(r));
}