Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
557 lines (465 loc) · 20.3 KB
/
Copy pathscript.js
File metadata and controls
557 lines (465 loc) · 20.3 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
/* =========================================
PHASE 3: VISION WORLD CLASS LOGIC
Features: Theme, Groups, Images, Shortcuts
========================================= */
// --- 1. DATABASE & CONFIG ---
const db = new Dexie('VisionWorldClassDB');
db.version(1).stores({
projects: '++id, name, data, thumbnail, modified, created'
});
let canvas;
let activeProjectId = null;
let currentMode = 'select';
// History State
let historyStack = [];
let historyIndex = -1;
let isHistoryLocked = false;
// Theme State
const savedTheme = localStorage.getItem('vision_theme') || 'theme-light';
document.body.className = savedTheme; // Apply immediately
// --- 2. CANVAS INITIALIZATION ---
function initCanvas() {
canvas = new fabric.Canvas('c', {
backgroundColor: 'transparent',
selection: true,
preserveObjectStacking: true,
fireRightClick: true,
stopContextMenu: true
});
// Premium Styling (Dynamic based on CSS var, but setup here)
fabric.Object.prototype.set({
transparentCorners: false,
cornerColor: '#ffffff',
cornerStrokeColor: '#007AFF',
borderColor: '#007AFF',
cornerSize: 12,
padding: 8,
cornerStyle: 'circle',
borderDashArray: [4, 4],
centeredScaling: true
});
// Fix Rotation Handle
fabric.Object.prototype.controls.mtr.y = 0.5;
fabric.Object.prototype.controls.mtr.offsetY = 30;
// Resize Logic
window.addEventListener('resize', () => {
canvas.setWidth(window.innerWidth);
canvas.setHeight(window.innerHeight);
});
canvas.setWidth(window.innerWidth);
canvas.setHeight(window.innerHeight);
// Set Date
const options = { weekday: 'long', month: 'long', day: 'numeric' };
document.getElementById('current-date-display').innerText = new Date().toLocaleDateString('en-US', options);
bindCanvasEvents();
}
function bindCanvasEvents() {
// 1. Auto Save & History
canvas.on('object:modified', () => { saveState(); autoSave(); });
canvas.on('object:added', () => { saveState(); autoSave(); });
canvas.on('object:removed', () => { saveState(); autoSave(); });
// 2. UI Updates (Bubble)
canvas.on('selection:created', updateBubble);
canvas.on('selection:updated', updateBubble);
canvas.on('object:moving', (e) => {
handleMagneticSnap(e.target); // Magnetic Alignment
updateBubble();
});
canvas.on('object:scaling', updateBubble);
canvas.on('selection:cleared', hideBubble);
}
// --- 3. MAGNETIC ALIGNMENT (Smart Guides Lite) ---
// Snaps objects to a 10px grid for perfect alignment
function handleMagneticSnap(obj) {
const gridSize = 10;
// Snap Left
if (Math.abs(obj.left % gridSize) < 5) {
obj.set('left', Math.round(obj.left / gridSize) * gridSize);
}
// Snap Top
if (Math.abs(obj.top % gridSize) < 5) {
obj.set('top', Math.round(obj.top / gridSize) * gridSize);
}
}
// --- 4. THEME ENGINE ---
const btnTheme = document.getElementById('btn-theme-toggle');
btnTheme.onclick = () => {
const body = document.body;
if (body.classList.contains('theme-light')) {
body.classList.replace('theme-light', 'theme-dark');
localStorage.setItem('vision_theme', 'theme-dark');
} else {
body.classList.replace('theme-dark', 'theme-light');
localStorage.setItem('vision_theme', 'theme-light');
}
};
// --- 5. IMAGE UPLOAD ENGINE ---
const imgInput = document.getElementById('img-upload-input');
const btnImg = document.getElementById('tool-image');
btnImg.onclick = () => imgInput.click();
imgInput.onchange = (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (f) => {
fabric.Image.fromURL(f.target.result, (img) => {
// Smart Scale: Don't let image be huge
const maxSize = 400;
if (img.width > maxSize) {
img.scaleToWidth(maxSize);
}
// Center it
const center = canvas.getCenter();
img.set({
left: center.left,
top: center.top,
originX: 'center',
originY: 'center'
});
canvas.add(img);
canvas.setActiveObject(img);
saveState();
autoSave();
// Reset input
imgInput.value = '';
});
};
reader.readAsDataURL(file);
};
// --- 6. GROUPING LOGIC ---
function toggleGroup() {
const activeObj = canvas.getActiveObject();
if (!activeObj) return;
if (activeObj.type === 'activeSelection') {
// Create Group
activeObj.toGroup();
canvas.requestRenderAll();
saveState();
autoSave();
showToast("Objects Grouped");
}
else if (activeObj.type === 'group') {
// Ungroup
activeObj.toActiveSelection();
canvas.requestRenderAll();
saveState();
autoSave();
showToast("Objects Ungrouped");
}
}
document.getElementById('btn-group-toggle').onclick = toggleGroup;
// --- 7. KEYBOARD SHORTCUTS ---
window.addEventListener('keydown', (e) => {
// Ignore if typing in an input field
if (e.target.tagName === 'INPUT') return;
const ctrl = e.ctrlKey || e.metaKey; // Windows or Mac
// Undo: Ctrl+Z
if (ctrl && e.key === 'z') { e.preventDefault(); undo(); }
// Redo: Ctrl+Y
if (ctrl && e.key === 'y') { e.preventDefault(); redo(); }
// Duplicate: Ctrl+D
if (ctrl && e.key === 'd') { e.preventDefault(); duplicateObject(); }
// Group: Ctrl+G
if (ctrl && e.key === 'g') { e.preventDefault(); toggleGroup(); }
// Delete: Delete Key
if (e.key === 'Delete') { e.preventDefault(); deleteObject(); }
// Select All: Ctrl+A
if (ctrl && e.key === 'a') {
e.preventDefault();
canvas.discardActiveObject();
const sel = new fabric.ActiveSelection(canvas.getObjects(), { canvas: canvas });
canvas.setActiveObject(sel);
canvas.requestRenderAll();
}
});
// --- 8. PROJECT MANAGER ---
const switcher = document.getElementById('project-switcher-view');
const grid = document.getElementById('project-grid-container');
const tabBar = document.getElementById('tabs-scroll-area');
async function openSwitcher() {
if (activeProjectId) await autoSave(true);
const projects = await db.projects.orderBy('modified').reverse().toArray();
renderGrid(projects);
switcher.classList.remove('hidden_overlay');
}
function renderGrid(projects) {
grid.innerHTML = '';
projects.forEach(proj => {
const card = document.createElement('div');
card.className = `project-card ${proj.id === activeProjectId ? 'active-card' : ''}`;
const date = new Date(proj.modified).toLocaleDateString();
const thumb = proj.thumbnail
? `<img src="${proj.thumbnail}" class="project-thumb">`
: `<div style="width:100%; height:100%; background:var(--bg-app);"></div>`;
card.innerHTML = `
${thumb}
<div class="project-label-overlay">
<div>${proj.name}</div>
<div style="font-size:11px; opacity:0.7;">Edited: ${date}</div>
</div>
`;
card.onclick = () => loadProject(proj.id);
card.oncontextmenu = (e) => { e.preventDefault(); openRenameModal(proj); };
grid.appendChild(card);
});
for(let i=0; i < (6 - projects.length); i++) {
const empty = document.createElement('div');
empty.className = 'project-card';
empty.style.opacity = '0.5';
empty.style.cursor = 'default';
empty.style.borderStyle = 'dashed';
empty.innerHTML = `<span style="color:var(--text-sub); font-size:12px;">Empty Slot</span>`;
grid.appendChild(empty);
}
}
async function renderTabs() {
const projects = await db.projects.orderBy('modified').reverse().limit(5).toArray();
tabBar.innerHTML = '';
projects.forEach(proj => {
const tab = document.createElement('div');
tab.className = `tab ${proj.id === activeProjectId ? 'active-tab' : ''}`;
tab.innerText = proj.name;
tab.onclick = () => loadProject(proj.id);
tabBar.appendChild(tab);
});
}
async function createNewProject() {
const id = await db.projects.add({
name: `Untitled Project`,
data: JSON.stringify({ objects: [] }),
thumbnail: null,
created: Date.now(),
modified: Date.now()
});
loadProject(id);
}
async function loadProject(id) {
activeProjectId = id;
const project = await db.projects.get(id);
if(project) {
isHistoryLocked = true;
canvas.loadFromJSON(project.data, () => {
canvas.renderAll();
switcher.classList.add('hidden_overlay');
historyStack = [JSON.stringify(canvas)];
historyIndex = 0;
isHistoryLocked = false;
renderTabs();
showToast(`Opened: ${project.name}`);
});
}
}
// --- 9. TOOLS & UTILS ---
function setActiveTool(mode, btnId) {
currentMode = mode;
document.querySelectorAll('.dock-btn').forEach(b => b.classList.remove('active'));
if(btnId) document.getElementById(btnId).classList.add('active');
canvas.isDrawingMode = (mode === 'draw');
canvas.selection = (mode === 'select');
if (mode === 'draw') {
canvas.freeDrawingBrush.width = 4;
// Smart Color: White in Dark Mode, Black in Light Mode logic could go here
// For now default black, user can change via bubble if we added brush color control
canvas.freeDrawingBrush.color = "#1d1d1f";
}
}
function addShape(type) {
const center = canvas.getCenter();
let obj;
// Air Defaults: Transparent Fill
const defaults = {
left: center.left, top: center.top,
fill: '', stroke: '#000000', strokeWidth: 2,
originX: 'center', originY: 'center'
};
if(type === 'rect') obj = new fabric.Rect({ ...defaults, width: 150, height: 100 });
if(type === 'circle') obj = new fabric.Circle({ ...defaults, radius: 60 });
if(type === 'text') obj = new fabric.IText('Type Here', { ...defaults, fill:'#000', strokeWidth:0, fontSize:32, fontFamily:'Inter' });
if(obj) {
canvas.add(obj); canvas.setActiveObject(obj);
setActiveTool('select', 'tool-select');
autoSave();
}
}
// Bind Tools
document.getElementById('tool-select').onclick = () => setActiveTool('select', 'tool-select');
document.getElementById('tool-rect').onclick = () => addShape('rect');
document.getElementById('tool-circle').onclick = () => addShape('circle');
document.getElementById('tool-text').onclick = () => addShape('text');
document.getElementById('tool-draw').onclick = () => setActiveTool('draw', 'tool-draw');
document.getElementById('trigger-project-switcher').onclick = openSwitcher;
document.getElementById('btn-create-new-project').onclick = createNewProject;
document.getElementById('btn-add-tab').onclick = createNewProject;
// --- 10. HISTORY & STATE ---
function saveState() {
if(isHistoryLocked) return;
if(historyIndex < historyStack.length - 1) historyStack = historyStack.slice(0, historyIndex + 1);
historyStack.push(JSON.stringify(canvas));
historyIndex++;
if(historyStack.length > 50) { historyStack.shift(); historyIndex--; }
}
function undo() {
if(historyIndex > 0) {
isHistoryLocked = true;
historyIndex--;
canvas.loadFromJSON(historyStack[historyIndex], () => {
canvas.renderAll(); isHistoryLocked = false; hideBubble();
});
}
}
function redo() {
if(historyIndex < historyStack.length - 1) {
isHistoryLocked = true;
historyIndex++;
canvas.loadFromJSON(historyStack[historyIndex], () => {
canvas.renderAll(); isHistoryLocked = false;
});
}
}
document.getElementById('action-undo').onclick = undo;
document.getElementById('action-redo').onclick = redo;
function deleteObject() {
const o = canvas.getActiveObjects();
if(o.length) { canvas.discardActiveObject(); o.forEach(x => canvas.remove(x)); hideBubble(); saveState(); autoSave(); }
}
function duplicateObject() {
const o = canvas.getActiveObject();
if(o) o.clone(c => { c.set({left:o.left+20, top:o.top+20}); canvas.add(c); canvas.setActiveObject(c); });
}
// --- 11. BUBBLE LOGIC ---
const bubble = document.getElementById('property-bubble');
const inputs = {
fill: document.getElementById('prop-fill-color'),
stroke: document.getElementById('prop-stroke-color'),
width: document.getElementById('prop-stroke-width'),
widthVal: document.getElementById('stroke-val-display'),
transBtn: document.getElementById('btn-toggle-transparent-fill'),
grpBtn: document.getElementById('btn-group-toggle')
};
function updateBubble() {
const obj = canvas.getActiveObject();
if(!obj) return;
bubble.classList.remove('hidden_bubble');
// Group Button State
if (obj.type === 'activeSelection') inputs.grpBtn.style.color = 'var(--blue)'; // Can Group
else if (obj.type === 'group') inputs.grpBtn.style.color = 'var(--purple)'; // Can Ungroup
else inputs.grpBtn.style.color = 'var(--text-sub)';
// Fill Sync
const fill = obj.get('fill');
if(!fill || fill === 'transparent') {
inputs.transBtn.classList.add('active'); inputs.fill.value = "#ffffff";
} else {
inputs.transBtn.classList.remove('active'); inputs.fill.value = fill;
}
inputs.stroke.value = obj.get('stroke') || '#000000';
const w = obj.get('strokeWidth') || 0;
inputs.width.value = w;
inputs.widthVal.innerText = w + 'px';
const objRect = obj.getBoundingRect();
const bubbleH = bubble.offsetHeight || 150;
const bubbleW = bubble.offsetWidth || 260;
bubble.style.top = `${objRect.top - bubbleH - 20}px`;
bubble.style.left = `${objRect.left + (objRect.width/2) - (bubbleW/2)}px`;
}
function hideBubble() { bubble.classList.add('hidden_bubble'); }
// Bubble Inputs
inputs.width.addEventListener('input', (e) => {
const obj = canvas.getActiveObject();
const val = parseInt(e.target.value);
inputs.widthVal.innerText = val + 'px';
if(obj) { obj.set('strokeWidth', val); canvas.requestRenderAll(); clearTimeout(saveTimer); saveTimer = setTimeout(() => {saveState(); autoSave();}, 500); }
});
inputs.fill.addEventListener('input', (e) => {
const obj = canvas.getActiveObject();
if(obj) { obj.set('fill', e.target.value); inputs.transBtn.classList.remove('active'); canvas.requestRenderAll(); autoSave(); }
});
inputs.transBtn.onclick = () => {
const obj = canvas.getActiveObject();
if(obj) {
const isTrans = inputs.transBtn.classList.contains('active');
obj.set('fill', isTrans ? inputs.fill.value : '');
inputs.transBtn.classList.toggle('active'); canvas.requestRenderAll(); autoSave();
}
};
inputs.stroke.addEventListener('input', (e) => {
const obj = canvas.getActiveObject();
if(obj) { obj.set('stroke', e.target.value); canvas.requestRenderAll(); autoSave(); }
});
// Layer Actions
document.getElementById('btn-layer-up').onclick = () => { const o = canvas.getActiveObject(); if(o) o.bringForward(); saveState(); };
document.getElementById('btn-layer-down').onclick = () => { const o = canvas.getActiveObject(); if(o) o.sendBackwards(); saveState(); };
document.getElementById('btn-clone').onclick = duplicateObject;
document.getElementById('btn-delete-obj').onclick = deleteObject;
// --- 12. UTILS (Export, Rename, Drag) ---
// Rename
const renameModal = document.getElementById('rename-modal');
const renameInput = document.getElementById('rename-input');
let renamingProj = null;
function openRenameModal(proj) { renamingProj = proj; renameInput.value = proj.name; renameModal.classList.remove('hidden_overlay'); renameInput.focus(); }
document.getElementById('confirm-rename').onclick = async () => {
if(renamingProj && renameInput.value) {
await db.projects.update(renamingProj.id, { name: renameInput.value });
renameModal.classList.add('hidden_overlay'); openSwitcher(); renderTabs(); showToast("Renamed");
}
};
document.getElementById('delete-project-btn').onclick = async () => {
if(renamingProj && confirm(`Delete "${renamingProj.name}"?`)) {
await db.projects.delete(renamingProj.id);
if(activeProjectId === renamingProj.id) { activeProjectId = null; canvas.clear(); }
renameModal.classList.add('hidden_overlay'); openSwitcher(); renderTabs(); showToast("Deleted");
}
};
document.getElementById('cancel-rename').onclick = () => renameModal.classList.add('hidden_overlay');
// Import
const fileInput = document.getElementById('file-input');
document.getElementById('btn-open-project').onclick = () => fileInput.click();
fileInput.onchange = (e) => {
const file = e.target.files[0]; if(!file) return;
const reader = new FileReader();
reader.onload = async (ev) => {
try {
const json = ev.target.result; JSON.parse(json);
const id = await db.projects.add({ name: file.name.replace('.json',''), data: json, created: Date.now(), modified: Date.now() });
loadProject(id);
} catch(e) { alert('Invalid File'); }
};
reader.readAsText(file);
};
// Export
const exportModal = document.getElementById('export-modal');
document.getElementById('trigger-export-modal').onclick = () => exportModal.classList.remove('hidden_overlay');
document.getElementById('close-export-modal').onclick = () => exportModal.classList.add('hidden_overlay');
function download(url, name) { const a = document.createElement('a'); a.href = url; a.download = name; a.click(); exportModal.classList.add('hidden_overlay'); }
document.getElementById('save-png').onclick = () => download(canvas.toDataURL({format:'png', multiplier:2}), 'Canvas.png');
document.getElementById('save-svg').onclick = () => { const b = new Blob([canvas.toSVG()], {type:"image/svg+xml"}); download(URL.createObjectURL(b), 'Vector.svg'); };
document.getElementById('save-json').onclick = () => { const b = new Blob([JSON.stringify(canvas.toJSON())], {type:"application/json"}); download(URL.createObjectURL(b), 'Project.json'); };
// Shortcuts Modal
const shortcutsModal = document.getElementById('shortcuts-modal');
document.getElementById('btn-shortcuts').onclick = () => shortcutsModal.classList.remove('hidden_overlay');
document.getElementById('close-shortcuts-modal').onclick = () => shortcutsModal.classList.add('hidden_overlay');
// Dock Drag
const dock = document.getElementById('main-dock-container');
const handle = document.querySelector('.dock-drag-handle');
let isDragging = false, startX, startY;
handle.onmousedown = (e) => { isDragging=true; startX=e.clientX-dock.offsetLeft; startY=e.clientY-dock.offsetTop; dock.style.bottom='auto'; dock.style.transform='none'; };
window.onmousemove = (e) => { if(isDragging) { dock.style.left=(e.clientX-startX)+'px'; dock.style.top=(e.clientY-startY)+'px'; } };
window.onmouseup = () => isDragging = false;
// Auto Save
let saveTimer;
async function autoSave(force=false) {
if(!activeProjectId) return;
if(force) { await performSave(); return; }
clearTimeout(saveTimer); saveTimer = setTimeout(performSave, 1000);
}
async function performSave() {
if(!activeProjectId) return;
const thumb = canvas.toDataURL({format:'png', multiplier:0.2});
const json = JSON.stringify(canvas.toJSON());
await db.projects.update(activeProjectId, {data:json, thumbnail:thumb, modified:Date.now()});
renderTabs();
}
function showToast(msg) { const t=document.getElementById('status-toast'); t.innerText=msg; t.classList.add('show'); setTimeout(()=>t.classList.remove('show'), 2000); }
document.getElementById('action-clear').onclick = () => { if(confirm('Clear?')) { canvas.clear(); saveState(); autoSave(); } };
// Start
initCanvas();
openSwitcher();