-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Expand file tree
/
Copy pathpicker-ui.js
More file actions
443 lines (379 loc) · 13.7 KB
/
Copy pathpicker-ui.js
File metadata and controls
443 lines (379 loc) · 13.7 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
/*******************************************************************************
uBlock Origin Lite - a comprehensive, MV3-compliant content blocker
Copyright (C) 2025-present Raymond Hill
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see {http://www.gnu.org/licenses/}.
Home: https://github.com/gorhill/uBlock
*/
import { dom, qs$, qsa$ } from './dom.js';
import { localRead, localWrite } from './ext.js';
import { ExtSelectorCompiler } from './static-filtering-parser.js';
import { toolOverlay } from './tool-overlay-ui.js';
/******************************************************************************/
const selectorCompiler = new ExtSelectorCompiler({ nativeCssHas: true });
let selectorPartsDB = new Map();
let sliderParts = [];
let sliderPartsPos = -1;
/******************************************************************************/
function validateSelector(selector) {
validateSelector.error = undefined;
if ( selector === '' ) { return; }
const result = {};
if ( selectorCompiler.compile(selector, result) ) {
return result.compiled;
}
validateSelector.error = 'Error';
}
/******************************************************************************/
function onSvgTouch(ev) {
if ( ev.type === 'touchstart' ) {
onSvgTouch.x0 = ev.touches[0].screenX;
onSvgTouch.y0 = ev.touches[0].screenY;
onSvgTouch.t0 = ev.timeStamp;
return;
}
if ( onSvgTouch.x0 === undefined ) { return; }
const stopX = ev.changedTouches[0].screenX;
const stopY = ev.changedTouches[0].screenY;
const distance = Math.sqrt(
Math.pow(stopX - onSvgTouch.x0, 2) +
Math.pow(stopY - onSvgTouch.y0, 2)
);
// Interpret touch events as a tap if:
// - Swipe is not valid; and
// - The time between start and stop was less than 200ms.
const duration = ev.timeStamp - onSvgTouch.t0;
if ( distance >= 32 || duration >= 200 ) { return; }
onSvgClicked({
type: 'touch',
target: ev.target,
clientX: ev.changedTouches[0].pageX,
clientY: ev.changedTouches[0].pageY,
});
ev.preventDefault();
}
onSvgTouch.x0 = onSvgTouch.y0 = 0;
onSvgTouch.t0 = 0;
/******************************************************************************/
function onSvgClicked(ev) {
// Unpause picker if:
// - click outside dialog AND
// - not in preview mode
if ( dom.cl.has(dom.root, 'paused') ) {
if ( dom.cl.has(dom.root, 'preview') ) {
updatePreview(false);
}
unpausePicker();
return;
}
// Force dialog to always be visible when using a touch-driven device.
if ( ev.type === 'touch' ) {
dom.cl.add(dom.root, 'show');
}
toolOverlay.postMessage({
what: 'candidatesAtPoint',
mx: ev.clientX,
my: ev.clientY,
broad: ev.ctrlKey,
}).then(details => {
showDialog(details);
});
}
/******************************************************************************/
function onKeyPressed(ev) {
if ( ev.key === 'Escape' || ev.which === 27 ) {
quitPicker();
return;
}
}
/******************************************************************************/
function onMinimizeClicked() {
if ( dom.cl.has(dom.root, 'paused') === false ) {
pausePicker();
highlightCandidate();
return;
}
dom.cl.toggle(dom.root, 'minimized');
}
/******************************************************************************/
function onFilterTextChanged() {
highlightCandidate();
}
/******************************************************************************/
function toggleView(view, persist = false) {
dom.root.dataset.view = `${view}`;
if ( persist !== true ) { return; }
localWrite('picker.view', dom.root.dataset.view);
}
function onViewToggled(dir) {
let view = parseInt(dom.root.dataset.view, 10);
view += dir;
if ( view < 0 ) { view = 0; }
if ( view > 2 ) { view = 2; }
toggleView(view, true);
}
/******************************************************************************/
function selectorFromCandidates() {
const selectorParts = [];
let liPrevious = null;
for ( const li of qsa$('#candidateFilters li') ) {
const selector = [];
for ( const span of qsa$(li, '.on[data-part]') ) {
selector.push(span.textContent);
}
if ( selector.length !== 0 ) {
if ( liPrevious !== null ) {
if ( li.previousElementSibling === liPrevious ) {
selectorParts.unshift(' > ');
} else if ( liPrevious !== li ) {
selectorParts.unshift(' ');
}
}
liPrevious = li;
selectorParts.unshift(selector.join(''));
}
}
return selectorParts.join('');
}
/******************************************************************************/
function onSliderChanged(ev) {
updateSlider(Math.round(ev.target.valueAsNumber));
}
function onArrowClicked(ev) {
const arrow = ev.target.closest('.arrow');
if ( arrow === null ) { return; }
const slider = qs$('#slider');
if ( slider.disabled ) { return; }
const isIncrement = arrow.dataset.action === 'increment';
let val = Math.round(slider.valueAsNumber);
if ( isIncrement ) {
val += 1;
} else {
val -= 1;
}
const max = parseInt(slider.max, 10);
if ( val < 0 ) { val = 0; }
if ( val > max ) { val = max; }
slider.value = val;
updateSlider(val);
}
function updateSlider(i) {
if ( i === sliderPartsPos ) { return; }
sliderPartsPos = i;
dom.cl.remove('#candidateFilters [data-part]', 'on');
const parts = sliderParts[i];
for ( const address of parts ) {
dom.cl.add(`#candidateFilters [data-part="${address}"]`, 'on');
}
const selector = selectorFromCandidates();
qs$('textarea').value = selector;
highlightCandidate();
}
/******************************************************************************/
function updateElementCount(details) {
const { count, error } = details;
const span = qs$('#resultsetCount');
if ( error ) {
span.textContent = 'Error';
span.setAttribute('title', error);
dom.attr('#create', 'disabled', '');
} else {
span.textContent = count;
span.removeAttribute('title');
dom.attr('#create', 'disabled', null);
}
updatePreview();
}
/******************************************************************************/
function onPreviewClicked() {
dom.cl.toggle(dom.root, 'preview');
updatePreview();
}
function updatePreview(state) {
if ( state === undefined ) {
state = dom.cl.has(dom.root, 'preview');
} else {
dom.cl.toggle(dom.root, 'preview', state)
}
const selector = state && validateSelector(qs$('textarea').value) || '';
return toolOverlay.postMessage({ what: 'previewSelector', selector });
}
/******************************************************************************/
async function onCreateClicked() {
const selector = validateSelector(qs$('textarea').value);
if ( selector === undefined ) { return; }
await toolOverlay.postMessage({ what: 'terminateCustomFilters' });
await toolOverlay.sendMessage({
what: 'addCustomFilters',
hostname: toolOverlay.url.hostname,
selectors: [ selector ],
});
await toolOverlay.postMessage({ what: 'startCustomFilters' });
qs$('textarea').value = '';
dom.cl.remove(dom.root, 'preview');
quitPicker();
}
/******************************************************************************/
function attributeNameFromSelector(part) {
const pos = part.search(/\^?=/);
return part.slice(1, pos);
}
/******************************************************************************/
function onCandidateClicked(ev) {
const target = ev.target;
if ( target.matches('[data-part]') ) {
const address = target.dataset.part;
const part = selectorPartsDB.get(parseInt(address, 10));
if ( part.startsWith('[') ) {
if ( target.textContent === part ) {
target.textContent = `[${attributeNameFromSelector(part)}]`;
dom.cl.remove(target, 'on');
} else if ( dom.cl.has(target, 'on') ) {
target.textContent = part;
} else {
dom.cl.add(target, 'on');
}
} else {
dom.cl.toggle(target, 'on');
}
} else if ( target.matches('li') ) {
if ( qs$(target, ':scope > span:not(.on)') !== null ) {
dom.cl.add(qsa$(target, ':scope > [data-part]:not(.on)'), 'on');
} else {
dom.cl.remove(qsa$(target, ':scope > [data-part]'), 'on');
}
}
const selector = selectorFromCandidates();
qs$('textarea').value = selector;
highlightCandidate();
}
/******************************************************************************/
function showDialog(msg) {
pausePicker();
/* global */selectorPartsDB = new Map(msg.partsDB);
const { listParts } = msg;
const root = qs$('#candidateFilters');
const ul = qs$(root, 'ul');
while ( ul.firstChild !== null ) {
ul.firstChild.remove();
}
for ( const parts of listParts ) {
const li = document.createElement('li');
for ( const address of parts ) {
const span = document.createElement('span');
const part = selectorPartsDB.get(address);
span.dataset.part = address;
if ( part.startsWith('[') ) {
span.textContent = `[${attributeNameFromSelector(part)}]`;
} else {
span.textContent = part;
}
li.append(span);
}
ul.appendChild(li);
}
/* global */sliderParts = msg.sliderParts;
/* global */sliderPartsPos = -1;
const slider = qs$('#slider');
const last = sliderParts.length - 1;
dom.attr(slider, 'max', last);
dom.attr(slider, 'value', last);
dom.attr(slider, 'disabled', last !== 0 ? null : '');
slider.value = last;
updateSlider(last);
}
/******************************************************************************/
function highlightCandidate() {
const selector = validateSelector(qs$('textarea').value);
if ( selector === undefined ) {
toolOverlay.postMessage({ what: 'unhighlight' });
updateElementCount({ count: 0, error: validateSelector.error });
return;
}
toolOverlay.postMessage({
what: 'highlightFromSelector',
selector,
}).then(result => {
updateElementCount(result);
});
}
/*******************************************************************************
*
* paused:
* - select element mode disabled
* - preview mode enabled or disabled
* - dialog unminimized
*
* unpaused:
* - select element mode enabled
* - preview mode disabled
* - dialog minimized
*
* */
function pausePicker() {
dom.cl.add(dom.root, 'paused');
dom.cl.remove(dom.root, 'minimized');
toolOverlay.highlightElementUnderMouse(false);
}
function unpausePicker() {
dom.cl.remove(dom.root, 'paused', 'preview');
dom.cl.add(dom.root, 'minimized');
updatePreview(false);
toolOverlay.highlightElementUnderMouse(true);
}
/******************************************************************************/
function startPicker() {
toolOverlay.postMessage({ what: 'startTool' });
localRead('picker.view').then(value => {
if ( Boolean(value) === false ) { return; }
toggleView(value);
});
self.addEventListener('keydown', onKeyPressed, true);
dom.on('svg#overlay', 'click', onSvgClicked);
dom.on('svg#overlay', 'touchstart', onSvgTouch, { passive: true });
dom.on('svg#overlay', 'touchend', onSvgTouch);
dom.on('#minimize', 'click', onMinimizeClicked);
dom.on('textarea', 'input', onFilterTextChanged);
dom.on('#quit', 'click', quitPicker);
dom.on('#slider', 'input', onSliderChanged);
dom.on('.slider-container .arrow', 'click', onArrowClicked);
dom.on('#pick', 'click', resetPicker);
dom.on('#preview', 'click', onPreviewClicked);
dom.on('#moreOrLess > span:first-of-type', 'click', ( ) => { onViewToggled(1); });
dom.on('#moreOrLess > span:last-of-type', 'click', ( ) => { onViewToggled(-1); });
dom.on('#create', 'click', ( ) => { onCreateClicked(); });
dom.on('#candidateFilters ul', 'click', onCandidateClicked);
toolOverlay.highlightElementUnderMouse(true);
}
/******************************************************************************/
function quitPicker() {
updatePreview(false);
toolOverlay.stop();
}
/******************************************************************************/
function resetPicker() {
toolOverlay.postMessage({ what: 'unhighlight' });
unpausePicker();
}
/******************************************************************************/
function onMessage(msg) {
switch ( msg.what ) {
case 'startTool':
startPicker();
break;
default:
break;
}
}
/******************************************************************************/
// Wait for the content script to establish communication
toolOverlay.start(onMessage);
/******************************************************************************/