Repository navigation
Expand file tree
/
Copy pathinterface.html
More file actions
702 lines (634 loc) · 25.6 KB
/
Copy pathinterface.html
File metadata and controls
702 lines (634 loc) · 25.6 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
<style>
/* touch-action:none lives on #canvas only - on the whole page it blocked
scrolling everywhere else too. */
.page{max-width:none!important;padding:16px 14px!important;display:flex;flex-direction:column;align-items:center;gap:8px}
.card{width:100%;max-width:420px;box-sizing:border-box}
.canvas-card{max-width:960px}
.card h3{display:flex;align-items:center;justify-content:space-between;gap:8px}
.toolbar{display:flex;gap:6px;flex-wrap:wrap;justify-content:center;align-items:center;margin-bottom:10px}
.toolbar button{width:36px;height:36px;border:2px solid var(--border);border-radius:8px;background:var(--surface);color:#fff;font-size:1rem;cursor:pointer;display:flex;align-items:center;justify-content:center}
.tool-wrap{position:relative;display:inline-flex}
.size-menu{display:none;position:absolute;bottom:100%;left:50%;transform:translateX(-50%);margin-bottom:6px;background:var(--surface2);border:1px solid var(--border);border-radius:8px;padding:4px;gap:4px;z-index:10;box-shadow:var(--shadow)}
.size-menu.open{display:flex}
.size-menu button{padding:4px 8px;border:none;border-radius:6px;background:var(--surface);color:var(--text);font-size:.7rem;cursor:pointer;white-space:nowrap}
.size-menu button:hover{background:var(--accent);color:#fff}
.toolbar button.active{border-color:var(--accent);box-shadow:0 0 6px rgba(124,111,255,.5)}
.action-row{margin-top:10px;justify-content:center}
/* toolbar + action-row share one .tool-rail item instead of two grid
cells - a spanning canvas-wrap across mixed auto/fr rows kept sizing
wrong; plain flex is predictable. */
.tool-rail{display:flex;flex-direction:column;flex-shrink:0}
.canvas-body{display:flex;flex-direction:column;width:100%;min-height:0}
.canvas-wrap{display:flex;justify-content:center;align-items:center;overflow-x:auto;margin:10px -16px;padding:10px 16px;background:#000}
#canvas{image-rendering:pixelated;cursor:crosshair;display:block;touch-action:none;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;border:2px solid rgba(255,255,255,.4);flex-shrink:0}
/* Fullscreen: canvas-wrap (flex:1) is anchored top-left, not centered -
SCALE is a whole number so leftover space is usually unavoidable, and
centering turns it into gaps on every side instead of one place.
Landscape gets a left tool rail with internal scroll (page can't scroll
in fullscreen, so a clipped rail would be unreachable); portrait keeps
the top toolbar. */
body.pt-fullscreen{overflow:hidden}
body.pt-fullscreen .navbar,body.pt-fullscreen .card:not(.canvas-card){display:none}
body.pt-fullscreen .page{padding:0;gap:0;max-width:none}
/* 100vh on iOS Safari is the largest possible viewport, not what's
visible now - can push fixed content below the real screen with no way
to scroll to it. 100dvh fixes this; 100vh is the fallback. */
body.pt-fullscreen .canvas-card{position:fixed;inset:0;z-index:1000;margin:0;border-radius:0;max-width:none;width:100vw;height:100vh;height:100dvh;box-sizing:border-box;display:flex;flex-direction:column}
body.pt-fullscreen .canvas-body{flex:1;min-height:0}
body.pt-fullscreen .canvas-wrap{flex:1;min-height:0;margin:10px 0;align-items:flex-start;justify-content:center}
@media (orientation:landscape){
body.pt-fullscreen .canvas-body{flex-direction:row;align-items:stretch;gap:8px}
body.pt-fullscreen .tool-rail{overflow-y:auto;min-height:0;padding-bottom:16px}
body.pt-fullscreen .toolbar{flex-direction:column;flex-wrap:nowrap;margin-bottom:0}
body.pt-fullscreen .action-row{flex-direction:column;justify-content:flex-start;margin-top:6px}
body.pt-fullscreen .canvas-wrap{flex:1;min-width:0;margin:0;align-items:flex-start;justify-content:flex-start}
}
.file-bar{display:grid;grid-template-columns:1fr auto;gap:8px;align-items:center;margin-top:10px}
.file-bar-row{display:contents}
.file-bar input,.file-bar select{width:100%}
.file-bar input,.file-bar select,.file-bar .btn{height:40px;box-sizing:border-box}
.btn-group{display:flex;gap:8px}
.btn-group .btn{flex:1}
pre{background:var(--surface2);border:1px solid var(--border);border-radius:8px;padding:10px 12px;overflow-x:auto;font-size:.78rem;line-height:1.5;color:var(--text)}
code{font-family:'Cascadia Mono','Fira Code','Consolas',monospace}
.route{display:inline-flex;align-items:center;gap:8px;margin-bottom:8px;font-family:'Cascadia Mono','Fira Code','Consolas',monospace}
.verb{padding:2px 7px;border-radius:5px;font-weight:700;font-size:.68rem;letter-spacing:.4px}
.verb-get{background:rgba(0,180,255,.15);color:#4fc3f7}
.verb-post{background:rgba(0,200,120,.15);color:#3ddc84}
.path{font-size:.82rem;color:var(--text)}
.api-route{margin-bottom:14px}
.api-route:last-child{margin-bottom:0}
</style>
<div class="card canvas-card">
<h3><span class="title-label">Paint</span>
<button type="button" class="btn btn-sm" id="fullscreenBtn" title="Fullscreen">⛶</button>
</h3>
<div class="canvas-body">
<div class="tool-rail">
<div class="toolbar">
<button id="t_brush" class="active" title="Brush">✎</button>
<button id="t_eraser" title="Eraser">⌫</button>
<button id="t_fill" title="Fill">◑</button>
<button id="t_line" title="Line">╱</button>
<button id="t_rect" title="Rectangle">▭</button>
<button id="t_circle" title="Circle">◯</button>
<div class="tool-wrap">
<button id="t_text" title="Text">T</button>
<div class="size-menu" id="textSizeMenu">
<button type="button" data-size="mini">mini</button>
<button type="button" data-size="small">small</button>
<button type="button" data-size="large">large</button>
</div>
</div>
<input type="color" id="colorPicker" value="#ffffff" title="Color">
</div>
<div class="action-row">
<button id="undoBtn" class="btn btn-sm" onclick="undo()" disabled title="Undo">↩</button>
<button class="btn btn-danger btn-sm" onclick="clearCanvas()">Clear</button>
</div>
</div>
<div class="canvas-wrap"><canvas id="canvas"></canvas></div>
</div>
</div>
<div class="card">
<h3>Save / Load</h3>
<div class="file-bar">
<div class="file-bar-row">
<input type="text" id="saveName" placeholder="name" maxlength="20">
<button class="btn btn-success btn-sm" onclick="saveProject()" title="Save">💾</button>
</div>
<div class="file-bar-row">
<select id="fileList"><option value="">-- load --</option></select>
<div class="btn-group">
<button class="btn btn-sm" onclick="loadProject()" title="Load">📂</button>
<button class="btn btn-danger btn-sm" onclick="deleteProject()" title="Delete">🗑</button>
</div>
</div>
</div>
</div>
<div class="card">
<h3>Remote API documentation
<button type="button" class="btn btn-sm" id="api_toggle" onclick="var a=document.getElementById('api_docs');var open=a.style.display!=='none';a.style.display=open?'none':'block';document.getElementById('api_toggle').textContent=open?'Show':'Hide'">Show</button>
</h3>
<div id="api_docs" style="display:none">
<p style="color:var(--muted);font-size:.82rem;margin-bottom:10px">
This page IS the API — every button above just calls one of these
routes. Any other device on the network can POST the same JSON to draw on
the __WIDTH__x__HEIGHT__ matrix. Base URL: <code>http://__IP__/</code>
</p>
<div class="api-route">
<div class="route"><span class="verb verb-get">GET</span><span class="path">/info</span></div>
<pre>{
"width": __WIDTH__,
"height": __HEIGHT__
}</pre>
</div>
<div class="api-route">
<div class="route"><span class="verb verb-get">GET</span><span class="path">/grid</span></div>
<p style="color:var(--muted);font-size:.82rem;margin-bottom:8px">Current canvas, one hex color per pixel.</p>
<pre>{
"d": [["#000000", "#ffffff", ...], ...]
}</pre>
</div>
<div class="api-route">
<div class="route"><span class="verb verb-post">POST</span><span class="path">/background</span></div>
<pre>{
"color": "#003366"
}</pre>
</div>
<div class="api-route">
<div class="route"><span class="verb verb-post">POST</span><span class="path">/clear</span></div>
<p style="color:var(--muted);font-size:.82rem;margin-bottom:8px">No body needed — resets to black.</p>
</div>
<div class="api-route">
<div class="route"><span class="verb verb-post">POST</span><span class="path">/pixel</span></div>
<pre>{
"color": "#ffffff",
"pts": [[5, 5], [6, 5]]
}</pre>
</div>
<div class="api-route">
<div class="route"><span class="verb verb-post">POST</span><span class="path">/fill</span></div>
<p style="color:var(--muted);font-size:.82rem;margin-bottom:8px">Flood fill from x/y, like the fill tool above.</p>
<pre>{
"x": 5,
"y": 5,
"color": "#ffffff"
}</pre>
</div>
<div class="api-route">
<div class="route"><span class="verb verb-post">POST</span><span class="path">/line</span></div>
<pre>{
"x0": 2,
"y0": 2,
"x1": 20,
"y1": 10,
"color": "#ffffff"
}</pre>
</div>
<div class="api-route">
<div class="route"><span class="verb verb-post">POST</span><span class="path">/rect</span></div>
<p style="color:var(--muted);font-size:.82rem;margin-bottom:8px">Include either or both colors.</p>
<pre>{
"x0": 2,
"y0": 2,
"x1": 20,
"y1": 10,
"border_color": "#ffffff",
"fill_color": "#ff0000"
}</pre>
</div>
<div class="api-route">
<div class="route"><span class="verb verb-post">POST</span><span class="path">/circle</span></div>
<p style="color:var(--muted);font-size:.82rem;margin-bottom:8px">x/y is the center. Include either or both colors.</p>
<pre>{
"x": 16,
"y": 16,
"radius": 8,
"border_color": "#ffffff",
"fill_color": "#ff0000"
}</pre>
</div>
<div class="api-route">
<div class="route"><span class="verb verb-post">POST</span><span class="path">/text</span></div>
<p style="color:var(--muted);font-size:.82rem;margin-bottom:8px">font_size is one of "mini", "small", "large". Give x/y for an exact
position, or align/valign with an optional padding (ignored on "center").</p>
<pre>{
"text": "Hello",
"font_size": "small",
"color": "#ffffff",
"align": "center",
"valign": "center"
}</pre>
</div>
<div class="api-route">
<div class="route"><span class="verb verb-get">GET</span><span class="path">/saves</span></div>
<p style="color:var(--muted);font-size:.82rem;margin-bottom:8px">List of saved names.</p>
<pre>["mydrawing", "another"]</pre>
</div>
<div class="api-route">
<div class="route"><span class="verb verb-post">POST</span><span class="path">/save</span></div>
<pre>{
"name": "mydrawing"
}</pre>
</div>
<div class="api-route">
<div class="route"><span class="verb verb-post">POST</span><span class="path">/load</span></div>
<pre>{
"name": "mydrawing"
}</pre>
</div>
<div class="api-route">
<div class="route"><span class="verb verb-post">POST</span><span class="path">/delete</span></div>
<pre>{
"name": "mydrawing"
}</pre>
</div>
<p style="color:var(--muted);font-size:.82rem">
Colors are <code>#RRGGBB</code> hex strings. The display only holds 16 at
once; past that, the least recently used custom color gets reassigned.
Drawing is additive; POST <code>/background</code> or <code>/clear</code>
first for a clean frame.
</p>
</div>
</div>
<script>
const W=__WIDTH__,H=__HEIGHT__;
const canvas=document.getElementById("canvas");
const ctx=canvas.getContext("2d");
const colorPicker=document.getElementById("colorPicker");
// Scale canvas so each pixel is large enough to tap. Recomputed on
// resize/orientation/fullscreen changes; outside fullscreen canvas-wrap
// has no intrinsic height, so height falls back to a viewport estimate.
let SCALE;
// Reserves canvas-wrap's padding + the canvas's border (both inside
// clientWidth/Height but outside the canvas's own box) so it can't overflow.
const CANVAS_CHROME=40;
function availSize(){
const wrap=canvas.parentElement;
const fullscreen=document.body.classList.contains("pt-fullscreen");
const availW=(wrap.clientWidth||(window.innerWidth-16))-CANVAS_CHROME;
const availH=(fullscreen?(wrap.clientHeight||window.innerHeight):(window.innerHeight-200))-CANVAS_CHROME;
return [availW,availH];
}
function resizeCanvas(){
const [availW,availH]=availSize();
// No hard ceiling on pixel size - availW/availH already bound it to
// what the container offers (a fixed cap only hurt fullscreen).
const newScale=Math.max(1,Math.min(Math.floor(availW/W),Math.floor(availH/H)));
// No-op if unchanged: resizing wipes the canvas's drawing surface,
// which can cancel an in-progress touch - and mobile browsers fire
// "resize" a lot even when nothing visible moved.
if(newScale===SCALE)return;
SCALE=newScale;
canvas.width=W*SCALE;
canvas.height=H*SCALE;
ctx.imageSmoothingEnabled=false;
redraw();
}
// Grid state: one hex color string per cell
const grid=[];
for(let y=0;y<H;y++){grid[y]=[];for(let x=0;x<W;x++)grid[y][x]="#000000";}
let tool="brush"; // brush|eraser|fill
function currentColor(){
return tool==="eraser"?"#000000":colorPicker.value;
}
// Tool buttons
const toolButtons={
brush:document.getElementById("t_brush"),
eraser:document.getElementById("t_eraser"),
fill:document.getElementById("t_fill"),
line:document.getElementById("t_line"),
rect:document.getElementById("t_rect"),
circle:document.getElementById("t_circle"),
text:document.getElementById("t_text"),
};
const SHAPE_TOOLS=["line","rect","circle"];
// Text size is picked from a small popover over the T button, not re-asked
// per click; it stays in effect until you press T again and pick a new
// one. No default - an empty value here means "not chosen yet".
let textFontSize="";
const textSizeMenu=document.getElementById("textSizeMenu");
function openTextSizeMenu(){textSizeMenu.classList.add("open");}
function closeTextSizeMenu(){textSizeMenu.classList.remove("open");}
textSizeMenu.querySelectorAll("button").forEach(function(btn){
btn.onclick=function(e){
e.stopPropagation();
textFontSize=btn.dataset.size;
closeTextSizeMenu();
};
});
document.addEventListener("pointerdown",function(e){
if(!textSizeMenu.contains(e.target)&&e.target.id!=="t_text")closeTextSizeMenu();
});
function updateToolUI(){
for(const name in toolButtons)toolButtons[name].classList.remove("active");
toolButtons[tool].classList.add("active");
closeTextSizeMenu();
redraw(); // clear any stale hover ghost left over from the previous tool
}
for(const name in toolButtons){
if(name==="text")continue;
toolButtons[name].onclick=function(){tool=name;updateToolUI();};
}
toolButtons.text.onclick=function(){
tool="text";
updateToolUI();
openTextSizeMenu();
};
colorPicker.onchange=function(){if(tool==="eraser"){tool="brush";updateToolUI();}};
// --- Fullscreen: CSS-only maximized layout works everywhere; the real
// Fullscreen API layers on top where supported (not iPhone Safari). Canvas
// is re-measured after either since available space changes.
const fullscreenBtn=document.getElementById("fullscreenBtn");
function setFullscreenUI(on){
document.body.classList.toggle("pt-fullscreen",on);
fullscreenBtn.innerHTML=on?"✕":"⛶";
fullscreenBtn.title=on?"Exit fullscreen":"Fullscreen";
requestAnimationFrame(resizeCanvas);
}
fullscreenBtn.onclick=function(){
const entering=!document.body.classList.contains("pt-fullscreen");
setFullscreenUI(entering);
if(entering&&document.documentElement.requestFullscreen){
document.documentElement.requestFullscreen().catch(function(){});
}else if(!entering&&document.fullscreenElement&&document.exitFullscreen){
document.exitFullscreen().catch(function(){});
}
};
document.addEventListener("fullscreenchange",function(){
// Catches exits the button didn't trigger (Esc, Android back gesture).
if(!document.fullscreenElement&&document.body.classList.contains("pt-fullscreen")){
setFullscreenUI(false);
}
});
function drawPixel(x,y,color){
grid[y][x]=color;
ctx.fillStyle=color;
ctx.fillRect(x*SCALE,y*SCALE,SCALE,SCALE);
}
function redraw(){
ctx.fillStyle="#000";
ctx.fillRect(0,0,canvas.width,canvas.height);
for(let y=0;y<H;y++)for(let x=0;x<W;x++){
const c=grid[y][x];
if(c&&c!=="#000000"){
ctx.fillStyle=c;
ctx.fillRect(x*SCALE,y*SCALE,SCALE,SCALE);
}
}
// Grid lines
if(SCALE>=4){
ctx.strokeStyle="rgba(255,255,255,0.22)";
ctx.lineWidth=0.5;
for(let x=0;x<=W;x++){ctx.beginPath();ctx.moveTo(x*SCALE,0);ctx.lineTo(x*SCALE,H*SCALE);ctx.stroke();}
for(let y=0;y<=H;y++){ctx.beginPath();ctx.moveTo(0,y*SCALE);ctx.lineTo(W*SCALE,y*SCALE);ctx.stroke();}
}
}
resizeCanvas();
// Debounced and deferred while painting: mobile browsers fire "resize" a
// lot (e.g. the address bar collapsing on touch), and resizing mid-stroke
// can cancel the touch outright.
let resizePending=false;
let resizeTimer=null;
function scheduleResize(){
clearTimeout(resizeTimer);
resizeTimer=setTimeout(function(){
if(painting){resizePending=true;return;}
resizeCanvas();
},150);
}
window.addEventListener("resize",scheduleResize);
window.addEventListener("orientationchange",scheduleResize);
// --- Drawing interaction ---
let painting=false;
let lastSent=0;
let pending=[];
function getXY(e){
// changedTouches works for all touch event types; "touches" is empty by touchend.
const t=e.changedTouches?e.changedTouches[0]:e;
const rect=canvas.getBoundingClientRect();
return[Math.floor((t.clientX-rect.left)/SCALE),Math.floor((t.clientY-rect.top)/SCALE)];
}
function sendPending(){
if(!pending.length)return;
const pts=pending.slice();
pending=[];
fetch("/pixel",{method:"POST",body:JSON.stringify({color:currentColor(),pts:pts})});
}
// --- Undo: one browser-tab-local history of grid snapshots, taken right
// before each committed mutation. Restoring pops one and bulk-writes it
// back to the device via POST /grid - it reverts "the canvas", not
// specifically "your last stroke", so a concurrent API/script draw made
// in between would get reverted too. Fine for a single-tab tool. ---
const undoStack=[];
const UNDO_LIMIT=20;
const undoBtn=document.getElementById("undoBtn");
function pushUndo(){
undoStack.push(grid.map(row=>row.slice()));
if(undoStack.length>UNDO_LIMIT)undoStack.shift();
undoBtn.disabled=false;
}
function undo(){
if(!undoStack.length)return;
const prev=undoStack.pop();
for(let y=0;y<H;y++)for(let x=0;x<W;x++)grid[y][x]=prev[y][x];
redraw();
fetch("/grid",{method:"POST",body:JSON.stringify({d:prev})});
undoBtn.disabled=undoStack.length===0;
}
function paint(e){
const[x,y]=getXY(e);
if(x<0||x>=W||y<0||y>=H)return;
const color=currentColor();
if(tool==="fill"){
// Local flood fill for instant feedback
const target=grid[y][x];
if(target===color)return;
const stack=[[x,y]];
const seen=new Set();
while(stack.length){
const[fx,fy]=stack.pop();
const k=fy*W+fx;
if(seen.has(k))continue;
if(fx<0||fx>=W||fy<0||fy>=H)continue;
if(grid[fy][fx]!==target)continue;
seen.add(k);
grid[fy][fx]=color;
stack.push([fx+1,fy],[fx-1,fy],[fx,fy+1],[fx,fy-1]);
}
redraw();
fetch("/fill",{method:"POST",body:JSON.stringify({x:x,y:y,color:color})});
return;
}
drawPixel(x,y,color);
pending.push([x,y]);
const now=Date.now();
if(now-lastSent>80){lastSent=now;sendPending();}
}
// --- Shape tools: line/rect/circle commit once on release, but preview
// live while dragging without touching the committed grid, so an
// undecided drag can't pollute state or fight the /grid poll. ---
let shapeStart=null;
function clampXY(x,y){
return [Math.max(0,Math.min(W-1,x)),Math.max(0,Math.min(H-1,y))];
}
function previewShape(e){
const [cx,cy]=clampXY(...getXY(e));
const [sx,sy]=shapeStart;
redraw();
ctx.strokeStyle=currentColor();
ctx.lineWidth=Math.max(1,SCALE*0.15);
ctx.beginPath();
if(tool==="line"){
ctx.moveTo(sx*SCALE+SCALE/2,sy*SCALE+SCALE/2);
ctx.lineTo(cx*SCALE+SCALE/2,cy*SCALE+SCALE/2);
}else if(tool==="rect"){
const x0=Math.min(sx,cx),y0=Math.min(sy,cy);
const rw=Math.abs(cx-sx)+1,rh=Math.abs(cy-sy)+1;
ctx.rect(x0*SCALE,y0*SCALE,rw*SCALE,rh*SCALE);
}else{
const r=Math.round(Math.hypot(cx-sx,cy-sy));
ctx.arc(sx*SCALE+SCALE/2,sy*SCALE+SCALE/2,r*SCALE,0,Math.PI*2);
}
ctx.stroke();
}
function commitShape(e){
const [cx,cy]=clampXY(...getXY(e));
const [sx,sy]=shapeStart;
const color=currentColor();
let url,body;
if(tool==="line"){
url="/line";body={x0:sx,y0:sy,x1:cx,y1:cy,color:color};
}else if(tool==="rect"){
url="/rect";body={x0:sx,y0:sy,x1:cx,y1:cy,border_color:color};
}else{
url="/circle";body={x:sx,y:sy,radius:Math.round(Math.hypot(cx-sx,cy-sy)),border_color:color};
}
pushUndo();
fetch(url,{method:"POST",body:JSON.stringify(body)});
shapeStart=null;
// Leave the last preview frame on screen; the next /grid poll (within
// ~1s) replaces it with the server's exact render, so nothing flashes
// empty in between.
}
// --- Text tool: click to place, using whatever size is picked in the
// dropdown. Approximate glyph heights, just for the hover ghost below -
// the real bitmap fonts live server-side; these only drive a preview.
const FONT_HEIGHTS={mini:5,small:8,large:14};
function placeText(x,y){
if(!textFontSize){
alert("Pick a text size from the dropdown first.");
return;
}
const text=prompt("Text to draw:");
if(!text)return;
pushUndo();
fetch("/text",{method:"POST",body:JSON.stringify({text:text,x:x,y:y,color:currentColor(),font_size:textFontSize})});
}
function showTextGhost(e){
const[x,y]=getXY(e);
redraw();
if(x<0||x>=W||y<0||y>=H)return;
const fh=FONT_HEIGHTS[textFontSize]||FONT_HEIGHTS.small;
const boxH=Math.min(fh,H-y);
ctx.fillStyle="rgba(255,255,255,0.25)";
ctx.fillRect(x*SCALE,y*SCALE,SCALE,boxH*SCALE);
ctx.strokeStyle="rgba(255,255,255,0.6)";
ctx.lineWidth=1;
ctx.strokeRect(x*SCALE+0.5,y*SCALE+0.5,SCALE-1,boxH*SCALE-1);
ctx.fillStyle="rgba(255,255,255,0.5)";
ctx.font=Math.max(fh*SCALE,10)+"px monospace";
ctx.textBaseline="top";
ctx.fillText("A",x*SCALE+SCALE,y*SCALE);
}
// Touch, not Pointer, events: a touch stays bound to its original target
// for the whole gesture no matter where the finger drifts - Pointer/Mouse
// retarget to whatever's underneath, which broke drags on small canvases
// even with pointer capture.
function startStroke(x,y,e){
if(x<0||x>=W||y<0||y>=H)return;
if(tool==="text"){placeText(x,y);return;}
if(tool==="fill"){pushUndo();paint(e);return;}
if(SHAPE_TOOLS.includes(tool)){
shapeStart=clampXY(x,y);
painting=true;
return;
}
pushUndo();
painting=true;paint(e);
}
function moveStroke(e){
if(!painting){
if(tool==="text")showTextGhost(e);
return;
}
if(SHAPE_TOOLS.includes(tool)){previewShape(e);return;}
paint(e);
}
function endStroke(e){
if(painting&&SHAPE_TOOLS.includes(tool))commitShape(e);
painting=false;
sendPending();
if(resizePending){resizePending=false;resizeCanvas();}
}
function cancelStroke(){
// OS aborted the gesture (e.g. incoming call) - drop any in-progress shape.
shapeStart=null;
painting=false;
redraw();
}
canvas.addEventListener("touchstart",function(e){
e.preventDefault();
startStroke(...getXY(e),e);
},{passive:false});
canvas.addEventListener("touchmove",function(e){
e.preventDefault();
moveStroke(e);
},{passive:false});
canvas.addEventListener("touchend",function(e){
e.preventDefault();
endStroke(e);
},{passive:false});
canvas.addEventListener("touchcancel",cancelStroke,{passive:false});
canvas.addEventListener("mousedown",function(e){startStroke(...getXY(e),e);});
canvas.addEventListener("mousemove",moveStroke);
canvas.addEventListener("mouseup",endStroke);
canvas.addEventListener("mouseleave",function(e){
// Unlike touch, a mouse leaving mid-drag is deliberate, so it ends the stroke.
if(painting)endStroke(e);
else redraw(); // clear a stale hover ghost
});
function clearCanvas(){
pushUndo();
for(let y=0;y<H;y++)for(let x=0;x<W;x++)grid[y][x]="#000000";
redraw();
fetch("/clear",{method:"POST"});
}
// --- Live sync: pick up draws made via the API (or another tab) ---
let syncing=false;
setInterval(function(){
if(painting||syncing)return;
syncing=true;
fetch("/grid").then(r=>r.json()).then(function(data){
const rows=data.d;
for(let y=0;y<H;y++)for(let x=0;x<W;x++)grid[y][x]=(rows[y]&&rows[y][x])||"#000000";
redraw();
}).catch(function(){}).finally(function(){syncing=false;});
},1000);
// --- Save / Load / Delete ---
const fileList=document.getElementById("fileList");
function refreshFiles(){
fetch("/saves").then(r=>r.json()).then(files=>{
fileList.innerHTML='<option value="">-- load --</option>';
files.forEach(f=>{
const o=document.createElement("option");
o.value=f;o.textContent=f;
fileList.appendChild(o);
});
});
}
refreshFiles();
function saveProject(){
const name=document.getElementById("saveName").value.trim();
if(!name){alert("Enter a name");return;}
fetch("/save",{method:"POST",body:JSON.stringify({name:name})}).then(()=>refreshFiles());
}
function loadProject(){
const name=fileList.value;
if(!name)return;
pushUndo();
fetch("/load",{method:"POST",body:JSON.stringify({name:name})}).then(r=>r.json()).then(data=>{
const rows=data.d;
for(let y=0;y<H;y++)for(let x=0;x<W;x++)grid[y][x]=(rows[y]&&rows[y][x])||"#000000";
redraw();
document.getElementById("saveName").value=name;
});
}
function deleteProject(){
const name=fileList.value;
if(!name)return;
if(!confirm("Delete \""+name+"\"?"))return;
fetch("/delete",{method:"POST",body:JSON.stringify({name:name})}).then(()=>refreshFiles());
}
</script>