-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathleetcodeRating_greasyfork.user.js
2530 lines (2408 loc) · 110 KB
/
leetcodeRating_greasyfork.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
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name LeetCodeRating|显示力扣周赛难度分
// @namespace https://github.com/zhang-wangz
// @version 2.4.7
// @license MIT
// @description LeetCodeRating 力扣周赛分数显现和相关力扣小功能,目前浏览器更新规则,使用该插件前请手动打开浏览器开发者模式再食用~
// @author 小东是个阳光蛋(力扣名)
// @leetcodehomepage https://leetcode.cn/u/runonline/
// @homepageURL https://github.com/zhang-wangz/LeetCodeRating
// @contributionURL https://www.showdoc.com.cn/2069209189620830
// @run-at document-end
// @match *://*leetcode.cn/*
// @grant GM_xmlhttpRequest
// @grant GM_registerMenuCommand
// @grant GM_unregisterMenuCommand
// @grant GM_openInTab
// @grant GM_notification
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_addStyle
// @grant GM_getResourceText
// @connect zerotrac.github.io
// @connect raw.gitmirror.com
// @connect raw.githubusercontents.com
// @connect raw.githubusercontent.com
// @require https://unpkg.com/jquery@3.5.1/dist/jquery.min.js
// @require https://unpkg.com/layui@2.9.6/dist/layui.js
// @require https://greasyfork.org/scripts/463455-nelementgetter/code/NElementGetter.js?version=1172110
// @grant unsafeWindow
// ==/UserScript==
(async function () {
'use strict';
let version = "2.4.7"
let pbstatusVersion = "version16"
const dummySend = XMLHttpRequest.prototype.send;
const originalOpen = XMLHttpRequest.prototype.open;
// css 渲染
$(document.body).append(`<link href="https://unpkg.com/leetcoderatingjs@1.0.7/index.min.css" rel="stylesheet">`)
// 页面相关url
const allUrl = "https://leetcode.cn/problemset/.*"
const tagUrl = "https://leetcode.cn/tag/.*"
const companyUrl = "https://leetcode.cn/company/.*"
const pblistUrl = "https://leetcode.cn/problem-list/.*"
const pbUrl = "https://leetcode.{2,7}/problems/.*"
// 限定pbstatus使用, 不匹配题解链接
const pbSolutionUrl = "https://leetcode.{2,7}/problems/.*/solution.*"
const searchUrl = "https://leetcode.cn/search/.*"
const studyUrl = "https://leetcode.cn/studyplan/.*"
const problemUrl = "https://leetcode.cn/problemset"
const discussUrl = "https://leetcode.cn/circle/discuss/.*"
// req相关url
const lcnojgo = "https://leetcode.cn/graphql/noj-go/"
const lcgraphql = "https://leetcode.cn/graphql/"
const chContestUrl = "https://leetcode.cn/contest/"
const zhContestUrl = "https://leetcode.com/contest/"
// 灵茶相关url
const teaSheetUrl = "https://docs.qq.com/sheet/DWGFoRGVZRmxNaXFz"
const lc0x3fsolveUrl = "https://huxulm.github.io/lc-rating/search"
// 用于延时函数的通用id
let id = ""
// rank 相关数据
let t2rate = JSON.parse(GM_getValue("t2ratedb", "{}").toString())
// pbstatus数据
let pbstatus = JSON.parse(GM_getValue("pbstatus", "{}").toString())
// 题目名称-id ContestID_zh-ID
// 中文
let pbName2Id = JSON.parse(GM_getValue("pbName2Id", "{}").toString())
// 英文
let pbNamee2Id = JSON.parse(GM_getValue("pbNamee2Id", "{}").toString())
// preDate为更新分数使用,preDate1为更新版本使用
let preDate = GM_getValue("preDate", "")
let preDate1 = GM_getValue("preDate1", "")
// level数据
let levelData = JSON.parse(GM_getValue("levelData", "{}").toString())
// 中文
let levelTc2Id = JSON.parse(GM_getValue("levelTc2Id", "{}").toString())
// 英文
let levelTe2Id = JSON.parse(GM_getValue("levelTe2Id", "{}").toString())
// 是否使用动态布局
let localVal = localStorage.getItem("used-dynamic-layout")
let isDynamic = localVal != null ? localVal.includes("true") : false
function getPbNameId(pbName) {
pbName2Id = JSON.parse(GM_getValue("pbName2Id", "{}").toString())
pbNamee2Id = JSON.parse(GM_getValue("pbNamee2Id", "{}").toString())
let id = null
if (pbName2Id[pbName]) {
id = pbName2Id[pbName]
} else if (pbNamee2Id[pbName]) {
id = pbNamee2Id[pbName]
}
return id
}
function getLevelId(pbName) {
levelTc2Id = JSON.parse(GM_getValue("levelTc2Id", "{}").toString())
levelTe2Id = JSON.parse(GM_getValue("levelTe2Id", "{}").toString())
if (levelTc2Id[pbName]) {
return levelTc2Id[pbName]
}
if (levelTe2Id[pbName]) {
return levelTe2Id[pbName]
}
return null
}
// 同步函数
function waitForKeyElements (selectorTxt, actionFunction, bWaitOnce, iframeSelector) {
let targetNodes, btargetsFound;
if (typeof iframeSelector == "null")
targetNodes = $(selectorTxt);
else
targetNodes = $(iframeSelector).contents().find (selectorTxt);
if (targetNodes && targetNodes.length > 0) {
btargetsFound = true;
targetNodes.each (function(){
let jThis = $(this);
let alreadyFound = jThis.data ('alreadyFound') || false;
if (!alreadyFound) {
let cancelFound = actionFunction (jThis);
if (cancelFound) btargetsFound = false;
else jThis.data ('alreadyFound', true);
}
});
} else {
btargetsFound = false;
}
let controlObj = waitForKeyElements.controlObj || {};
let controlKey = selectorTxt.replace (/[^\w]/g, "_");
let timeControl = controlObj [controlKey];
if (btargetsFound && bWaitOnce && timeControl) {
clearInterval (timeControl);
delete controlObj [controlKey]
}
else {
if (!timeControl) {
timeControl = setInterval (function() {
waitForKeyElements(selectorTxt,actionFunction,bWaitOnce,iframeSelector);
},300);
controlObj[controlKey] = timeControl;
}
}
waitForKeyElements.controlObj = controlObj;
}
let ajaxReq = (type, reqUrl, headers, data, successFuc, withCredentials=true) => {
$.ajax({
// 请求方式
type : type,
// 请求的媒体类型
contentType: "application/json;charset=UTF-8",
// 请求地址
url: reqUrl,
// 数据,json字符串
data : data != null? JSON.stringify(data): null,
// 同步方式
async: false,
xhrFields: {
withCredentials: true
},
headers: headers,
// 请求成功
success : function(result) {
successFuc(result)
},
// 请求失败,包含具体的错误信息
error : function(e){
console.log(e.status);
console.log(e.responseText);
}
});
}
// 刷新菜单
script_setting()
// 注册urlchange事件
initUrlChange()()
// 常量数据
const regDiss = '.*//leetcode.cn/problems/.*/discussion/.*'
const regSovle = '.*//leetcode.cn/problems/.*/solutions/.*'
const regPbSubmission = '.*//leetcode.cn/problems/.*/submissions/.*';
// 监听urlchange事件定义
function initUrlChange() {
let isLoad = false
const load = () => {
if (isLoad) return
isLoad = true
const oldPushState = history.pushState
const oldReplaceState = history.replaceState
history.pushState = function pushState(...args) {
const res = oldPushState.apply(this, args)
window.dispatchEvent(new Event('urlchange'))
return res
}
history.replaceState = function replaceState(...args) {
const res = oldReplaceState.apply(this, args)
window.dispatchEvent(new Event('urlchange'))
return res
}
window.addEventListener('popstate', () => {
window.dispatchEvent(new Event('urlchange'))
})
}
return load
}
let isVpn = !GM_getValue("switchvpn")
// 访问相关url
let versionUrl, sciptUrl, rakingUrl, levelUrl
if (isVpn) {
versionUrl = "https://raw.githubusercontent.com/zhang-wangz/LeetCodeRating/main/version.json"
sciptUrl = "https://raw.githubusercontent.com/zhang-wangz/LeetCodeRating/main/leetcodeRating_greasyfork.user.js"
rakingUrl = "https://zerotrac.github.io/leetcode_problem_rating/data.json"
levelUrl = "https://raw.githubusercontent.com/zhang-wangz/LeetCodeRating/main/stormlevel/data.json"
} else {
versionUrl = "https://raw.gitmirror.com/zhang-wangz/LeetCodeRating/main/version.json"
sciptUrl = "https://raw.gitmirror.com/zhang-wangz/LeetCodeRating/main/leetcodeRating_greasyfork.user.js"
rakingUrl = "https://raw.gitmirror.com/zerotrac/leetcode_problem_rating/main/data.json"
levelUrl = "https://raw.gitmirror.com/zhang-wangz/LeetCodeRating/main/stormlevel/data.json"
}
// 菜单方法定义
function script_setting(){
let menu_ALL = [
['switchvpn', 'vpn', '是否使用cdn访问数据', false, false],
['switchupdate', 'switchupdate', '是否每天最多只更新一次', true, true],
['switchTea', '0x3f tea', '题库页灵茶信息显示', true, true],
['switchpbRepo', 'pbRepo function', '题库页周赛难度评分(不包括灵茶)', true, false],
['switchdelvip', 'delvip function', '题库页去除vip加锁题目', false, true],
['switchpbscore', 'pb function', '题目页周赛难度评分', true, true],
['switchcopyright', 'pb function', '题解复制去除版权信息', true, true],
['switchcode', 'switchcode function', '题目页代码输入阻止联想', false, true],
['switchpbside', 'switchpbside function', '题目页侧边栏分数显示', true, true],
['switchpbsearch', 'switchpbsearch function', '题目页题目搜索框', true, true],
['switchsearch', 'search function', '题目搜索页周赛难度评分', true, false],
['switchtag', 'tag function', 'tag题单页周赛难度评分(动态规划等分类题库)', true, false],
['switchpblist', 'pbList function', 'pbList题单页评分', true, false],
['switchstudy', 'studyplan function', '学习计划周赛难度评分', true, false],
['switchcontestpage', 'contestpage function', '竞赛页面双栏布局', true, false],
['switchlevel', 'studyplan level function', '算术评级(显示左侧栏和学习计划中)', true, false],
['switchrealoj', 'delvip function', '模拟oj环境(去除通过率,难度,周赛Qidx等)', false, true],
['switchdark', 'dark function', '自动切换白天黑夜模式(早8晚8切换制)', false, true],
['switchpbstatus', 'pbstatus function', '讨论区和题目页显示题目完成状态', true, true],
['switchpbstatusscore', 'pbstatusscore function', '题目完成状态增加难度分和会员题状态', true, true],
['switchpbstatusLocation', 'switchpbstatusLocation function', '题目显示完成状态(位置改为左方)', false, true],
['switchpbstatusBtn', 'pbstatusBtn function', '讨论区和题目页添加同步题目状态按钮', true, true],
['switchperson', 'person function', '纸片人', false, true],
], menu_ID = [], menu_ID_Content = [];
for (const element of menu_ALL){ // 如果读取到的值为 null 就写入默认值
if (GM_getValue(element[0]) == null){GM_setValue(element[0], element[3])};
}
registerMenuCommand();
// 注册脚本菜单
function registerMenuCommand() {
if (menu_ID.length > menu_ALL.length){ // 如果菜单ID数组多于菜单数组,说明不是首次添加菜单,需要卸载所有脚本菜单
for (const element of menu_ID){
GM_unregisterMenuCommand(element);
}
}
for (let i=0;i < menu_ALL.length;i++){ // 循环注册脚本菜单
menu_ALL[i][3] = GM_getValue(menu_ALL[i][0]);
let content = `${menu_ALL[i][3]?'✅':'❎'} ${ menu_ALL[i][2]}`
menu_ID[i] = GM_registerMenuCommand(content, function(){ menu_switch(`${menu_ALL[i][0]}`,`${menu_ALL[i][1]}`,`${menu_ALL[i][2]}`,`${menu_ALL[i][3]}`)});
menu_ID_Content[i] = content
}
menu_ID[menu_ID.length] = GM_registerMenuCommand(`🏁 当前版本 ${version}`, function () {window.GM_openInTab('https://greasyfork.org/zh-CN/scripts/450890-leetcoderating-%E6%98%BE%E7%A4%BA%E5%8A%9B%E6%89%A3%E5%91%A8%E8%B5%9B%E9%9A%BE%E5%BA%A6%E5%88%86', {active: true,insert: true,setParent: true});});
menu_ID_Content[menu_ID_Content.length] = `🏁 当前版本 ${version}`
menu_ID[menu_ID.length+1] = GM_registerMenuCommand(`🏁 企鹅群号 654726006`, function () {});
menu_ID_Content[menu_ID_Content.length+1] = `🏁 654726006`
}
//切换选项
function menu_switch(name, ename, cname, value){
if(value == 'false'){
GM_setValue(`${name}`, true);
registerMenuCommand(); // 重新注册脚本菜单
location.reload(); // 刷新网页
GM_notification({text: `「${cname}」已开启\n`, timeout: 3500}); // 提示消息
} else {
GM_setValue(`${name}`, false);
registerMenuCommand(); // 重新注册脚本菜单
location.reload(); // 刷新网页
GM_notification({text: `「${cname}」已关闭\n`, timeout: 3500}); // 提示消息
}
registerMenuCommand(); // 重新注册脚本菜单
}
}
function copyNoRight() {
new ElementGetter().each('.WRmCx > div:has(code)', document, (item) => {
addCopy(item)
let observer = new MutationObserver(function(mutationsList, observer) {
// 检查每个变化
mutationsList.forEach(function(mutation) {
addCopy(item)
});
});
// 配置 MutationObserver 监听的内容和选项
let config = { attributes: false, childList: true, subtree: false };
observer.observe(item, config);
});
function addCopy(item) {
let nowShow = item.querySelector('div:not(.hidden) > div.group.relative > pre > code')
let copyNode = nowShow.parentElement.nextElementSibling.cloneNode(true)
nowShow.parentElement.nextElementSibling.setAttribute("hidden", true)
copyNode.classList.add("copyNode")
copyNode.onclick = function () {
let nowShow = item.querySelector('div:not(.hidden) > div.group.relative > pre > code');
navigator.clipboard.writeText(nowShow.textContent).then(() => {
layer.msg('复制成功');
});
};
nowShow.parentNode.parentNode.appendChild(copyNode);
}
}
if(GM_getValue("switchcopyright") && location.href.match(pbUrl)) copyNoRight()
// lc 基础req
let baseReq = (type, reqUrl, query, variables, successFuc) => {
//请求参数
let list = {"query":query, "variables":variables };
//
ajaxReq(type, reqUrl, null, list, successFuc)
};
// post请求
let postReq = (reqUrl, query, variables, successFuc) => {
baseReq("POST", reqUrl, query, variables, successFuc)
}
// 基础函数休眠
async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
let lcTheme = (mode) => {
let headers = {
accept: '*/*',
'accept-language': 'zh-CN,zh;q=0.9,zh-TW;q=0.8,en;q=0.7',
'content-type': 'application/json',
}
let body = {
operationName: 'setTheme',
query: '\n mutation setTheme($darkMode: String!) {\n setDarkSide(darkMode: $darkMode)\n}\n ',
variables: {
'darkMode': mode
},
}
ajaxReq("POST", lcnojgo, headers, body, ()=>{})
}
if(GM_getValue("switchdark")) {
let h = new Date().getHours()
if (h >= 8 && h < 20) {
lcTheme('light')
localStorage.setItem("lc-dark-side", "light")
console.log("修改至light mode...")
}
else {
lcTheme('dark')
localStorage.setItem("lc-dark-side", "dark")
console.log("修改至dark mode...")
}
}
function allPbPostData(skip, limit) {
let reqs = {
"query":
`query problemsetQuestionList($categorySlug: String, $limit: Int, $skip: Int, $filters: QuestionListFilterInput) {
problemsetQuestionList(
categorySlug: $categorySlug
limit: $limit
skip: $skip
filters: $filters
) {
hasMore
total
questions {
acRate
difficulty
freqBar
frontendQuestionId
isFavor
paidOnly
solutionNum
status
title
titleCn
titleSlug
topicTags {
name
nameTranslated
id
slug
}
extra {
hasVideoSolution
topCompanyTags {
imgUrl
slug
numSubscribed
}
}
}
}
}`,
"variables": {
"categorySlug": "all-code-essentials",
"skip": skip,
"limit": limit,
"filters": {}
}
};
reqs.key = "LeetcodeRating";
return reqs;
}
function getpbCnt() {
let total = 0;
let headers = {
'Content-Type': 'application/json'
};
ajaxReq("POST", lcgraphql, headers, allPbPostData(0, 0), res => {
total = res.data.problemsetQuestionList.total;
})
return total;
}
// 从题目链接提取slug
// 在这之前需要匹配出所有符合条件的a标签链接
function getSlug(problemUrl) {
let preUrl = "https://leetcode-cn.com/problems/";
let nowurl = "https://leetcode.cn/problems/";
if (problemUrl.startsWith(preUrl))
return problemUrl.replace(preUrl, '').split('/')[0];
else if(problemUrl.startsWith(nowurl))
return problemUrl.replace(nowurl, '').split('/')[0];
return null;
}
// 获取题目相关内容
function getpbRelation(pburl) {
let pbstatus = JSON.parse(GM_getValue("pbstatus", "{}").toString());
let titleSlug = getSlug(pburl);
if (!titleSlug) return [null, null, null];
let status = pbstatus[titleSlug] == null ? "NOT_STARTED": pbstatus[titleSlug]["status"];
// 获取分数
let score;
let idExist = pbstatus[titleSlug] != null && t2rate[pbstatus[titleSlug]['id']] != null;
if (idExist) {
score = t2rate[pbstatus[titleSlug]['id']]["Rating"]
}
let paid = pbstatus[titleSlug] == null ? null : pbstatus[titleSlug]["paidOnly"];
return [status, score, paid]
};
// 1 ac 2 tried 3 not_started
function getPbstatusIcon(code, score, paid) {
let value;
switch(code) {
case 1:
value = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" fill="currentColor" class="myiconsvg h-[18px] w-[18px] text-green-s dark:text-dark-green-s"><path fill-rule="evenodd" d="M20 12.005v-.828a1 1 0 112 0v.829a10 10 0 11-5.93-9.14 1 1 0 01-.814 1.826A8 8 0 1020 12.005zM8.593 10.852a1 1 0 011.414 0L12 12.844l8.293-8.3a1 1 0 011.415 1.413l-9 9.009a1 1 0 01-1.415 0l-2.7-2.7a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg> `;
break;
case 2:
value = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="1.6 0 12.5 14" width="1.2em" height="1.2em" fill="currentColor" class="myiconsvg text-message-warning dark:text-message-warning"><path d="M6.998 7v-.6a.6.6 0 00-.6.6h.6zm.05 0h.6a.6.6 0 00-.6-.6V7zm0 .045v.6a.6.6 0 00.6-.6h-.6zm-.05 0h-.6a.6.6 0 00.6.6v-.6zm5-.045a5 5 0 01-5 5v1.2a6.2 6.2 0 006.2-6.2h-1.2zm-5 5a5 5 0 01-5-5h-1.2a6.2 6.2 0 006.2 6.2V12zm-5-5a5 5 0 015-5V.8A6.2 6.2 0 00.798 7h1.2zm5-5a5 5 0 015 5h1.2a6.2 6.2 0 00-6.2-6.2V2zm2.2 5a2.2 2.2 0 01-2.2 2.2v1.2a3.4 3.4 0 003.4-3.4h-1.2zm-2.2 2.2a2.2 2.2 0 01-2.2-2.2h-1.2a3.4 3.4 0 003.4 3.4V9.2zM4.798 7a2.2 2.2 0 012.2-2.2V3.6a3.4 3.4 0 00-3.4 3.4h1.2zm2.2-2.2a2.2 2.2 0 012.2 2.2h1.2a3.4 3.4 0 00-3.4-3.4v1.2zm0 2.8h.05V6.4h-.05v1.2zm-.55-.6v.045h1.2V7h-1.2zm.6-.555h-.05v1.2h.05v-1.2zm.55.6V7h-1.2v.045h1.2z"></path></svg> `;
break;
// code3 的时候需要调整style,所以设置了class,调整在css中
case 3:
value = `<svg class="myiconsvg" width="21" height="20">
<circle class="mycircle" stroke="black" stroke-width="2" fill="white"></circle>
</svg> `;
break;
default:
value = "";
break;
}
// [难度分 1980] (会员题)
if(GM_getValue("switchpbstatusscore")){
if (score) {
value += ` [难度分 ${score}] `;
}
if (paid != null && paid != false) {
value += ` (会员题) `;
}
}
return value;
}
function handleLink(link) {
// 每日一题或者是标签icon内容,不做更改直接跳过
// no-underline是标题
// rounded排除每日一题的火花和题目侧边栏,火花一开始刷新时候href为空,直到lc请求接口之后才显示每日一题链接,所以有一瞬间的时间会错误识别
if (link.href.includes("daily-question")
|| link.getAttribute("class")?.includes("rounded")
|| link.getAttribute("data-state")
|| link.getAttribute("class")?.includes("no-underline")) {
link.setAttribute("linkId", "leetcodeRating");
return;
}
// console.log(link.href)
// console.log(link)
let linkId = link.getAttribute("linkId");
if(linkId != null && linkId == "leetcodeRating") {
console.log(getSlug(link.href) + "已经替换..., 略过");
return;
}
let [status, score, paid] = getpbRelation(link.href);
if (!status) {
link.setAttribute("linkId", "leetcodeRating");
return;
}
// console.log(status);
// 1 ac 2 tried 3 not_started
let code = status == 'NOT_STARTED'? 3 : status == 'AC'? 1 : 2;
// console.log(code);
let iconStr = getPbstatusIcon(code, score, paid);
let iconEle = document.createElement("span");
iconEle.innerHTML = iconStr;
// console.log(iconEle);
// 获取元素的父节点
link.setAttribute("linkId", "leetcodeRating");
const parent = link.parentNode;
// 改变方位
if (GM_getValue("switchpbstatusLocation")) {
parent.insertBefore(iconEle, link);
} else {
if (link.nextSibling) {
parent.insertBefore(iconEle, link.nextSibling);
} else {
parent.appendChild(iconEle);
}
}
}
async function createstatusBtn() {
if(document.querySelector("#statusBtn")) return;
let span = document.createElement("span");
span.setAttribute("data-small-spacing", "true");
span.setAttribute("id", "statusBtn");
// 判断同步按钮
if (GM_getValue("switchpbstatusBtn")) {
// console.log(levelData[id])
span.innerHTML = `<i style="font-size:12px;" class="layui-icon layui-icon-refresh"></i> 同步题目状态`
span.onclick = function(e) {
layer.open({
type: 1,
content: `${pbstatusContent}`,
title: '同步所有题目状态',
area: ['550px', '250px'],
shade: 0.6,
});
}
// 使用layui的渲染
layuiload();
}
new ElementGetter().each(".css-5d7bnq-QuestionInfoContainer.e2v1tt11", document, (userinfo) => {
span.setAttribute("class", userinfo.lastChild.getAttribute("class"));
span.setAttribute("class", span.getAttribute("class")+" hover:text-blue-s");
span.setAttribute("style", "cursor:pointer");
userinfo.appendChild(span);
});
}
// 监听变化
// 改变大小
let whetherSolution = location.href.match(pbUrl);
if (whetherSolution) {
if(GM_getValue("switchpbstatusLocation")) {
GM_addStyle(`
circle.mycircle {
cx: 9;
cy: 9;
r: 7;
}
`)
} else {
GM_addStyle(`
circle.mycircle {
cx: 13;
cy: 9;
r: 7;
}
`)
}
} else {
if(GM_getValue("switchpbstatusLocation")) {
GM_addStyle(`
circle.mycircle {
cx: 8;
cy: 12;
r: 7;
}
`)
} else {
GM_addStyle(`
circle.mycircle {
cx: 13;
cy: 12;
r: 7;
}
`)
}
}
function realOpr() {
// 只有讨论区才制作同步按钮,题解区不做更改
if(window.location.href.match(discussUrl)) {
createstatusBtn();
}
// 只有讨论区和题目页进行a标签制作
if(window.location.href.match(discussUrl) || window.location.href.match(pbUrl)) {
// 获取所有的<a>标签
let links = document.querySelectorAll('a');
// 过滤出符合条件的<a>标签
let matchingLinks = Array.from(links).filter(link => {
return !link.getAttribute("linkId")
&& link.href.match(pbUrl)
&& !link.href.match(pbSolutionUrl);
});
// console.log(matchingLinks);
// 符合条件的<a>标签
matchingLinks.forEach(link => {
handleLink(link);
});
}
}
function waitOprpbStatus() {
if (GM_getValue("switchpbstatus")) {
if(window.location.href.match(discussUrl) || window.location.href.match(pbUrl)) {
let css_flag = "";
if(window.location.href.match(discussUrl)) {
css_flag = ".css-qciawt-Wrapper";
} else {
css_flag = "#qd-content";
}
new ElementGetter().each(css_flag, document, (item) => {
if(window.location.href.match(discussUrl)) realOpr();
let observer = new MutationObserver(function(mutationsList, observer) {
// 检查变化
mutationsList.forEach(function(mutation) {
realOpr();
});
});
// 配置 MutationObserver 监听的内容和选项
let config = { attributes: false, childList: true, subtree: true};
observer.observe(item, config);
});
}
}
}
waitOprpbStatus();
function pbsubmitListen() {
var originalFetch = fetch;
window.unsafeWindow.fetch = function() {
return originalFetch.apply(this, arguments).then(function(response) {
let checkUrl = "https://leetcode.cn/submissions/detail/[0-9]*/check/.*"
let clonedResponse = response.clone();
clonedResponse.text().then(function(bodyText) {
if(clonedResponse.url.match(checkUrl) && clonedResponse.status == 200 && clonedResponse.ok) {
// console.log('HTTP请求完成:', arguments[0]);
let resp = JSON.parse(bodyText);
// console.log('响应数据:', resp);
if (resp?.status_msg?.includes("Accepted")) {
let pbstatus = JSON.parse(GM_getValue("pbstatus", "{}").toString());
let slug = getSlug(location.href);
if (!pbstatus[slug]) pbstatus[slug] = {};
pbstatus[slug]["status"] = "AC";
GM_setValue("pbstatus", JSON.stringify(pbstatus));
console.log("提交成功,当前题目状态已更新");
} else if (resp?.status_msg && !resp.status_msg.includes("Accepted")) {
let pbstatus = JSON.parse(GM_getValue("pbstatus", "{}").toString());
let slug = getSlug(location.href);
// 同步一下之前的记录是什么状态
let query = "\n query userQuestionStatus($titleSlug: String!) {\n question(titleSlug: $titleSlug) {\n status\n }\n}\n ";
let headers = {
'Content-Type': 'application/json'
};
let postdata = {
"query": query,
"variables": {
"titleSlug": slug
},
"operationName": "userQuestionStatus"
}
let status;
ajaxReq("POST", lcgraphql, headers, postdata, response => {
status = response.data.question.status;
});
// 如果之前为ac状态,那么停止更新,直接返回
if(status && status == 'ac') {
if (!pbstatus[slug]) pbstatus[slug] = {};
pbstatus[slug]["status"] = "AC";
GM_setValue("pbstatus", JSON.stringify(pbstatus));
console.log("提交失败,但是之前已经ac过该题,所以状态为ac");
} else {
// 之前没有提交过或者提交过但是没有ac的状态,那么仍然更新为提交失败状态
if (!pbstatus[slug]) pbstatus[slug] = {};
pbstatus[slug]["status"] = "TRIED";
GM_setValue("pbstatus", JSON.stringify(pbstatus));
console.log("提交失败, 当前题目状态已更新");
}
}
}
});
return response;
});
};
};
if(GM_getValue("switchpbstatus") && location.href.match(pbUrl)) pbsubmitListen();
// 获取数字
function getcontestNumber(url) {
return parseInt(url.substr(15));
}
// 获取时间
function getCurrentDate(format) {
let now = new Date();
let year = now.getFullYear(); //得到年份
let month = now.getMonth(); //得到月份
let date = now.getDate(); //得到日期
let hour = now.getHours(); //得到小时
let minu = now.getMinutes(); //得到分钟
let sec = now.getSeconds(); //得到秒
month = month + 1;
if (month < 10) month = "0" + month;
if (date < 10) date = "0" + date;
if (hour < 10) hour = "0" + hour;
if (minu < 10) minu = "0" + minu;
if (sec < 10) sec = "0" + sec;
let time = "";
// 精确到天
if (format == 1) {
time = year + "年" + month + "月" + date + "日";
}
// 精确到分
else if (format == 2) {
time = year + "-" + month + "-" + date + " " + hour + ":" + minu + ":" + sec;
}
else if (format == 3) {
time = year + "/" + month + "/" + date;
}
return time;
}
GM_addStyle(`
.containerlingtea {
background: rgba(233, 183, 33, 0.2);
white-space: pre-wrap;
word-wrap: break-word;
display: block;
}
`)
// 因为力扣未捕获错误信息,所以重写一下removechild方法
const removeChildFn = Node.prototype.removeChild;
Node.prototype.removeChild = function (n) {
let err = null;
try {
err = removeChildFn.call(this, n); // 正常删除
} catch(error) {
if(!error.toString().includes("NotFoundError")) console.log("力扣api发生错误: ", error.toString().substr(0, 150))
}
return err
}
// 竞赛页面双栏布局
// 来源 better contest page / author ExplodingKonjac
let switchcontestpage = GM_getValue("switchcontestpage")
if(location.href.match("https://leetcode.cn/contest/.*/problems/.*") && switchcontestpage) {
const CSS = `
body {
display: flex;
flex-direction: column;
}
body .content-wrapper {
height: 0;
min-height: 0 !important;
flex: 1;
display: flex;
flex-direction: column;
padding-bottom: 0 !important;
}
.content-wrapper #base_content {
display: flex;
overflow: hidden;
height: 0;
flex: 1;
}
.content-wrapper #base_content > .container {
width: 40%;
overflow: scroll;
}
.content-wrapper #base_content > .container .question-content {
overflow: unset !important;
}
.content-wrapper #base_content > .container .question-content > pre {
white-space: break-spaces;
}
.content-wrapper #base_content > .editor-container {
flex: 1;
overflow: scroll;
}
.content-wrapper #base_content > .editor-container .container {
width: 100% !important;
}
.content-wrapper #base_content > .custom-resize {
width: 4px;
height: 100%;
background: #eee;
cursor: ew-resize;
margin: 0 2px;
}
.content-wrapper #base_content > .custom-resize:hover {
background: #1a90ff;
}
`
const storageKey = '--previous-editor-size';
(function () {
const $css = document.createElement('style')
$css.innerHTML = CSS
document.head.append($css)
const $problem = document.querySelector('.content-wrapper #base_content > .container')
const $editor = document.querySelector('.content-wrapper #base_content > .editor-container')
const $resize = document.createElement('div')
if (localStorage.getItem(storageKey)) {
$problem.style.width = localStorage.getItem(storageKey)
}
$editor.parentElement.insertBefore($resize, $editor)
$resize.classList.add('custom-resize')
let currentSize, startX, resizing = false
$resize.addEventListener('mousedown', (e) => {
currentSize = $problem.getBoundingClientRect().width
startX = e.clientX
resizing = true
$resize.style.background = '#1a90ff'
})
window.addEventListener('mousemove', (e) => {
if (!resizing) return
const deltaX = e.clientX - startX
const newSize = Math.max(450, Math.min(1200, currentSize + deltaX))
$problem.style.width = `${newSize}px`
e.preventDefault()
})
window.addEventListener('mouseup', (e) => {
if (!resizing) return
e.preventDefault()
resizing = false
$resize.style.background = ''
localStorage.setItem(storageKey, $problem.style.width)
})
})()
}
function callback(body) {
let data;
body.key = "leetcodeRatingReq";
ajaxReq("POST", lcgraphql, null, body, (res) => {
// console.log(res);
res.data.problemsetQuestionList.questions = res.data.problemsetQuestionList.questions.filter(e => !e.paidOnly)
data = res
})
return data
}
// 写一个拦截题库页面的工具
function intercept() {
XMLHttpRequest.prototype.open = function newOpen(method, url, async, user, password, disbaleIntercept) {
if (!disbaleIntercept && method.toLocaleLowerCase().includes('post') && url.includes(`/graphql/`)) {
const originalSend = this.send
this.send = async str => {
try {
if (typeof str === 'string') {
const body = JSON.parse(str)
if (body?.query?.includes('query problemsetQuestionList') && !body.key) {
for (const key of ['response', 'responseText']) {
Object.defineProperty(this, key, {
get: function() {
const data = callback(body)
return JSON.stringify(data)
},
configurable: true,
})
}
}
str = JSON.stringify(body)
}
} catch (error) {
console.log(error)
}
return originalSend.call(this, str)
}
}
originalOpen.apply(this, [method, url, async, user, password])
}
}
function restore() {
XMLHttpRequest.prototype.open = originalOpen
}
if(GM_getValue("switchdelvip")) intercept(); else restore()
let tFirst, tLast // all
let lcCnt = 0
function getData() {
let switchpbRepo = GM_getValue("switchpbRepo")
let switchTea = GM_getValue("switchTea")
let switchrealoj = GM_getValue("switchrealoj")
let arrList = document.querySelectorAll("div[role='rowgroup']")
let arr = arrList[0]
for (let ele of arrList) {
if (ele.childNodes.length != 0) {
arr = ele
break
}
}
// pb页面加载时直接返回
if (arr == null) {
return
}
let lastchild = arr.lastChild
let first = switchTea ? 1 : 0
if ((!switchpbRepo || (tFirst && tFirst == arr?.childNodes[first]?.textContent && tLast && tLast == lastchild?.textContent))
&& (!switchTea || arr.childNodes[0].childNodes[2].textContent == "灵神题解集")
&& (!switchrealoj) || lastchild.textContent.includes("隐藏")) {
// 到达次数之后删除定时防止卡顿
if (lcCnt == shortCnt) {
clearId("all")
}
lcCnt += 1
return
}
t2rate = JSON.parse(GM_getValue("t2ratedb", "{}").toString())
// 灵茶题目渲染
if (switchTea) {
// console.log(arr.childNodes[0].childNodes[2].textContent)
if (arr.childNodes[0].childNodes[2].textContent != "灵神题解集") {
let div = document.createElement('div')
div.setAttribute("role", "row")
div.setAttribute("style", "display:flex;flex:1 0 auto;min-width:0px")
div.setAttribute("class", "odd:bg-layer-1 even:bg-overlay-1 dark:odd:bg-dark-layer-bg dark:even:bg-dark-fill-4")
div.innerHTML += `<div role="cell" style="box-sizing:border-box;flex:60 0 auto;min-width:0px;width:60px" class="mx-2 py-[11px]"><a href="" target='_blank'>${getCurrentDate(3)}</a</div>`
div.innerHTML += `<div role="cell" style="box-sizing:border-box;flex:160 0 auto;min-width:0px;width:160px" class="mx-2 py-[11px]"><div class="max-w-[302px] flex items-center"><div class="overflow-hidden"><div class="flex items-center"><div class="truncate overflow-hidden"><a href=${teaSheetUrl} target="_blank" class="h-5 hover:text-blue-s dark:hover:text-dark-blue-s">灵茶题集</a></div></div></div></div></div>`
div.innerHTML += `<div role="cell" style="box-sizing:border-box;flex:96 0 auto;min-width:0px;width:96px" class="mx-2 py-[11px]"><span class="flex items-center space-x-2 text-label-1 dark:text-dark-label-1"><a href="${lc0x3fsolveUrl}" class="truncate" target="_blank" hover:text-blue-s aria-label="solution">灵神题解集</a></span></div><div \
role="cell" style="box-sizing:border-box;flex:82 0 auto;min-width:0px;width:82px" class="mx-2 py-[11px]"><span><a href="javascript:;" class="truncate" aria-label="solution">——</a></span></div><div \
role="cell" style="box-sizing:border-box;flex:60 0 auto;min-width:0px;width:60px" class="mx-2 py-[11px]"><span class="text-purple dark:text-dark-purple">——</span></div><div \
role="cell" style="box-sizing:border-box;flex:88 0 auto;min-width:0px;width:88px" class="mx-2 py-[11px]"><span><a href="javascript:;" >——</a></span></div>`
arr.insertBefore(div, arr.childNodes[0])
console.log("has refreshed ling pb...")
}
}
// console.log(tFirst)
// console.log(tLast)
if (switchpbRepo) {
let allpbHead = document.querySelector("div[role='row']")
let rateRefresh = false
let headndidx, acrateidx
let i = 0
allpbHead.childNodes.forEach(e => {
if (e.textContent.includes("难度")) {
headndidx = i
}
if (e.textContent.includes("通过率")) {
acrateidx = i
}