forked from dodying/UserJs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mark.old.user.js
622 lines (574 loc) · 21.6 KB
/
mark.old.user.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
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
/* eslint-env browser */
// ==UserScript==
// @name []mark
// @description mark
// @include *
// @version 1.2.1
// @modified 2021-11-28 13:19:20
// @author dodying
// @namespace https://github.com/dodying/UserJs
// @supportURL https://github.com/dodying/UserJs/issues
// @icon https://gitee.com/dodying/userJs/raw/master/Logo.png
// @run-at document-end
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_openInTab
// @noframes
// @require https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js
// ==/UserScript==
/* global GM_setValue GM_getValue GM_openInTab */
/* global $ */
/* eslint-disable no-debugger */
(function () {
const selectCalc = (any, position) => {
any = [].concat(any);
const out = [];
for (let i = 0; i < any.length; i++) {
const anyI = any[i];
if (typeof anyI === 'string') {
out[i] = position.string(anyI);
} else if (typeof anyI === 'number') {
out[i] = position.number(anyI);
} else if (typeof anyI === 'function') {
out[i] = position.function(anyI);
} else if (typeof anyI === 'boolean') {
out[i] = position.boolean(anyI);
} else if (anyI instanceof RegExp) {
out[i] = position.RegExp(anyI);
} else {
out[i] = position.default(anyI);
}
}
return out;
};
/* eslint-disable comma-dangle */
const libs = {
novel: [
// 示例
{
/**
* filterUrl <= Array
* string / RegExp 检测链接
* Function 无参,返回true
*
* 特定网站生效
*/
filterUrl: 'my.qidian.com/bookcase',
/**
* ?excludeUrl
* 类型同filterUrl,匹配时不生效
*/
/**
* elems <= Array
* string 选择器
* Function 无参,返回元素
*
* 元素
*/
elems: ['.shelf-table-name [data-bid]'],
/**
* ?elementDo
* Array of function(elem)
*/
/**
* ?textReplace, textReplaceEvery
* Array of [match, replace]
* 替换元素下的首个textNode
* like elementDo: [ function (elem){elem.textContent=elem.textContent.replace(match, replace)} ]
*/
/**
* ?search
* string '名称|网址' 包含%s
*/
search: '书架搜索|https://my.qidian.com/bookcase/search?kw=%s'
/**
* ?do 仅在匹配页面生效
* ?doEvery 即使不匹配,只要是这个lib都生效
* Function
*/
}
],
manga: [
{
filterUrl: /i.dmzj.com\/(record|subscribe)/,
elems: [
'.dy_content_li h3>a',
'.history_des>h3>a'
]
}
]
};
/* eslint-enable comma-dangle */
let libName; let
lib;
for (const i in libs) {
libName = i;
lib = libs[i];
const found = lib.some((i) => {
const filtered = selectCalc(i.filterUrl, {
string: (text) => window.location.href.match(text),
RegExp: (regexp) => window.location.href.match(regexp),
function: (func) => func(),
}).some((i) => i);
const excluded = i.excludeUrl ? selectCalc(i.excludeUrl, {
string: (text) => window.location.href.match(text),
RegExp: (regexp) => window.location.href.match(regexp),
function: (func) => func(),
}).some((i) => i) : false;
return filtered && !excluded;
});
if (found) break;
if (i === Object.keys(libs).slice(-1)[0]) return;
}
console.log({ libName, lib });
const getValue = () => JSON.parse(GM_getValue(`database_${libName}`) || '{}');
const setValue = (value) => (value || window.confirm('value false\ncontinue?') ? GM_setValue(`database_${libName}`, JSON.stringify(value)) : null);
$('<style></style>').html([
'mark-panel,mark-search-bar{all:initial;}',
'[data-mark]:hover{background-color:unset!important;}',
'[data-mark]{border:1px black solid;margin:-1px;}',
//
'.mark-show-container,.mark-edit-container{position:fixed;left:0;right:0;top:0;bottom:0;margin-left:auto;margin-right:auto;margin-top:auto;margin-bottom:auto;}',
'.mark-show-container,.mark-edit-container{z-index:99999;background:white;max-width:60vw;max-height:60vh;overflow:scroll;}',
'.mark-show-nav,.mark-show-nav-select{display:inline}',
'.mark-show-nav-select:before{content:attr(name)}',
'.mark-show-nav-select{margin:2px;border:solid 1px black}',
'.mark-show-nav-selected{color:red}',
'.mark-show-pre{white-space:pre-wrap;word-break:break-word;font-family:Consolas,Monaco,monospace;}',
'.mark-show-pre::before{content:"《"}',
'.mark-show-pre::after{content:"》"}',
'.mark-show-search{margin:0 10px;color:#00f;}',
//
'.mark-edit-textarea{width:99%;height:calc(99% - 16px);}',
].join('\n')).appendTo('head');
/**
* database:
*
* - book:
* -- name -> type
* - match:
* -- match -> type
* - color:
* -- type -> color
*/
let panelRoot;
const searchLib = [];
let firstRun = true;
const ask = (q, a) => {
const database = getValue();
const answer = window.prompt(q, a || database.answer || '');
if (answer) {
database.answer = answer;
setValue(database);
}
return answer;
};
let elems;
const updateElems = () => {
let temp = [];
for (const i of lib) {
if (firstRun) {
if (typeof i.doEvery === 'function') i.doEvery();
}
const filtered = selectCalc(i.filterUrl, {
string: (text) => window.location.href.match(text),
RegExp: (regexp) => window.location.href.match(regexp),
function: (func) => func(),
}).some((i) => i);
const excluded = i.excludeUrl ? selectCalc(i.excludeUrl, {
string: (text) => window.location.href.match(text),
RegExp: (regexp) => window.location.href.match(regexp),
function: (func) => func(),
}).some((i) => i) : false;
if (!filtered || excluded) continue;
if (firstRun) {
searchLib.push(i);
if (typeof i.do === 'function') i.do();
}
let elem = selectCalc(i.elems, {
string: (text) => $(text).toArray(),
function: (func) => func(),
}).reduce((pre, cur) => [].concat(cur, pre));
elem = $(elem).add('[data-mark]').filter(':visible').toArray()
.filter((i) => i.textContent.trim());
if (i.elementDo instanceof Array && i.elementDo.every((i) => typeof i === 'function')) {
const elems = $([].concat(elem, temp)).filter(':not([mark-do="true"])');
for (const elem of elems) {
for (const func of i.elementDo) {
func(elem);
}
$(elem).attr('mark-do', 'true');
}
}
if (i.textReplace instanceof Array || lib.find((i) => i.textReplaceEvery instanceof Array)) {
const elems = $([].concat(elem, temp)).filter(':not([mark-replace="true"])');
for (const elem of elems) {
const node = $(elem).find(':not(iframe)').addBack().contents()
.toArray()
.find((j) => j.nodeType === 3);
let text = node.textContent.trim();
const dict = [].concat(i.textReplace || [], ...lib.filter((i) => i.textReplaceEvery instanceof Array).map((i) => i.textReplaceEvery));
let replace = dict.find((i) => text.match(i[0]));
let replaceLast = null;
let textLast = null;
while (replace) {
if (replace === replaceLast && textLast === text) {
console.error(`mark: 替换文本陷入死循环\n替换规则: ${replace}`);
dict.splice(dict.indexOf(replace), 1);
}
textLast = text;
text = text.replace(replace[0], replace[1] || '').trim();
replaceLast = replace;
replace = dict.find((i) => text.match(i[0]));
}
node.textContent = text.trim();
$(elem).attr('mark-replace', 'true');
}
}
temp = temp.concat(elem);
}
if (firstRun) {
let mouseDown = false;
$(document).on('mousemove', '[data-mark]', () => {
if (!mouseDown && document.defaultView.getSelection().toString().trim()) {
$('mark-search-bar').show();
}
});
$(document).on('mousedown', (e) => {
mouseDown = true;
});
$(document).on('mouseup', (e) => {
mouseDown = false;
if ($(e.target).is('mark-search-bar')) {
setTimeout(() => {
$('mark-search-bar').hide();
}, 400);
return;
}
if (e.which !== 1 || !$(e.target).is('[data-mark],[data-mark] *,:has([data-mark])')) return $('mark-search-bar').hide();
const text = document.defaultView.getSelection().toString().trim();
if (text === '') return $('mark-search-bar').hide();
if ($('mark-search-bar').length === 0) $('<mark-search-bar>').insertAfter('body');
const _width = $('mark-search-bar').outerWidth();
const _height = $('mark-search-bar').outerHeight();
let left = _width + e.clientX + 10 < window.innerWidth ? e.clientX + 5 : e.clientX - _width - 5;
let top = _height + e.clientY + 10 < window.innerHeight ? e.clientY + 5 : e.clientY - _height - 5;
if (left < 0) left = 0;
if (top < 0) top = 0;
$('mark-search-bar').attr('css', JSON.stringify({
left,
top,
})).show();
});
}
firstRun = false;
elems = temp;
};
const updateHighlight = () => {
const database = getValue();
const books = database.book || {};
const matches = database.match || {};
updateElems();
elems.forEach((i) => {
const name = i.textContent.trim();
if (name in books) {
$(i).attr('data-mark', String(books[name]));
} else if (Object.keys(matches).some((i) => name.match(i))) {
const filtered = Object.keys(matches).filter((i) => name.match(i))[0];
$(i).attr('data-mark', matches[filtered]);
} else {
$(i).attr('data-mark', 'null');
}
});
const colors = database.color || {};
const style = Object.keys(colors).map((i) => `[data-mark="${i}"]{background-color:${colors[i]}!important;}`);
const styleEle = $('style.mark-style').length ? $('style.mark-style') : $('<style class="mark-style"></style>');
styleEle.html(style).appendTo('head');
$('[name="info"]', panelRoot).attr('length', $('[data-mark]').length).attr('null', $('[data-mark="null"]').length);
};
const promptSetting = (keyName) => {
const database = getValue();
const obj = database[keyName] || {};
const answer = ask(`已存在:\n- - -\n${Object.keys(obj).map((i) => `${i}: ${obj[i]}`).join('\n')}\n- - -\n请使用:分割,值为null表示删除`);
if (!answer) return;
const arr = answer.split(/:|:/);
if (arr.length > 1) {
if (arr[0] === 'null') return;
if (arr[1] === 'null') {
delete obj[arr[0]];
} else {
obj[arr[0]] = arr.slice(1).join(':');
}
database[keyName] = obj;
setValue(database);
updateHighlight();
}
};
const markBatch = (elems) => {
const database = getValue();
const colors = database.color || {};
const type = ask(`要标记的状态,值为null表示删除:\n- - -\n${Object.keys(colors).map((i) => `${i}:${colors[i]}`).join('\n')}\n- - -`);
if (!type) return;
const obj = database.book || {};
updateElems();
elems.forEach((i) => {
const name = i.textContent.trim();
if (type === 'null') {
delete obj[name];
} else {
obj[name] = type;
}
});
database.book = obj;
setValue(database);
updateHighlight();
};
function markDirect(name, type) {
const database = getValue();
const obj = database.book || {};
if (type === 'null') {
delete obj[name];
} else {
obj[name] = type;
}
database.book = obj;
setValue(database);
updateHighlight();
}
updateHighlight();
const observer = new window.MutationObserver((mutationsList) => {
if (mutationsList.some((i) => i.addedNodes && [].concat(...i.addedNodes).some((j) => j.nodeType === 1))) updateHighlight();
});
observer.observe(document.body, {
childList: true,
subtree: true,
});
$('<mark-panel>').insertAfter('body');
class markPanel extends window.HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: 'open' });
panelRoot = this.shadowRoot;
$('<style>').text([
'div{z-index:99999;position:fixed;top:0;left:0;}',
'.mark-switch{background:#0F0;}',
'.mark-switch::after{content:"on";}',
'.mark-switch.mark-switch-disabled{background:#F00;}',
'.mark-switch.mark-switch-disabled::after{content:"off";}',
'[name="mark"]{background:#F00;}',
'[name="mark"].mark-mark-on{background:#0F0;}',
'[name="info"]::after{content:"-"attr(length)"-"attr(null)!important;}',
'[name]::after{content:attr(name)}',
'.mark-less.mark-less-on::after{content:">>";}',
'.mark-less::after{content:"<<";}',
].join('')).appendTo(shadow);
const container = $('<div>').appendTo(shadow);
$('<button class="mark-close">x</button>').on({
click: () => $(this).hide(),
}).appendTo(container);
$('<button name="info" disabled>').text(libName).appendTo(container);
$('<button class="mark-switch"></button>').on({
click: (e) => {
$(e.target).toggleClass('mark-switch-disabled');
if ($(e.target).is('.mark-switch-disabled')) {
$('style.mark-style').remove();
} else {
updateHighlight();
}
},
contextmenu: (e) => {
updateHighlight();
return false;
},
}).appendTo(container);
$('<button name="color" class="mark-color mark-less-hide"></button>').on({
click: () => promptSetting('color'),
}).appendTo(container);
$('<button name="match" class="mark-less-hide"></button>').on({
click: () => promptSetting('match'),
}).appendTo(container);
$('<button name="mark"></button>').on({
click: (e) => {
let type;
const markEvent = (e) => {
e.preventDefault();
e.stopPropagation();
const database = getValue();
const obj = database.book || {};
const name = e.target.textContent.trim();
if (type === 'null') {
delete obj[name];
} else {
obj[name] = type;
}
database.book = obj;
setValue(database);
updateHighlight();
};
$(e.target).toggleClass('mark-mark-on');
if ($(e.target).is('.mark-mark-on')) {
const database = getValue();
const colors = database.color || {};
type = ask(`要标记的状态,值为null表示删除:\n- - -\n${Object.keys(colors).map((i) => `${i}:${colors[i]}`).join('\n')}\n- - -`);
if (!type) {
$(e.target).toggleClass('mark-mark-on');
return;
}
$('body').on('click', '[data-mark]', markEvent);
} else {
$('body').off('click', '[data-mark]');
}
},
}).appendTo(container);
$('<button name="mark-one"></button>').on({
click: (e) => {
let type;
const markOneEvent = (e) => {
e.preventDefault();
e.stopPropagation();
const database = getValue();
const obj = database.book || {};
const name = e.target.textContent.trim();
if (type === 'null') {
delete obj[name];
} else {
obj[name] = type;
}
type = null;
database.book = obj;
setValue(database);
updateHighlight();
$('body').off('click', '[data-mark]', markOneEvent);
};
const database = getValue();
type = database.answer;
$('body').on('click', '[data-mark]', markOneEvent);
},
}).appendTo(container);
$('<button name="mark-all" class="mark-less-hide"></button>').on({
click: () => markBatch($('[data-mark]').toArray()),
}).appendTo(container);
$('<button name="mark-null" class="mark-less-hide"></button>').on({
click: () => markBatch($('[data-mark="null"]').toArray()),
}).appendTo(container);
$('<button name="hide-marked" class="mark-less-hide"></button>').on({
click: () => {
const marked = $('[data-mark]:not([data-mark=""]):not([data-mark="null"])').toArray();
for (const elem of marked) {
$(elem).parents().filter((index, e) => $(e).find('[data-mark]').length === 1).eq(-1)
.toggle();
}
},
}).appendTo(container);
$('<button name="show" class="mark-less-hide"></button>').on({
click: () => {
if ($('.mark-show-container').length) {
$('.mark-show-container').remove();
return;
}
const database = getValue();
const books = database.book || {};
const types = Object.values(books).sort().filter((item, index, array) => array.indexOf(item) === index);
const elem = $('<div class="mark-show-container"><ul class="mark-show-nav"></ul><div class="mark-show-content"></div></div>');
for (const type of types) {
$('<li class="mark-show-nav-select"></li>').attr('name', type).appendTo($(elem).find('.mark-show-nav'));
let html = '<ol>';
const names = Object.keys(books).filter((i) => books[i] === type);
for (const name of names) {
html = `${html}<li>`;
html = `${html}<span class="mark-show-pre">${name}</span>`;
html = html + Array.from(new Set(searchLib.concat(lib))).map((lib) => {
if (!lib.search) return;
const [info, url] = lib.search.split('|');
return `<a class="mark-show-search" href="${url.replace('%s', encodeURIComponent(name))}">${info}</a>`;
}).join('');
html = `${html}</li>`;
}
html = `${html}</ol>`;
$(html).attr('name', type).appendTo($(elem).find('.mark-show-content'));
}
elem.appendTo('body');
$('.mark-show-nav-select').on({
click: (e) => {
$('.mark-show-nav-select').removeClass('mark-show-nav-selected');
$(e.target).addClass('mark-show-nav-selected');
$('.mark-show-content>ol').hide();
$('.mark-show-content>ol').filter((order, i) => $(i).attr('name') === $(e.target).attr('name')).show();
},
});
$('.mark-show-nav-select:eq(0)').addClass('mark-show-nav-selected');
$('.mark-show-content>ol').hide();
$('.mark-show-content>ol:eq(0)').show();
},
}).appendTo(container);
$('<button name="edit" class="mark-less-hide"></button>').on({
click: () => {
if ($('.mark-edit-container').length) {
$('.mark-edit-container').remove();
return;
}
const database = getValue();
$('<div class="mark-edit-container"><textarea class="mark-edit-textarea"></textarea></div>').appendTo('body');
$('<button class="mark-edit-save">Save</button>').on({
click: () => {
try {
const obj = JSON.parse($('.mark-edit-textarea').val());
setValue(obj);
} catch (error) {
console.log(error);
window.alert('Save Failed');
}
},
}).appendTo('.mark-edit-container');
$('.mark-edit-textarea').text(JSON.stringify(database, null, 2));
},
}).appendTo(container);
// 最后
$('<button class="mark-less"></button>').on({
click: (e) => {
$(e.target).toggleClass('mark-less-on');
$('.mark-less-hide', panelRoot).toggle();
},
}).appendTo(container);
$('.mark-less', panelRoot).click();
}
}
class markSearchBar extends window.HTMLElement {
static get observedAttributes() { return ['css']; }
constructor() {
super();
const shadow = this.attachShadow({ mode: 'open' });
$('<style>').text([
'div{background:#fcfcfc;text-align:center;position:fixed;}',
'div>a{display:inline-block;cursor:pointer;margin:3px;}',
'div>a>img{width:24px;height:24px;}',
'div>a>span{display:block;}',
// 'div>a:hover>span{display:block;}'
].join('')).appendTo(shadow);
const buttons = Array.from(new Set(searchLib.concat(lib))).map((lib) => {
if (!lib.search) return;
const [info, url] = lib.search.split('|');
return `<a data-url="${url}"><img src="https://favicon.yandex.net/favicon/${new URL(url).host}/" /><span>${info}</span></a>`;
}).join('');
if (buttons === '') {
$(document).off('mouseup');
return;
}
$('<div>').html(buttons).appendTo(shadow).on('click', (e) => {
const elem = $(e.target).parentsUntil('div').eq(-1);
const text = document.defaultView.getSelection().toString().trim();
if (text === '') return $(this).hide();
const url = $(elem).attr('data-url').replace('%s', encodeURIComponent(text));
GM_openInTab(url);
});
}
attributeChangedCallback(name, oldValue, newValue) {
$('div', this.shadowRoot).css(JSON.parse($(this).attr('css')));
}
}
window.customElements.define('mark-panel', markPanel);
window.customElements.define('mark-search-bar', markSearchBar);
$(window).on('focus', (e) => {
updateHighlight();
});
}());