Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1816 lines (1679 loc) · 80.4 KB
/
Copy pathscript.js
File metadata and controls
1816 lines (1679 loc) · 80.4 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
/**
* ============================================================
* 「下课吃啥」- 食堂推荐助手(最终修复版)
* 修复:收藏、添加分组绝对可用;排序下拉撑开面板高度
* ============================================================
*/
document.addEventListener('DOMContentLoaded', function() {
// ===== 0. 全局配置常量 =====
const FILE_DEBOUNCE_MS = 800;
const PLACEHOLDER = '-';
const LIST_TXT_VERSION = '1.0';
const SAVE_TXT_VERSION = '1.0';
const HIGHLIGHT_CLASS = 'highlighted';
// ===== 1. 模拟数据 =====
const DISHES_DB = [];
const BAD_REVIEWS = [];
// ===== 1.5 店铺树 STORES_DB(食堂 → 楼层 → 窗口,含独立店)=====
const STORE_ROOT_ID = 0;
const STORES_DB = [
{ id: 0, name: '全部店铺', parentId: null },
// 一食堂
{ id: 101, name: '一食堂', parentId: 0 },
{ id: 111, name: '一楼', parentId: 101 },
{ id: 1111, name: '风味面点', parentId: 111 },
{ id: 1112, name: '肉夹馍窗口', parentId: 111 },
{ id: 112, name: '二楼', parentId: 101 },
{ id: 1121, name: '麻辣香锅窗口', parentId: 112 },
{ id: 1122, name: '家常炒菜窗口', parentId: 112 },
{ id: 113, name: '三楼', parentId: 101 },
{ id: 1131, name: '烤鸭饭窗口', parentId: 113 },
{ id: 1132, name: '特色盖浇窗口', parentId: 113 },
// 二食堂
{ id: 201, name: '二食堂', parentId: 0 },
{ id: 211, name: '一楼', parentId: 201 },
{ id: 2111, name: '凉皮窗口', parentId: 211 },
{ id: 2112, name: '小吃窗口', parentId: 211 },
{ id: 212, name: '二楼', parentId: 201 },
{ id: 2121, name: '健康轻食窗口', parentId: 212 },
{ id: 2122, name: '沙拉窗口', parentId: 212 },
{ id: 213, name: '三楼', parentId: 201 },
{ id: 2131, name: '黄焖鸡窗口', parentId: 213 },
{ id: 2132, name: '煲仔饭窗口', parentId: 213 },
// 三食堂
{ id: 301, name: '三食堂', parentId: 0 },
{ id: 311, name: '一楼', parentId: 301 },
{ id: 3111, name: '煎饼果子窗口', parentId: 311 },
{ id: 3112, name: '早点窗口', parentId: 311 },
{ id: 312, name: '二楼', parentId: 301 },
{ id: 3121, name: '螺蛳粉窗口', parentId: 312 },
{ id: 3122, name: '粉面窗口', parentId: 312 },
// 独立店
{ id: 401, name: '罗森便利店', parentId: 0 },
];
// ===== 1.6 店铺树工具:节点查询 / 路径 / 子孙 / 迁移 =====
function getStoreNode(id) {
return STORES_DB.find(s => s.id === id) || null;
}
function getStoreName(id) {
const n = getStoreNode(id);
return n ? n.name : '未知门店';
}
function getStorePath(id) {
const names = [];
let cur = getStoreNode(id);
while (cur && cur.id !== STORE_ROOT_ID) {
names.unshift(cur.name);
cur = getStoreNode(cur.parentId);
}
return names.length > 0 ? names.join('/') : '未分配';
}
function getDescendantIds(nodeId) {
const result = [];
const walk = (id) => {
result.push(id);
STORES_DB.filter(s => s.parentId === id).forEach(c => walk(c.id));
};
walk(nodeId);
return result;
}
// 取某节点下第一个叶子(窗口)节点,用于把旧字符串落到最底层窗口
function firstLeafId(nodeId) {
const children = STORES_DB.filter(s => s.parentId === nodeId);
if (children.length === 0) return nodeId;
children.sort((a, b) => a.id - b.id);
return firstLeafId(children[0].id);
}
// 迁移:解析旧 canteen 字符串 → storeId
function migrateToStoreId(canteenStr) {
if (!canteenStr || typeof canteenStr !== 'string') return null;
const s = canteenStr.trim();
if (!s) return null;
// 1. 精确匹配节点名
const exact = STORES_DB.find(n => n.name === s);
if (exact) return firstLeafId(exact.id);
// 2. 匹配「X食堂Y楼」
const m = s.match(/^([一二三四五六七八九十]+食堂)([一二三四五六七八九十]+楼)$/);
if (m) {
const canteen = STORES_DB.find(n => n.name === m[1] && n.parentId === STORE_ROOT_ID);
if (canteen) {
const floor = STORES_DB.find(n => n.name === m[2] && n.parentId === canteen.id);
if (floor) return firstLeafId(floor.id);
return firstLeafId(canteen.id);
}
}
// 3. 模糊匹配(包含关系)
for (const n of STORES_DB) {
if (n.id === STORE_ROOT_ID) continue;
if (s.includes(n.name) || n.name.includes(s)) return firstLeafId(n.id);
}
return null;
}
// 迁移:把 DISHES_DB 的旧 canteen 字段替换为 storeId
function runMigration() {
let migrated = 0;
DISHES_DB.forEach(d => {
if (d.storeId === undefined || d.storeId === null) {
d.storeId = migrateToStoreId(d.canteen);
delete d.canteen;
migrated++;
}
});
return migrated;
}
// ===== 1.7 店铺节点创建与路径解析(list.txt 以文字路径驱动店铺树)=====
// 新建店铺节点:id 自动分配,返回新节点(持久化由 list.txt 写回完成)
function addStoreNode(name, parentId, type) {
const newId = STORES_DB.reduce((m, s) => Math.max(m, s.id), 0) + 1;
const node = { id: newId, name: name.trim(), parentId: parentId };
if (type) node.type = type;
STORES_DB.push(node);
return node;
}
// 推断节点类型(新节点显式带 type,老节点按层级推断)
function getStoreType(node) {
if (!node) return 'root';
if (node.type) return node.type;
if (node.id === STORE_ROOT_ID) return 'root';
if (node.parentId === STORE_ROOT_ID) {
return getStoreChildren(node.id).length > 0 ? 'canteen' : 'standalone';
}
const parent = getStoreNode(node.parentId);
if (parent && getStoreType(parent) === 'canteen') return 'floor';
return 'window';
}
// 解析文字路径(如「一食堂/二楼/小吃窗口」),逐级查找,缺失则自动创建节点
function resolveStorePath(pathStr) {
if (!pathStr || typeof pathStr !== 'string') return null;
const parts = pathStr.split('/').map(s => s.trim()).filter(Boolean);
if (parts.length === 0) return null;
let parentId = STORE_ROOT_ID;
let node = null;
for (const name of parts) {
node = STORES_DB.find(s => s.parentId === parentId && s.name === name);
if (!node) node = addStoreNode(name, parentId);
parentId = node.id;
}
return node ? node.id : null;
}
// 解析 list.txt 的 store 字段:数字 id(旧格式)/ 文字路径(新格式)/ 旧 canteen 文字
function parseStoreRef(raw) {
if (raw === undefined || raw === null || raw === '' || raw === PLACEHOLDER) return null;
const s = String(raw).trim();
if (!s) return null;
if (/^\d+$/.test(s)) {
const id = Number(s);
return getStoreNode(id) ? id : id;
}
if (s.includes('/')) return resolveStorePath(s);
return migrateToStoreId(s);
}
// ===== 2. 存储 =====
const STORAGE_KEY = 'canteen_helper_data';
function loadStorage() {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (raw) return JSON.parse(raw);
} catch (_) {}
return { favorites: [], groups: [], tagStates: {} };
}
function saveStorage(data) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
}
// ===== 3. 全局状态 =====
let currentGroup = 'all';
let currentSort = 'default';
let currentDishes = [];
let selectedStoreIds = new Set();
let storeTreeExpanded = new Set([STORE_ROOT_ID]);
// ============================================================
// 基础设施层:FileGateway / 序列化器 / UserData / DataSource
// ============================================================
// ===== 3.1 FileGateway 文件读写适配层 =====
const FileGateway = (function() {
async function writeText(filename, content) {
try {
if (window.showSaveFilePicker) {
const handle = await window.showSaveFilePicker({
suggestedName: filename,
types: [{ description: '文本文件', accept: { 'text/plain': ['.txt'] } }]
});
const writable = await handle.createWritable();
await writable.write(content);
await writable.close();
return true;
}
} catch (err) {
if (err && err.name === 'AbortError') return false;
}
try {
const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
return true;
} catch (err) {
console.warn('FileGateway.writeText 失败:', err);
return false;
}
}
function readText(filename) {
return new Promise(resolve => {
try {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.txt,text/plain';
let settled = false;
input.onchange = async function() {
const file = input.files[0];
if (!file) { if (!settled) { settled = true; resolve(null); } return; }
try {
const text = await file.text();
settled = true;
resolve(text);
} catch (e) {
settled = true;
resolve(null);
}
};
input.oncancel = function() { if (!settled) { settled = true; resolve(null); } };
input.click();
} catch (err) {
console.warn('FileGateway.readText 失败:', err);
resolve(null);
}
});
}
// 获取(或让用户选择)项目目录下的 Pictures 文件夹句柄
let picturesDirHandle = null;
async function ensurePicturesDir() {
if (!window.showDirectoryPicker) return null;
try {
if (picturesDirHandle) {
const perm = await picturesDirHandle.queryPermission({ mode: 'readwrite' });
if (perm === 'granted') return picturesDirHandle;
if ((await picturesDirHandle.requestPermission({ mode: 'readwrite' })) === 'granted') return picturesDirHandle;
picturesDirHandle = null;
}
const root = await window.showDirectoryPicker({ mode: 'readwrite' });
picturesDirHandle = await root.getDirectoryHandle('Pictures', { create: true });
return picturesDirHandle;
} catch (err) {
if (err && err.name !== 'AbortError') console.warn('ensurePicturesDir 失败:', err);
picturesDirHandle = null;
return null;
}
}
// 向 Pictures 目录写入图片文件
async function writeImageToPictures(dirHandle, filename, blob) {
try {
const fileHandle = await dirHandle.getFileHandle(filename, { create: true });
const writable = await fileHandle.createWritable();
await writable.write(blob);
await writable.close();
return true;
} catch (err) {
console.warn('writeImageToPictures 失败:', err);
return false;
}
}
// 降级方案:下载文件(用户手动放入 Pictures)
function downloadBlob(filename, blob) {
try {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
return true;
} catch (err) {
console.warn('downloadBlob 失败:', err);
return false;
}
}
return { writeText, readText, ensurePicturesDir, writeImageToPictures, downloadBlob };
})();
// ===== 3.2 list.txt 载入与导出(fetch 读取同级 list.txt)=====
async function persistListFile() {
const text = ListTxtSerializer.serialize(DataSource.getAllDishes());
const ok = await FileGateway.writeText('list.txt', text);
if (!ok) showToast('list.txt 导出失败,请检查文件权限');
}
function showDropHint(msg) {
if (resultStatus) {
resultStatus.textContent = msg || '📥 请将 list.txt 拖拽到窗口中导入';
resultStatus.style.display = '';
}
}
async function bootstrapListFile() {
try {
const resp = await fetch('list.txt', { cache: 'no-store' });
if (!resp.ok) { showDropHint(); return; }
const text = await resp.text();
const res = ListTxtSerializer.deserialize(text);
if (res.formatError) { showDropHint('📥 list.txt 格式异常,请拖拽正确的文件导入'); return; }
if (res.dishes.length > 0) {
DISHES_DB.length = 0;
res.dishes.forEach(d => DISHES_DB.push(d));
}
} catch (err) {
console.warn('fetch list.txt 失败(可能在 file:// 协议下运行):', err);
showDropHint();
}
}
async function importListFromText(text) {
const res = ListTxtSerializer.deserialize(text);
if (res.formatError) { showToast('文件格式异常,已取消导入'); return false; }
DISHES_DB.length = 0;
res.dishes.forEach(d => DISHES_DB.push(d));
initTagModes();
applyFilters();
const msg = res.skippedCount > 0
? '导入完成,载入 ' + res.dishes.length + ' 条菜品(跳过 ' + res.skippedCount + ' 条不完整记录)'
: '导入完成,载入 ' + res.dishes.length + ' 条菜品';
showToast(msg);
return true;
}
// ===== 3.2 ListTxtSerializer 序列化器(分隔符 |,店铺字段 store 存文字路径)=====
const ListTxtSerializer = (function() {
const FIELDS = ['id', 'name', 'price', 'store', 'rating', 'tags', 'popular', 'note', 'localCategory', 'emoji', 'img'];
const SEP = '|';
function serialize(dishes) {
const header = '# list.txt 字段顺序: ' + FIELDS.join('/') + ' | 分隔符 | | tags以逗号分隔 | 空值用' + PLACEHOLDER + ' | 字段值勿含 |';
const lines = dishes.map(d => FIELDS.map(f => {
if (f === 'tags') return Array.isArray(d.tags) && d.tags.length > 0 ? d.tags.join(',') : PLACEHOLDER;
if (f === 'store') {
if (d.storeId === undefined || d.storeId === null) return PLACEHOLDER;
const p = getStorePath(d.storeId);
return p && p !== '未分配' ? p : PLACEHOLDER;
}
return (d[f] !== undefined && d[f] !== null && d[f] !== '') ? String(d[f]) : PLACEHOLDER;
}).join(SEP));
return header + '\n' + lines.join('\n') + (lines.length > 0 ? '\n' : '');
}
function deserialize(text) {
const result = { dishes: [], skippedCount: 0, formatError: false };
if (!text || typeof text !== 'string') { result.formatError = true; return result; }
text.split(/\r?\n/).forEach(line => {
if (!line.trim() || line.startsWith('#')) return;
// 试探分隔符:新格式用 |,旧格式用 /(旧数据字段值不含 /)
const sep = (line.includes('|') && line.split('|').length >= FIELDS.length) ? '|' : '/';
const parts = line.split(sep);
if (parts.length < FIELDS.length) { result.skippedCount++; return; }
const b = {};
FIELDS.forEach((f, i) => { b[f] = parts[i]; });
if (!b.id || !b.name || b.id === PLACEHOLDER || b.name === PLACEHOLDER) { result.skippedCount++; return; }
const dish = {
id: Number(b.id),
name: b.name,
price: b.price !== PLACEHOLDER ? Number(b.price) : 0,
storeId: parseStoreRef(b.store),
rating: b.rating !== PLACEHOLDER ? Number(b.rating) : 0,
tags: b.tags && b.tags !== PLACEHOLDER ? b.tags.split(',').filter(Boolean) : [],
popular: b.popular !== PLACEHOLDER && b.popular !== undefined ? Number(b.popular) : 0,
note: b.note !== PLACEHOLDER && b.note !== undefined ? b.note : '',
localCategory: b.localCategory !== PLACEHOLDER && b.localCategory !== undefined ? b.localCategory : '',
emoji: b.emoji !== PLACEHOLDER && b.emoji !== undefined ? b.emoji : '🍽️',
img: b.img !== PLACEHOLDER && b.img !== undefined ? b.img : ''
};
if (isNaN(dish.id) || isNaN(dish.price)) { result.skippedCount++; return; }
result.dishes.push(dish);
});
return result;
}
return { serialize, deserialize, FIELDS };
})();
// ===== 3.3 SaveTxtSerializer 序列化器 =====
const SaveTxtSerializer = (function() {
const FIELDS = ['id', 'name', 'note', 'localCategory'];
function serialize(entries) {
const header = '# save.txt 字段顺序: ' + FIELDS.join('/') + ' | 空值用' + PLACEHOLDER + ' | 字段值勿含/';
const list = Array.isArray(entries) ? entries : [];
const lines = list.map(e => FIELDS.map(f => {
return (e[f] !== undefined && e[f] !== null && e[f] !== '') ? String(e[f]) : PLACEHOLDER;
}).join('/'));
return header + '\n' + lines.join('\n') + (lines.length > 0 ? '\n' : '');
}
function deserialize(text) {
const result = { entries: [], corrupt: false };
if (!text || typeof text !== 'string') return result;
try {
text.split(/\r?\n/).forEach(line => {
if (!line.trim() || line.startsWith('#')) return;
const parts = line.split('/');
if (parts.length < FIELDS.length) return;
const b = {};
FIELDS.forEach((f, i) => { b[f] = parts[i]; });
if (!b.id || b.id === PLACEHOLDER) return;
result.entries.push({
id: Number(b.id),
name: b.name !== PLACEHOLDER ? b.name : '',
note: b.note !== PLACEHOLDER && b.note !== undefined ? b.note : '',
localCategory: b.localCategory !== PLACEHOLDER && b.localCategory !== undefined ? b.localCategory : ''
});
});
} catch (e) {
result.corrupt = true;
}
return result;
}
return { serialize, deserialize };
})();
// ===== 3.4 UserData 用户数据层 =====
const UserData = (function() {
const STORAGE_KEY_USER = 'canteen_user_data';
function loadMap() {
try {
const raw = localStorage.getItem(STORAGE_KEY_USER);
if (raw) return new Map(JSON.parse(raw));
} catch (_) {}
return new Map();
}
function saveMap(map) {
try { localStorage.setItem(STORAGE_KEY_USER, JSON.stringify(Array.from(map.entries()))); } catch (_) {}
}
let store = loadMap();
function get(dishId) {
return store.get(dishId) || { note: '', localCategory: '' };
}
function update(dishId, fields) {
const cur = store.get(dishId) || { note: '', localCategory: '' };
const next = Object.assign({}, cur, fields);
store.set(dishId, next);
saveMap(store);
}
function getAll() {
const arr = [];
store.forEach((v, k) => arr.push(Object.assign({ id: k }, v)));
return arr;
}
function loadAll() {
store = loadMap();
}
async function exportSave() {
const entries = [];
store.forEach((v, k) => {
if (v.note || v.localCategory) {
const dish = DISHES_DB.find(d => d.id === k);
entries.push({ id: k, name: dish ? dish.name : '', note: v.note, localCategory: v.localCategory });
}
});
const content = SaveTxtSerializer.serialize(entries);
return await FileGateway.writeText('save.txt', content);
}
async function importSave() {
const text = await FileGateway.readText('save.txt');
if (text === null) return { ok: false, reason: 'no-file' };
const res = SaveTxtSerializer.deserialize(text);
if (res.corrupt) return { ok: false, reason: 'corrupt' };
const newMap = new Map();
res.entries.forEach(e => {
const exists = DISHES_DB.some(d => d.id === e.id);
if (!exists) { console.warn('save.txt 关联菜品不存在: id=' + e.id); return; }
newMap.set(e.id, { note: e.note, localCategory: e.localCategory });
});
store = newMap;
saveMap(store);
return { ok: true };
}
return { get, update, getAll, loadAll, exportSave, importSave };
})();
// ===== 3.5 DataSource 数据统一出口 =====
const DataSource = (function() {
function buildView(d) {
if (!d) return null;
const u = UserData.get(d.id);
return {
id: d.id,
name: d.name,
price: d.price,
storeId: d.storeId,
storeName: getStoreName(d.storeId),
storePath: getStorePath(d.storeId),
rating: d.rating,
tags: Array.isArray(d.tags) ? [...d.tags] : [],
popular: d.popular || 0,
emoji: d.emoji || '🍽️',
img: d.img || '',
note: u.note || '',
localCategory: u.localCategory || ''
};
}
function getDishById(id) {
const d = DISHES_DB.find(x => x.id === id);
return buildView(d);
}
function getAllDishes() {
return DISHES_DB.map(buildView).filter(Boolean);
}
function getCurrentPageDishes() {
return (currentDishes || []).map(d => {
const base = DISHES_DB.find(x => x.id === d.id) || d;
return buildView(base);
}).filter(Boolean);
}
return { getDishById, getAllDishes, getCurrentPageDishes };
})();
// 轻提示(复用模态框,不使用 alert)
function showToast(msg) {
openModal('提示', '<p style="text-align:center;color:#5a6b7a;">' + msg + '</p><div class="modal-actions"><button class="btn-secondary">知道了</button></div>', null);
}
// ===== 4. DOM 引用 =====
const $ = id => document.getElementById(id);
const searchInput = $('searchInput');
const recommendBtn = $('recommendBtn');
const resultList = $('resultList');
const resultStatus = $('resultStatus');
const showGood = $('showGood');
const showBad = $('showBad');
const resetViewBtn = $('resetView');
const filterTags = document.querySelectorAll('.filter-tag');
const filterToggle = $('filterToggle');
const filterPanel = $('filterPanel');
const tagModeGroup = $('tagModeGroup');
const groupBtnGroup = $('groupBtnGroup');
const addGroupBtn = $('addGroupBtn');
const modalOverlay = $('modalOverlay');
const modalTitle = $('modalTitle');
const modalBody = $('modalBody');
const modalClose = $('modalClose');
const customSelect = $('customSelect');
const selectSelected = $('selectSelected');
const selectOptionsWrapper = document.querySelector('.select-options-wrapper');
const selectOptions = $('selectOptions');
const tagCommentHint = $('tagCommentHint');
const exportListBtn = $('exportListBtn');
const importListBtn = $('importListBtn');
const exportSaveBtn = $('exportSaveBtn');
const importSaveBtn = $('importSaveBtn');
const diceBtn = $('diceBtn');
const storeFilterTrigger = $('storeFilterTrigger');
const storeTreePopup = $('storeTreePopup');
const storeTree = $('storeTree');
// ===== 5. 主题切换 =====
function initThemes() {
const saved = localStorage.getItem('canteen_theme') || 'default';
document.body.className = 'theme-' + saved;
document.querySelectorAll('.theme-option').forEach(el => {
el.classList.toggle('active', el.dataset.theme === saved);
});
}
document.addEventListener('click', function(e) {
const opt = e.target.closest('.theme-option');
if (!opt) return;
const theme = opt.dataset.theme;
document.body.className = 'theme-' + theme;
document.querySelectorAll('.theme-option').forEach(el => el.classList.remove('active'));
opt.classList.add('active');
localStorage.setItem('canteen_theme', theme);
});
// ===== 6. 高级筛选展开/收起 =====
if (filterToggle && filterPanel) {
filterToggle.addEventListener('click', function() {
const isOpen = filterPanel.classList.contains('open');
filterPanel.classList.toggle('open');
filterToggle.textContent = isOpen ? '⚙️ 高级筛选 ▾' : '⚙️ 高级筛选 ▴';
});
}
// ===== 7. 模态框(带关闭动画) =====
let modalCallback = null;
let modalKeyHandler = null;
function openModal(title, html, onConfirm) {
modalTitle.textContent = title;
modalBody.innerHTML = html;
modalOverlay.style.display = 'flex';
modalOverlay.classList.remove('closing');
modalCallback = onConfirm || null;
// 确认按钮(.modal-actions 内的 .btn-primary 或 .btn-danger)
const confirmBtn = modalBody.querySelector('.modal-actions .btn-primary, .modal-actions .btn-danger');
if (confirmBtn) {
confirmBtn.onclick = function(e) {
e.stopPropagation();
if (modalCallback) {
const result = modalCallback();
if (result === false) return;
}
closeModal();
};
}
// 取消按钮(.modal-actions 内的 .btn-secondary)
const cancelBtn = modalBody.querySelector('.modal-actions .btn-secondary');
if (cancelBtn) {
cancelBtn.onclick = function(e) {
e.stopPropagation();
closeModal();
};
}
modalClose.onclick = closeModal;
modalOverlay.onclick = function(e) { if (e.target === modalOverlay) closeModal(); };
// Esc 键关闭
if (modalKeyHandler) document.removeEventListener('keydown', modalKeyHandler);
modalKeyHandler = function(e) { if (e.key === 'Escape') closeModal(); };
document.addEventListener('keydown', modalKeyHandler);
}
function closeModal() {
if (modalOverlay.style.display === 'none') return;
if (modalKeyHandler) {
document.removeEventListener('keydown', modalKeyHandler);
modalKeyHandler = null;
}
modalOverlay.classList.add('closing');
setTimeout(() => {
modalOverlay.style.display = 'none';
modalOverlay.classList.remove('closing');
}, 350);
}
// ===== 8. 分组管理(核心修复) =====
function getGroups() {
return loadStorage().groups;
}
function addGroup(name) {
const data = loadStorage();
const newGroup = { id: 'g' + Date.now(), name: name.trim(), dishes: [] };
data.groups.push(newGroup);
saveStorage(data);
renderGroupButtons();
// 自动切换到新分组
setActiveGroup(newGroup.id);
return newGroup;
}
function deleteGroup(groupId) {
const data = loadStorage();
data.groups = data.groups.filter(g => g.id !== groupId);
saveStorage(data);
if (currentGroup === groupId) {
currentGroup = 'all';
}
renderGroupButtons();
applyFilters();
}
function toggleDishInGroup(dishId, groupId) {
const data = loadStorage();
const group = data.groups.find(g => g.id === groupId);
if (!group) return;
const idx = group.dishes.indexOf(dishId);
if (idx >= 0) group.dishes.splice(idx, 1);
else group.dishes.push(dishId);
saveStorage(data);
if (currentGroup === groupId) applyFilters();
else renderGroupButtons();
}
// ===== 9. 渲染分组按钮(事件委托,修复 all/favorites 切换) =====
function renderGroupButtons() {
const data = loadStorage();
const groups = data.groups;
// 清除已生成的自定义分组按钮(保留"全部"和"收藏"以及"添加"按钮)
const existingBtns = groupBtnGroup.querySelectorAll('.group-btn:not(.add-group-btn)');
existingBtns.forEach(btn => {
if (btn.dataset.group !== 'all' && btn.dataset.group !== 'favorites') {
btn.remove();
}
});
const addBtn = groupBtnGroup.querySelector('.add-group-btn');
groups.forEach(group => {
const btn = document.createElement('button');
btn.className = 'group-btn';
btn.dataset.group = group.id;
btn.innerHTML = `${group.name} <span class="delete-group-btn" data-group-id="${group.id}">✕</span>`;
groupBtnGroup.insertBefore(btn, addBtn);
});
// 高亮当前分组
setActiveGroup(currentGroup);
}
// 分组按钮事件委托(统一处理 all/favorites/自定义)
groupBtnGroup.addEventListener('click', function(e) {
const del = e.target.closest('.delete-group-btn');
if (del) {
e.stopPropagation();
const gid = del.dataset.groupId;
const group = getGroups().find(g => g.id === gid);
if (group) {
openModal('确认删除', `<p class="group-manager-title">确定要删除分组"${group.name}"吗?</p><div class="modal-actions"><button class="btn-secondary">取消</button><button class="btn-danger">删除</button></div>`, function() {
deleteGroup(gid);
});
}
return;
}
const btn = e.target.closest('.group-btn:not(.add-group-btn)');
if (btn) {
setActiveGroup(btn.dataset.group);
}
});
function setActiveGroup(groupId) {
currentGroup = groupId;
const btns = groupBtnGroup.querySelectorAll('.group-btn');
btns.forEach(btn => {
btn.classList.remove('active');
if (btn.dataset.group === groupId) {
btn.classList.add('active');
}
});
applyFilters();
}
// ===== 10. 添加分组按钮事件 =====
if (addGroupBtn) {
addGroupBtn.addEventListener('click', function() {
openModal('添加我的分组', `<input type="text" id="newGroupNameInput" placeholder="输入分组名称" /><div class="modal-actions"><button class="btn-secondary">取消</button><button class="btn-primary">创建</button></div>`, function() {
const nameInput = document.getElementById('newGroupNameInput');
if (nameInput && nameInput.value.trim()) {
addGroup(nameInput.value.trim());
} else {
return false;
}
});
});
}
// ===== 11. 标签四态系统 =====
const TAG_STATES = ['none', 'must', 'optional', 'exclude'];
const STATE_SYMBOLS = { none: '', must: '✓', optional: '+', exclude: '✕' };
const STATE_CLASSES = { none: '', must: 'mode-must', optional: 'mode-optional', exclude: 'mode-exclude' };
function getTagStates() {
const data = loadStorage();
if (!data.tagStates) {
data.tagStates = {};
const allTags = new Set();
DISHES_DB.forEach(d => d.tags.forEach(t => allTags.add(t)));
allTags.forEach(t => data.tagStates[t] = 'none');
saveStorage(data);
}
return data.tagStates;
}
function setTagState(tag, state) {
const data = loadStorage();
if (!data.tagStates) data.tagStates = {};
data.tagStates[tag] = state;
saveStorage(data);
renderTagModes();
applyFilters();
}
function initTagModes() {
const allTags = new Set();
DISHES_DB.forEach(d => d.tags.forEach(t => allTags.add(t)));
const states = getTagStates();
allTags.forEach(t => { if (!states[t]) states[t] = 'none'; });
saveStorage({ ...loadStorage(), tagStates: states });
renderTagModes();
}
function renderTagModes() {
const states = getTagStates();
const allTags = Object.keys(states);
tagModeGroup.innerHTML = '';
allTags.forEach(tag => {
const state = states[tag] || 'none';
const symbol = STATE_SYMBOLS[state];
const cls = STATE_CLASSES[state];
const item = document.createElement('div');
item.className = `tag-mode-item ${cls}`;
item.dataset.tag = tag;
item.innerHTML = `
<span class="mode-symbol">${symbol}</span>
<span class="tag-name">${tag}</span>
`;
// 点击循环切换
item.addEventListener('click', function() {
const current = states[tag] || 'none';
const idx = TAG_STATES.indexOf(current);
const nextIdx = (idx + 1) % TAG_STATES.length;
const nextState = TAG_STATES[nextIdx];
setTagState(tag, nextState);
});
tagModeGroup.appendChild(item);
});
}
// ===== 12. 标签全局提示 =====
if (tagCommentHint) {
tagCommentHint.addEventListener('click', function() {
const html = `
<div class="tag-filter-logic">
<p><strong>标签筛选逻辑</strong></p>
<ul>
<li><strong>✕ 错号(排除)</strong>:具有最高优先级。只要菜品包含任一"错号"标签,不会在结果中显示。</li>
<li><strong>✓ 对号(必须)</strong>:菜品必须同时包含所有"对号"标签,才进行显示。</li>
<li><strong>+ 加号(可选)</strong>:在"对号"的基础上,将包含任一"加号"标签的菜品并入结果显示(若没有"对号",则直接从全量菜品中取并集)。</li>
<li><strong>空(不限)</strong>:不做任何处理,完全忽略该标签。</li>
</ul>
</div>
<div class="modal-actions"><button class="btn-secondary">知道了</button></div>
`;
openModal('标签筛选逻辑', html, null);
});
}
// ===== 13. 自定义下拉(块级展开,撑开父容器) =====
if (selectSelected && selectOptionsWrapper) {
// 仅通过点击列表头切换开/关,不被其它操作打断
selectSelected.addEventListener('click', function(e) {
e.stopPropagation();
const isOpen = selectOptionsWrapper.classList.contains('open');
selectOptionsWrapper.classList.toggle('open');
selectSelected.textContent = selectSelected.textContent.replace(/[▴▾]/, '') + (isOpen ? ' ▾' : ' ▴');
});
// 选项点击(不关闭列表,保持打开直到点击列表头收起)
selectOptions.querySelectorAll('.select-option').forEach(opt => {
opt.addEventListener('click', function(e) {
e.stopPropagation();
const value = this.dataset.value;
const label = this.textContent;
const isOpen = selectOptionsWrapper.classList.contains('open');
selectSelected.textContent = label + (isOpen ? ' ▴' : ' ▾');
currentSort = value;
// 高亮选中
selectOptions.querySelectorAll('.select-option').forEach(o => o.classList.remove('selected'));
this.classList.add('selected');
applyFilters();
});
});
}
// ===== 14. 筛选与排序核心(含四态) =====
function getFilteredAndSorted() {
const data = loadStorage();
const tagStates = data.tagStates || {};
let result = [...DISHES_DB];
// 分组
if (currentGroup === 'favorites') {
result = result.filter(d => data.favorites.includes(d.id));
} else if (currentGroup !== 'all') {
const group = data.groups.find(g => g.id === currentGroup);
if (group) {
result = result.filter(d => group.dishes.includes(d.id));
} else {
currentGroup = 'all';
renderGroupButtons();
}
}
// 店铺筛选(勾选的叶子节点取并集,含各自子孙)
if (selectedStoreIds.size > 0) {
const allowed = new Set();
selectedStoreIds.forEach(id => getDescendantIds(id).forEach(x => allowed.add(x)));
result = result.filter(d => allowed.has(d.storeId));
}
// 标签四态
const excludeTags = Object.keys(tagStates).filter(t => tagStates[t] === 'exclude');
const mustTags = Object.keys(tagStates).filter(t => tagStates[t] === 'must');
const optionalTags = Object.keys(tagStates).filter(t => tagStates[t] === 'optional');
if (excludeTags.length > 0) {
result = result.filter(d => !d.tags.some(t => excludeTags.includes(t)));
}
if (mustTags.length > 0) {
result = result.filter(d => mustTags.every(t => d.tags.includes(t)));
}
if (optionalTags.length > 0) {
const optionalDishes = DISHES_DB.filter(d => d.tags.some(t => optionalTags.includes(t)));
const merged = new Map();
result.forEach(d => merged.set(d.id, d));
optionalDishes.forEach(d => merged.set(d.id, d));
result = Array.from(merged.values());
}
// 排序
switch (currentSort) {
case 'price': result.sort((a, b) => a.price - b.price); break;
case 'price-desc': result.sort((a, b) => b.price - a.price); break;
case 'rating': result.sort((a, b) => b.rating - a.rating); break;
case 'popular': result.sort((a, b) => (b.popular || 0) - (a.popular || 0)); break;
default: break;
}
return result;
}
function applyFilters() {
const filtered = getFilteredAndSorted();
currentDishes = filtered;
renderDishes(filtered);
}
// ===== 14.5 悬浮店铺树筛选器(多选勾选、保持开启、外侧关闭)=====
function getStoreChildren(nodeId) {
return STORES_DB.filter(s => s.parentId === nodeId).sort((a, b) => a.id - b.id);
}
function renderStoreTree() {
if (!storeTree) return;
storeTree.innerHTML = '';
const fragment = document.createDocumentFragment();
function buildNode(node, depth) {
const wrap = document.createElement('div');
wrap.className = 'store-tree-node';
const row = document.createElement('div');
row.className = 'store-node-row';
row.dataset.id = node.id;
row.style.paddingLeft = (10 + depth * 14) + 'px';
const children = getStoreChildren(node.id);
const hasChildren = children.length > 0;
const expanded = storeTreeExpanded.has(node.id);
// 勾选框(仅叶子节点显示,可展开项不勾选)
const check = document.createElement('span');
check.className = 'store-node-check';
if (!hasChildren) {
if (selectedStoreIds.has(node.id)) {
check.classList.add('checked');
check.textContent = '✓';
}
} else {
check.classList.add('placeholder');
}
const toggle = document.createElement('span');