-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
3621 lines (3214 loc) · 139 KB
/
Copy pathindex.html
File metadata and controls
3621 lines (3214 loc) · 139 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
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
<!-- stopwatch.html 主页面 -->
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>本地网页秒表</title>
<script>
// timer.js
let t_Initial = Number(localStorage.getItem('t_Initial')) || Date.now();
let t_Last = Number(localStorage.getItem('t_Last')) || t_Initial;
let intervals = JSON.parse(localStorage.getItem('intervals') || '[]');
let logs = JSON.parse(localStorage.getItem('logs') || '[]');
let undoStack = JSON.parse(localStorage.getItem('undoStack') || '[]'); // 撤回栈:记录被删除的item和其原始索引
let redoStack = JSON.parse(localStorage.getItem('redoStack') || '[]'); // 重做栈
migrateLegacyIntervals();
function migrateLegacyIntervals() {
// 为旧版本 LocalStorage 记录补齐新字段。
// Add new fields to legacy LocalStorage records without changing memo/tag content.
if (!Array.isArray(intervals)) {
intervals = [];
localStorage.setItem('intervals', JSON.stringify(intervals));
return;
}
let changed = false;
intervals = intervals.map((item, idx) => {
if (!item || typeof item !== 'object') {
changed = true;
return {
id: `legacy_${Date.now()}_${idx}_${Math.random().toString(36).slice(2)}`,
memo: String(item ?? ''),
tag: '',
duration: '',
durationMs: 0,
endTime: Date.now(),
setDuration: '',
parsed: false,
withdrawn: false,
withdrawnAt: null
};
}
if (!item.id) {
const stableTime = Number(item.endTime) || Date.now();
item.id = `legacy_${stableTime}_${idx}_${Math.random().toString(36).slice(2)}`;
changed = true;
}
if (typeof item.withdrawn === 'undefined') {
item.withdrawn = false;
changed = true;
}
if (typeof item.withdrawnAt === 'undefined') {
item.withdrawnAt = null;
changed = true;
}
return item;
});
if (changed) {
localStorage.setItem('intervals', JSON.stringify(intervals));
}
}
const NUTSTORE_CFG_KEY = 'nutstore_backup_config_v1';
const NUTSTORE_BASE_URL = 'https://dav.jianguoyun.com/dav/';
const NUTSTORE_REQUIRED_PREFIX = 'NewMars/';
const BACKUP_REMINDER_CFG_KEY = 'backup_download_reminder_cfg_v1';
const ADVANCED_MODE_KEY = 'advanced_mode_enabled_v1';
const THEME_KEY = 'ui_theme_id_v1';
const UI_FONT_SIZE_KEY = 'ui_font_size_px_v1';
const UI_BUTTON_SIZE_KEY = 'ui_button_size_px_v1';
const UI_TITLE_SIZE_KEY = 'ui_title_size_px_v1';
const UI_INPUT_FONT_SIZE_KEY = 'ui_input_font_size_px_v1';
const UI_MAIN_BTN_HEIGHT_KEY = 'ui_main_btn_height_px_v1';
const UI_OTHER_BTN_HEIGHT_KEY = 'ui_other_btn_height_px_v1';
const NUTSTORE_FEATURE_ENABLED = false;
let nutstoreAutoTimer = null;
let backupReminderTimer = null;
let isAdvancedMode = localStorage.getItem(ADVANCED_MODE_KEY) === '1';
let uiFontSize = Number(localStorage.getItem(UI_FONT_SIZE_KEY)) || 18;
let uiButtonSize = Number(localStorage.getItem(UI_BUTTON_SIZE_KEY)) || 16;
let uiTitleSize = Number(localStorage.getItem(UI_TITLE_SIZE_KEY)) || 32;
let uiInputFontSize = Number(localStorage.getItem(UI_INPUT_FONT_SIZE_KEY)) || 18;
let uiMainBtnHeight = Number(localStorage.getItem(UI_MAIN_BTN_HEIGHT_KEY)) || 58;
let uiOtherBtnHeight = Number(localStorage.getItem(UI_OTHER_BTN_HEIGHT_KEY)) || 50;
const THEMES = [
{
id: 'noir',
labels: { zh: '黑曜', mix: '黑曜', en: 'Noir' },
vars: { bg: '#000000', panel: '#0a0a0a', panel2: '#131313', text: '#e9e9e9', muted: '#a3a3a3', border: '#2a2a2a', accent: '#7a7a7a', danger: '#d46a6a', input: '#141414', pre: '#101010', tab: '#0f0f0f', record: '#121212', dialog: '#0f0f0f', shadow: '0 8px 32px rgba(0,0,0,0.55)' }
},
{
id: 'graphite',
labels: { zh: '石墨灰', mix: '石墨灰', en: 'Graphite' },
vars: { bg: '#111111', panel: '#171717', panel2: '#1f1f1f', text: '#ececec', muted: '#b8b8b8', border: '#3a3a3a', accent: '#8f8f8f', danger: '#d87979', input: '#202020', pre: '#1c1c1c', tab: '#191919', record: '#202020', dialog: '#181818', shadow: '0 8px 28px rgba(0,0,0,0.5)' }
},
{
id: 'porcelain',
labels: { zh: '瓷白', mix: '瓷白', en: 'Porcelain' },
vars: { bg: '#f4f4f2', panel: '#ffffff', panel2: '#ececeb', text: '#202020', muted: '#5d5d5d', border: '#cfcfcf', accent: '#7f7f7f', danger: '#b45050', input: '#ffffff', pre: '#f1f1f1', tab: '#ffffff', record: '#f7f7f7', dialog: '#ffffff', shadow: '0 10px 24px rgba(0,0,0,0.14)' }
},
{
id: 'cobalt',
labels: { zh: '钴蓝', mix: '钴蓝', en: 'Cobalt' },
vars: { bg: '#0a1020', panel: '#131b33', panel2: '#1d2744', text: '#e9efff', muted: '#9fb0d8', border: '#2f3d62', accent: '#7da7ff', danger: '#e08080', input: '#171f38', pre: '#131b31', tab: '#121a31', record: '#1a2340', dialog: '#121a31', shadow: '0 8px 32px rgba(0,0,0,0.5)' }
},
{
id: 'amber',
labels: { zh: '琥珀橙', mix: '琥珀橙', en: 'Amber' },
vars: { bg: '#1a120a', panel: '#23180e', panel2: '#2f2012', text: '#ffeede', muted: '#d7bda1', border: '#5d3e22', accent: '#ffb164', danger: '#f38f80', input: '#2a1b10', pre: '#26190f', tab: '#24180f', record: '#2a1d12', dialog: '#24180f', shadow: '0 8px 32px rgba(0,0,0,0.48)' }
},
{
id: 'mauve',
labels: { zh: '暮紫', mix: '暮紫', en: 'Mauve' },
vars: { bg: '#141018', panel: '#1b1621', panel2: '#251d2d', text: '#f2eaff', muted: '#baa7cf', border: '#3f3350', accent: '#c49cff', danger: '#df8a98', input: '#221b2b', pre: '#1e1826', tab: '#1c1723', record: '#241d2f', dialog: '#1c1723', shadow: '0 8px 32px rgba(0,0,0,0.5)' }
}
];
function pad(n, z = 2) { return ('00' + n).slice(-z); }
function formatTime(ms) {
let totalSeconds = Math.floor(ms / 1000);
let hours = Math.floor(totalSeconds / 3600);
let minutes = Math.floor((totalSeconds % 3600) / 60);
let seconds = totalSeconds % 60;
let fraction = Math.floor((ms % 1000));
return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}.${String(fraction).padStart(3, '0')}`;
}
function formatDateWithTimezone(date) {
const dateStr = date.toLocaleString(undefined, { timeZoneName: 'short' });
const ms = String(date.getMilliseconds()).padStart(3, '0');
return `${dateStr}.${ms}`;
}
function buildIntervalsCsv(includeWithdrawn = false) {
const rows = [
[
'持续时间(分钟)',
'持续时间毫秒',
'格式化时间',
'备注',
'标签',
'结束时间',
'结束时间戳',
'指定持续时间(分钟)',
'已解析',
'状态'
]
];
intervals.forEach(item => {
if (!includeWithdrawn && item.withdrawn) return; // 排除撤回记录
const durationMs = Number(item.durationMs) || 0;
const mins = durationMs ? (durationMs / 60000).toFixed(2) : '';
const endTimeMs = Number(item.endTime) || '';
const endTimeStr = endTimeMs ? formatDateWithTimezone(new Date(endTimeMs)) : '';
const status = item.withdrawn ? '已撤回' : '';
rows.push([
mins,
durationMs,
item.duration || (durationMs ? formatTime(durationMs) : ''),
item.memo || '',
item.tag || '',
endTimeStr,
endTimeMs,
item.setDuration ?? '',
item.parsed ? '已解析' : '',
status
]);
});
return rows.map(row => row.map(csvEscape).join(',')).join('\n');
}
function csvEscape(val) {
return `"${String(val ?? '').replace(/"/g, '""')}"`;
}
function downloadCsvContent(csv, filename) {
const blob = new Blob([csv], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
function buildNormalCsvFilename(now) {
return `Uncleared_${now.toLocaleTimeString().replace(/:/g, ':')} ${now.toLocaleDateString()} ${Intl.DateTimeFormat(undefined, { timeZoneName: 'short' }).format(now).split(' ').pop()}.csv`;
}
function buildBackupCsvFilename(now) {
const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}_${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
return `backup_${stamp}.csv`;
}
function exportIntervalsToCSV() {
const activeRecords = intervals.filter(item => !item.withdrawn);
if (!activeRecords.length) {
alert('没有未撤回的记录可导出');
return false;
}
const csv = buildIntervalsCsv(false); // 普通导出排除撤回记录
downloadCsvContent(csv, buildNormalCsvFilename(new Date()));
return true;
}
function exportBackupCSVNoClear() {
if (!intervals.length) {
alert(getI18n('noRecords'));
return;
}
const now = new Date();
const csv = buildIntervalsCsv(true); // 备份导出包含全部记录
downloadCsvContent(csv, buildBackupCsvFilename(now));
return now;
}
function updateDisplay() {
const now = Date.now();
const elapsed = now - t_Last;
const firstStart = getFirstIntervalStartTime();
document.getElementById('current-duration').textContent = formatTime(elapsed);
document.getElementById('absolute-time').textContent = new Date(now).toLocaleTimeString();
document.getElementById('absolute-date').textContent = new Date(now).toLocaleDateString();
document.getElementById('initial-time').textContent = new Date(firstStart).toLocaleTimeString();
document.getElementById('initial-date').textContent = new Date(firstStart).toLocaleDateString();
requestAnimationFrame(updateDisplay);
}
function getFirstIntervalStartTime() {
if (!intervals.length) return t_Initial;
const first = intervals[0];
const end = Number(first.endTime) || t_Initial;
const dur = Number(first.durationMs) || 0;
return end - dur;
}
function renderIntervals() {
const container = document.getElementById('intervals-container');
container.innerHTML = '';
intervals.slice().reverse().forEach((item, index) => {
const trueIndex = intervals.length - 1 - index;
const div = document.createElement('div');
div.className = 'interval-record';
// 如果是软撤回的记录,视觉上弱化显示
if (item.withdrawn) {
div.style.opacity = '0.5';
div.style.background = 'rgba(128, 128, 128, 0.1)';
}
const mins = item.durationMs ? (item.durationMs / 60000).toFixed(2) : '--';
const endTimeStr = formatDateWithTimezone(new Date(item.endTime));
const advancedFields = isAdvancedMode ? `
<div>Tag: <input value="${item.tag || ''}" oninput="updateTag(${trueIndex}, this.value)"></div>
<div>指定时间(分钟): <input type="number" value="${item.setDuration || ''}" oninput="updateSetDuration(${trueIndex}, this.value)"></div>
` : '';
// 精简模式下显示解析后的标签和时间
const simpleModeTag = !isAdvancedMode && item.parsed && item.tag ? `
<span style="color: var(--muted); font-size: 0.9em; margin-left: 1em; margin-right: 1em;">${item.tag}</span>
` : '';
const simpleModeDuration = !isAdvancedMode && item.parsed && item.setDuration ? `
<span style="color: var(--muted); font-size: 0.9em; margin-left: 1em;">${item.setDuration}分钟</span>
` : '';
const withdrawnIndicator = item.withdrawn ? `<div style="color: #666; font-style: italic;">已撤回</div>` : '';
div.innerHTML = `
${withdrawnIndicator}
<div><strong class="duration">${mins} 分钟</strong></div>
<div>Memo: ${simpleModeTag}<input value="${item.memo}" oninput="updateMemo(${trueIndex}, this.value)">${simpleModeDuration}</div>
${advancedFields}
<div>结束时间: ${endTimeStr}</div>
<button onclick="parseMemo(${trueIndex})" ${item.withdrawn ? 'disabled' : ''}>解析Memo</button>
<button onclick="undoParse(${trueIndex})" ${item.withdrawn ? 'disabled' : ''}>撤销</button>
`;
if (isAdvancedMode && item.parsed) div.style.background = '#eee';
container.appendChild(div);
});
}
function getAdvancedToggleLabel() {
const lang = window.currentLang || 'zh';
const labels = {
off: {
zh: '🧩 高级模式',
mix: '🧩 高级模式',
en: '🧩 Advanced'
},
on: {
zh: '🧩 精简模式',
mix: '🧩 精简模式',
en: '🧩 Simple'
}
};
return (isAdvancedMode ? labels.on : labels.off)[lang] || (isAdvancedMode ? labels.on.zh : labels.off.zh);
}
function getThemeButtonLabel() {
const lang = window.currentLang || 'zh';
const labels = {
zh: '🎨 颜色主题',
mix: '🎨 颜色主题',
en: '🎨 Theme'
};
return labels[lang] || labels.zh;
}
function applyThemeById(themeId) {
const theme = THEMES.find(t => t.id === themeId) || THEMES[0];
const root = document.documentElement;
root.style.setProperty('--bg', theme.vars.bg);
root.style.setProperty('--panel', theme.vars.panel);
root.style.setProperty('--panel-2', theme.vars.panel2);
root.style.setProperty('--text', theme.vars.text);
root.style.setProperty('--muted', theme.vars.muted);
root.style.setProperty('--border', theme.vars.border);
root.style.setProperty('--accent', theme.vars.accent);
root.style.setProperty('--danger', theme.vars.danger);
root.style.setProperty('--input-bg', theme.vars.input);
root.style.setProperty('--pre-bg', theme.vars.pre);
root.style.setProperty('--tab-bg', theme.vars.tab);
root.style.setProperty('--record-bg', theme.vars.record);
root.style.setProperty('--dialog-bg', theme.vars.dialog);
root.style.setProperty('--dialog-shadow', theme.vars.shadow);
}
function initTheme() {
const saved = localStorage.getItem(THEME_KEY);
const fallback = THEMES[0].id;
const valid = THEMES.some(t => t.id === saved) ? saved : fallback;
localStorage.setItem(THEME_KEY, valid);
applyThemeById(valid);
}
function renderThemePickerOptions() {
const wrap = document.getElementById('theme-picker-options');
if (!wrap) return;
const lang = window.currentLang || 'zh';
const current = localStorage.getItem(THEME_KEY) || THEMES[0].id;
wrap.innerHTML = '';
THEMES.forEach(theme => {
const btn = document.createElement('button');
const name = (theme.labels && (theme.labels[lang] || theme.labels.zh)) || theme.id;
btn.textContent = theme.id === current ? `✓ ${name}` : name;
btn.style.margin = '0.25rem';
btn.onclick = () => selectThemeFromPicker(theme.id);
wrap.appendChild(btn);
});
}
function openThemePickerDialog() {
renderThemePickerOptions();
const dialog = document.getElementById('theme-picker-dialog');
if (!dialog) return;
dialog.style.display = 'block';
}
function closeThemePickerDialog() {
const dialog = document.getElementById('theme-picker-dialog');
if (!dialog) return;
dialog.style.display = 'none';
}
function selectThemeFromPicker(themeId) {
localStorage.setItem(THEME_KEY, themeId);
applyThemeById(themeId);
updateAdvancedModeUI();
closeThemePickerDialog();
}
function getUiRange(kind) {
const ranges = {
font: [1, 50],
button: [1, 50],
title: [1, 50],
inputFont: [1, 50],
mainBtnHeight: [20, 140],
otherBtnHeight: [20, 140]
};
return ranges[kind] || [1, 50];
}
function clampUiSizeByKind(kind, v) {
const [minV, maxV] = getUiRange(kind);
return Math.max(minV, Math.min(maxV, Number(v) || minV));
}
function applyUIFontSize(sizePx) {
const v = clampUiSizeByKind('font', sizePx);
uiFontSize = v;
localStorage.setItem(UI_FONT_SIZE_KEY, String(v));
document.documentElement.style.setProperty('--ui-font-size', `${v}px`);
const input = document.getElementById('font-size-input');
if (input) input.dataset.lastValid = String(v);
}
function applyUIButtonSize(sizePx) {
const v = clampUiSizeByKind('button', sizePx);
uiButtonSize = v;
localStorage.setItem(UI_BUTTON_SIZE_KEY, String(v));
document.documentElement.style.setProperty('--ui-button-font-size', `${v}px`);
const py = Math.max(4, Math.round(v * 0.32));
const px = Math.max(8, Math.round(v * 0.58));
document.documentElement.style.setProperty('--ui-button-pad-y', `${py}px`);
document.documentElement.style.setProperty('--ui-button-pad-x', `${px}px`);
const input = document.getElementById('button-size-input');
if (input) input.dataset.lastValid = String(v);
autoFitButtonText();
}
function applyUITitleSize(sizePx) {
const v = clampUiSizeByKind('title', sizePx);
uiTitleSize = v;
localStorage.setItem(UI_TITLE_SIZE_KEY, String(v));
document.documentElement.style.setProperty('--ui-h1-size', `${v}px`);
document.documentElement.style.setProperty('--ui-h2-size', `${Math.max(1, Math.round(v * 0.65))}px`);
document.documentElement.style.setProperty('--ui-h3-size', `${Math.max(1, Math.round(v * 0.56))}px`);
const input = document.getElementById('title-size-input');
if (input) input.dataset.lastValid = String(v);
}
function applyUIInputFontSize(sizePx) {
const v = clampUiSizeByKind('inputFont', sizePx);
uiInputFontSize = v;
localStorage.setItem(UI_INPUT_FONT_SIZE_KEY, String(v));
document.documentElement.style.setProperty('--ui-input-font-size', `${v}px`);
const input = document.getElementById('input-font-size-input');
if (input) input.dataset.lastValid = String(v);
}
function applyUIMainBtnHeight(sizePx) {
const v = clampUiSizeByKind('mainBtnHeight', sizePx);
uiMainBtnHeight = v;
localStorage.setItem(UI_MAIN_BTN_HEIGHT_KEY, String(v));
document.documentElement.style.setProperty('--ui-main-btn-height', `${v}px`);
const input = document.getElementById('main-btn-height-input');
if (input) input.dataset.lastValid = String(v);
autoFitButtonText();
}
function applyUIOtherBtnHeight(sizePx) {
const v = clampUiSizeByKind('otherBtnHeight', sizePx);
uiOtherBtnHeight = v;
localStorage.setItem(UI_OTHER_BTN_HEIGHT_KEY, String(v));
document.documentElement.style.setProperty('--ui-other-btn-height', `${v}px`);
const input = document.getElementById('other-btn-height-input');
if (input) input.dataset.lastValid = String(v);
autoFitButtonText();
}
function onUiSizeInput(kind, value) {
if (value === '') return;
const n = Number(value);
if (!Number.isFinite(n)) return;
const [minV, maxV] = getUiRange(kind);
if (n < minV || n > maxV) return;
if (kind === 'font') applyUIFontSize(n);
if (kind === 'button') applyUIButtonSize(n);
if (kind === 'title') applyUITitleSize(n);
if (kind === 'inputFont') applyUIInputFontSize(n);
if (kind === 'mainBtnHeight') applyUIMainBtnHeight(n);
if (kind === 'otherBtnHeight') applyUIOtherBtnHeight(n);
}
function onUiSizeBlur(kind, inputId) {
const input = document.getElementById(inputId);
if (!input) return;
const fallback = Number(input.dataset.lastValid || input.defaultValue || 18);
const raw = input.value.trim();
const [minV, maxV] = getUiRange(kind);
if (raw === '' || !Number.isFinite(Number(raw)) || Number(raw) < minV || Number(raw) > maxV) {
input.value = String(fallback);
return;
}
onUiSizeInput(kind, raw);
input.value = String(clampUiSizeByKind(kind, raw));
}
function syncUiSizeInputs() {
const f = document.getElementById('font-size-input');
const b = document.getElementById('button-size-input');
const t = document.getElementById('title-size-input');
const i = document.getElementById('input-font-size-input');
const mh = document.getElementById('main-btn-height-input');
const oh = document.getElementById('other-btn-height-input');
if (f) { f.value = String(uiFontSize); f.dataset.lastValid = String(uiFontSize); }
if (b) { b.value = String(uiButtonSize); b.dataset.lastValid = String(uiButtonSize); }
if (t) { t.value = String(uiTitleSize); t.dataset.lastValid = String(uiTitleSize); }
if (i) { i.value = String(uiInputFontSize); i.dataset.lastValid = String(uiInputFontSize); }
if (mh) { mh.value = String(uiMainBtnHeight); mh.dataset.lastValid = String(uiMainBtnHeight); }
if (oh) { oh.value = String(uiOtherBtnHeight); oh.dataset.lastValid = String(uiOtherBtnHeight); }
}
function autoFitButtonText() {
const buttons = Array.from(document.querySelectorAll('button'));
buttons.forEach(btn => {
const rect = btn.getBoundingClientRect();
const area = Math.max(1, rect.width * rect.height);
const areaMax = Math.max(10, Math.floor(Math.sqrt(area) * 0.22));
const target = Math.min(uiButtonSize, areaMax);
btn.style.fontSize = `${target}px`;
});
}
function updateAdvancedModeUI() {
const btn = document.getElementById('advanced-toggle');
if (btn) {
btn.textContent = getAdvancedToggleLabel();
btn.classList.toggle('is-on', isAdvancedMode);
}
const themeBtn = document.getElementById('theme-toggle');
if (themeBtn) {
themeBtn.textContent = getThemeButtonLabel();
}
const exportTabBtn = document.getElementById('tab-export-btn');
if (exportTabBtn) {
exportTabBtn.style.display = isAdvancedMode ? '' : 'none';
}
const exportCatTabBtn = document.getElementById('tab-export-cat-btn');
if (exportCatTabBtn) {
// 选定类别日志导出在普通模式也可用
exportCatTabBtn.style.display = '';
}
const importBtn = document.getElementById('import-records-btn');
if (importBtn) {
importBtn.style.display = isAdvancedMode ? '' : 'none';
}
if (!isAdvancedMode) {
const exportTab = document.getElementById('tab-export');
if (exportTab && exportTab.style.display !== 'none') {
showTab('tab-log');
}
const exportCatTab = document.getElementById('tab-export-cat');
if (exportCatTab && exportCatTab.style.display !== 'none') {
showTab('tab-log');
}
}
// 字体配置不再随高级模式自动显示,而是通过长按按钮控制
syncUiSizeInputs();
autoFitButtonText();
renderIntervals();
}
function toggleAdvancedMode() {
isAdvancedMode = !isAdvancedMode;
localStorage.setItem(ADVANCED_MODE_KEY, isAdvancedMode ? '1' : '0');
updateAdvancedModeUI();
}
function rememberInterval() {
const now = Date.now();
const localCopy = JSON.parse(localStorage.getItem('intervals') || '[]');
if (localCopy.length > intervals.length) {
alert(getI18n('outdatedWarning'));
return;
}
const durationMs = now - t_Last;
const memo = document.getElementById('memo-input').value.trim();
const item = {
id: `${Date.now()}_${Math.random().toString(36).slice(2)}`, // 唯一ID
memo,
tag: '',
duration: formatTime(durationMs),
durationMs,
endTime: now,
setDuration: '',
originalMemo: memo,
parsed: false,
withdrawn: false, // 软撤回标记
withdrawnAt: null
};
intervals.push(item);
localStorage.setItem('intervals', JSON.stringify(intervals));
// 添加记录后清空撤回栈和恢复栈,确保撤回后新增记录不能恢复旧撤回
undoStack = [];
redoStack = [];
localStorage.setItem('undoStack', JSON.stringify(undoStack));
localStorage.setItem('redoStack', JSON.stringify(redoStack));
document.getElementById('memo-input').value = '';
t_Last = now;
localStorage.setItem('t_Last', t_Last);
renderIntervals();
updateUndoRedoButtons(); // 更新撤回/恢复按钮状态
}
// === 撤回/恢复功能 ===
function undoLastRecord() {
if (!intervals.length) {
alert('没有记录可以撤回');
return;
}
// 只处理未撤回的最后一条记录
const lastIndex = intervals.length - 1;
if (intervals[lastIndex].withdrawn) {
alert('最后一条记录已经被撤回');
return;
}
const item = intervals[lastIndex];
// 软撤回
item.withdrawn = true;
item.withdrawnAt = Date.now();
// 记录到撤回栈
undoStack.push({
index: lastIndex,
itemId: item.id
});
localStorage.setItem('undoStack', JSON.stringify(undoStack));
localStorage.setItem('intervals', JSON.stringify(intervals));
// 恢复秒表到误点前的起点
if (intervals.length === lastIndex + 1) {
t_Last = item.endTime - item.durationMs;
localStorage.setItem('t_Last', t_Last);
}
renderIntervals();
updateUndoRedoButtons();
}
function redoLastRecord() {
if (!undoStack.length) {
alert('没有记录可以恢复');
return;
}
const undoItem = undoStack.pop();
const item = intervals[undoItem.index];
if (!item || item.id !== undoItem.itemId) {
alert('记录状态已改变,无法恢复');
return;
}
// 恢复
item.withdrawn = false;
item.withdrawnAt = null;
// 记录到重做栈
redoStack.push({
index: undoItem.index,
itemId: undoItem.itemId
});
localStorage.setItem('redoStack', JSON.stringify(redoStack));
localStorage.setItem('undoStack', JSON.stringify(undoStack));
localStorage.setItem('intervals', JSON.stringify(intervals));
// 恢复秒表
if (intervals.length === undoItem.index + 1) {
t_Last = item.endTime;
localStorage.setItem('t_Last', t_Last);
}
renderIntervals();
updateUndoRedoButtons();
}
function updateUndoRedoButtons() {
// 更新按钮可见性或状态
const undoBtn = document.getElementById('undo-last-btn');
const redoBtn = document.getElementById('redo-last-btn');
if (undoBtn) {
undoBtn.disabled = !intervals.length || intervals[intervals.length - 1].withdrawn;
}
if (redoBtn) {
redoBtn.disabled = !undoStack.length;
}
}
function updateTag(index, value) {
intervals[index].tag = value;
localStorage.setItem('intervals', JSON.stringify(intervals));
}
function updateMemo(index, value) {
intervals[index].memo = value;
localStorage.setItem('intervals', JSON.stringify(intervals));
}
function updateSetDuration(index, value) {
intervals[index].setDuration = value;
localStorage.setItem('intervals', JSON.stringify(intervals));
}
function resetTimer() {
t_Initial = Date.now();
t_Last = t_Initial;
localStorage.setItem('t_Initial', t_Initial);
localStorage.setItem('t_Last', t_Initial);
}
function updateLogDisplay() {
const logText = logs.map(l => `【${l.type}】${l.time}`).join('\n---\n');
document.getElementById('log-content').textContent = logText;
}
function refreshLog() {
logs = logs.filter(l => l.type !== 'Interval');
intervals.forEach(item => {
logs.push({
type: 'Interval',
time: formatDateWithTimezone(new Date(item.endTime))
});
});
localStorage.setItem('logs', JSON.stringify(logs));
updateLogDisplay();
}
function clearLog() {
logs = [];
localStorage.setItem('logs', JSON.stringify(logs));
updateLogDisplay();
}
function copyLog() {
navigator.clipboard.writeText(document.getElementById('log-content').textContent);
}
window.onload = () => {
updateDisplay();
renderIntervals();
logs.push({ type: '刷新', time: formatDateWithTimezone(new Date()) });
localStorage.setItem('logs', JSON.stringify(logs));
updateLogDisplay();
};
// === 🔤 全局多语言提示表 ===
const i18n = {
noRecords: {
zh: '没有记录可导出',
mix: '没有记录可导出',
en: 'No records to export'
},
outdatedWarning: {
zh: '⚠️ 当前页面不是最新版本,记录已被其他标签页修改,请刷新后再尝试。',
mix: '⚠️ 当前页面不是最新版本,记录已被其他标签页修改,请刷新后再尝试。',
en: '⚠️ This page is outdated. Records have been updated in another tab. Please refresh and try again.'
},
manualBackupSaved: {
zh: '✅ 手动备份已保存',
mix: '✅ 手动备份已保存',
en: '✅ Manual backup saved'
},
noBackup: {
zh: '暂无备份',
mix: '暂无备份',
en: 'No backups found'
},
csvImportError: {
zh: '❌ CSV格式错误,导入失败',
mix: '❌ CSV格式错误',
en: '❌ Invalid CSV format'
},
parseFailed: {
zh: '❌ 解析失败:找不到对应的记录。',
mix: '❌ 解析失败:找不到对应的记录。',
en: '❌ Parsing failed: item not found.'
},
undoFailed: {
zh: '⚠️ 无法撤销:该记录未被解析。',
mix: '⚠️ 无法撤销:该记录未被解析。',
en: '⚠️ Cannot undo: this item was not parsed.'
},
ruleHelp: {
zh: `
规则说明:
1. 第一行是标签名(Tag),可点击编辑;
2. 每列为一个标签,下面填写该标签的关键字;
3. 精确匹配,大小写敏感;
4. 若关键字前加 ~ 表示“备注中不包含该词”时匹配;
5. 标签的匹配顺序从左到右,找到一个匹配就会停止;
6. 感叹号开头的关键词(如 !sp)会严格匹配并从 Memo 中删除,且仅在 Memo 末尾部分生效;
7. 默认会清除匹配的关键词,但你可以通过感叹号前缀或否定关键词保留特定的匹配项;
8. 备份规则可以通过 CSV 导入或导出进行操作。
`,
mix: `
Rule Explanation:
1. The first row is for the tag names (Tag), editable;
2. Each column represents a tag, with keywords listed below each tag;
3. Exact matching, case-sensitive;
4. Keywords prefixed with ~ match when the word is not present in Memo;
5. Tags are matched from left to right, and matching stops once a keyword is found;
6. Keywords starting with ! (e.g., !sp) will strictly match and remove the keyword from the end of the Memo only;
7. By default, matched keywords are removed, but you can preserve specific matches by using the exclamation mark or the negation keyword;
8. Backup rules can be imported or exported via CSV.
`,
en: `
Rule Explanation:
1. The first row is for the tag names (Tag), editable;
2. Each column represents a tag, with keywords listed below each tag;
3. Exact matching, case-sensitive;
4. Keywords prefixed with ~ match when the word is not present in Memo;
5. Tags are matched from left to right, and matching stops once a keyword is found;
6. Keywords starting with ! (e.g., !sp) will strictly match and remove the keyword from the Memo’s end, only for the last part;
7. By default, matched keywords are removed, but you can preserve specific matches using the exclamation mark or negation keyword;
8. Backup rules can be imported or exported via CSV.
`
},
nutstoreConfigSaved: {
zh: '✅ 坚果云配置已保存',
mix: '✅ 坚果云配置已保存',
en: '✅ Nutstore config saved'
},
nutstoreNeedCredential: {
zh: '请先填写坚果云账号和应用密码',
mix: '请先填写坚果云账号和应用密码',
en: 'Please provide Nutstore account and app password first'
},
nutstoreNeedPath: {
zh: '请先填写可写的远程路径(例如:目录/文件名.json)',
mix: '请先填写可写的远程路径(例如:目录/文件名.json)',
en: 'Please provide a writable remote path first (e.g. folder/file.json)'
},
nutstoreNeedPrefix: {
zh: '远程路径必须以 NewMars/ 开头',
mix: '远程路径必须以 NewMars/ 开头',
en: 'Remote path must start with NewMars/'
},
nutstoreCorsBlocked: {
zh: '❌ 浏览器拦截了跨域请求(CORS),这通常不是账号或密码错误。',
mix: '❌ 浏览器拦截了跨域请求(CORS),这通常不是账号或密码错误。',
en: '❌ Browser blocked cross-origin request (CORS). Usually not a credential issue.'
},
nutstoreUploadOk: {
zh: '✅ 坚果云备份上传成功',
mix: '✅ 坚果云备份上传成功',
en: '✅ Nutstore backup uploaded'
},
nutstoreAutoOn: {
zh: '✅ 已启用坚果云自动备份',
mix: '✅ 已启用坚果云自动备份',
en: '✅ Nutstore auto backup enabled'
},
nutstoreAutoOff: {
zh: '⏸️ 已关闭坚果云自动备份',
mix: '⏸️ 已关闭坚果云自动备份',
en: '⏸️ Nutstore auto backup disabled'
},
backupReminderSaved: {
zh: '✅ 备份提醒配置已保存',
mix: '✅ 备份提醒配置已保存',
en: '✅ Backup reminder settings saved'
},
backupReminderOn: {
zh: '✅ 已启用定时备份提醒',
mix: '✅ 已启用定时备份提醒',
en: '✅ Periodic backup reminder enabled'
},
backupReminderOff: {
zh: '⏸️ 已关闭定时备份提醒',
mix: '⏸️ 已关闭定时备份提醒',
en: '⏸️ Periodic backup reminder disabled'
},
backupReminderRisk: {
zh: '一旦浏览器更新或清理 localStorage,未备份数据可能丢失。',
mix: '一旦浏览器更新或清理 localStorage,未备份数据可能丢失。',
en: 'If browser updates or clears localStorage, unbacked data may be lost.'
},
backupReminderNever: {
zh: '你还没有下载过备份。',
mix: '你还没有下载过备份。',
en: 'No backup has been downloaded yet.'
}
};
function getI18n(key) {
const lang = window.currentLang || 'zh';
return (i18n[key] && i18n[key][lang]) || i18n[key]?.zh || '';
}
function getBackupReminderConfig() {
const fallback = {
intervalHours: 2,
enabled: false,
lastDownloadedAt: ''
};
const raw = localStorage.getItem(BACKUP_REMINDER_CFG_KEY);
if (!raw) return fallback;
try {
return { ...fallback, ...JSON.parse(raw) };
} catch (err) {
return fallback;
}
}
function setBackupReminderConfig(config) {
localStorage.setItem(BACKUP_REMINDER_CFG_KEY, JSON.stringify(config));
}
function setBackupReminderStatus(message, isError = false) {
const el = document.getElementById('backup-reminder-status');
if (!el) return;
el.textContent = message;
el.style.color = isError ? '#b91c1c' : 'var(--muted)';
}
function applyBackupReminderConfigToUI(config) {
const input = document.getElementById('backup-reminder-hours');
if (!input) return;
input.value = String(Math.max(1, Number(config.intervalHours) || 2));
}
function readBackupReminderConfigFromUI() {
const prev = getBackupReminderConfig();
const input = document.getElementById('backup-reminder-hours');
return {
...prev,
intervalHours: Math.max(1, Number(input?.value || prev.intervalHours || 2))
};
}
function updateBackupReminderToggleButton() {
const btn = document.getElementById('backup-reminder-toggle-btn');
if (!btn) return;
const lang = window.currentLang || 'zh';
const enabled = getBackupReminderConfig().enabled;
const text = enabled
? { zh: '⏸️ 关闭提醒', mix: '⏸️ 关闭提醒', en: '⏸️ Stop Reminder' }
: { zh: '▶️ 启用提醒', mix: '▶️ 启用提醒', en: '▶️ Start Reminder' };
btn.textContent = text[lang] || text.zh;
}
function formatElapsedSince(isoString) {
if (!isoString) return null;
const start = new Date(isoString).getTime();
if (!Number.isFinite(start)) return null;
let diff = Date.now() - start;
if (diff < 0) diff = 0;
const totalMinutes = Math.floor(diff / 60000);
const days = Math.floor(totalMinutes / (60 * 24));
const hours = Math.floor((totalMinutes % (60 * 24)) / 60);
const minutes = totalMinutes % 60;
return { days, hours, minutes };
}
function buildBackupReminderMessage(lastDownloadedAt) {
const lang = window.currentLang || 'zh';
const elapsed = formatElapsedSince(lastDownloadedAt);
if (!elapsed) {
if (lang === 'en') {
return `${getI18n('backupReminderNever')} ${getI18n('backupReminderRisk')}`;
}
return `上次备份后已经很久未备份(尚无备份记录)。${getI18n('backupReminderRisk')}`;
}
if (lang === 'en') {
return `It has been ${elapsed.days}d ${elapsed.hours}h ${elapsed.minutes}m since your last backup. ${getI18n('backupReminderRisk')}`;
}
return `上次备份后已经 ${elapsed.days}天${elapsed.hours}小时${elapsed.minutes}分钟 没备份。${getI18n('backupReminderRisk')}`;
}
function openBackupReminderDialog(message) {
const dialog = document.getElementById('backup-reminder-dialog');
const messageEl = document.getElementById('backup-reminder-message');
if (!dialog || !messageEl) return;
messageEl.textContent = message;
dialog.style.display = 'block';
}
function closeBackupReminderDialog() {
const dialog = document.getElementById('backup-reminder-dialog');
if (!dialog) return;
dialog.style.display = 'none';
}
function downloadBackupNowFromReminder() {
const cfg = getBackupReminderConfig();
const downloadedAt = exportBackupCSVNoClear();
if (!downloadedAt) return;
const nextCfg = { ...cfg, lastDownloadedAt: downloadedAt.toISOString() };
setBackupReminderConfig(nextCfg);
setBackupReminderStatus(`已下载:${new Date(nextCfg.lastDownloadedAt).toLocaleString()}`);
closeBackupReminderDialog();
}