This repository has been archived by the owner on Jun 10, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
selector-set.next.js
439 lines (395 loc) · 10.5 KB
/
selector-set.next.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
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
// Public: Create a new SelectorSet.
export default function SelectorSet() {
// Construct new SelectorSet if called as a function.
if (!(this instanceof SelectorSet)) {
return new SelectorSet();
}
// Public: Number of selectors added to the set
this.size = 0;
// Internal: Incrementing ID counter
this.uid = 0;
// Internal: Array of String selectors in the set
this.selectors = [];
// Internal: Map of selector ids to objects
this.selectorObjects = {};
// Internal: All Object index String names mapping to Index objects.
this.indexes = Object.create(this.indexes);
// Internal: Used Object index String names mapping to Index objects.
this.activeIndexes = [];
}
// Detect prefixed Element#matches function.
var docElem = window.document.documentElement;
var matches =
docElem.matches ||
docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector;
// Public: Check if element matches selector.
//
// Maybe overridden with custom Element.matches function.
//
// el - An Element
// selector - String CSS selector
//
// Returns true or false.
SelectorSet.prototype.matchesSelector = function(el, selector) {
return matches.call(el, selector);
};
// Public: Find all elements in the context that match the selector.
//
// Maybe overridden with custom querySelectorAll function.
//
// selectors - String CSS selectors.
// context - Element context
//
// Returns non-live list of Elements.
SelectorSet.prototype.querySelectorAll = function(selectors, context) {
return context.querySelectorAll(selectors);
};
// Public: Array of indexes.
//
// name - Unique String name
// selector - Function that takes a String selector and returns a String key
// or undefined if it can't be used by the index.
// element - Function that takes an Element and returns an Array of String
// keys that point to indexed values.
//
SelectorSet.prototype.indexes = [];
// Index by element id
var idRe = /^#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/g;
SelectorSet.prototype.indexes.push({
name: 'ID',
selector: function matchIdSelector(sel) {
var m;
if ((m = sel.match(idRe))) {
return m[0].slice(1);
}
},
element: function getElementId(el) {
if (el.id) {
return [el.id];
}
}
});
// Index by all of its class names
var classRe = /^\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/g;
SelectorSet.prototype.indexes.push({
name: 'CLASS',
selector: function matchClassSelector(sel) {
var m;
if ((m = sel.match(classRe))) {
return m[0].slice(1);
}
},
element: function getElementClassNames(el) {
var className = el.className;
if (className) {
if (typeof className === 'string') {
return className.split(/\s/);
} else if (typeof className === 'object' && 'baseVal' in className) {
// className is a SVGAnimatedString
// global SVGAnimatedString is not an exposed global in Opera 12
return className.baseVal.split(/\s/);
}
}
}
});
// Index by tag/node name: `DIV`, `FORM`, `A`
var tagRe = /^((?:[\w\u00c0-\uFFFF\-]|\\.)+)/g;
SelectorSet.prototype.indexes.push({
name: 'TAG',
selector: function matchTagSelector(sel) {
var m;
if ((m = sel.match(tagRe))) {
return m[0].toUpperCase();
}
},
element: function getElementTagName(el) {
return [el.nodeName.toUpperCase()];
}
});
// Default index just contains a single array of elements.
SelectorSet.prototype.indexes['default'] = {
name: 'UNIVERSAL',
selector: function() {
return true;
},
element: function() {
return [true];
}
};
// Use ES Maps when supported
var Map;
if (typeof window.Map === 'function') {
Map = window.Map;
} else {
Map = (function() {
function Map() {
this.map = {};
}
Map.prototype.get = function(key) {
return this.map[key + ' '];
};
Map.prototype.set = function(key, value) {
this.map[key + ' '] = value;
};
return Map;
})();
}
// Regexps adopted from Sizzle
// https://github.com/jquery/sizzle/blob/1.7/sizzle.js
//
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g;
// Internal: Get indexes for selector.
//
// selector - String CSS selector
//
// Returns Array of {index, key}.
function parseSelectorIndexes(allIndexes, selector) {
allIndexes = allIndexes.slice(0).concat(allIndexes['default']);
var allIndexesLen = allIndexes.length,
i,
j,
m,
dup,
rest = selector,
key,
index,
indexes = [];
do {
chunker.exec('');
if ((m = chunker.exec(rest))) {
rest = m[3];
if (m[2] || !rest) {
for (i = 0; i < allIndexesLen; i++) {
index = allIndexes[i];
if ((key = index.selector(m[1]))) {
j = indexes.length;
dup = false;
while (j--) {
if (indexes[j].index === index && indexes[j].key === key) {
dup = true;
break;
}
}
if (!dup) {
indexes.push({ index: index, key: key });
}
break;
}
}
}
}
} while (m);
return indexes;
}
// Internal: Find first item in Array that is a prototype of `proto`.
//
// ary - Array of objects
// proto - Prototype of expected item in `ary`
//
// Returns object from `ary` if found. Otherwise returns undefined.
function findByPrototype(ary, proto) {
var i, len, item;
for (i = 0, len = ary.length; i < len; i++) {
item = ary[i];
if (proto.isPrototypeOf(item)) {
return item;
}
}
}
// Public: Log when added selector falls under the default index.
//
// This API should not be considered stable. May change between
// minor versions.
//
// obj - {selector, data} Object
//
// SelectorSet.prototype.logDefaultIndexUsed = function(obj) {
// console.warn(obj.selector, "could not be indexed");
// };
//
// Returns nothing.
SelectorSet.prototype.logDefaultIndexUsed = function() {};
// Public: Add selector to set.
//
// selector - String CSS selector
// data - Optional data Object (default: undefined)
//
// Returns nothing.
SelectorSet.prototype.add = function(selector, data) {
var obj,
i,
indexProto,
key,
index,
objs,
selectorIndexes,
selectorIndex,
indexes = this.activeIndexes,
selectors = this.selectors,
selectorObjects = this.selectorObjects;
if (typeof selector !== 'string') {
return;
}
obj = {
id: this.uid++,
selector: selector,
data: data
};
selectorObjects[obj.id] = obj;
selectorIndexes = parseSelectorIndexes(this.indexes, selector);
for (i = 0; i < selectorIndexes.length; i++) {
selectorIndex = selectorIndexes[i];
key = selectorIndex.key;
indexProto = selectorIndex.index;
index = findByPrototype(indexes, indexProto);
if (!index) {
index = Object.create(indexProto);
index.map = new Map();
indexes.push(index);
}
if (indexProto === this.indexes['default']) {
this.logDefaultIndexUsed(obj);
}
objs = index.map.get(key);
if (!objs) {
objs = [];
index.map.set(key, objs);
}
objs.push(obj);
}
this.size++;
selectors.push(selector);
};
// Public: Remove selector from set.
//
// selector - String CSS selector
// data - Optional data Object (default: undefined)
//
// Returns nothing.
SelectorSet.prototype.remove = function(selector, data) {
if (typeof selector !== 'string') {
return;
}
var selectorIndexes,
selectorIndex,
i,
j,
k,
selIndex,
objs,
obj,
indexes = this.activeIndexes,
selectors = (this.selectors = []),
selectorObjects = this.selectorObjects,
removedIds = {},
removeAll = arguments.length === 1;
selectorIndexes = parseSelectorIndexes(this.indexes, selector);
for (i = 0; i < selectorIndexes.length; i++) {
selectorIndex = selectorIndexes[i];
j = indexes.length;
while (j--) {
selIndex = indexes[j];
if (selectorIndex.index.isPrototypeOf(selIndex)) {
objs = selIndex.map.get(selectorIndex.key);
if (objs) {
k = objs.length;
while (k--) {
obj = objs[k];
if (obj.selector === selector && (removeAll || obj.data === data)) {
objs.splice(k, 1);
removedIds[obj.id] = true;
}
}
}
break;
}
}
}
for (i in removedIds) {
delete selectorObjects[i];
this.size--;
}
for (i in selectorObjects) {
selectors.push(selectorObjects[i].selector);
}
};
// Sort by id property handler.
//
// a - Selector obj.
// b - Selector obj.
//
// Returns Number.
function sortById(a, b) {
return a.id - b.id;
}
// Public: Find all matching decendants of the context element.
//
// context - An Element
//
// Returns Array of {selector, data, elements} matches.
SelectorSet.prototype.queryAll = function(context) {
if (!this.selectors.length) {
return [];
}
var matches = {},
results = [];
var els = this.querySelectorAll(this.selectors.join(', '), context);
var i, j, len, len2, el, m, match, obj;
for (i = 0, len = els.length; i < len; i++) {
el = els[i];
m = this.matches(el);
for (j = 0, len2 = m.length; j < len2; j++) {
obj = m[j];
if (!matches[obj.id]) {
match = {
id: obj.id,
selector: obj.selector,
data: obj.data,
elements: []
};
matches[obj.id] = match;
results.push(match);
} else {
match = matches[obj.id];
}
match.elements.push(el);
}
}
return results.sort(sortById);
};
// Public: Match element against all selectors in set.
//
// el - An Element
//
// Returns Array of {selector, data} matches.
SelectorSet.prototype.matches = function(el) {
if (!el) {
return [];
}
var i, j, k, len, len2, len3, index, keys, objs, obj, id;
var indexes = this.activeIndexes,
matchedIds = {},
matches = [];
for (i = 0, len = indexes.length; i < len; i++) {
index = indexes[i];
keys = index.element(el);
if (keys) {
for (j = 0, len2 = keys.length; j < len2; j++) {
if ((objs = index.map.get(keys[j]))) {
for (k = 0, len3 = objs.length; k < len3; k++) {
obj = objs[k];
id = obj.id;
if (!matchedIds[id] && this.matchesSelector(el, obj.selector)) {
matchedIds[id] = true;
matches.push(obj);
}
}
}
}
}
}
return matches.sort(sortById);
};