-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathque.js
More file actions
649 lines (553 loc) · 18.8 KB
/
que.js
File metadata and controls
649 lines (553 loc) · 18.8 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
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
/**
* --------------------------------------------------------
* A Simple Javascript MVVM Framework (in ES6)
* @version: 2.2.1
* @author: Ai Chen
* @copyright (c) 2019-2023 https://github.com/metadream
* @references: https://github.com/vuejs/vue
* https://github.com/qieguo2016/Vueuv
* https://es6.ruanyifeng.com
* --------------------------------------------------------
*/
class Que {
static customEvents = {};
static directive(event, binding) {
this.customEvents[event] = binding;
}
// Proxy, observe, compile and execute 'ready' method in options
constructor(options = {}) {
const proxy = this.# proxy(options);
new Observer(options.data);
document.addEventListener('DOMContentLoaded', function() {
new Compiler(document.body, proxy);
proxy.ready && proxy.ready(decodeURI(location.pathname), location.search.slice(1));
});
document.addEventListener('deviceready', () => {
proxy.onDeviceReady && proxy.onDeviceReady();
}, false);
}
// Proxy all methods of 'options' to 'options.data'
# proxy(options) {
Object.keys(options).forEach(key => {
if (typeof options[key] === 'function') {
options.data[key] = options[key];
}
})
return options.data;
}
}
/* --------------------------------------------------------
* Observer Class
* ----------------------------------------------------- */
class Observer {
constructor(data) {
this.observe(data);
}
// Observe all properties in data
observe(data) {
if (data && typeof data === 'object') {
Object.keys(data).forEach(key => {
this.observeObject(data, key, data[key]);
});
}
}
// Observe property value's change
// Add watcher when 'get' and notify watcher when 'set'
observeObject(data, key, value) {
const dep = new Dep();
this.observeRecursive(value, dep);
Object.defineProperty(data, key, {
enumerable: true,
configurable: false,
get: () => {
Dep.target && dep.addSub(Dep.target);
return value;
},
set: newValue => {
if (value !== newValue) {
value = newValue;
// BUG: The follow line code will cause a problem when 'this.xxx = this.yyy'
// You must use this: this.xxx = Object.create(this.yyy)
this.observeRecursive(value, dep);
dep.notify();
}
}
});
}
// Observe object/array recursive
observeRecursive(value, dep) {
if (Array.isArray(value)) {
value.__proto__ = this.definePrototype(dep);
value.forEach(item => this.observe(item));
} else {
this.observe(value);
}
}
// Rewrite array's prototype methods
definePrototype(dep) {
const arrayPrototype = Object.create(Array.prototype);
const arrayMethods = ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'];
// deno-lint-ignore no-this-alias
const self = this;
arrayMethods.forEach(method => {
const original = arrayPrototype[method];
Object.defineProperty(arrayPrototype, method, {
enumerable: true,
writable: true,
configurable: true,
value: function() {
const result = original.apply(this, arguments);
let inserted = null;
switch (method) {
case 'push':
case 'unshift':
inserted = arguments;
break;
case 'splice':
if (arguments.length > 2) {
inserted = Array.prototype.slice.call(arguments, 2);
}
break;
}
if (inserted) {
self.observeRecursive(inserted, dep);
}
dep.notify({ method, args: arguments });
return result;
}
})
})
return arrayPrototype;
}
}
/* --------------------------------------------------------
* Dependence Class
* ----------------------------------------------------- */
class Dep {
constructor() {
this.subs = {};
}
addSub(target) {
if (!this.subs[target.id]) {
this.subs[target.id] = target;
}
}
removeSub(target) {
delete this.subs[target.id];
}
/**
* options parameter only for array changed
* @param options = {method, args}
*/
notify(options) {
Object.keys(this.subs).forEach(id => {
this.subs[id].update(options);
});
}
}
/* --------------------------------------------------------
* Watcher Class
* ----------------------------------------------------- */
class Watcher {
static _id = 0;
/**
* @param scope Data scope for compute expression
* @param expr Expression from Directive
* @param callback Function for notify
*/
constructor(scope, expr, callback) {
this.scope = scope;
this.expr = expr;
this.callback = callback;
this.id = ++Watcher._id;
this.compute = Parser.buildFunction(expr);
this.update();
}
update(options) {
let value = this.get();
value = value == undefined ? '' : value;
this.callback(value, options);
}
/**
* 'Get' method will trigger 'Observer' listening
* then add 'Watcher' instance to 'Dep'
*/
get() {
Dep.target = this;
const value = this.compute(this.scope);
Dep.target = null;
return value;
}
}
/* --------------------------------------------------------
* Directive Class
* ----------------------------------------------------- */
class Directive {
constructor(node, scope, options) {
this.node = node;
this.scope = scope;
Object.assign(this, options);
// Generates watcher observe based on compiled DOM node
this.init && this.init()
if (this.expr && this.update) {
this.watcher = new Watcher(this.scope, this.expr, (v, o) => this.update(v, o));
}
}
/**
* Create anchor of node position
*/
createAnchor(node) {
const anchor = document.createTextNode('');
node = node || this.node;
node.replace(anchor);
return anchor;
}
}
/* --------------------------------------------------------
* Text Directive Object
* ----------------------------------------------------- */
Directive.text = {
update(value) {
this.node.textContent = value;
}
}
/* --------------------------------------------------------
* Attribute Directive Object
* ----------------------------------------------------- */
Directive.attr = {
update(value) {
if (this.name == 'data-src') {
this.node.removeAttribute('data-src');
this.node.setAttribute('src', value);
} else {
this.node.setAttribute(this.name, value);
}
}
}
/* --------------------------------------------------------
* Hidden Directive Object
* ----------------------------------------------------- */
Directive.hidden = {
update(value) {
if (value) {
this.node.removeAttribute(this.name);
} else {
this.node.setAttribute(this.name, !value);
}
}
}
/* --------------------------------------------------------
* Model Directive Object
* Only supports input type="text" and textarea
* ----------------------------------------------------- */
Directive.model = {
init() {
this.node.removeAttribute(this.name);
this.node.addEventListener('input', () => {
// 由于eval语句双向设置value时会再次触发update方法更新文本框内容
// 造成光标自动跳到末尾,故增加标志位用于判断更新来源
this.node.isInputing = true;
// CAN NOT ASSIGN BY '[]' MODE
// this.scope[this.expr] = e.currentTarget.value
eval('this.scope.' + this.expr + '=e.currentTarget.value');
});
this.node.addEventListener('blur', () => {
this.node.isInputing = false;
});
},
update(value) {
// 如果由input监听触发则不重复更新文本框内容(input本身即由用户手动更新)
if (!this.node.isInputing) this.node.value = value;
}
}
/* --------------------------------------------------------
* Event Directive Object
* ----------------------------------------------------- */
Directive.event = {
init() {
const method = this.scope[this.fn];
this.node.removeAttribute('@' + this.name);
if (typeof method === 'function') {
const binding = Que.customEvents[this.name];
if (binding) {
binding(this.node, e => {
e.currentTarget = this.node;
method.call(this.scope, e);
});
} else {
this.node.addEventListener(this.name, e => {
method.call(this.scope, e);
});
}
}
}
}
/* --------------------------------------------------------
* If Directive Object
* ----------------------------------------------------- */
Directive.if = {
init() {
// Pre binding 'else' node to current directive if exists
const nextNode = this.node.nextElementSibling;
if (nextNode && nextNode.hasAttribute('else')) {
nextNode.removeAttribute('else');
this.elseNode = nextNode;
this.elseAnchor = this.createAnchor(nextNode);
this.compile(nextNode, this.scope);
}
this.anchor = this.createAnchor();
this.compile(this.node, this.scope);
},
update(value) {
if (value) {
// MUST BE USE 'REPLACE' INSTEAD OF 'INSERT'
// OTHERWISE WILL CAUSE ARRAY LENGTH CHANGE WHEN COMPILING
this.anchor.replace(this.node);
if (this.elseNode) this.elseNode.replace(this.elseAnchor);
} else {
this.node.replace(this.anchor);
if (this.elseNode) this.elseAnchor.replace(this.elseNode);
}
},
}
/* --------------------------------------------------------
* Foreach Directive Object
* ----------------------------------------------------- */
Directive.foreach = {
init() {
this.anchor = this.createAnchor();
this.itemNodes = [];
// Expression as 'item in/of list'
const regForeach = /(.+) (?:in|of) (.+)/;
const regIterator = /\((.+),(.+)\)/;
const inMatch = this.expr.match(regForeach);
if (inMatch) {
this.expr = inMatch[2];
this.alias = inMatch[1].trim();
// Expression as '(item, index) in/of list'
const itMatch = inMatch[1].match(regIterator);
if (itMatch) {
this.alias = itMatch[1].trim();
this.index = itMatch[2].trim();
}
}
},
update(array, _options) {
// Clear all item nodes
let node = null;
while ((node = this.itemNodes.pop())) {
node.remove();
}
// Update all nodes totally
array && array.forEach((value, i) => {
const scope = Object.create(this.scope);
scope[this.alias] = value;
if (this.index) scope[this.index] = i;
const cloneNode = this.node.cloneNode(true);
this.anchor.insert(cloneNode);
this.itemNodes.push(cloneNode);
this.compile(cloneNode, scope);
})
}
}
/* --------------------------------------------------------
* Compiler Class
* ----------------------------------------------------- */
class Compiler {
constructor(el, scope) {
const fragment = Compiler.createFragment(el);
this.compile(fragment, scope);
el.appendChild(fragment);
}
createDirective(node, scope, options) {
const drctHandler = Directive[options.type];
if (drctHandler) {
Object.assign(options, drctHandler);
options.compile = this.compile.bind(this);
new Directive(node, scope, options);
}
}
compile(node, scope) {
if (node.nodeType === 1 && node.tagName != 'SCRIPT') {
this.compileElementNode(node, scope);
} else if (node.nodeType === 11) {
this.compileElementNodes(node, scope);
} else if (node.nodeType === 3) {
this.compileTextNode(node, scope);
}
}
compileElementNode(node, scope) {
// Skip compile 'for' or 'if' directive
let drct = Compiler.checkTerminalDirective(node);
if (drct) {
node.removeAttribute(drct.type);
this.createDirective(node, scope, drct);
return;
}
// Compile attributes with directive
const attrs = [].slice.call(node.attributes);
attrs.forEach(attr => {
drct = Compiler.checkDirective(attr);
if (drct) this.createDirective(node, scope, drct);
})
// Compile child nodes recursively
this.compileElementNodes(node, scope);
}
compileElementNodes(node, scope) {
const children = node.childNodes;
if (children && children.length) {
children.forEach(child => this.compile(child, scope));
}
}
compileTextNode(node, scope) {
const text = node.wholeText.trim();
if (text) {
const expr = Parser.parseMustache(text);
if (expr) {
this.createDirective(node, scope, { type: 'text', expr });
}
}
}
static createFragment(el) {
const fragment = document.createDocumentFragment();
let child = null;
while ((child = el.firstChild)) {
if (this.isIgnorableNode(child)) {
el.removeChild(child);
} else {
fragment.appendChild(child);
}
}
return fragment;
}
static isIgnorableNode(el) {
const regIgnorable = /^[\t\n\r]+/;
return (el.nodeType == 8) || (el.nodeType == 3 && regIgnorable.test(el.textContent));
}
static checkTerminalDirective(node) {
const terminals = ['foreach', 'if'];
let drct = null;
terminals.some(t => {
if (node.hasAttribute(t)) {
return drct = { type: t, expr: node.getAttribute(t) };
}
})
return drct;
}
static checkDirective(attr) {
if (attr.name.indexOf('@') === 0) {
return {
type: 'event',
name: attr.name.substring(1),
fn: attr.value
};
}
const matches = attr.name.match(/(hidden|model)/);
if (matches) {
return {
type: matches[1],
name: attr.name,
expr: attr.value,
};
}
const expr = Parser.parseMustache(attr.value);
if (expr) {
return {
type: 'attr',
name: attr.name,
expr: expr,
};
}
}
}
/* --------------------------------------------------------
* Expression Parser Class
* ----------------------------------------------------- */
class Parser {
static cache = {} // Cache is necessary!
static regMustache = /\{\{(.+?)\}\}/g;
static regSimple = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?'\]|\[".*?"\]|\[\d+\]|\[[A-Za-z_$][\w$]*\])*$/;
static regKeyword = /^(?:true|false|null|undefined|Infinity|NaN|Math)$/;
static regQuote = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/g;
static regIdent = /[^\w$\.](?:[A-Za-z_$][\w$]*)/g;
/**
* Parse expression with mustache syntax to constant and variable formula:
* 'a {{b+"text"}} c {{d+Math.PI}}' => '"a " + b + "text" + " c" + d + Math.PI'
*/
static parseMustache(text) {
const matches = text.match(this.regMustache);
if (matches) {
const tokens = [];
const pieces = text.split(this.regMustache);
pieces.forEach(piece => {
if (matches.indexOf('{{' + piece + '}}') > -1) {
tokens.push('(' + piece + ')');
} else if (piece) {
tokens.push('"' + piece + '"');
}
})
return tokens.join('+');
}
}
static compute(expr, scope) {
return this.buildFunction(expr)(scope);
}
/**
* Parse expression and return executable function
* For complex expression, it seems 'eval' more simpler,
* but strict mode not Supported 'with' keyword
*/
static buildFunction(expr) {
let fn = this.cache[expr];
if (!fn) {
const body = this.isSimple(expr) ? 'vm.' + expr : this.parseComplex(expr);
fn = this.cache[expr] = new Function('vm', 'return ' + body);
}
return fn;
}
/**
* Simple expression like 'a.b', it can parse to 'scope.a.b'
*/
static isSimple(expr) {
return this.regSimple.test(expr) && !this.regKeyword.test(expr);
}
/**
* Complex expression like 'a.b + a.c', it will parse to 'scope.a.b + scope.a.c'
*/
static parseComplex(expr) {
const strCache = [];
// Extract the characters in quotation and replace them with ordinal numbers
// and cache them
expr = expr.replace(this.regQuote, $ => {
const i = strCache.length;
strCache[i] = $;
return '"' + i + '"';
});
// Clear blank characters
expr = expr.replace(/\s/g, '');
// Extract words and replace them with variable forms
expr = (' ' + expr).replace(this.regIdent, $ => {
const begin = $.charAt(0);
const path = $.slice(1);
return this.regKeyword.test(path) ? $ : begin + 'vm.' + path;
});
// Replace the characters in quotation with ordinal numbers
expr = expr.replace(/"(\d+)"/g, (_$, i) => {
return strCache[i];
});
return expr;
}
}
[Element, Text, DocumentFragment].forEach(e => {
Object.assign(e.prototype, {
insert(node) {
return this.parentNode && this.parentNode.insertBefore(node, this);
},
replace(node) {
return this.parentNode && this.parentNode.replaceChild(node, this);
},
remove() {
return this.parentNode && this.parentNode.removeChild(this);
}
})
});