-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
794 lines (661 loc) · 27.4 KB
/
app.js
File metadata and controls
794 lines (661 loc) · 27.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
// 应用数据
const apps = [
{ id: 1, icon: '💬', name: '消息', location: 'desktop', position: 0, url: 'message.html' },
{ id: 2, icon: '💬', name: '论坛', location: 'desktop', position: 1, url: 'forum.html' },
{ id: 3, icon: '🌐', name: '世界微博', location: 'desktop', position: 2, url: 'couple-twitter.html' },
{ id: 4, icon: '📖', name: '共读', location: 'desktop', position: 3, url: 'reading.html' },
{ id: 5, icon: '❤️', name: '健康', location: 'desktop', position: 4, url: 'health.html' },
{ id: 6, icon: '📝', name: '备忘录', location: 'desktop', position: 5, url: 'memo.html' },
{ id: 7, icon: '💳', name: '支付宝', location: 'dock', position: 0, url: 'alipay.html' },
{ id: 8, icon: '🛍️', name: '商店', location: 'dock', position: 1, url: 'shop.html' },
{ id: 9, icon: '🎵', name: '网易云音乐', location: 'dock', position: 2, url: 'music.html' },
{ id: 10, icon: '📦', name: '物流', location: 'dock', position: 3, url: 'logistics.html' },
{ id: 11, icon: '⚙️', name: '设置', location: 'dock', position: 4, url: 'settings.html' },
{ id: 12, icon: '🎨', name: '外观', location: 'dock', position: 5, url: 'appearance.html' },
{ id: 13, icon: '🐾', name: '魔法生物', location: 'desktop', position: 6, url: 'pet.html' }
];
let draggedApp = null;
let draggedElement = null;
let longPressTimer = null;
let isDragging = false;
// 防止双指缩放和长按上下文菜单
document.addEventListener('gesturestart', (e) => e.preventDefault());
document.addEventListener('gesturechange', (e) => e.preventDefault());
document.addEventListener('gestureend', (e) => e.preventDefault());
document.addEventListener('contextmenu', (e) => e.preventDefault());
// 防止双指缩放(Android)
let lastTouchEnd = 0;
document.addEventListener('touchend', (e) => {
const now = Date.now();
if (now - lastTouchEnd <= 300) {
e.preventDefault();
}
lastTouchEnd = now;
}, { passive: false });
// 阻止多指触摸缩放
document.addEventListener('touchstart', (e) => {
if (e.touches.length > 1) {
e.preventDefault();
}
}, { passive: false });
// 辅助函数:从localStorage获取并解析JSON
function getStorageJSON(key, defaultValue = null) {
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : defaultValue;
} catch (e) {
console.error(`解析 ${key} 失败:`, e);
return defaultValue;
}
}
// 辅助函数:保存JSON到localStorage
function setStorageJSON(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
return true;
} catch (e) {
console.error(`保存 ${key} 失败:`, e);
return false;
}
}
// 初始化
async function init() {
loadLayout();
applyWallpaper();
await applyCustomFont();
renderApps();
updateTime();
setInterval(updateTime, 60000);
}
// 从其他页面返回时重置视口缩放
window.addEventListener('pageshow', () => {
const viewport = document.querySelector('meta[name="viewport"]');
if (viewport) {
viewport.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover';
}
});
// 应用壁纸
function applyWallpaper() {
const wallpaper = localStorage.getItem('wallpaper');
if (wallpaper) {
const screen = document.querySelector('.ipad-screen');
const mode = localStorage.getItem('wallpaperMode') || 'cover';
screen.style.backgroundImage = wallpaper;
if (mode === 'repeat') {
screen.style.backgroundSize = 'auto';
screen.style.backgroundRepeat = 'repeat';
} else {
screen.style.backgroundSize = mode;
screen.style.backgroundRepeat = 'no-repeat';
}
screen.style.backgroundPosition = 'center';
}
}
// 应用自定义字体
async function applyCustomFont() {
// 初始化 IndexedDB
const fontDB = await initFontDB();
// 加载字体方案元数据
const fontSchemes = getStorageJSON('fontSchemes', {});
const activeFontScheme = localStorage.getItem('activeFontScheme'); // 这是字符串,不是JSON
if (activeFontScheme && fontSchemes[activeFontScheme]) {
const scheme = fontSchemes[activeFontScheme];
// 从 IndexedDB 加载完整数据
let fontData;
if (scheme.type === 'file') {
try {
const dbData = await loadFontFromDB(fontDB, activeFontScheme);
if (dbData && dbData.data) {
fontData = dbData.data;
}
} catch (error) {
console.error('从 IndexedDB 加载字体失败:', error);
}
} else if (scheme.type === 'url') {
// URL 类型需要重新构建 fontFace
let format = scheme.format || 'woff2';
fontData = {
fontFace: `@font-face {
font-family: 'CustomFont_${activeFontScheme}';
src: url('${fontSchemes[activeFontScheme].source}') format('${format}');
font-weight: normal;
font-style: normal;
font-display: swap;
}`
};
}
if (fontData) {
let style = document.getElementById('customFontStyle');
if (!style) {
style = document.createElement('style');
style.id = 'customFontStyle';
document.head.appendChild(style);
}
style.textContent = fontData.fontFace;
// 应用字体到所有元素
applyFontToAllElements(scheme.fontFamily);
}
} else {
const systemFont = localStorage.getItem('systemFont');
if (systemFont) {
applyFontToAllElements(systemFont);
}
}
}
// 初始化 IndexedDB
function initFontDB() {
return new Promise((resolve, reject) => {
const request = indexedDB.open('FontStorage', 1);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
request.onupgradeneeded = (event) => {
const db = event.target.result;
if (!db.objectStoreNames.contains('fonts')) {
db.createObjectStore('fonts', { keyPath: 'name' });
}
};
});
}
// 从 IndexedDB 加载字体
function loadFontFromDB(db, schemeName) {
return new Promise((resolve, reject) => {
const transaction = db.transaction(['fonts'], 'readonly');
const store = transaction.objectStore('fonts');
const request = store.get(schemeName);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
// 应用字体到所有元素
function applyFontToAllElements(fontFamily) {
document.body.style.fontFamily = fontFamily;
// 应用到所有表单元素
const elements = document.querySelectorAll('input, textarea, select, button, option');
elements.forEach(el => {
el.style.fontFamily = fontFamily;
});
}
// 加载布局
function loadLayout() {
const savedApps = getStorageJSON('ipadLayout', []);
savedApps.forEach(savedApp => {
const app = apps.find(a => a.id === savedApp.id);
if (app) {
app.location = savedApp.location;
app.position = savedApp.position;
}
});
// 修复可能的重叠问题
fixOverlaps();
}
// 修复重叠问题
function fixOverlaps() {
const widgets = getStorageJSON('widgets', []);
const occupiedSlots = new Set();
let needsSave = false;
// 标记小组件占用的槽位
widgets.forEach(widget => {
occupiedSlots.add(`${widget.location}-${widget.position}`);
occupiedSlots.add(`${widget.location}-${widget.position + 1}`);
});
// 检查应用是否与小组件重叠
apps.forEach(app => {
const slotKey = `${app.location}-${app.position}`;
if (occupiedSlots.has(slotKey)) {
// 找到新的空位
const newPos = findEmptySlot(app.location, occupiedSlots, apps);
if (newPos !== null) {
app.position = newPos;
occupiedSlots.add(`${app.location}-${newPos}`);
needsSave = true;
}
} else {
occupiedSlots.add(slotKey);
}
});
if (needsSave) {
saveLayout();
}
}
// 查找空槽位
function findEmptySlot(location, occupiedSlots, apps) {
const maxSlots = location === 'desktop' ? 24 : 12;
for (let i = 0; i < maxSlots; i++) {
const slotKey = `${location}-${i}`;
if (!occupiedSlots.has(slotKey)) {
return i;
}
}
return null;
}
// 保存布局
function saveLayout() {
setStorageJSON('ipadLayout', apps);
}
// 渲染应用
function renderApps() {
const desktopGrid = document.getElementById('desktopGrid');
const dock = document.getElementById('dock');
const customIcons = getStorageJSON('customIcons', {});
desktopGrid.innerHTML = '';
dock.innerHTML = '';
// 创建桌面槽位 (4行 x 6列 = 24)
for (let i = 0; i < 24; i++) {
const slot = createSlot('desktop', i);
desktopGrid.appendChild(slot);
}
// 创建 Dock 槽位 (12个)
for (let i = 0; i < 12; i++) {
const slot = createSlot('dock', i);
dock.appendChild(slot);
}
// 标记被占用的槽位
const occupiedSlots = new Set();
// 先放置小组件(因为它们占2格)
const widgets = getStorageJSON('widgets', []);
widgets.forEach(widget => {
const container = widget.location === 'desktop' ? desktopGrid : dock;
const maxSlots = widget.location === 'desktop' ? 24 : 12;
const slot = container.children[widget.position];
const nextSlot = widget.position + 1 < maxSlots ? container.children[widget.position + 1] : null;
if (slot && nextSlot) {
slot.classList.remove('empty');
slot.classList.add('widget-slot');
// 标记占用的槽位
occupiedSlots.add(`${widget.location}-${widget.position}`);
occupiedSlots.add(`${widget.location}-${widget.position + 1}`);
// 隐藏下一个槽位(因为小组件占2格)
nextSlot.style.display = 'none';
nextSlot.classList.add('occupied-by-widget');
let widgetElement;
if (widget.type === 'clock') {
widgetElement = createClockWidget();
} else if (widget.type === 'todo') {
widgetElement = createTodoWidget();
} else if (widget.type === 'calendar') {
widgetElement = createCalendarWidget();
}
if (widgetElement) {
// 应用自定义样式
applyWidgetCustomStyle(widgetElement, widget.type);
slot.innerHTML = '';
slot.appendChild(widgetElement);
attachWidgetDragEvents(slot, widget);
}
}
});
// 再放置应用图标
apps.forEach(app => {
const slotKey = `${app.location}-${app.position}`;
// 检查槽位是否被占用
if (occupiedSlots.has(slotKey)) {
return; // 跳过被占用的槽位
}
const container = app.location === 'desktop' ? desktopGrid : dock;
const slot = container.children[app.position];
if (slot && !slot.classList.contains('occupied-by-widget')) {
slot.classList.remove('empty');
occupiedSlots.add(slotKey);
const displayIcon = customIcons[app.id] || app.icon;
slot.innerHTML = `
<div class="app-icon" data-id="${app.id}" onclick="openApp(${app.id})">
${displayIcon}
</div>
<div class="app-name">${app.name}</div>
`;
attachDragEvents(slot, app);
}
});
// Dock 自适应:拖拽时才显示空槽位,平时全部隐藏
}
// 应用小组件自定义样式
function applyWidgetCustomStyle(widgetElement, type) {
const customStyles = getStorageJSON('widgetCustomStyles', {});
const activeScheme = localStorage.getItem(`widget_${type}_activeScheme`) || 'default'; // 这是字符串,不是JSON
// 查找CSS:优先用户自定义 > 内置预设
let css = null;
if (customStyles[type] && customStyles[type][activeScheme]) {
css = customStyles[type][activeScheme];
} else if (typeof builtinWidgetSchemes !== 'undefined' && builtinWidgetSchemes[type] && builtinWidgetSchemes[type][activeScheme]) {
css = builtinWidgetSchemes[type][activeScheme];
}
if (css) {
const styleId = `widget-custom-${type}`;
let styleElement = document.getElementById(styleId);
if (!styleElement) {
styleElement = document.createElement('style');
styleElement.id = styleId;
document.head.appendChild(styleElement);
}
styleElement.textContent = css;
}
}
// 打开应用
function openApp(appId) {
if (isDragging) return;
const app = apps.find(a => a.id === appId);
if (app && app.url) {
window.location.href = app.url;
}
}
// 创建槽位
function createSlot(location, position) {
const slot = document.createElement('div');
slot.className = 'icon-slot empty';
slot.dataset.location = location;
slot.dataset.position = position;
return slot;
}
// 附加拖拽事件
function attachDragEvents(slot, app) {
const icon = slot.querySelector('.app-icon');
// 鼠标事件
icon.addEventListener('mousedown', (e) => startDrag(e, app, slot));
// 触摸事件 - 记录触摸起始信息用于判断是点击还是拖拽
let touchStartTime = 0;
let touchStartX = 0;
let touchStartY = 0;
icon.addEventListener('touchstart', (e) => {
e.preventDefault(); // 阻止长按弹出系统菜单
touchStartTime = Date.now();
touchStartX = e.touches[0].clientX;
touchStartY = e.touches[0].clientY;
startDrag(e, app, slot);
}, { passive: false });
// 在 touchend 直接处理点击(因为 preventDefault 阻止了 click 合成)
icon.addEventListener('touchend', (e) => {
if (isDragging) return;
const dt = Date.now() - touchStartTime;
const touch = e.changedTouches[0];
const dx = Math.abs(touch.clientX - touchStartX);
const dy = Math.abs(touch.clientY - touchStartY);
// 短按 + 没有大幅移动 = 点击
if (dt < 300 && dx < 15 && dy < 15) {
openApp(app.id);
}
});
}
// 开始拖拽
function startDrag(e, app, slot) {
// 不要立即 preventDefault,否则会阻止触摸设备上的 click 事件
const startX = e.type === 'touchstart' ? e.touches[0].clientX : e.clientX;
const startY = e.type === 'touchstart' ? e.touches[0].clientY : e.clientY;
longPressTimer = setTimeout(() => {
isDragging = true;
draggedApp = app;
// 创建拖拽元素
draggedElement = document.createElement('div');
draggedElement.className = 'app-icon dragging-icon';
draggedElement.innerHTML = app.icon;
draggedElement.style.width = '80px';
draggedElement.style.height = '80px';
document.body.appendChild(draggedElement);
slot.classList.add('dragging');
// 拖拽时显示 dock 所有空槽位作为放置目标
document.querySelectorAll('.dock .icon-slot.empty').forEach(s => {
s.classList.add('dock-drop-target');
});
// 移动事件
document.addEventListener('mousemove', onDragMove);
document.addEventListener('touchmove', onDragMove, { passive: false });
// 结束事件
document.addEventListener('mouseup', onDragEnd);
document.addEventListener('touchend', onDragEnd);
// 初始位置
updateDragPosition(startX, startY);
}, 300);
// 监听移动,如果手指移动超过阈值则取消长按(防止滚动时误触发)
const cancelOnMove = (moveEvent) => {
const mx = moveEvent.type.includes('touch') ? moveEvent.touches[0].clientX : moveEvent.clientX;
const my = moveEvent.type.includes('touch') ? moveEvent.touches[0].clientY : moveEvent.clientY;
if (Math.abs(mx - startX) > 10 || Math.abs(my - startY) > 10) {
clearTimeout(longPressTimer);
cleanup();
}
};
const cleanup = () => {
document.removeEventListener('mouseup', cancelLongPress);
document.removeEventListener('touchend', cancelLongPress);
document.removeEventListener('mousemove', cancelOnMove);
document.removeEventListener('touchmove', cancelOnMove);
};
// 如果提前释放,取消长按
const cancelLongPress = () => {
clearTimeout(longPressTimer);
cleanup();
};
document.addEventListener('mouseup', cancelLongPress);
document.addEventListener('touchend', cancelLongPress);
document.addEventListener('mousemove', cancelOnMove);
document.addEventListener('touchmove', cancelOnMove, { passive: true });
}
// 拖拽移动
function onDragMove(e) {
if (!isDragging) return;
e.preventDefault();
const clientX = e.type === 'touchmove' ? e.touches[0].clientX : e.clientX;
const clientY = e.type === 'touchmove' ? e.touches[0].clientY : e.clientY;
updateDragPosition(clientX, clientY);
// 检测悬停的槽位
const target = document.elementFromPoint(clientX, clientY);
const slot = target?.closest('.icon-slot');
document.querySelectorAll('.icon-slot').forEach(s => {
s.classList.remove('drag-over', 'drag-invalid');
});
if (slot) {
const location = slot.dataset.location;
const position = parseInt(slot.dataset.position);
// 检查是否是有效的放置位置
const widgets = getStorageJSON('widgets', []);
const isOccupiedByWidget = widgets.some(w =>
w.location === location &&
(w.position === position || w.position === position - 1)
);
if (isOccupiedByWidget || slot.classList.contains('occupied-by-widget')) {
slot.classList.add('drag-invalid');
} else {
slot.classList.add('drag-over');
}
}
}
// 更新拖拽位置
function updateDragPosition(x, y) {
if (draggedElement) {
draggedElement.style.left = (x - 40) + 'px';
draggedElement.style.top = (y - 40) + 'px';
}
}
// 结束拖拽
function onDragEnd(e) {
if (!isDragging) return;
clearTimeout(longPressTimer);
const clientX = e.type === 'touchend' ? e.changedTouches[0].clientX : e.clientX;
const clientY = e.type === 'touchend' ? e.changedTouches[0].clientY : e.clientY;
const target = document.elementFromPoint(clientX, clientY);
const targetSlot = target?.closest('.icon-slot');
if (targetSlot && draggedApp && !targetSlot.classList.contains('occupied-by-widget')) {
const newLocation = targetSlot.dataset.location;
const newPosition = parseInt(targetSlot.dataset.position);
// 检查目标位置是否被小组件占用
const widgets = getStorageJSON('widgets', []);
const isOccupiedByWidget = widgets.some(w =>
w.location === newLocation &&
(w.position === newPosition || w.position === newPosition - 1)
);
if (isOccupiedByWidget) {
// 不允许放置到小组件占用的位置
alert('该位置被小组件占用');
} else {
// 检查目标位置是否有应用
const targetApp = apps.find(a =>
a.location === newLocation &&
a.position === newPosition &&
a.id !== draggedApp.id
);
if (targetApp) {
// 交换位置
targetApp.location = draggedApp.location;
targetApp.position = draggedApp.position;
}
// 更新拖拽应用位置
draggedApp.location = newLocation;
draggedApp.position = newPosition;
saveLayout();
}
}
// 清理
if (draggedElement) {
draggedElement.remove();
draggedElement = null;
}
document.querySelectorAll('.icon-slot').forEach(s => {
s.classList.remove('dragging', 'drag-over');
});
document.removeEventListener('mousemove', onDragMove);
document.removeEventListener('touchmove', onDragMove);
document.removeEventListener('mouseup', onDragEnd);
document.removeEventListener('touchend', onDragEnd);
isDragging = false;
draggedApp = null;
renderApps();
}
// 更新时间
function updateTime() {
const now = new Date();
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
document.getElementById('time').textContent = `${hours}:${minutes}`;
}
// 启动
init();
// 附加小组件拖拽事件
function attachWidgetDragEvents(slot, widget) {
const widgetElement = slot.querySelector('.widget');
if (!widgetElement) return;
widgetElement.addEventListener('mousedown', (e) => {
if (e.target.classList.contains('widget-close')) return;
startWidgetDrag(e, widget, slot);
});
widgetElement.addEventListener('touchstart', (e) => {
if (e.target.classList.contains('widget-close')) return;
e.preventDefault(); // 阻止长按弹出系统菜单
startWidgetDrag(e, widget, slot);
}, { passive: false });
}
// 开始拖拽小组件
function startWidgetDrag(e, widget, slot) {
// 不要立即 preventDefault,否则会阻止触摸设备上的 click 事件
const startX = e.type === 'touchstart' ? e.touches[0].clientX : e.clientX;
const startY = e.type === 'touchstart' ? e.touches[0].clientY : e.clientY;
longPressTimer = setTimeout(() => {
isDragging = true;
draggedApp = widget;
// 创建拖拽元素
draggedElement = document.createElement('div');
draggedElement.className = 'widget dragging-icon';
draggedElement.style.width = '80px';
draggedElement.style.height = '80px';
draggedElement.innerHTML = widget.type === 'clock' ? '🕐' : widget.type === 'todo' ? '✅' : '📅';
document.body.appendChild(draggedElement);
slot.classList.add('dragging');
// 拖拽时显示 dock 所有空槽位作为放置目标
document.querySelectorAll('.dock .icon-slot.empty').forEach(s => {
s.classList.add('dock-drop-target');
});
document.addEventListener('mousemove', onDragMove);
document.addEventListener('touchmove', onDragMove, { passive: false });
document.addEventListener('mouseup', onWidgetDragEnd);
document.addEventListener('touchend', onWidgetDragEnd);
updateDragPosition(startX, startY);
}, 300);
const cancelOnMove = (moveEvent) => {
const mx = moveEvent.type.includes('touch') ? moveEvent.touches[0].clientX : moveEvent.clientX;
const my = moveEvent.type.includes('touch') ? moveEvent.touches[0].clientY : moveEvent.clientY;
if (Math.abs(mx - startX) > 10 || Math.abs(my - startY) > 10) {
clearTimeout(longPressTimer);
cleanup();
}
};
const cleanup = () => {
document.removeEventListener('mouseup', cancelLongPress);
document.removeEventListener('touchend', cancelLongPress);
document.removeEventListener('mousemove', cancelOnMove);
document.removeEventListener('touchmove', cancelOnMove);
};
const cancelLongPress = () => {
clearTimeout(longPressTimer);
cleanup();
};
document.addEventListener('mouseup', cancelLongPress);
document.addEventListener('touchend', cancelLongPress);
document.addEventListener('mousemove', cancelOnMove);
document.addEventListener('touchmove', cancelOnMove, { passive: true });
}
// 结束小组件拖拽
function onWidgetDragEnd(e) {
if (!isDragging) return;
clearTimeout(longPressTimer);
const clientX = e.type === 'touchend' ? e.changedTouches[0].clientX : e.clientX;
const clientY = e.type === 'touchend' ? e.changedTouches[0].clientY : e.clientY;
const target = document.elementFromPoint(clientX, clientY);
const targetSlot = target?.closest('.icon-slot');
if (targetSlot && draggedApp && !targetSlot.classList.contains('occupied-by-widget')) {
const newLocation = targetSlot.dataset.location;
const newPosition = parseInt(targetSlot.dataset.position);
const maxSlots = newLocation === 'desktop' ? 24 : 12;
// 检查小组件是否会超出边界(需要2个槽位)
if (newPosition + 1 >= maxSlots) {
alert('小组件需要2个槽位,无法放置在最后一个位置');
} else {
// 更新小组件位置
const widgets = getStorageJSON('widgets', []);
const widgetIndex = widgets.findIndex(w =>
w.location === draggedApp.location &&
w.position === draggedApp.position
);
if (widgetIndex !== -1) {
// 检查目标位置和下一个位置是否被占用
const targetOccupied = widgets.some((w, idx) =>
idx !== widgetIndex &&
w.location === newLocation &&
(w.position === newPosition || w.position === newPosition + 1 ||
w.position === newPosition - 1)
);
const targetHasApp = apps.find(a =>
a.location === newLocation &&
(a.position === newPosition || a.position === newPosition + 1)
);
if (targetOccupied) {
alert('目标位置被其他小组件占用');
} else if (targetHasApp) {
// 将应用移动到小组件原来的位置
targetHasApp.location = draggedApp.location;
targetHasApp.position = draggedApp.position;
saveLayout();
widgets[widgetIndex].location = newLocation;
widgets[widgetIndex].position = newPosition;
setStorageJSON('widgets', widgets);
} else {
// 目标位置为空,直接移动
widgets[widgetIndex].location = newLocation;
widgets[widgetIndex].position = newPosition;
setStorageJSON('widgets', widgets);
}
}
}
}
if (draggedElement) {
draggedElement.remove();
draggedElement = null;
}
document.querySelectorAll('.icon-slot').forEach(s => {
s.classList.remove('dragging', 'drag-over');
});
document.removeEventListener('mousemove', onDragMove);
document.removeEventListener('touchmove', onDragMove);
document.removeEventListener('mouseup', onWidgetDragEnd);
document.removeEventListener('touchend', onWidgetDragEnd);
isDragging = false;
draggedApp = null;
renderApps();
}