This repository has been archived by the owner on Jun 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tampermonkey-script.js
1432 lines (1355 loc) · 47.1 KB
/
tampermonkey-script.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 apollo-enhance
// @namespace apollo-enhance
// @version 0.9.16
// @description make old apollo better
// @homepage https://github.com/xyz327/old-apollo-portal-enhance
// @website https://github.com/xyz327/old-apollo-portal-enhance
// @source https://github.com/xyz327/old-apollo-portal-enhance
// @downloadURL https://raw.githubusercontent.com/xyz327/old-apollo-portal-enhance/main/tampermonkey-script.js
// @updateURL https://raw.githubusercontent.com/xyz327/old-apollo-portal-enhance/main/tampermonkey-script.js
// @author xizhou
// @match *://*/config.html*
// @resource highlight_xcode_css https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/highlight.js/9.18.5/styles/xcode.min.css
// @require https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/diff_match_patch/20121119/diff_match_patch_uncompressed.js
// @require https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/highlight.js/9.18.5/highlight.min.js
// @require https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/highlight.js/9.18.5/languages/json.min.js
// @resource text_different_css https://cdn.jsdelivr.net/npm/[email protected]/build/style/text-different.min.css
// @require https://cdn.jsdelivr.net/combine/npm/[email protected]/build/text-different.min.js,npm/[email protected]/build/text-different-for-html.min.js
// @noframes
// @grant GM_getResourceText
// @grant GM_addStyle
// @grant GM_addElement
// ==/UserScript==
(function (_$1) {
'use strict';
var allFeature = [
{
name: "fixEnvTab",
desc: "固定左侧菜单",
defaultEnabled: true
},
{
name: "fixNiceScroll",
desc: "修复 CTRL+F 搜索不能跳转的问题",
defaultEnabled: true
},
{
name: "gotoNamespace",
desc: "一键跳转到对应的 namespace",
defaultEnabled: true
},
{
name: "releaseDiff",
desc: "发布界面差异对比",
defaultEnabled: true
},
{
name: "releaseModal",
desc: "发布界面增强",
defaultEnabled: true
},
{
name: "showText",
desc: "单 key 差异对比",
defaultEnabled: true
},
{
name: "stash",
more: true,
desc: "",
defaultEnabled: false,
enabledWarn: "实验性功能,请谨慎操作"
},
{
name: "copyNamespace",
desc: "复制namespace",
defaultEnabled: true
},
{
name: "prodWarnDisable",
desc: "谨慎使用",
more: true,
defaultEnabled: false,
enabledWarn: "实验性功能,请谨慎操作"
},
{
name: "valueCodeEditor",
desc: "配置值编辑器增强",
defaultEnabled: false
}
];
var enhanceNavId = "apollo-enhance-nav";
var featureId = "apollo-enhance-feature";
var allFeatureMap = {};
allFeature.forEach((feature) => {
allFeatureMap[feature.name] = feature;
});
const BASE_INFO = {};
function appendNavBar(child) {
$(`#${enhanceNavId}`).append(child);
}
loadFeature("nav", false, function () {
var $navBar = $("#bs-example-navbar-collapse-1");
$navBar.append(`
<ul id="${enhanceNavId}" class="nav navbar-nav navbar-right">
</ul>
`);
return true;
});
const loadedJs = {};
const srcMapping = {
"bootstrap-switch": "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap-switch.min.js",
"bootstrap-switch.css": "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap3/bootstrap-switch.min.css",
};
function require(deps) {
deps = _.isArray(deps) ? deps : [deps];
return Promise.all(deps.map(dep => loadJs(dep)))
}
function loadJs(src) {
src = srcMapping[src] || src;
if (_.endsWith(src, '.css')) {
return loadCss(src)
}
if (loadedJs[src]) {
return loadedJs[src];
}
const loader = new Promise(function (resolve, reject) {
const gmAdd = GM_addElement("script", {
src,
type: "text/javascript"
});
if (gmAdd) {
gmAdd.onload = function () {
resolve();
};
} else {
resolve();
}
});
loadedJs[src] = loader;
return loader;
}
function loadCss(href) {
GM_addElement("link", {
href,
rel: "stylesheet",
});
}
(function () {
initFeatureId();
initDiffModal();
// 绑定复制事件
$(document).on("click", "[data-copy]", function (e) {
copy($(e.currentTarget).attr("data-copy-value")).then(function () {
var $icon = $(e.target).parent().find(".glyphicon");
$icon.removeClass("glyphicon-duplicate").addClass("glyphicon-ok");
setTimeout(function () {
$icon.addClass("glyphicon-duplicate").removeClass("glyphicon-ok");
}, 2000);
});
});
// 加载 layer 因为依赖 $ 所以在代码里面进行加载
loadCss("https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap3/bootstrap-switch.min.css");
const highlight_xcode_css = GM_getResourceText("highlight_xcode_css");
const text_different_css = GM_getResourceText("text_different_css");
GM_addStyle(highlight_xcode_css);
GM_addStyle(text_different_css);
})();
function getAllFeaturenMap() {
return allFeatureMap;
}
var onNamesacpeLoadedCbs = [];
var firsetNamespaceLoaded = false;
function onNamesacpeLoaded(cb) {
if (typeof cb === "function") {
onNamesacpeLoadedCbs.push(cb);
}
return {
then: function (cb) {
if (firsetNamespaceLoaded) {
cb();
}
onNamesacpeLoadedCbs.push(cb);
},
};
}
loadFeature("onNamesacpeLoaded", true, function () {
var $namespaces = $(".namespace-name");
if ($namespaces.length == 0) {
return false;
}
console.log("trigger namespaceLoaded");
$("body").on("namespaceLoaded", () => {
onNamesacpeLoadedCbs.forEach((cb) => cb());
});
$("body").trigger("namespaceLoaded");
const observer = new MutationObserver(function () {
console.log("rebuild", arguments);
$("body").trigger("namespaceLoaded");
});
$.each($(".config-item-container"), (index, el) => {
observer.observe(el, { childList: true });
});
firsetNamespaceLoaded = true;
});
function getAppId() {
let hash = location.hash;
if (hash) {
hash = hash.substring(2);
const url = new URL("http://localhost?" + hash);
return url.searchParams.get("appid");
}
}
function loadFeature(name, options, feature) {
options =
typeof options === "object"
? options
: {
switch: true,
reloadOnHashChange: options,
};
if (options.switch) {
// allFeature.push(name);
if (isFeatureDisabled(name)) {
console.log(`loadFeature: ${name} has disabled`);
return;
}
}
var reloadOnHashChange = !!options.reloadOnHashChange;
loadFeature0(name, feature, false);
if (reloadOnHashChange) {
$(window).on("hashchange", function (e) {
console.log("hashchange");
loadFeature0(name, feature, true);
});
}
}
function isFeatureDisabled(name) {
var state = featureState(name);
if (state === true) {
// 明确设置过为启用
return false;
}
if (state === false) {
// 明确设置过为不启用
return true;
}
// 默认开关
if (allFeatureMap[name] && !allFeatureMap[name].defaultEnabled) {
console.log(`loadFeature: ${name} has disabled by deafult`);
return true;
}
return false;
}
function featureState(name, state) {
return featureTypeState(name, null, state);
}
function featureTypeState(name, subtype, state) {
var feature = subtype ? name + "-" + subtype : name;
var stateMap = JSON.parse(localStorage.getItem("featureState")) || {};
if (state == undefined) {
// get
return stateMap[feature];
}
//set
stateMap[feature] = state;
localStorage.setItem("featureState", JSON.stringify(stateMap));
}
function switchFeature(name, enabled) {
featureState(name, enabled);
}
function copy(content) {
return new Promise(function (res, rej) {
let copy = function (e) {
try {
e.preventDefault();
e.clipboardData.setData("text/plain", content);
document.removeEventListener("copy", copy);
console.log("copy value:", content);
res();
} catch (e) {
rej();
}
};
document.addEventListener("copy", copy);
document.execCommand("Copy");
});
}
function toPerttyJson(val) {
try {
return JSON.stringify(JSON.parse(val), null, 2);
} catch (e) {
return val;
}
}
function loadFeature0(name, feature, isReloadByHash) {
try {
if (!isReloadByHash && $("#feature-" + name).length !== 0) {
// 已经加载过了
console.log(`loadFeature: ${name} has loaded`);
return;
}
var clear = setInterval(function () {
if (feature(isReloadByHash) !== false) {
console.log(`loadFeature: ${name} finished`);
$(`${"#" + featureId}`).append(`<div id="feature-${name}"></div>`);
clearInterval(clear);
}
}, 1000);
} catch (e) {
console.error(`load feature failed :${name}`, e.message);
}
}
function initFeatureId() {
$("body").prepend(`<div id="${featureId}" class="hidden"></div>`);
}
function showDiffModal(key, newVal, oldVal) {
const tdfh = new TextDifferentForHtml(
$("#diff-container")[0], // The dom used to render the display code
"json" // Type of code
);
$("#diff-detail-title").html(`${key}`);
$("#copyOld").attr("data-copy-value", oldVal);
$("#copyNew").attr("data-copy-value", newVal);
tdfh.render({
oldCode: toPerttyJson(oldVal), // Old code
newCode: toPerttyJson(newVal), // New code
hasLineNumber: false, // Whether to display the line number
});
$("#diffModal").modal();
}
function initDiffModal() {
$("body").append(`
<!-- Modal -->
<div class="modal" id="diffModal" tabindex="-1" role="dialog" aria-labelledby="diffModal">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title"><span class="text-danger" id="diff-detail-title"></span> 差异对比</h4>
</div>
<div class="modal-body" >
<div class="row">
<div class="col-xs-6 text-center">
<span data-tooltip="tooltip" title="点击复制" id="copyOld" data-copy="copy" data-copy-value="" class="label label-default">旧值
<label class="glyphicon glyphicon-duplicate"></label>
</span>
</div>
<div class="col-xs-6 text-center">
<span data-tooltip="tooltip" title="点击复制" id="copyNew" data-copy="copy" data-copy-value="" class="label label-success">新值
<label class="glyphicon glyphicon-duplicate"></label>
</span>
</div>
</div>
<div id="diff-container" style="display:flex"></div>
</div>
</div>
</div>
</div>
`);
}
loadFeature("copyNamespace", false, function () {
onNamesacpeLoaded(function () {
$("header.panel-heading .header-namespace>span:first-child")
.toArray()
.forEach(function (el) {
var name = el.innerText.trim();
var $el = $(el);
if ($el.nextAll(".copyNamespace").length != 0) {
return;
}
$el.next("span").after(`
<span data-tooltip="tooltip" title="点击复制namespace" data-copy="copy"
data-copy-value="${name}" class="copyNamespace label label-success">复制
<label class="glyphicon glyphicon-duplicate"></label>
</span>
`);
});
});
return true;
});
loadFeature("fixEnvTab", true, function (isReloadByHash) {
var $tab = $(".J_appFound");
if ($tab.length == 0) {
return false;
}
const infoVal = sessionStorage[getAppId()];
const infoObj = JSON.parse(infoVal);
infoObj.cluster;
infoObj.env;
var $panelHeader = $tab.find(".panel-heading:first");
var $curEnvInfo = $panelHeader.find("#curEnvInfo");
if ($curEnvInfo.length == 0) {
$tab.find(".panel-heading>span").after(`
<button type="button" class="slideBtn btn btn-primary btn-xs">(点击展开/收缩)</button>
`);
$panelHeader.append(`<div id="curEnvInfo"></div>`);
$curEnvInfo = $panelHeader.find("#curEnvInfo");
}
var $scope = $('div[ng-controller="ConfigBaseInfoController"]').scope();
var pageContext = $scope.pageContext;
$curEnvInfo.html(`
<span class="label label-success">${pageContext.env}</span> - <span class="label label-info">${pageContext.clusterName}</span>
`);
if (!isReloadByHash) {
// 不是通过 hash change reload 的才需要绑定事件
$tab.find(".panel-heading .slideBtn").on("click", function (e) {
const $header = $(e.target).parent(".panel-heading");
$header.next("div").slideToggle("normal", function () {});
});
$tab = $tab.parent();
$tab.on("affixed.bs.affix", function (e) {
$tab.css({ position: "fixed" });
$tab
.find(".panel-heading")
.next("div")
.slideUp("normal", function () {});
});
$tab.on("affixed-top.bs.affix ", function (e) {
$tab.css({ position: "" });
$tab
.find(".panel-heading")
.next("div")
.slideDown("normal", function () {});
});
$tab.affix({
offset: {
top: 60,
},
});
}
return true;
});
loadFeature("fixNiceScroll", false, function () {
$(document).ready(function () {
$().niceScroll;
$.prototype.niceScroll = function(){
};
// 放在初始化之后执行
setTimeout(function () {
$("html").css("overflow", "");
var htmlScroll = $("html").getNiceScroll && $("html").getNiceScroll(0);
htmlScroll && htmlScroll.remove();
}, 200);
});
return true;
});
function scrollTo(el) {
$(el)[0].scrollIntoView({ behavior: 'smooth' });
}
let inited = false;
loadFeature("gotoNamespace", false, () => {
if ($("#affixPlaceholder").length == 0) {
$("body>nav.navbar").after(
'<div id="affixPlaceholder" style="height:60px"></div>'
);
$("body>nav.navbar")
.width("100%")
.css({ "z-index": 999, position: "fixed" });
}
goToNamespace0();
return true;
});
function goToNamespace0() {
onNamesacpeLoaded().then(() => {
if (!inited) {
buildGotoNamespace();
inited = true;
}
refreshGogoNamespace();
});
}
function refreshGogoNamespace() {
var $select = $("#namespaceSelecter");
if ($select.hasClass("select2-hidden-accessible")) {
// Select2 has been initialized
$select.select2("destroy");
}
// init
$select.select2({
placeholder: "跳转到 Namespace",
templateResult: formatOptions,
templateSelection: formatOptions,
});
}
function formatOptions(state) {
if (state.disabled) {
return state.text;
}
var namespaceScope = $(
'div[ng-controller="ConfigNamespaceController"]'
).scope();
var namespace = namespaceScope.namespaces.find((namespace) => {
return namespace.viewName === state.id;
});
if (namespace.itemModifiedCnt > 0) {
return $(
`<label>${state.text} <span class="label label-warning ">改</span></label>`
);
}
return state.text;
}
var compiled = _$1.template(`<% _.forEach(namespaces, function(namespace) { %>
<option value="<%- namespace.viewName%>"><%- namespace.viewName %></option><%
});
%>`);
function buildGotoNamespace() {
var $select = $("#namespaceSelecter");
if ($select.length > 0) {
return;
}
var namespaceScope = $(
'div[ng-controller="ConfigNamespaceController"]'
).scope();
var optionsTpl = compiled({ namespaces: namespaceScope.namespaces });
appendNavBar(`
<li id="goToNamespace" style="margin-top: 10px;">
<select id="namespaceSelecter">${optionsTpl}</select>
</li>
`);
$select = $("#namespaceSelecter");
$select.on("select2:open", function (e) {
$("#select2-namespaceSelecter-results").css({ "max-height": "600px" });
});
//var htmlScroll = $("html").getNiceScroll && $("html").getNiceScroll(0);
// 修改选项时 滚动页面到对应位置
$select.on("select2:select", function (e) {
var namespaceId = $select.val();
var namespaceEl = $(".namespace-name")
.toArray()
.find((el) => el.innerHTML == namespaceId);
scrollTo(namespaceEl);
// htmlScroll && htmlScroll.doScrollTop($(namespaceEl).offset().top - 100, 1000);
});
// 滚动页面时同步改变 当前选择的 namespace 选项
changeSelectedOnScroll($select);
}
function changeSelectedOnScroll($select) {
var selectedVal;
// 防抖
var listener = _$1.debounce(function (entries) {
if (entries.length == 0) {
return;
}
var entry = entries[0];
if (!entry.isIntersecting) {
// 从可视区移出
return;
}
var el = entry.target;
var curNamespace = $(el).text();
if (selectedVal != curNamespace) {
selectedVal = curNamespace;
$select.val(selectedVal).trigger("change");
}
}, 200);
const io = new IntersectionObserver(listener, { threshold: 1.0 });
$(".namespace-name").each((i, el) => {
io.observe(el);
});
}
loadFeature("prodWarnDisable", false, function () {
prodWarnDisable();
});
function prodWarnDisable() {
var $btn = $("#releaseModal div.modal-footer").find("button[type=submit]");
$btn.click(function (e) {
var namespaceScope = $(
'div[ng-controller="ConfigNamespaceController"]'
).scope();
var env = namespaceScope.pageContext.env;
if (!isProd(env)) {
return;
}
// var my = namespaceScope.$root.userName
// var toReleaseNamespace = $(releaseForm).isolateScope()?.toReleaseNamespace;
// var selfModify = true;
// if (toReleaseNamespace) {
// selfModify = toReleaseNamespace.items.filter(item => item.isModified).find(item => item.item.dataChangeLastModifiedBy === my)
// }
if (!isFeatureDisabled("prodWarnDisable")) {
if (confirm("已关闭生产环境发布校验,是否继续?")) {
namespaceScope.$root.userName = "disabledProdWarn";
}
}
});
}
function isProd(env) {
return env && env === "PRO";
}
var DiffMatch = new diff_match_patch();
loadFeature("releaseDiff", false, function () {
var releaseModalNode = document.querySelector("#releaseModal");
if (releaseModalNode == null) {
return false;
}
bindDiffInfo(releaseModalNode);
return true;
});
function bindDiffInfo(node) {
var observer = new MutationObserver(function () {
initChangeInfoHeader();
// 每次都需要隐藏
initChangeInfoDetail();
var $cols = $("#releaseModal table tr.ng-scope");
var kvInfo = {};
for (const col of $cols) {
var $col = $(col);
var tds = $(col).find("td");
kvInfo = {
key: tds[0].title,
oldVal: tds[1].title,
newVal: tds[2].title,
};
buildDiffHtml(
$col.find("td.diff-text"),
kvInfo.key,
kvInfo.oldVal,
kvInfo.newVal
);
}
});
observer.observe(node, {
attributeFilter: ["style"],
});
}
function toggleDiff() {
$(".change-diff").toggle();
var needShow = $(".change-diff").is(":hidden");
if (needShow) {
$(".change-detail").show();
} else {
$(".change-detail").hide();
}
}
function initChangeInfoDetail() {
$(".change-detail").hide();
var $cols = $("#releaseModal table tr.ng-scope");
for (var col of $cols) {
var $col = $(col);
if ($col.hasClass("diff-info-inited")) {
return;
}
initChageCol();
$col.addClass("diff-info-inited");
}
}
function initChageCol() {
var bodyRows = $("#releaseModal table tr.ng-scope");
for (var row of bodyRows) {
var $row = $(row);
if ($row.find("td.change-diff").length == 0) {
$row.find("td:gt(0)").addClass("change-detail x-detail").hide();
$row.append(
'<td class="change-diff diff-text" data-toggle="tooltip" data-placement="top" title="点击查看详细差异对比"></td>'
);
}
}
$(".change-diff.diff-text").tooltip();
}
function initChangeInfoHeader() {
if ($("#releaseModal table thead tr>th").length == 0) {
return;
}
if ($("#toggleDiff").length != 0) {
return;
}
// 隐藏原有信息
$("#releaseModal table thead tr>th:gt(0)").addClass("change-detail").hide();
// 增加差异信息展示
var headCol = $("#releaseModal table thead tr");
headCol.append('<th class="change-diff">差异(点击查看新旧值对比)</th>');
$("#releaseModal table thead tr>th:eq(0)").append(
'<button id="toggleDiff">切换显示</button>'
);
$("#toggleDiff").click(function () {
toggleDiff();
return false;
});
}
function buildDiffHtml($node, key, oldVal, newVal) {
// 新增或删除
var diff = DiffMatch.diff_main(oldVal, newVal);
DiffMatch.diff_cleanupSemantic(diff);
var html = DiffMatch.diff_prettyHtml(diff);
$node.html(html);
var errorJson = isErrorJson(newVal);
if (errorJson) {
var $td = $node.parent().find("td:first");
var errorJsonLabelId = `${key}-errorJson`;
if ($(`#${errorJsonLabelId}`).length == 0) {
$td.append(
`<span id="${errorJsonLabelId}" class="label label-danger">错误的json</span>`
);
$td.addClass("alert alert-danger");
}
}
$node.on("click", function () {
showDiffModal(key, newVal, oldVal);
});
}
function isErrorJson(val) {
val = val.trim();
if (val.startsWith("{") || val.startsWith("[")) {
try {
JSON.parse(val);
return false;
} catch (e) {
return true;
}
}
return false;
}
loadFeature("releaseModal", true, function () {
if ($("#goReleaseMoadlBottom").length == 0) {
$('#releaseModal div.modal-header .modal-title:not(".ng-hide")').append(
`<span id="goReleaseMoadlBottom" class="glyphicon glyphicon-circle-arrow-down" data-tooltip="tooltip" data-placement="top" title="定位到发布按钮"></span>`
);
}
if ($("#goReleaseMoadlTop").length == 0) {
$("#releaseModal div.modal-footer").prepend(`
<span id="goReleaseMoadlTop" class="pull-left glyphicon glyphicon-circle-arrow-up" data-tooltip="tooltip" data-placement="top" title="回到顶部"></span>`);
}
// for scroll
$("#goReleaseMoadlBottom").on("click", function () {
scrollTo($("#goReleaseMoadlTop"));
});
$("#goReleaseMoadlTop").on("click", function () {
scrollTo($("#goReleaseMoadlBottom"));
});
return true;
});
loadFeature(
"settings",
{ switch: false, reloadOnHashChange: false },
function () {
require(["bootstrap-switch"])
.then(() => {
buildSettings();
});
}
);
function buildSettings() {
initSettingsModal();
$("[data-toggle=switch]")
.bootstrapSwitch({
onText: "开启",
offText: "关闭",
onSwitchChange: function (event, state) {
var $el = $(this);
var featureName = $el.val();
var feature = getAllFeaturenMap()[featureName];
if (
feature &&
state &&
!featureTypeState(featureName, "enabledWarn") &&
feature.enabledWarn
) {
layer.confirm(
feature.enabledWarn,
{ icon: 3, btn: ["确定", "取消"] },
function (index) {
switchFeature(featureName, true);
featureTypeState(featureName, "enabledWarn", true);
$el.bootstrapSwitch("state", true);
layer.close(index);
layer.confirm('切换成功,刷新生效。是否立即刷新页面?', function (idx) {
location.reload();
});
},
function () { }
);
return false;
} else {
switchFeature(featureName, state);
layer.confirm('切换成功,刷新生效。是否立即刷新页面?', function (idx) {
location.reload();
});
}
},
});
appendNavBar(`
<li>
<a href="javascript:void(0);" id="showSettings">
<span class="glyphicon glyphicon-cog"></span>
</a>
</li>
`);
$("#showSettings").on("click", showSettings);
}
function showSettings() {
$("#settingsModal").modal();
}
function initSettingsModal() {
var tpl = "";
var moreTpl = "";
allFeature.forEach((feature) => {
var key = feature.name.replace(".", "-");
var checked = isFeatureDisabled(feature.name) ? "" : "checked";
var _tpl = `
<div class="form-group" style="width:45%;margin:5px 0px;">
<label class="col-sm-6 control-label" for="feature-switch-${key}">${feature.name}
<span class="glyphicon glyphicon-question-sign" data-tooltip="tooltip" title="${feature.desc}"></span>
</label>
<div class="col-sm-6">
<input type="checkbox" data-toggle="switch" value="${feature.name}" id="feature-switch-${key}" ${checked}/>
</div>
</div>
`;
if (feature.more) {
moreTpl += _tpl;
} else {
tpl += _tpl;
}
});
$("body").append(`
<!-- Modal -->
<div class="modal fade" id="settingsModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title"><span class="text-danger" id="diff-detail-title"></span> 设置 (修改后刷新生效)
<a href="javascript:void(0);" id="showFeatureInfo">
<span class="glyphicon glyphicon-question-sign"></span>
</a>
</h4>
</div>
<div class="modal-body" >
<form class="form-inline">
${tpl}
</form>
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" data-parent="#accordion"
onclick="$('#collapseOne').collapse('toggle');" aria-controls="collapseOne">
更多功能
</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse out" role="tabpanel" aria-labelledby="headingOne">
<div class="panel-body">
<form class="form-inline">
${moreTpl}
</form>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div><a href="https://greasyfork.org/zh-CN/scripts/447045-apollo-enhance" target="_blank" title="更新检测">${BASE_INFO.version}</a> </div>
<div class="center-block">
企微反馈👉 <a href="wxwork://message?username=xizhouxi">@xizhouxi</a>
</div>
</div>
</div>
</div>
</div>
`);
}
loadFeature("showText", true, function () {
var $namespaces = $(".namespace-view-table");
if ($namespaces.length == 0) {
return false;
}
var currItem;
$("#showTextModal .modal-body")
.tooltip({
title: "点击查看差异对比",
})
.on("click", function () {
if (currItem && currItem.isModified) {
showDiffModal(currItem.item.key, currItem.newValue, currItem.oldValue);
}
});
// 点击查看时 选择当前的 item
$('body').on('click', "td.cursor-pointer", function(e){
var $target = $(e.currentTarget);
if($target.prev('td.cursor-pointer').length == 0){
// 说明点击的是 key 忽略
return;
}
var $tr = $target.parent();
var key = $tr.find("td:eq(1)").find('span:eq(0)').text().trim();
var namespace = $tr
.parents("section.master-panel-body.ng-scope")
.find("b.namespace-name.ng-binding")
.text()
.trim();
var namespaceScope = $(
'div[ng-controller="ConfigNamespaceController"]'
).scope();
var namesapce = namespaceScope.namespaces.find(
(e) => e.baseInfo.namespaceName === namespace
);
console.log('show key:', namespace, key);
currItem = namesapce.items.find((e) => e.item.key === key);
});
});
loadFeature("stash", true, function () {
onNamesacpeLoaded(function () {
console.log("stash");
$.each(
$("section.master-panel-body.ng-scope>.panel-heading>"),
function (idx, el) {
var $panel = $(el);
if ($panel.find(".stashFeature").length > 0) {
return;
}
$panel.append(`<label class="stashFeature hidden"/>`);
var namespaceName = $panel
.find("b.namespace-name.ng-binding")
.text()
.trim();
var namespaceScope = $(
'div[ng-controller="ConfigNamespaceController"]'
).scope();
var ConfigService = angular
.injector(["application"])
.get("ConfigService");
var namespace = namespaceScope.namespaces.find(
(e) => e.baseInfo.namespaceName === namespaceName
);
var $menu = $(el).find(".dropdown-menu");
$menu.append('<li role="separator" class="divider"></li>');
$(`
<li><a href="javascript:void(0);" ><span class="glyphicon glyphicon-save"></span>暂存改动</a></li>
`)
.on("click", function () {
layer.confirm("是否要暂存改动?", function (index) {
console.log(namespaceName);
console.log(namespace);
console.log(ConfigService);
var items = namespace.items.filter((item) => item.isModified);
if (items.length === 0) {
layer.close(index);
layer.msg("没有改动");
return;
}
localStorage.setItem(
getStashKey(namespaceScope, namespace),
JSON.stringify(items)
);