-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsave js
More file actions
738 lines (614 loc) · 21.4 KB
/
Copy pathsave js
File metadata and controls
738 lines (614 loc) · 21.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
// Constants
const ROWS = 32;
const COLS = 32;
const SQUARE_SIZE = 20;
const GRID_COLOR = '#ddd';
const GRID_LINE_WIDTH = 1;
const OFFSET_INDICATOR_COLOR = 'red';
// Application state
let currentMode = 0; // 0 means "eraser" mode
let matrix = Array(ROWS).fill().map(() => Array(COLS).fill(0));
let xOffset = 0;
let zOffset = 0;
let isDragging = false;
let lastCell = null;
//let mobile = "checked";
// Color data for different commands
const colorData = {
0: {
name: "None",
fill: "#ffffff",
template: ""
}
};
// Initialize application when the DOM is fully loaded
document.addEventListener('DOMContentLoaded', () => {
initCanvas();
setupEventListeners();
updateCurrentModeDisplay();
});
// Initialize the canvas
function initCanvas() {
const canvas = document.getElementById('grid-canvas');
const ctx = canvas.getContext('2d');
// Set canvas dimensions based on grid size
canvas.width = COLS * SQUARE_SIZE;
canvas.height = ROWS * SQUARE_SIZE;
// Draw the initial grid
drawGrid();
}
// Draw the grid and all filled squares
function drawGrid() {
const canvas = document.getElementById('grid-canvas');
const ctx = canvas.getContext('2d');
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw all filled squares first
for (let row = 0; row < ROWS; row++) {
for (let col = 0; col < COLS; col++) {
const squareValue = matrix[row][col];
if (squareValue > 0) {
const x = col * SQUARE_SIZE;
const y = row * SQUARE_SIZE;
ctx.fillStyle = colorData[squareValue].fill;
ctx.fillRect(x, y, SQUARE_SIZE, SQUARE_SIZE);
}
}
}
// Draw grid lines
ctx.beginPath();
ctx.strokeStyle = GRID_COLOR;
ctx.lineWidth = GRID_LINE_WIDTH;
// Draw vertical grid lines
for (let i = 0; i <= COLS; i++) {
const x = i * SQUARE_SIZE;
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.height);
}
// Draw horizontal grid lines
for (let i = 0; i <= ROWS; i++) {
const y = i * SQUARE_SIZE;
ctx.moveTo(0, y);
ctx.lineTo(canvas.width, y);
}
ctx.stroke();
// Draw the offset indicator
drawOffsetIndicator(ctx);
}
//Draw the offset indicator in the grid
function drawOffsetIndicator(ctx) {
const centerRow = Math.floor(ROWS / 2);
const centerCol = Math.floor(COLS / 2);
const x = centerCol * SQUARE_SIZE;
const y = centerRow * SQUARE_SIZE;
ctx.save();
ctx.strokeStyle = OFFSET_INDICATOR_COLOR;
ctx.lineWidth = 2;
// Draw the crosshair
ctx.beginPath();
ctx.moveTo(x, y - 10);
ctx.lineTo(x, y + 10);
ctx.moveTo(x - 10, y);
ctx.lineTo(x + 10, y);
ctx.stroke();
// Draw offset text
ctx.fillStyle = OFFSET_INDICATOR_COLOR;
ctx.font = '12px Arial';
ctx.textAlign = 'center';
ctx.fillText(`Offset: (${xOffset}, ${zOffset})`, x, y - 15);
ctx.restore();
}
// Update the current mode display
function updateCurrentModeDisplay() {
const modeNameElement = document.getElementById('mode-name');
const modeColorElement = document.getElementById('mode-color');
modeNameElement.textContent = colorData[currentMode].name;
modeColorElement.style.backgroundColor = colorData[currentMode].fill;
}
// Update a square in the grid
function updateSquare(row, col, mode, toggle = false) {
if (row < 0 || row >= ROWS || col < 0 || col >= COLS) {
return; // Out of bounds
}
// If toggle is true, toggle between the current mode and 0 (none)
if (toggle) {
matrix[row][col] = matrix[row][col] === mode ? 0 : mode;
} else {
matrix[row][col] = mode;
}
// Redraw the grid
drawGrid();
}
// Show an alert modal
function showAlert(title, message) {
const modal = document.getElementById('alert-modal');
const titleElement = document.getElementById('alert-title');
const messageElement = document.getElementById('alert-message');
titleElement.textContent = title;
messageElement.textContent = message;
showModal(modal);
}
// Add a new command/color
function addCommand(name, fill, template) {
// Find the next available ID
const nextId = Math.max(0, ...Object.keys(colorData).map(Number)) + 1;
// Add the new command to colorData
colorData[nextId] = {
name,
fill,
template
};
// If this is the first real command (besides "None"), select it
if (nextId === 1) {
currentMode = nextId;
updateCurrentModeDisplay();
}
return nextId;
}
// Get preview content for the generated commands
function getPreviewContent() {
let commands = [];
// Loop through the matrix
for (let row = 0; row < ROWS; row++) {
for (let col = 0; col < COLS; col++) {
const value = matrix[row][col];
if (value > 0 && colorData[value].template) {
// Calculate the actual coordinates with offsets
const x = col + (xOffset * -1);
const y = 0; // Y is always 0 for 2D grid
const z = row + (zOffset * -1);
// Special functions
let command = colorData[value].template
.replace(/{x}/g, x)
.replace(/{y}/g, y)
.replace(/{z}/g, z);
//test crouch
try {
command = command.replace(/{crouch:True}/g, "execute at @s as @s positioned ~~1.5~ unless entity @s[dx=0] run");
command = command.replace(/{crouch:False}/g, "execute at @s as @s positioned ~~1.5~ if entity @s[dx=0] run");
} catch (e) {
console.error("error in crouch test", e);
}
//test water
try {
command = command.replace(/{inWater:True}/g, "execute at @s as @s if block ~~~ water run ");
command = command.replace(/{inWater:False}/g, "execute at @s as @s unless block ~~-1~ water unless block ~~1~ water run ");
} catch (e) {
console.error("error in crouch test", e);
}
//test air
try {
command = command.replace(/{inAir:True}/g, "execute at @s as @s if block ~~-1~ air run ");
command = command.replace(/{inAir:False}/g, "execute at @s as @s unless block ~~-1~ air run ");
} catch (e) {
console.error("error in crouch test", e);
}
//random num
try {
command = command.replace(/{random:(.+?)}/g, (_, expr) => {
let [min, max] = expr.split(",");
min = Number(min);
max = Number(max);
return Math.floor(Math.random() * (max - min) + min);
});
} catch (e) {
console.error("error in random test", e);
}
//Repeat
let rptest = 0;
try {
command = command.replace(/#repeat:(.+?)#/g, (_, expr) => {
let [cmd, loops, variables] = expr.split("|");
loops = Number(loops);
let result = "";
console.log(cmd, loops, variables, expr);
for (let i = 0; i < loops; i++) {
try {
// Replace {i} with the current iteration number
let currentVariables = variables;
try {
currentVariables = currentVariables.replace(/@i@/g, i);
} catch (e) {
console.error("Error replacing {i}:", e);
}
// Split variables string into an array
let varsArr = [];
try {
varsArr = currentVariables.split(";");
} catch (e) {
console.error("Error splitting variables:", e);
}
// Replace variable placeholders {var0}, {var1}, etc.
let repeatedCmd = "";
try {
repeatedCmd = cmd.replace(/@var(\d+)@/g, (_, index) => {
return varsArr[Number(index)];
});
} catch (e) {
console.error("Error replacing {var} placeholders:", e);
}
// Replace math expressions
try {
repeatedCmd = repeatedCmd.replace(/{math:(.+?)}/g, (_, expr) => eval(expr));
} catch (e) {
console.error("Error evaluating math expression:", e);
}
result += repeatedCmd + "\n";
} catch (e) {
console.error(`Error processing iteration ${i}:`, e);
}
}
result = result.trimEnd();
rptest++;
return result;
});
} catch (e) {
console.error("Error in repeater:", e);
}
// Test math replacement outside the repeater if no repeats occurred
if (rptest === 0) {
try {
command = command.replace(/{math:(.+?)}/g, (_, expr) => eval(expr));
} catch (e) {
console.error("Error evaluating math expression:", e);
}
} else {
console.warn("Repeated:", rptest);
}
commands.push(command);
}
}
}
if (commands.length === 0) {
return "# No commands to preview";
}
return commands.join('\n');
}
// Get content for saving to a file
function getSaveContent() {
// For now, save content is the same as preview content
return getPreviewContent();
}
// Show a modal
function showModal(modal) {
modal.classList.add('visible');
}
// Hide a modal
function hideModal(modal) {
modal.classList.remove('visible');
}
// Populate the color selection list
function populateColorList() {
const colorList = document.getElementById('color-list');
colorList.innerHTML = '';
// Create a color item for each entry in colorData
Object.entries(colorData).forEach(([id, data]) => {
const item = document.createElement('div');
item.className = 'color-item';
item.dataset.id = id;
const colorSquare = document.createElement('div');
colorSquare.className = 'color-square';
colorSquare.style.backgroundColor = data.fill;
const name = document.createElement('div');
name.className = 'color-item-name';
name.textContent = data.name;
item.appendChild(colorSquare);
item.appendChild(name);
colorList.appendChild(item);
});
}
// Handle canvas click
function handleCanvasClick(e) {
if (mobile == "checked" || moveGrid == "on") {
return;
}
const canvas = document.getElementById('grid-canvas');
const rect = canvas.getBoundingClientRect();
// Calculate the grid cell from the click coordinates
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const col = Math.floor(x / SQUARE_SIZE);
const row = Math.floor(y / SQUARE_SIZE);
// Update the square (toggle behavior on click)
updateSquare(row, col, currentMode, true);
// Start dragging
isDragging = true;
lastCell = { row, col };
}
// Handle canvas drag
function handleCanvasDrag(e) {
if (!isDragging || mobile == "checked" || moveGrid == "on") {
return;
}
const canvas = document.getElementById('grid-canvas');
const rect = canvas.getBoundingClientRect();
// Calculate the grid cell from the current coordinates
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const col = Math.floor(x / SQUARE_SIZE);
const row = Math.floor(y / SQUARE_SIZE);
// Skip if we're still on the same cell
if (lastCell && lastCell.row === row && lastCell.col === col) {
return;
}
// Update the square (no toggle during drag)
updateSquare(row, col, currentMode, false);
// Update last cell
lastCell = { row, col };
}
//mobile version
function handleCanvasClickm(e) {
if (mobile == "unchecked" || moveGrid == "on") {
return;
}
const canvas = document.getElementById('grid-canvas');
const rect = canvas.getBoundingClientRect();
// Calculate the grid cell from the click/touch coordinates
const x = (e.clientX || e.touches[0].clientX) - rect.left;
const y = (e.clientY || e.touches[0].clientY) - rect.top;
const col = Math.floor(x / SQUARE_SIZE);
const row = Math.floor(y / SQUARE_SIZE);
// Update the square (toggle behavior on click/touch)
updateSquare(row, col, currentMode, true);
// Start dragging
isDragging = true;
lastCell = { row, col };
}
function handleCanvasDragm(e) {
if (!isDragging || mobile == "unchecked" || moveGrid == "on") {
return;
}
const canvas = document.getElementById('grid-canvas');
const rect = canvas.getBoundingClientRect();
// Calculate the grid cell from the current coordinates
const x = (e.clientX || e.touches[0].clientX) - rect.left;
const y = (e.clientY || e.touches[0].clientY) - rect.top;
const col = Math.floor(x / SQUARE_SIZE);
const row = Math.floor(y / SQUARE_SIZE);
// Skip if we're still on the same cell
if (lastCell && lastCell.row === row && lastCell.col === col) {
return;
}
// Update the square (no toggle during drag)
updateSquare(row, col, currentMode, false);
// Update last cell
lastCell = { row, col };
}
function setupEventListeners() {
let mobile;
let moveGrid;
setupControl();
setupCanvasEvents();
setupOffsetInputs();
setupColorSelection();
setupAddCommand();
setupPreview();
setupSave();
setupModalCloseHandlers();
setupTemplatesModal();
setupControl();
}
function setupCanvasEvents() {
const canvas = document.getElementById('grid-canvas');
canvas.addEventListener('mousedown', handleCanvasClick);
canvas.addEventListener('mousemove', handleCanvasDrag);
window.addEventListener('mouseup', () => {
isDragging = false;
lastCell = null;
});
canvas.addEventListener('touchstart', handleCanvasClickm);
canvas.addEventListener('touchmove', handleCanvasDragm);
window.addEventListener('touchend', () => {
isDragging = false;
lastCell = null;
});
}
function setupOffsetInputs() {
const xOffsetInput = document.getElementById('x-offset');
const zOffsetInput = document.getElementById('z-offset');
xOffsetInput.addEventListener('change', () => {
xOffset = parseInt(xOffsetInput.value) || 0;
drawGrid();
});
zOffsetInput.addEventListener('change', () => {
zOffset = parseInt(zOffsetInput.value) || 0;
drawGrid();
});
}
function setupColorSelection() {
const selectColorBtn = document.getElementById('select-color-btn');
const selectColorModal = document.getElementById('select-color-modal');
selectColorBtn.addEventListener('click', () => {
populateColorList();
showModal(selectColorModal);
});
document.getElementById('color-list').addEventListener('click', (e) => {
let targetItem = e.target;
while (targetItem && !targetItem.classList.contains('color-item')) {
targetItem = targetItem.parentElement;
}
if (targetItem) {
const colorId = parseInt(targetItem.dataset.id);
currentMode = colorId;
updateCurrentModeDisplay();
hideModal(selectColorModal);
}
});
}
function setupAddCommand() {
const addCommandBtn = document.getElementById('add-command-btn');
const addCommandModal = document.getElementById('add-command-modal');
const addCommandForm = document.getElementById('add-command-form');
const colorInput = document.getElementById('command-color');
const colorPreview = document.getElementById('color-preview');
addCommandBtn.addEventListener('click', () => {
showModal(addCommandModal);
// Update color preview on input
const updatePreview = () => {
colorPreview.style.backgroundColor = colorInput.value;
};
colorInput.addEventListener('input', updatePreview);
updatePreview(); // Initial update
});
colorPreview.addEventListener('click', (e) => {
const randomColor = () => {
return `#${Math.floor(Math.random() * 16777215).toString(16).padStart(6, "0")}`;
};
const newColor = randomColor();
colorPreview.style.backgroundColor = newColor;
colorInput.value = newColor;
e.preventDefault();
});
addCommandForm.addEventListener('submit', (e) => {
e.preventDefault();
const name = document.getElementById('command-name').value;
const fill = document.getElementById('command-color').value;
const template = document.getElementById('command-template').value;
if (!name || !fill || !template) {
showAlert('Error', 'Please fill in all fields');
return;
}
const newId = addCommand(name, fill, template);
currentMode = newId;
updateCurrentModeDisplay();
// Reset the form to default values
addCommandForm.reset();
if (document.getElementById('debug-auto').checked ? true : false) {
const randomColor = () => {
return `#${Math.floor(Math.random() * 16777215).toString(16).padStart(6, "0")}`;
};
const newColor = randomColor();
document.getElementById('command-color').value = newColor;
document.getElementById('command-template').value = '';
document.getElementById('color-preview').style.backgroundColor = newColor;
document.getElementById('command-name').value = randomColor();
} else {
document.getElementById('command-color').value = '#';
document.getElementById('command-template').value = '';
document.getElementById('color-preview').style.backgroundColor = '#';
}
hideModal(addCommandModal);
});
}
function setupPreview() {
const previewBtn = document.getElementById('preview-btn');
const previewModal = document.getElementById('preview-modal');
const copyBtn = document.getElementById('copy-btn');
previewBtn.addEventListener('click', () => {
const previewContent = document.getElementById('preview-content');
previewContent.textContent = getPreviewContent();
showModal(previewModal);
});
copyBtn.addEventListener('click', () => {
const previewContent = document.getElementById('preview-content');
const textarea = document.createElement('textarea');
textarea.value = previewContent.textContent;
document.body.appendChild(textarea);
textarea.select();
try {
document.execCommand('copy');
showAlert('Success', 'Commands copied to clipboard');
} catch (err) {
showAlert('Error', 'Failed to copy commands');
} finally {
document.body.removeChild(textarea);
}
hideModal(previewModal);
});
}
function setupSave() {
const saveBtn = document.getElementById('save-btn');
const saveModal = document.getElementById('save-modal');
const saveForm = document.getElementById('save-form');
saveBtn.addEventListener('click', () => {
showModal(saveModal);
});
saveForm.addEventListener('submit', (e) => {
e.preventDefault();
const fileName = document.getElementById('file-name').value;
if (!fileName) {
showAlert('Error', 'Please enter a file name');
return;
}
const content = getSaveContent();
const blob = new Blob([content], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
setTimeout(() => {
URL.revokeObjectURL(url);
document.body.removeChild(a);
}, 100);
hideModal(saveModal);
});
}
function setupModalCloseHandlers() {
document.querySelectorAll('.close-modal').forEach(button => {
button.addEventListener('click', () => {
const modal = button.closest('.modal');
hideModal(modal);
});
});
document.querySelectorAll('.modal').forEach(modal => {
modal.addEventListener('click', (e) => {
if (e.target === modal) {
hideModal(modal);
}
});
});
}
function setupTemplatesModal() {
const templatesBtn = document.getElementById('templates-btn');
const templatesModal = document.getElementById('templates-modal');
const closeTemplateBtns = templatesModal.querySelectorAll('.close-modal');
const commandTemplateTextarea = document.getElementById('command-template');
const templateCopyButtons = document.querySelectorAll('.copy-template-btn');
templatesBtn.addEventListener('click', (e) => {
e.preventDefault(); // Prevent form submission if inside a form
templatesModal.style.display = 'block';
});
closeTemplateBtns.forEach(btn => {
btn.addEventListener('click', () => {
templatesModal.style.display = 'none';
});
});
// Close modal if clicking outside the modal-content
window.addEventListener('click', (e) => {
if (e.target === templatesModal) {
templatesModal.style.display = 'none';
}
});
// Copy template text on button click
templateCopyButtons.forEach(button => {
button.addEventListener('click', () => {
const templateText = button.getAttribute('data-template');
// Option 1: Insert into the command template textarea
// commandTemplateTextarea.value = templateText;
// Option 2: Copy to clipboard directly
navigator.clipboard.writeText(templateText)
.then(() => alert('Template copied to clipboard!'))
.catch(err => console.error('Failed to copy!', err));
// Optionally close the modal after selection
templatesModal.style.display = 'none';
});
});
}
function setupControl() {
const controlButton = document.getElementById('switch-mobile-pc');
const moveControlBtn = document.getElementById('move-grid');
//Dragging setup
mobile = controlButton.checked ? controlButton.value : "unchecked";
controlButton.addEventListener('change', () => {
mobile = controlButton.checked ? controlButton.value : "unchecked";
});
//Move on screen setup
moveGrid = moveControlBtn.checked ? "on" : "off";
moveControlBtn.addEventListener('change', () => {
moveGrid = moveControlBtn.checked ? "on" : "off";
const canvasMovingElement = document.getElementById('grid-canvas');
canvasMovingElement.style.touchAction = moveControlBtn.checked ? "auto" : "none";
});
}