Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
647 lines (529 loc) · 21.5 KB
/
Copy pathscript.js
File metadata and controls
647 lines (529 loc) · 21.5 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
/**
* CSS Grid Prototyper - Main Script
*/
const STATE = {
config: {
cols: 4,
rows: 4,
colTemplate: '1fr 1fr 1fr 1fr',
rowTemplate: '1fr 1fr 1fr 1fr',
gap: 16, // px
showLines: true
},
boxes: [], // Array of box objects { id, colStart, colEnd, rowStart, rowEnd }
nextId: 1,
dragState: null // { type: 'new' | 'resize', boxId: ..., startX, startY, ... }
};
// DOM Elements
const elements = {
canvas: document.getElementById('grid-canvas'),
linesLayer: document.getElementById('grid-lines-layer'),
itemsLayer: document.getElementById('grid-items-layer'),
previewLayer: document.getElementById('grid-preview-layer'),
inputs: {
cols: document.getElementById('col-count'),
rows: document.getElementById('row-count'),
colTemplate: document.getElementById('col-template'),
rowTemplate: document.getElementById('row-template'),
gap: document.getElementById('gap-size'),
showLines: document.getElementById('show-lines')
},
codeOutput: document.getElementById('code-output'),
copyBtn: document.getElementById('copy-btn'),
newBoxSource: document.getElementById('new-box-source')
};
// Initialization
function init() {
setupEventListeners();
renderGrid();
updateCodeOutput();
}
function updateTemplateFromCount(type, count) {
// Generate simple 1fr repeat
const template = Array(count).fill('1fr').join(' ');
if (type === 'cols') {
STATE.config.colTemplate = template;
elements.inputs.colTemplate.value = template;
} else {
STATE.config.rowTemplate = template;
elements.inputs.rowTemplate.value = template;
}
}
function updateCountFromTemplate(type, template) {
// Just update the config string and let renderGrid handle the counting via computed styles
if (type === 'cols') {
STATE.config.colTemplate = template;
} else {
STATE.config.rowTemplate = template;
}
}
// helper functions
function updateConfig(key, value) {
STATE.config[key] = value;
renderGrid();
updateCodeOutput();
}
// function renderGrid moved to bottom
function renderPreview(box, isColliding) {
elements.previewLayer.innerHTML = '';
const el = document.createElement('div');
el.className = 'preview-box';
el.style.gridColumnStart = box.colStart;
el.style.gridColumnEnd = box.colEnd;
el.style.gridRowStart = box.rowStart;
el.style.gridRowEnd = box.rowEnd;
if (isColliding) {
el.style.backgroundColor = 'rgba(239, 68, 68, 0.2)'; // Red
el.style.borderColor = '#ef4444';
el.style.cursor = 'not-allowed';
}
elements.previewLayer.appendChild(el);
}
function setupEventListeners() {
// Config inputs
elements.inputs.cols.addEventListener('input', (e) => {
let val = parseInt(e.target.value);
if (val < 1) val = 1; if (val > 12) val = 12;
STATE.config.cols = val;
updateTemplateFromCount('cols', val);
renderGrid();
updateCodeOutput();
});
elements.inputs.rows.addEventListener('input', (e) => {
let val = parseInt(e.target.value);
if (val < 1) val = 1; if (val > 12) val = 12;
STATE.config.rows = val;
updateTemplateFromCount('rows', val);
renderGrid();
updateCodeOutput();
});
elements.inputs.colTemplate.addEventListener('change', (e) => {
updateCountFromTemplate('cols', e.target.value);
renderGrid();
updateCodeOutput();
});
elements.inputs.rowTemplate.addEventListener('change', (e) => {
updateCountFromTemplate('rows', e.target.value);
renderGrid();
updateCodeOutput();
});
elements.inputs.gap.addEventListener('input', (e) => updateConfig('gap', parseInt(e.target.value)));
elements.inputs.showLines.addEventListener('change', (e) => updateConfig('showLines', e.target.checked));
// Window resize
window.addEventListener('resize', () => {
renderGrid();
});
// Drag start for new box
elements.newBoxSource.addEventListener('dragstart', (e) => {
STATE.dragState = { type: 'new' };
});
// Canvas DnD events
elements.canvas.addEventListener('dragover', (e) => {
e.preventDefault();
if (!STATE.dragState) return;
const coords = getGridCoordinates(e.clientX, e.clientY);
let previewBox = null;
let isColliding = false;
if (STATE.dragState.type === 'new') {
previewBox = {
colStart: coords.col,
colEnd: coords.col + 1,
rowStart: coords.row,
rowEnd: coords.row + 1
};
isColliding = checkCollision(previewBox);
} else if (STATE.dragState.type === 'move') {
const { initialBox, offset, boxId } = STATE.dragState;
// Calculate new start position based on mouse cell - offset
let newColStart = coords.col - offset.col;
let newRowStart = coords.row - offset.row;
// Dimensions
const colSpan = initialBox.colEnd - initialBox.colStart;
const rowSpan = initialBox.rowEnd - initialBox.rowStart;
// Clamp to grid boundaries
// We want the box to stay within 1..cols
// Min colStart is 1.
// Max colStart is cols - colSpan + 1.
newColStart = Math.max(1, Math.min(newColStart, STATE.config.cols - colSpan + 1));
newRowStart = Math.max(1, Math.min(newRowStart, STATE.config.rows - rowSpan + 1));
const newColEnd = newColStart + colSpan;
const newRowEnd = newRowStart + rowSpan;
previewBox = {
colStart: newColStart,
colEnd: newColEnd,
rowStart: newRowStart,
rowEnd: newRowEnd
};
isColliding = checkCollision(previewBox, boxId); // Pass boxId to ignore self
}
if (previewBox) {
renderPreview(previewBox, isColliding);
STATE.dragState.previewBox = previewBox; // Store specifically for drop
STATE.dragState.isColliding = isColliding;
}
});
elements.canvas.addEventListener('dragleave', (e) => {
elements.previewLayer.innerHTML = '';
});
elements.canvas.addEventListener('drop', (e) => {
e.preventDefault();
if (!STATE.dragState) return;
if (STATE.dragState.type === 'new') {
// For 'new', we originally used dragover's STATE.dragState.currentHover
// But now we use calculated previewBox.
// Re-calculate or use stored?
// dragover runs frequently. Let's use the last calculated valid preview.
if (!STATE.dragState.isColliding && STATE.dragState.previewBox) {
addBox({ col: STATE.dragState.previewBox.colStart, row: STATE.dragState.previewBox.rowStart });
}
} else if (STATE.dragState.type === 'move') {
if (!STATE.dragState.isColliding && STATE.dragState.previewBox) {
// Update box
const boxIndex = STATE.boxes.findIndex(b => b.id === STATE.dragState.boxId);
if (boxIndex !== -1) {
STATE.boxes[boxIndex] = {
...STATE.boxes[boxIndex],
colStart: STATE.dragState.previewBox.colStart,
colEnd: STATE.dragState.previewBox.colEnd,
rowStart: STATE.dragState.previewBox.rowStart,
rowEnd: STATE.dragState.previewBox.rowEnd
};
renderBoxes(); // This will re-attach listeners
updateCodeOutput();
}
}
}
elements.previewLayer.innerHTML = '';
STATE.dragState = null;
});
}
function handleResizeStart(e, box, corner) {
e.stopPropagation();
e.preventDefault();
// Store initial state
STATE.dragState = {
type: 'resize',
boxId: box.id,
corner: corner,
// Current box state
initialBox: { ...box },
// Anchor point (the corner that DOESN't move)
anchor: getAnchorPoint(box, corner)
};
// Add global listeners
document.addEventListener('mousemove', handleGlobalMouseMove);
document.addEventListener('mouseup', handleGlobalMouseUp);
}
function getAnchorPoint(box, corner) {
// Returns the grid coordinates of the fixed opposite corner
// corner is nw, ne, sw, se
switch (corner) {
case 'nw': return { col: box.colEnd, row: box.rowEnd }; // Anchor is SE
case 'ne': return { col: box.colStart, row: box.rowEnd }; // Anchor is SW
case 'sw': return { col: box.colEnd, row: box.rowStart }; // Anchor is NE
case 'se': return { col: box.colStart, row: box.rowStart }; // Anchor is NW
}
}
function handleGlobalMouseMove(e) {
if (!STATE.dragState || STATE.dragState.type !== 'resize') return;
const coords = getGridCoordinates(e.clientX, e.clientY);
const { anchor, boxId } = STATE.dragState;
// Calculate new box dimensions based on anchor and current mouse grid pos
let newBox = { id: boxId };
// Determine new start/end based on anchor and current
// Note: Grid lines are 1-based.
// If dragging 'se' handle, anchor is 'nw' (start, start).
// Current coords should become end.
// We need to handle swapping directions if user drags past anchor?
// CSS Grid area: row-start / col-start / row-end / col-end
// Typically start < end.
const col1 = anchor.col;
const col2 = coords.col; // this is the cell we are hovering
// If we are hovering col 2, and anchor is at line 1 (start),
// If we drag SE, we want the box to end AFTER col 2. So end line is col 2 + 1?
// Wait, let's look at how we store box data:
// colStart: 1, colEnd: 2 means it occupies column 1.
// If anchor is Start (left/top), it refers to the Start LINE.
// If anchor is End (right/bottom), it refers to the End LINE.
// Actually, getAnchorPoint returns the LINE numbers or stored properties?
// Stored properties: colEnd is exclusive (line number).
// Simplification: Calculate min and max of (anchor, current) to determine start/end.
// But we need to know if we are 'including' the current cell.
// Let's treat the handle as pointing to the specific corner of the layout.
// SE handle controls colEnd and rowEnd.
// If I drag SE handle to col 3, I expect the box to end at line 4 (end of col 3).
// Refined logic:
// 1. Determine which lines change based on corner.
// 2. Clamp values.
let c1, c2, r1, r2;
// Used for calculation
// 'coords' is the cell index (1-based).
// If I drag to cell 3, I usually mean I want to include cell 3.
// So the line depends on direction.
// Let's try a min/max approach with the anchor "cell" vs current "cell"?
// No, anchor returns the fixed lines.
// Let's look at SE resize:
// Anchor is NW (colStart, rowStart).
// We want to change colEnd, rowEnd.
// If mouse is at cell 3, we want colEnd to be 4.
// Let's use the corner type to decide logic.
const corner = STATE.dragState.corner;
const init = STATE.dragState.initialBox;
if (corner === 'se') {
// Changing End lines.
// If mouse is at cell C, line is C + 1.
let newColEnd = coords.col + 1;
let newRowEnd = coords.row + 1;
// Validation: Must be > Start
newColEnd = Math.max(init.colStart + 1, newColEnd);
newRowEnd = Math.max(init.rowStart + 1, newRowEnd);
newBox.colStart = init.colStart;
newBox.rowStart = init.rowStart;
newBox.colEnd = newColEnd;
newBox.rowEnd = newRowEnd;
} else if (corner === 'sw') {
// Changing Start Col, End Row
// If mouse is at cell C, Start line is C.
let newColStart = coords.col;
let newRowEnd = coords.row + 1;
// Validation: Must be < End
newColStart = Math.min(init.colEnd - 1, newColStart);
newColStart = Math.max(1, newColStart); // Clamp to grid
newRowEnd = Math.max(init.rowStart + 1, newRowEnd);
newBox.colStart = newColStart;
newBox.rowStart = init.rowStart;
newBox.colEnd = init.colEnd;
newBox.rowEnd = newRowEnd;
} else if (corner === 'ne') {
// Changing End Col, Start Row
let newColEnd = coords.col + 1;
let newRowStart = coords.row;
newColEnd = Math.max(init.colStart + 1, newColEnd);
newRowStart = Math.min(init.rowEnd - 1, newRowStart);
newRowStart = Math.max(1, newRowStart);
newBox.colStart = init.colStart;
newBox.rowStart = newRowStart;
newBox.colEnd = newColEnd;
newBox.rowEnd = init.rowEnd;
} else if (corner === 'nw') {
// Changing Start Col, Start Row
let newColStart = coords.col;
let newRowStart = coords.row;
newColStart = Math.min(init.colEnd - 1, newColStart);
newColStart = Math.max(1, newColStart);
newRowStart = Math.min(init.rowEnd - 1, newRowStart);
newRowStart = Math.max(1, newRowStart);
newBox.colStart = newColStart;
newBox.rowStart = newRowStart;
newBox.colEnd = init.colEnd;
newBox.rowEnd = init.rowEnd;
}
// Check collision
const isColliding = checkCollision(newBox, boxId);
// Update preview layer to show "ghost" of new size
// For resizing, maybe we just update the box itself if valid?
// Or use preview. The prompt says "Visual feedback: show which cells the box will occupy".
// Let's use the preview layer for feedback.
renderPreview(newBox, isColliding);
STATE.dragState.currentResizeBox = newBox;
STATE.dragState.isColliding = isColliding;
}
function handleGlobalMouseUp(e) {
if (!STATE.dragState || STATE.dragState.type !== 'resize') return;
document.removeEventListener('mousemove', handleGlobalMouseMove);
document.removeEventListener('mouseup', handleGlobalMouseUp);
const { isColliding, currentResizeBox, boxId } = STATE.dragState;
if (currentResizeBox && !isColliding) {
// Apply changes
const boxIndex = STATE.boxes.findIndex(b => b.id === boxId);
if (boxIndex !== -1) {
STATE.boxes[boxIndex] = { ...STATE.boxes[boxIndex], ...currentResizeBox };
renderBoxes();
updateCodeOutput();
}
}
elements.previewLayer.innerHTML = '';
STATE.dragState = null;
}
function addBox(coords) {
const box = {
id: STATE.nextId++,
colStart: coords.col,
colEnd: coords.col + 1,
rowStart: coords.row,
rowEnd: coords.row + 1
};
STATE.boxes.push(box);
renderBoxes();
updateCodeOutput();
}
function deleteBox(id) {
STATE.boxes = STATE.boxes.filter(b => b.id !== id);
renderBoxes();
updateCodeOutput();
}
function createBoxElement(box) {
const el = document.createElement('div');
el.className = 'grid-box';
el.style.gridColumnStart = box.colStart;
el.style.gridColumnEnd = box.colEnd;
el.style.gridRowStart = box.rowStart;
el.style.gridRowEnd = box.rowEnd;
el.textContent = `Box ${box.id}`;
// Enable dragging for move
el.draggable = true;
el.addEventListener('dragstart', (e) => {
e.stopPropagation();
const coords = getGridCoordinates(e.clientX, e.clientY);
STATE.dragState = {
type: 'move',
boxId: box.id,
initialBox: { ...box },
offset: {
col: coords.col - box.colStart,
row: coords.row - box.rowStart
}
};
e.dataTransfer.effectAllowed = 'move';
});
// Delete button
const delBtn = document.createElement('div');
delBtn.className = 'delete-btn';
delBtn.innerHTML = '×';
delBtn.onclick = (e) => {
e.stopPropagation();
deleteBox(box.id);
};
el.appendChild(delBtn);
// Resize handles
const corners = ['nw', 'ne', 'sw', 'se'];
corners.forEach(corner => {
const handle = document.createElement('div');
handle.className = `resize-handle handle-${corner}`;
handle.draggable = false;
handle.addEventListener('dragstart', (e) => {
e.stopPropagation();
e.preventDefault();
});
handle.onmousedown = (e) => handleResizeStart(e, box, corner);
el.appendChild(handle);
});
return el;
}
function renderBoxes() {
elements.itemsLayer.innerHTML = '';
STATE.boxes.forEach(box => {
elements.itemsLayer.appendChild(createBoxElement(box));
});
}
// Helper: Get grid cell coordinates from mouse position
function getGridCoordinates(x, y) {
// Find the cell element under the cursor
// The lines layer is underneath, but we can iterate its children to check bounds.
const cells = elements.linesLayer.children; // array of grid-cell-markers
// Fallback if no cells (e.g. init failure)
if (cells.length === 0) return { col: 1, row: 1 };
const { cols } = STATE.config;
// We can't easily map index to col/row if tracks are arbitrary.
// However, the cells are rendered in order: row 1 (col 1..N), row 2...
// So 1D index mapping works if we know 'cols'.
// BUT 'cols' might be 1 if renderGrid failed.
// Let's assume STATE.config.cols is correct (it should be).
for (let i = 0; i < cells.length; i++) {
const cell = cells[i];
const box = cell.getBoundingClientRect();
// Check if point is inside cell box
if (x >= box.left && x <= box.right && y >= box.top && y <= box.bottom) {
// Found it.
// Map index 'i' to col/row (1-based)
const row = Math.floor(i / cols) + 1;
const col = (i % cols) + 1;
return { col, row };
}
}
return { col: 1, row: 1 }; // Fallback
}
function checkCollision(targetBox, ignoreBoxId = null) {
// targetBox: { colStart, colEnd, rowStart, rowEnd }
// Check against all existing boxes in STATE.boxes
for (const box of STATE.boxes) {
if (box.id === ignoreBoxId) continue;
// Check overlap
const overlaps = !(
targetBox.colEnd <= box.colStart ||
targetBox.colStart >= box.colEnd ||
targetBox.rowEnd <= box.rowStart ||
targetBox.rowStart >= box.rowEnd
);
if (overlaps) return true;
}
return false;
}
function updateCodeOutput() {
const { cols, rows, gap, colTemplate, rowTemplate } = STATE.config;
// Determine Tailwind Classes for container
let classCols = `grid-cols-${cols}`;
let classRows = `grid-rows-${rows}`;
// Check if templates are uniform "1fr"
// Use the stored templates or the count
const isUniformCol = colTemplate.trim().split(/\s+/).every(s => s === '1fr') && colTemplate.trim().split(/\s+/).length === cols;
if (!isUniformCol) {
const val = colTemplate.trim().replace(/\s+/g, '_');
classCols = `grid-cols-[${val}]`;
}
const isUniformRow = rowTemplate.trim().split(/\s+/).every(s => s === '1fr') && rowTemplate.trim().split(/\s+/).length === rows;
if (!isUniformRow) {
const val = rowTemplate.trim().replace(/\s+/g, '_');
classRows = `grid-rows-[${val}]`;
}
let code = `<div class="grid ${classCols} ${classRows} gap-[${gap}px] p-[${gap}px]">\n`;
STATE.boxes.forEach(box => {
let classes = [];
classes.push(`col-start-${box.colStart}`);
classes.push(`col-end-${box.colEnd}`);
classes.push(`row-start-${box.rowStart}`);
classes.push(`row-end-${box.rowEnd}`);
code += ` <div class="${classes.join(' ')}">Box ${box.id}</div>\n`;
});
code += `</div>`;
elements.codeOutput.textContent = code;
}
// Redefine renderGrid to be more robust
// We replaced it earlier but let's make sure it's correct here if we want to override it.
// Actually, earlier definition is fine IF we make sure STATE is correct.
// But the issue was 'getComputedStyle' returning 1 track.
// Let's overwrite renderGrid with a safe version that trusts STATE.config first if headers are present.
function renderGrid() {
const { gap, showLines, colTemplate, rowTemplate } = STATE.config;
// 1. Apply styles
elements.linesLayer.style.display = 'grid';
elements.linesLayer.style.gridTemplateColumns = colTemplate;
elements.linesLayer.style.gridTemplateRows = rowTemplate;
elements.linesLayer.style.gap = `${gap}px`;
elements.canvas.style.gridTemplateColumns = colTemplate;
elements.canvas.style.gridTemplateRows = rowTemplate;
elements.canvas.style.gap = `${gap}px`;
elements.canvas.style.padding = `${gap}px`; // Add outer padding matching gap
// 2. Determine track counts
// Rely on STATE.config.cols/rows which are maintained by the Input Listeners/Split Logic.
// 'computedCount' is only needed if we want to confirm what the browser saw, but for generating markers,
// we should trust the config count that matches the template logic.
// If the user typed "1fr 1fr", we know it's 2.
// We already update STATE.config.cols/rows in the listeners. So trust them.
const cCount = STATE.config.cols;
const rCount = STATE.config.rows;
// 4. Render Grid Lines
elements.linesLayer.innerHTML = '';
if (showLines) {
const totalCells = cCount * rCount;
for (let i = 0; i < totalCells; i++) {
const cell = document.createElement('div');
cell.className = 'grid-cell-marker';
elements.linesLayer.appendChild(cell);
}
} else {
elements.linesLayer.style.display = 'none';
}
}
// Start
init();