| 1 | const PAPER_LEFT = -10; |
| 2 | const PAPER_TOP = 4; |
| 3 | const PAPER_RIGHT = 190; |
| 4 | const PAPER_BOTTOM = -293; |
| 5 | const BED_W = 200; |
| 6 | const BED_H = 297; |
| 7 | const A4W = PAPER_RIGHT - PAPER_LEFT; |
| 8 | const A4H = PAPER_TOP - PAPER_BOTTOM; |
| 9 | const PEN_MM = 0.4; |
| 10 | |
| 11 | const $ = (id) => document.getElementById(id); |
| 12 | const canvas = $("page"); |
| 13 | const ctx = canvas.getContext("2d"); |
| 14 | |
| 15 | let objects = []; |
| 16 | let selectedId = null; |
| 17 | let clipboard = null; |
| 18 | let preview = null; |
| 19 | let previewGen = 0; |
| 20 | let interacting = false; |
| 21 | let zoom = 1; |
| 22 | let panX = 0; |
| 23 | let panY = 0; |
| 24 | let filling = false; |
| 25 | let textTimer = 0; |
| 26 | let userDisconnected = false; |
| 27 | let autoTried = ""; |
| 28 | let pen = null; |
| 29 | let penJob = false; |
| 30 | let penRoute = null; |
| 31 | let penGuide = null; |
| 32 | let penAlong = 0; |
| 33 | let penGoal = 0; |
| 34 | let penHint = 0; |
| 35 | let penSpeed = 3000; |
| 36 | let penFrame = 0; |
| 37 | let penStamp = 0; |
| 38 | let penDraw = null; |
| 39 | const PORT_KEY = "timdraw-port"; |
| 40 | |
| 41 | const defaults = { |
| 42 | drawLine: true, |
| 43 | drawFill: false, |
| 44 | hatchAngle: 45, |
| 45 | hatchSpacing: 2, |
| 46 | crosshatch: false, |
| 47 | grayscale: false, |
| 48 | graySteps: 5, |
| 49 | spacingMin: 0.8, |
| 50 | spacingMax: 4, |
| 51 | }; |
| 52 | |
| 53 | function selected () |
| 54 | { |
| 55 | return objects.find((obj) => obj.id === selectedId) || null; |
| 56 | } |
| 57 | |
| 58 | let toastTimer = 0; |
| 59 | |
| 60 | function toast (message, hideAfter) |
| 61 | { |
| 62 | const el = $("toast"); |
| 63 | clearTimeout(toastTimer); |
| 64 | el.hidden = !message; |
| 65 | el.textContent = message || ""; |
| 66 | if (message && hideAfter) |
| 67 | { |
| 68 | toastTimer = setTimeout(() => |
| 69 | { |
| 70 | el.hidden = true; |
| 71 | el.textContent = ""; |
| 72 | }, hideAfter); |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | async function api (path, body) |
| 77 | { |
| 78 | const options = body |
| 79 | ? { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } |
| 80 | : {}; |
| 81 | const response = await fetch(path, options); |
| 82 | const data = await response.json().catch(() => ({})); |
| 83 | if (!response.ok) throw new Error(data.error || response.statusText); |
| 84 | return data; |
| 85 | } |
| 86 | |
| 87 | function readSettings () |
| 88 | { |
| 89 | return { |
| 90 | drawSpeed: Number($("draw-speed").value), |
| 91 | travelSpeed: Number($("travel-speed").value), |
| 92 | penUpZ: Number($("pen-up").value), |
| 93 | penDownZ: Number($("pen-down").value), |
| 94 | dwellMs: Number($("dwell").value), |
| 95 | origin: $("origin").value, |
| 96 | perObject: $("per-object").checked, |
| 97 | showTravel: $("show-travel").checked, |
| 98 | jogStep: Number($("jog-step").value), |
| 99 | }; |
| 100 | } |
| 101 | |
| 102 | function styleFlags (obj) |
| 103 | { |
| 104 | if (obj.drawLine != null || obj.drawFill != null) |
| 105 | return { drawLine: !!obj.drawLine, drawFill: !!obj.drawFill }; |
| 106 | if (obj.mode === "fill") return { drawLine: false, drawFill: true }; |
| 107 | return { drawLine: true, drawFill: false }; |
| 108 | } |
| 109 | |
| 110 | function styleLabel (obj) |
| 111 | { |
| 112 | const flags = styleFlags(obj); |
| 113 | if (flags.drawLine && flags.drawFill) return "lijn + vulling"; |
| 114 | if (flags.drawFill) return "vulling"; |
| 115 | if (flags.drawLine) return "lijn"; |
| 116 | return "uit"; |
| 117 | } |
| 118 | |
| 119 | function hatchFromForm () |
| 120 | { |
| 121 | return { |
| 122 | drawLine: $("prop-line").checked, |
| 123 | drawFill: $("prop-fill").checked, |
| 124 | hatchAngle: Number($("prop-angle").value), |
| 125 | hatchSpacing: Number($("prop-spacing").value), |
| 126 | crosshatch: $("prop-cross").checked, |
| 127 | grayscale: $("prop-gray").checked, |
| 128 | graySteps: Number($("prop-steps").value), |
| 129 | spacingMin: Number($("prop-dark").value), |
| 130 | spacingMax: Number($("prop-light").value), |
| 131 | }; |
| 132 | } |
| 133 | |
| 134 | function layout () |
| 135 | { |
| 136 | const rect = canvas.getBoundingClientRect(); |
| 137 | const margin = 28; |
| 138 | const span = viewSpan(); |
| 139 | const fit = Math.min((rect.width - margin * 2) / span.w, (rect.height - margin * 2) / span.h); |
| 140 | const scale = fit * zoom; |
| 141 | return { |
| 142 | scale, |
| 143 | ox: (rect.width - span.w * scale) / 2 + panX, |
| 144 | oy: (rect.height - span.h * scale) / 2 + panY, |
| 145 | width: rect.width, |
| 146 | height: rect.height, |
| 147 | }; |
| 148 | } |
| 149 | |
| 150 | function viewSpan () |
| 151 | { |
| 152 | const far = pageFromMachine(BED_W, -BED_H); |
| 153 | return { |
| 154 | w: Math.max(A4W, far.x) - Math.min(0, far.x), |
| 155 | h: Math.max(A4H, far.y) - Math.min(0, far.y), |
| 156 | }; |
| 157 | } |
| 158 | |
| 159 | function mmToPx (x, y) |
| 160 | { |
| 161 | const view = layout(); |
| 162 | return [view.ox + x * view.scale, view.oy + (A4H - y) * view.scale]; |
| 163 | } |
| 164 | |
| 165 | function pxToMm (px, py) |
| 166 | { |
| 167 | const view = layout(); |
| 168 | return [(px - view.ox) / view.scale, A4H - (py - view.oy) / view.scale]; |
| 169 | } |
| 170 | |
| 171 | function objPoint (obj, x, y) |
| 172 | { |
| 173 | const scale = obj.scale || 1; |
| 174 | x *= scale; |
| 175 | y *= scale; |
| 176 | const angle = (obj.rotation || 0) * Math.PI / 180; |
| 177 | const ca = Math.cos(angle); |
| 178 | const sa = Math.sin(angle); |
| 179 | return [x * ca - y * sa + obj.x, x * sa + y * ca + obj.y]; |
| 180 | } |
| 181 | |
| 182 | function eachLocal (obj, fn) |
| 183 | { |
| 184 | for (const stroke of obj.strokes || []) |
| 185 | { |
| 186 | for (const point of stroke.pts || stroke) fn(point[0], point[1]); |
| 187 | } |
| 188 | for (const fill of obj.fills || []) |
| 189 | { |
| 190 | for (const ring of fill.rings || []) |
| 191 | { |
| 192 | for (const point of ring) fn(point[0], point[1]); |
| 193 | } |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | function bbox (obj) |
| 198 | { |
| 199 | let minx = Infinity; |
| 200 | let miny = Infinity; |
| 201 | let maxx = -Infinity; |
| 202 | let maxy = -Infinity; |
| 203 | eachLocal(obj, (x, y) => |
| 204 | { |
| 205 | const point = objPoint(obj, x, y); |
| 206 | minx = Math.min(minx, point[0]); |
| 207 | miny = Math.min(miny, point[1]); |
| 208 | maxx = Math.max(maxx, point[0]); |
| 209 | maxy = Math.max(maxy, point[1]); |
| 210 | }); |
| 211 | if (!Number.isFinite(minx)) |
| 212 | { |
| 213 | return { minx: obj.x - 5, miny: obj.y - 5, maxx: obj.x + 5, maxy: obj.y + 5 }; |
| 214 | } |
| 215 | return { minx, miny, maxx, maxy }; |
| 216 | } |
| 217 | |
| 218 | function resize () |
| 219 | { |
| 220 | const rect = canvas.getBoundingClientRect(); |
| 221 | const dpr = window.devicePixelRatio || 1; |
| 222 | canvas.width = Math.max(1, rect.width * dpr); |
| 223 | canvas.height = Math.max(1, rect.height * dpr); |
| 224 | ctx.setTransform(dpr, 0, 0, dpr, 0, 0); |
| 225 | draw(); |
| 226 | } |
| 227 | |
| 228 | function drawSheet (view) |
| 229 | { |
| 230 | const origin = mmToPx(0, 0); |
| 231 | const far = mmToPx(A4W, A4H); |
| 232 | const x = Math.min(origin[0], far[0]); |
| 233 | const y = Math.min(origin[1], far[1]); |
| 234 | const w = Math.abs(far[0] - origin[0]); |
| 235 | const h = Math.abs(far[1] - origin[1]); |
| 236 | ctx.save(); |
| 237 | ctx.fillStyle = "rgba(0,0,0,0.35)"; |
| 238 | ctx.fillRect(x + 8, y + 10, w, h); |
| 239 | ctx.fillStyle = "#f6f1e6"; |
| 240 | ctx.fillRect(x, y, w, h); |
| 241 | ctx.fillStyle = "rgba(70, 52, 36, 0.16)"; |
| 242 | const home = pageFromMachine(0, 0); |
| 243 | fillMmRect(0, 0, home.x, A4H); |
| 244 | fillMmRect(home.x, home.y, A4W, A4H); |
| 245 | ctx.strokeStyle = "rgba(80,60,40,0.18)"; |
| 246 | ctx.lineWidth = 1; |
| 247 | ctx.beginPath(); |
| 248 | for (let i = 10; i < A4W; i += 10) |
| 249 | { |
| 250 | const a = mmToPx(i, 0); |
| 251 | const b = mmToPx(i, A4H); |
| 252 | ctx.moveTo(a[0], a[1]); |
| 253 | ctx.lineTo(b[0], b[1]); |
| 254 | } |
| 255 | for (let i = 10; i < A4H; i += 10) |
| 256 | { |
| 257 | const a = mmToPx(0, i); |
| 258 | const b = mmToPx(A4W, i); |
| 259 | ctx.moveTo(a[0], a[1]); |
| 260 | ctx.lineTo(b[0], b[1]); |
| 261 | } |
| 262 | ctx.stroke(); |
| 263 | ctx.strokeStyle = "#2b241e"; |
| 264 | ctx.lineWidth = 1.5; |
| 265 | ctx.strokeRect(x, y, w, h); |
| 266 | const frameHome = pageFromMachine(0, 0); |
| 267 | const frameFar = pageFromMachine(BED_W, -BED_H); |
| 268 | const frameA = mmToPx(frameHome.x, frameHome.y); |
| 269 | const frameB = mmToPx(frameFar.x, frameFar.y); |
| 270 | ctx.strokeStyle = "#d7263d"; |
| 271 | ctx.lineWidth = 1.5; |
| 272 | ctx.strokeRect( |
| 273 | Math.min(frameA[0], frameB[0]), |
| 274 | Math.min(frameA[1], frameB[1]), |
| 275 | Math.abs(frameB[0] - frameA[0]), |
| 276 | Math.abs(frameB[1] - frameA[1]), |
| 277 | ); |
| 278 | ctx.fillStyle = "#8a7b6c"; |
| 279 | ctx.font = "12px Liberation Sans, sans-serif"; |
| 280 | const originTop = $("origin").value === "top-left"; |
| 281 | const zero = originTop ? mmToPx(frameHome.x, frameHome.y) : mmToPx(0, 0); |
| 282 | ctx.fillText("0,0", zero[0] + 6, zero[1] + (originTop ? 16 : -8)); |
| 283 | ctx.fillText("A4", x + w - 26, y + h - 8); |
| 284 | ctx.restore(); |
| 285 | } |
| 286 | |
| 287 | function fillMmRect (x0, y0, x1, y1) |
| 288 | { |
| 289 | const a = mmToPx(x0, y0); |
| 290 | const b = mmToPx(x1, y1); |
| 291 | ctx.fillRect(Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.abs(b[0] - a[0]), Math.abs(b[1] - a[1])); |
| 292 | } |
| 293 | |
| 294 | function tracePoly (points) |
| 295 | { |
| 296 | if (!points.length) return; |
| 297 | const first = mmToPx(points[0][0], points[0][1]); |
| 298 | ctx.moveTo(first[0], first[1]); |
| 299 | for (let i = 1; i < points.length; i++) |
| 300 | { |
| 301 | const point = mmToPx(points[i][0], points[i][1]); |
| 302 | ctx.lineTo(point[0], point[1]); |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | function drawObject (obj, active) |
| 307 | { |
| 308 | ctx.save(); |
| 309 | ctx.lineWidth = active ? 1.6 : 1.15; |
| 310 | ctx.strokeStyle = "#1d1a17"; |
| 311 | ctx.fillStyle = "rgba(224,122,61,0.13)"; |
| 312 | ctx.lineJoin = "round"; |
| 313 | ctx.lineCap = "round"; |
| 314 | ctx.beginPath(); |
| 315 | for (const fill of obj.fills || []) |
| 316 | { |
| 317 | for (const ring of fill.rings || []) |
| 318 | { |
| 319 | const page = ring.map((point) => objPoint(obj, point[0], point[1])); |
| 320 | tracePoly(page); |
| 321 | ctx.closePath(); |
| 322 | } |
| 323 | } |
| 324 | ctx.fill("evenodd"); |
| 325 | ctx.beginPath(); |
| 326 | for (const stroke of obj.strokes || []) |
| 327 | { |
| 328 | const pts = (stroke.pts || stroke).map((point) => objPoint(obj, point[0], point[1])); |
| 329 | tracePoly(pts); |
| 330 | } |
| 331 | ctx.stroke(); |
| 332 | ctx.restore(); |
| 333 | } |
| 334 | |
| 335 | function drawPreview () |
| 336 | { |
| 337 | ctx.save(); |
| 338 | ctx.lineCap = "round"; |
| 339 | ctx.lineJoin = "round"; |
| 340 | ctx.strokeStyle = "#1d1a17"; |
| 341 | ctx.lineWidth = 1.15; |
| 342 | ctx.beginPath(); |
| 343 | for (const line of preview.draw || []) tracePoly(line); |
| 344 | ctx.stroke(); |
| 345 | if ($("show-travel").checked) |
| 346 | { |
| 347 | ctx.strokeStyle = "rgba(176,122,62,0.85)"; |
| 348 | ctx.setLineDash([4, 4]); |
| 349 | ctx.lineWidth = 1; |
| 350 | ctx.beginPath(); |
| 351 | for (const line of preview.travel || []) tracePoly(line); |
| 352 | ctx.stroke(); |
| 353 | } |
| 354 | ctx.restore(); |
| 355 | } |
| 356 | |
| 357 | function drawHandles (obj) |
| 358 | { |
| 359 | const box = bbox(obj); |
| 360 | const corners = [ |
| 361 | mmToPx(box.minx, box.maxy), |
| 362 | mmToPx(box.maxx, box.maxy), |
| 363 | mmToPx(box.maxx, box.miny), |
| 364 | mmToPx(box.minx, box.miny), |
| 365 | ]; |
| 366 | ctx.save(); |
| 367 | ctx.strokeStyle = "#e07a3d"; |
| 368 | ctx.fillStyle = "#fff"; |
| 369 | ctx.lineWidth = 1.4; |
| 370 | ctx.beginPath(); |
| 371 | corners.forEach((point, index) => index ? ctx.lineTo(point[0], point[1]) : ctx.moveTo(point[0], point[1])); |
| 372 | ctx.closePath(); |
| 373 | ctx.stroke(); |
| 374 | const top = mmToPx((box.minx + box.maxx) / 2, box.maxy); |
| 375 | ctx.beginPath(); |
| 376 | ctx.moveTo(top[0], top[1]); |
| 377 | ctx.lineTo(top[0], top[1] - 22); |
| 378 | ctx.stroke(); |
| 379 | ctx.beginPath(); |
| 380 | ctx.arc(top[0], top[1] - 22, 5, 0, Math.PI * 2); |
| 381 | ctx.fill(); |
| 382 | ctx.stroke(); |
| 383 | for (const point of corners) |
| 384 | { |
| 385 | ctx.fillRect(point[0] - 4, point[1] - 4, 8, 8); |
| 386 | ctx.strokeRect(point[0] - 4, point[1] - 4, 8, 8); |
| 387 | } |
| 388 | ctx.restore(); |
| 389 | } |
| 390 | |
| 391 | function pageFromMachine (x, y) |
| 392 | { |
| 393 | return { x: x - PAPER_LEFT, y: y - PAPER_BOTTOM }; |
| 394 | } |
| 395 | |
| 396 | function drawPen () |
| 397 | { |
| 398 | if (!pen) return; |
| 399 | const point = mmToPx(pen.x, pen.y); |
| 400 | ctx.save(); |
| 401 | ctx.fillStyle = "#d7263d"; |
| 402 | ctx.beginPath(); |
| 403 | ctx.arc(point[0], point[1], 5, 0, Math.PI * 2); |
| 404 | ctx.fill(); |
| 405 | ctx.restore(); |
| 406 | } |
| 407 | |
| 408 | function homePage () |
| 409 | { |
| 410 | const home = pageFromMachine(0, 0); |
| 411 | return [home.x, home.y]; |
| 412 | } |
| 413 | |
| 414 | function showPen (page, speed) |
| 415 | { |
| 416 | penSpeed = speed; |
| 417 | const hit = penRoute && penProject(penRoute, page.x, page.y, penHint); |
| 418 | if (hit && hit.err <= 12) |
| 419 | { |
| 420 | if (penGuide !== penRoute) |
| 421 | { |
| 422 | const back = pen ? penProject(penRoute, pen.x, pen.y, penHint) : hit; |
| 423 | penAlong = back.err <= 12 ? back.along : hit.along; |
| 424 | penGuide = penRoute; |
| 425 | } |
| 426 | penGoal = hit.along; |
| 427 | penHint = hit.along; |
| 428 | return; |
| 429 | } |
| 430 | const from = pen || page; |
| 431 | const length = Math.hypot(page.x - from.x, page.y - from.y); |
| 432 | penGuide = { pts: [[from.x, from.y], [page.x, page.y]], cum: [0, length] }; |
| 433 | penAlong = 0; |
| 434 | penGoal = length; |
| 435 | } |
| 436 | |
| 437 | function ensurePenLoop () |
| 438 | { |
| 439 | if (penFrame) return; |
| 440 | penStamp = 0; |
| 441 | penFrame = requestAnimationFrame(tickPen); |
| 442 | } |
| 443 | |
| 444 | function tickPen (now) |
| 445 | { |
| 446 | if (!penGuide) |
| 447 | { |
| 448 | penFrame = 0; |
| 449 | return; |
| 450 | } |
| 451 | penFrame = requestAnimationFrame(tickPen); |
| 452 | const dt = penStamp ? Math.min(0.05, (now - penStamp) / 1000) : 0; |
| 453 | penStamp = now; |
| 454 | if (Math.abs(penGoal - penAlong) < 0.02) |
| 455 | { |
| 456 | penAlong = penGoal; |
| 457 | const arrived = penAt(penGuide, penAlong); |
| 458 | pen = { x: arrived[0], y: arrived[1] }; |
| 459 | if (!penJob) penGuide = null; |
| 460 | if (!drag) draw(); |
| 461 | return; |
| 462 | } |
| 463 | if (dt <= 0) return; |
| 464 | const next = penStep(penAlong, penGoal, penSpeed, dt); |
| 465 | penAlong = next; |
| 466 | const point = penAt(penGuide, penAlong); |
| 467 | pen = { x: point[0], y: point[1] }; |
| 468 | if (!drag) draw(); |
| 469 | } |
| 470 | |
| 471 | function placePen (page) |
| 472 | { |
| 473 | penJob = false; |
| 474 | penRoute = null; |
| 475 | penDraw = null; |
| 476 | penSpeed = Number($("travel-speed").value) || 5000; |
| 477 | if (!pen) |
| 478 | { |
| 479 | pen = page; |
| 480 | penGuide = null; |
| 481 | return true; |
| 482 | } |
| 483 | const length = Math.hypot(page.x - pen.x, page.y - pen.y); |
| 484 | if (length < 0.05) |
| 485 | { |
| 486 | pen = page; |
| 487 | return false; |
| 488 | } |
| 489 | penGuide = { pts: [[pen.x, pen.y], [page.x, page.y]], cum: [0, length] }; |
| 490 | penAlong = 0; |
| 491 | penGoal = length; |
| 492 | penHint = 0; |
| 493 | ensurePenLoop(); |
| 494 | return true; |
| 495 | } |
| 496 | |
| 497 | function startPenJob (page, speed) |
| 498 | { |
| 499 | penJob = true; |
| 500 | penRoute = penRouteFrom(penDraw || (preview && preview.draw), homePage()); |
| 501 | penGuide = penRoute; |
| 502 | penSpeed = speed; |
| 503 | if (penRoute) |
| 504 | { |
| 505 | const hit = penProject(penRoute, page.x, page.y, 0); |
| 506 | if (hit.err <= 12) |
| 507 | { |
| 508 | penAlong = hit.along; |
| 509 | penGoal = hit.along; |
| 510 | penHint = hit.along; |
| 511 | const point = penAt(penRoute, penAlong); |
| 512 | pen = { x: point[0], y: point[1] }; |
| 513 | } |
| 514 | else |
| 515 | { |
| 516 | penGuide = null; |
| 517 | pen = page; |
| 518 | penAlong = 0; |
| 519 | penGoal = 0; |
| 520 | penHint = 0; |
| 521 | } |
| 522 | } |
| 523 | else |
| 524 | { |
| 525 | pen = page; |
| 526 | penAlong = 0; |
| 527 | penGoal = 0; |
| 528 | penHint = 0; |
| 529 | } |
| 530 | ensurePenLoop(); |
| 531 | } |
| 532 | |
| 533 | function stopPenJob () |
| 534 | { |
| 535 | const was = penJob || pen; |
| 536 | penJob = false; |
| 537 | pen = null; |
| 538 | penRoute = null; |
| 539 | penGuide = null; |
| 540 | penDraw = null; |
| 541 | penAlong = 0; |
| 542 | penGoal = 0; |
| 543 | penHint = 0; |
| 544 | if (penFrame) |
| 545 | { |
| 546 | cancelAnimationFrame(penFrame); |
| 547 | penFrame = 0; |
| 548 | penStamp = 0; |
| 549 | } |
| 550 | if (was && !drag) draw(); |
| 551 | } |
| 552 | |
| 553 | function draw () |
| 554 | { |
| 555 | const view = layout(); |
| 556 | ctx.clearRect(0, 0, view.width, view.height); |
| 557 | drawSheet(view); |
| 558 | const current = selected(); |
| 559 | if (preview && !interacting) drawPreview(); |
| 560 | else objects.forEach((obj) => drawObject(obj, obj === current)); |
| 561 | if (current) drawHandles(current); |
| 562 | drawPen(); |
| 563 | } |
| 564 | |
| 565 | const SETTINGS_KEY = "timdraw-settings"; |
| 566 | |
| 567 | function persist () |
| 568 | { |
| 569 | const state = { |
| 570 | settings: readSettings(), |
| 571 | defaults, |
| 572 | composer: { |
| 573 | text: $("new-text").value, |
| 574 | font: $("new-font").value, |
| 575 | size: Number($("new-size").value), |
| 576 | }, |
| 577 | view: { zoom, panX, panY }, |
| 578 | }; |
| 579 | localStorage.setItem(SETTINGS_KEY, JSON.stringify(state)); |
| 580 | } |
| 581 | |
| 582 | function applySaved (saved) |
| 583 | { |
| 584 | if (!saved) return; |
| 585 | Object.assign(defaults, saved.defaults || {}); |
| 586 | const settings = saved.settings || {}; |
| 587 | if (settings.drawSpeed) $("draw-speed").value = settings.drawSpeed; |
| 588 | if (settings.travelSpeed) $("travel-speed").value = settings.travelSpeed; |
| 589 | if (settings.penUpZ != null) $("pen-up").value = settings.penUpZ; |
| 590 | if (settings.penDownZ != null) $("pen-down").value = settings.penDownZ; |
| 591 | if (settings.dwellMs != null) $("dwell").value = settings.dwellMs; |
| 592 | if (!localStorage.getItem("timdraw-pen-v2")) |
| 593 | { |
| 594 | if (settings.penDownZ == null || Number(settings.penDownZ) === 5) $("pen-down").value = "10"; |
| 595 | if (settings.dwellMs == null || Number(settings.dwellMs) === 120) $("dwell").value = "0"; |
| 596 | localStorage.setItem("timdraw-pen-v2", "1"); |
| 597 | persist(); |
| 598 | } |
| 599 | if (localStorage.getItem("timdraw-origin-v2") && settings.origin) $("origin").value = settings.origin; |
| 600 | else $("origin").value = "top-left"; |
| 601 | localStorage.setItem("timdraw-origin-v2", "1"); |
| 602 | $("per-object").checked = !!settings.perObject; |
| 603 | $("show-travel").checked = !!settings.showTravel; |
| 604 | if (settings.jogStep) $("jog-step").value = String(settings.jogStep); |
| 605 | const composer = saved.composer || {}; |
| 606 | if (composer.text != null) $("new-text").value = composer.text; |
| 607 | if (composer.font) $("new-font").value = composer.font; |
| 608 | if (composer.size) $("new-size").value = composer.size; |
| 609 | const view = saved.view || {}; |
| 610 | if (view.zoom) zoom = view.zoom; |
| 611 | if (view.panX) panX = view.panX; |
| 612 | if (view.panY) panY = view.panY; |
| 613 | } |
| 614 | |
| 615 | function schedulePreview () |
| 616 | { |
| 617 | clearTimeout(schedulePreview.timer); |
| 618 | schedulePreview.timer = setTimeout(refreshPreview, 160); |
| 619 | } |
| 620 | |
| 621 | async function refreshPreview () |
| 622 | { |
| 623 | const gen = ++previewGen; |
| 624 | try |
| 625 | { |
| 626 | const data = await api("/api/preview", { objects, settings: readSettings() }); |
| 627 | if (gen !== previewGen) return; |
| 628 | preview = data; |
| 629 | const stats = data.stats || {}; |
| 630 | const minutes = Math.floor((stats.seconds || 0) / 60); |
| 631 | const seconds = Math.round((stats.seconds || 0) % 60); |
| 632 | $("stats").textContent = objects.length |
| 633 | ? `${stats.drawMm || 0} mm tekenen · ${stats.travelMm || 0} mm reizen · ongeveer ${minutes} min ${seconds} s` |
| 634 | : ""; |
| 635 | if (data.warnings && data.warnings.length) toast(data.warnings[0]); |
| 636 | } catch (error) |
| 637 | { |
| 638 | toast(error.message); |
| 639 | } |
| 640 | draw(); |
| 641 | persist(); |
| 642 | } |
| 643 | |
| 644 | function renderList () |
| 645 | { |
| 646 | const list = $("layers"); |
| 647 | list.innerHTML = ""; |
| 648 | objects.forEach((obj) => |
| 649 | { |
| 650 | const item = document.createElement("li"); |
| 651 | const button = document.createElement("button"); |
| 652 | button.type = "button"; |
| 653 | button.className = obj.id === selectedId ? "active" : ""; |
| 654 | button.innerHTML = `<span>${obj.name || "Object"}</span><span class="tag">${styleLabel(obj)}</span>`; |
| 655 | button.onclick = () => |
| 656 | { |
| 657 | selectedId = obj.id; |
| 658 | renderList(); |
| 659 | fillForm(); |
| 660 | draw(); |
| 661 | }; |
| 662 | item.appendChild(button); |
| 663 | list.appendChild(item); |
| 664 | }); |
| 665 | } |
| 666 | |
| 667 | function fillForm () |
| 668 | { |
| 669 | const obj = selected() || defaults; |
| 670 | filling = true; |
| 671 | $("prop-title").textContent = selected() ? (selected().name || "Object") : "Voor nieuwe objecten"; |
| 672 | const flags = styleFlags(obj); |
| 673 | $("prop-line").checked = flags.drawLine; |
| 674 | $("prop-fill").checked = flags.drawFill; |
| 675 | $("prop-angle").value = obj.hatchAngle; |
| 676 | $("prop-spacing").value = obj.hatchSpacing; |
| 677 | $("prop-percent").value = Math.round(Math.min(100, Math.max(2, (PEN_MM / obj.hatchSpacing) * 100))); |
| 678 | $("prop-cross").checked = !!obj.crosshatch; |
| 679 | $("prop-gray").checked = !!obj.grayscale; |
| 680 | $("prop-steps").value = obj.graySteps; |
| 681 | $("prop-dark").value = obj.spacingMin; |
| 682 | $("prop-light").value = obj.spacingMax; |
| 683 | $("gray-props").hidden = !obj.grayscale; |
| 684 | const isText = selected() && selected().kind === "text"; |
| 685 | $("text-props").hidden = !isText; |
| 686 | if (isText) |
| 687 | { |
| 688 | $("prop-text").value = selected().text || ""; |
| 689 | $("prop-font").value = selected().font || "futural"; |
| 690 | $("prop-size").value = selected().fontSize || 12; |
| 691 | } |
| 692 | filling = false; |
| 693 | } |
| 694 | |
| 695 | function applyForm () |
| 696 | { |
| 697 | if (filling) return; |
| 698 | const values = hatchFromForm(); |
| 699 | const obj = selected(); |
| 700 | if (obj) Object.assign(obj, values); |
| 701 | else Object.assign(defaults, values); |
| 702 | $("gray-props").hidden = !values.grayscale; |
| 703 | renderList(); |
| 704 | schedulePreview(); |
| 705 | } |
| 706 | |
| 707 | function syncPercent (fromPercent) |
| 708 | { |
| 709 | if (filling) return; |
| 710 | if (fromPercent) |
| 711 | { |
| 712 | const percent = Math.min(100, Math.max(2, Number($("prop-percent").value) || 2)); |
| 713 | $("prop-spacing").value = (PEN_MM / (percent / 100)).toFixed(2); |
| 714 | } else |
| 715 | { |
| 716 | const spacing = Math.max(0.3, Number($("prop-spacing").value) || 0.3); |
| 717 | $("prop-percent").value = Math.round(Math.min(100, (PEN_MM / spacing) * 100)); |
| 718 | } |
| 719 | applyForm(); |
| 720 | } |
| 721 | |
| 722 | function addObject (geo, name, extra = {}) |
| 723 | { |
| 724 | const grays = [...new Set((geo.fills || []).map((fill) => Math.round(fill.gray * 20)))]; |
| 725 | const obj = { |
| 726 | id: crypto.randomUUID(), |
| 727 | name, |
| 728 | kind: extra.kind || "svg", |
| 729 | x: geo.x, |
| 730 | y: geo.y, |
| 731 | scale: 1, |
| 732 | rotation: 0, |
| 733 | strokes: geo.strokes || [], |
| 734 | fills: geo.fills || [], |
| 735 | ...defaults, |
| 736 | grayscale: grays.length > 1 || defaults.grayscale, |
| 737 | ...extra, |
| 738 | drawLine: extra.drawLine != null ? extra.drawLine : defaults.drawLine, |
| 739 | drawFill: extra.drawFill != null ? extra.drawFill : (grays.length > 1 || defaults.drawFill), |
| 740 | }; |
| 741 | objects.push(obj); |
| 742 | selectedId = obj.id; |
| 743 | renderList(); |
| 744 | fillForm(); |
| 745 | if (geo.warnings && geo.warnings.length) toast(geo.warnings.join(" ")); |
| 746 | schedulePreview(); |
| 747 | } |
| 748 | |
| 749 | async function importSvgText (svg, name) |
| 750 | { |
| 751 | const geo = await api("/api/svg", { svg, name }); |
| 752 | addObject(geo, geo.name || name || "SVG"); |
| 753 | } |
| 754 | |
| 755 | function cloneSelected (offset) |
| 756 | { |
| 757 | const obj = selected(); |
| 758 | if (!obj) return; |
| 759 | const copy = structuredClone(obj); |
| 760 | copy.id = crypto.randomUUID(); |
| 761 | copy.x += offset; |
| 762 | copy.y += offset; |
| 763 | copy.name = `${obj.name} kopie`; |
| 764 | objects.push(copy); |
| 765 | selectedId = copy.id; |
| 766 | renderList(); |
| 767 | fillForm(); |
| 768 | schedulePreview(); |
| 769 | } |
| 770 | |
| 771 | async function rebuildText (obj) |
| 772 | { |
| 773 | const geo = await api("/api/text", { |
| 774 | text: obj.text, |
| 775 | font: obj.font, |
| 776 | fontSize: obj.fontSize, |
| 777 | lineSpacing: 1.4, |
| 778 | }); |
| 779 | obj.strokes = geo.strokes; |
| 780 | obj.fills = geo.fills; |
| 781 | schedulePreview(); |
| 782 | draw(); |
| 783 | } |
| 784 | |
| 785 | function handleAt (px, py) |
| 786 | { |
| 787 | const obj = selected(); |
| 788 | if (!obj) return null; |
| 789 | const box = bbox(obj); |
| 790 | const corners = { |
| 791 | nw: mmToPx(box.minx, box.maxy), |
| 792 | ne: mmToPx(box.maxx, box.maxy), |
| 793 | se: mmToPx(box.maxx, box.miny), |
| 794 | sw: mmToPx(box.minx, box.miny), |
| 795 | }; |
| 796 | const top = mmToPx((box.minx + box.maxx) / 2, box.maxy); |
| 797 | if (Math.hypot(top[0] - px, top[1] - 22 - py) < 9) return "rot"; |
| 798 | for (const [name, point] of Object.entries(corners)) |
| 799 | { |
| 800 | if (Math.hypot(point[0] - px, point[1] - py) < 9) return name; |
| 801 | } |
| 802 | return null; |
| 803 | } |
| 804 | |
| 805 | function hitObject (x, y) |
| 806 | { |
| 807 | const view = layout(); |
| 808 | const pad = 5 / view.scale; |
| 809 | for (let i = objects.length - 1; i >= 0; i--) |
| 810 | { |
| 811 | const box = bbox(objects[i]); |
| 812 | if (x >= box.minx - pad && x <= box.maxx + pad && y >= box.miny - pad && y <= box.maxy + pad) return objects[i]; |
| 813 | } |
| 814 | return null; |
| 815 | } |
| 816 | |
| 817 | let drag = null; |
| 818 | |
| 819 | canvas.addEventListener("pointerdown", (event) => |
| 820 | { |
| 821 | if (event.button === 1 || event.altKey) |
| 822 | { |
| 823 | drag = { type: "pan", x: event.clientX, y: event.clientY, panX, panY }; |
| 824 | canvas.setPointerCapture(event.pointerId); |
| 825 | return; |
| 826 | } |
| 827 | const rect = canvas.getBoundingClientRect(); |
| 828 | const px = event.clientX - rect.left; |
| 829 | const py = event.clientY - rect.top; |
| 830 | const handle = handleAt(px, py); |
| 831 | const [x, y] = pxToMm(px, py); |
| 832 | const obj = selected(); |
| 833 | if (handle && obj) |
| 834 | { |
| 835 | const box = bbox(obj); |
| 836 | const cx = (box.minx + box.maxx) / 2; |
| 837 | const cy = (box.miny + box.maxy) / 2; |
| 838 | drag = { |
| 839 | type: handle === "rot" ? "rot" : "scale", |
| 840 | id: obj.id, |
| 841 | cx, cy, |
| 842 | startAngle: Math.atan2(y - cy, x - cx), |
| 843 | startRot: obj.rotation || 0, |
| 844 | startDist: Math.hypot(x - cx, y - cy) || 1, |
| 845 | startScale: obj.scale || 1, |
| 846 | }; |
| 847 | } else |
| 848 | { |
| 849 | const hit = hitObject(x, y); |
| 850 | selectedId = hit ? hit.id : null; |
| 851 | renderList(); |
| 852 | fillForm(); |
| 853 | if (hit) drag = { type: "move", id: hit.id, x, y, ox: hit.x, oy: hit.y }; |
| 854 | } |
| 855 | interacting = !!drag; |
| 856 | canvas.setPointerCapture(event.pointerId); |
| 857 | draw(); |
| 858 | }); |
| 859 | |
| 860 | canvas.addEventListener("pointermove", (event) => |
| 861 | { |
| 862 | if (!drag) return; |
| 863 | if (drag.type === "pan") |
| 864 | { |
| 865 | panX = drag.panX + (event.clientX - drag.x); |
| 866 | panY = drag.panY + (event.clientY - drag.y); |
| 867 | draw(); |
| 868 | return; |
| 869 | } |
| 870 | const rect = canvas.getBoundingClientRect(); |
| 871 | const [x, y] = pxToMm(event.clientX - rect.left, event.clientY - rect.top); |
| 872 | const obj = objects.find((item) => item.id === drag.id); |
| 873 | if (!obj) return; |
| 874 | if (drag.type === "move") |
| 875 | { |
| 876 | obj.x = drag.ox + (x - drag.x); |
| 877 | obj.y = drag.oy + (y - drag.y); |
| 878 | } else if (drag.type === "scale") |
| 879 | { |
| 880 | const dist = Math.hypot(x - drag.cx, y - drag.cy); |
| 881 | obj.scale = Math.max(0.05, Math.min(20, drag.startScale * (dist / drag.startDist))); |
| 882 | } else if (drag.type === "rot") |
| 883 | { |
| 884 | const angle = Math.atan2(y - drag.cy, x - drag.cx); |
| 885 | obj.rotation = Math.round(drag.startRot + (angle - drag.startAngle) * 180 / Math.PI); |
| 886 | } |
| 887 | draw(); |
| 888 | }); |
| 889 | |
| 890 | function endDrag () |
| 891 | { |
| 892 | if (drag && drag.type !== "pan") schedulePreview(); |
| 893 | else if (drag && drag.type === "pan") persist(); |
| 894 | drag = null; |
| 895 | interacting = false; |
| 896 | } |
| 897 | |
| 898 | canvas.addEventListener("pointerup", endDrag); |
| 899 | canvas.addEventListener("pointercancel", endDrag); |
| 900 | canvas.addEventListener("wheel", (event) => |
| 901 | { |
| 902 | event.preventDefault(); |
| 903 | zoom = Math.max(0.35, Math.min(8, zoom * (event.deltaY < 0 ? 1.08 : 0.92))); |
| 904 | draw(); |
| 905 | persist(); |
| 906 | }, { passive: false }); |
| 907 | |
| 908 | window.addEventListener("keydown", (event) => |
| 909 | { |
| 910 | const typing = ["INPUT", "TEXTAREA", "SELECT"].includes(event.target.tagName); |
| 911 | if ((event.key === "Delete" || event.key === "Backspace") && !typing) |
| 912 | { |
| 913 | objects = objects.filter((obj) => obj.id !== selectedId); |
| 914 | selectedId = null; |
| 915 | renderList(); |
| 916 | fillForm(); |
| 917 | schedulePreview(); |
| 918 | } else if (event.key === "Escape") |
| 919 | { |
| 920 | selectedId = null; |
| 921 | renderList(); |
| 922 | fillForm(); |
| 923 | draw(); |
| 924 | } else if (!typing && (event.key.startsWith("Arrow"))) |
| 925 | { |
| 926 | const obj = selected(); |
| 927 | if (!obj) return; |
| 928 | const step = event.shiftKey ? 0.1 : 1; |
| 929 | if (event.key === "ArrowLeft") obj.x -= step; |
| 930 | if (event.key === "ArrowRight") obj.x += step; |
| 931 | if (event.key === "ArrowUp") obj.y += step; |
| 932 | if (event.key === "ArrowDown") obj.y -= step; |
| 933 | event.preventDefault(); |
| 934 | schedulePreview(); |
| 935 | draw(); |
| 936 | } else if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "c" && !typing) |
| 937 | { |
| 938 | clipboard = selected() ? structuredClone(selected()) : clipboard; |
| 939 | } else if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "v" && !typing) |
| 940 | { |
| 941 | if (!clipboard) return; |
| 942 | const copy = structuredClone(clipboard); |
| 943 | copy.id = crypto.randomUUID(); |
| 944 | copy.x += 8; |
| 945 | copy.y += 8; |
| 946 | objects.push(copy); |
| 947 | selectedId = copy.id; |
| 948 | renderList(); |
| 949 | fillForm(); |
| 950 | schedulePreview(); |
| 951 | } else if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "d" && !typing) |
| 952 | { |
| 953 | event.preventDefault(); |
| 954 | cloneSelected(8); |
| 955 | } |
| 956 | }); |
| 957 | |
| 958 | document.querySelectorAll('#prop-angle,#prop-steps,#prop-dark,#prop-light').forEach((el) => el.addEventListener("input", applyForm)); |
| 959 | $("prop-spacing").addEventListener("input", () => syncPercent(false)); |
| 960 | $("prop-percent").addEventListener("input", () => syncPercent(true)); |
| 961 | $("prop-cross").addEventListener("change", applyForm); |
| 962 | $("prop-gray").addEventListener("change", applyForm); |
| 963 | $("prop-line").addEventListener("change", applyForm); |
| 964 | $("prop-fill").addEventListener("change", applyForm); |
| 965 | |
| 966 | function queueTextRebuild () |
| 967 | { |
| 968 | const obj = selected(); |
| 969 | if (!obj || obj.kind !== "text" || filling) return; |
| 970 | obj.text = $("prop-text").value; |
| 971 | obj.font = $("prop-font").value; |
| 972 | obj.fontSize = Number($("prop-size").value); |
| 973 | obj.name = (obj.text || "Tekst").split("\n")[0].slice(0, 28) || "Tekst"; |
| 974 | clearTimeout(textTimer); |
| 975 | textTimer = setTimeout(() => rebuildText(obj).catch((error) => toast(error.message)), 180); |
| 976 | renderList(); |
| 977 | } |
| 978 | $("prop-text").addEventListener("input", queueTextRebuild); |
| 979 | $("prop-font").addEventListener("change", queueTextRebuild); |
| 980 | $("prop-size").addEventListener("input", queueTextRebuild); |
| 981 | |
| 982 | $("btn-import").onclick = () => $("file").click(); |
| 983 | $("btn-open").onclick = () => $("open-file").click(); |
| 984 | $("btn-save").onclick = saveSheet; |
| 985 | $("file").onchange = async () => |
| 986 | { |
| 987 | const file = $("file").files[0]; |
| 988 | $("file").value = ""; |
| 989 | if (!file) return; |
| 990 | try |
| 991 | { |
| 992 | await importSvgText(await file.text(), file.name); |
| 993 | } catch (error) |
| 994 | { |
| 995 | toast(error.message); |
| 996 | } |
| 997 | }; |
| 998 | |
| 999 | function saveSheet () |
| 1000 | { |
| 1001 | const payload = { format: "timdraw", version: 1, objects }; |
| 1002 | const blob = new Blob([JSON.stringify(payload)], { type: "application/json" }); |
| 1003 | const link = document.createElement("a"); |
| 1004 | const raw = (objects[0] && objects[0].name) || "tekening"; |
| 1005 | link.href = URL.createObjectURL(blob); |
| 1006 | link.download = `${raw.replace(/[^\w.-]+/g, "_").slice(0, 40) || "tekening"}.tdrw`; |
| 1007 | link.click(); |
| 1008 | setTimeout(() => URL.revokeObjectURL(link.href), 1000); |
| 1009 | } |
| 1010 | |
| 1011 | function loadSheet (data) |
| 1012 | { |
| 1013 | if (!data || data.format !== "timdraw" || !Array.isArray(data.objects)) |
| 1014 | throw new Error("Dit is geen Timdraw-bestand."); |
| 1015 | objects = data.objects.map((obj) => ({ ...obj, id: obj.id || crypto.randomUUID() })); |
| 1016 | selectedId = null; |
| 1017 | clipboard = null; |
| 1018 | renderList(); |
| 1019 | fillForm(); |
| 1020 | schedulePreview(); |
| 1021 | } |
| 1022 | |
| 1023 | $("open-file").onchange = async () => |
| 1024 | { |
| 1025 | const file = $("open-file").files[0]; |
| 1026 | $("open-file").value = ""; |
| 1027 | if (!file) return; |
| 1028 | try |
| 1029 | { |
| 1030 | loadSheet(JSON.parse(await file.text())); |
| 1031 | } catch (error) |
| 1032 | { |
| 1033 | toast(error instanceof SyntaxError ? "Dit is geen Timdraw-bestand." : error.message); |
| 1034 | } |
| 1035 | }; |
| 1036 | |
| 1037 | $("demos").onchange = async () => |
| 1038 | { |
| 1039 | const name = $("demos").value; |
| 1040 | if (!name) return; |
| 1041 | try |
| 1042 | { |
| 1043 | const response = await fetch("/api/demos/" + encodeURIComponent(name)); |
| 1044 | if (!response.ok) throw new Error("Voorbeeld niet gevonden"); |
| 1045 | await importSvgText(await response.text(), name); |
| 1046 | } catch (error) |
| 1047 | { |
| 1048 | toast(error.message); |
| 1049 | } |
| 1050 | $("demos").value = ""; |
| 1051 | }; |
| 1052 | |
| 1053 | $("btn-text").onclick = async () => |
| 1054 | { |
| 1055 | try |
| 1056 | { |
| 1057 | const text = $("new-text").value || "Timdraw"; |
| 1058 | const font = $("new-font").value; |
| 1059 | const fontSize = Number($("new-size").value) || 12; |
| 1060 | const geo = await api("/api/text", { text, font, fontSize, lineSpacing: 1.4 }); |
| 1061 | addObject(geo, text.split("\n")[0].slice(0, 28) || "Tekst", { |
| 1062 | kind: "text", text, font, fontSize, lineSpacing: 1.4, drawLine: true, drawFill: false, grayscale: false, |
| 1063 | }); |
| 1064 | } catch (error) |
| 1065 | { |
| 1066 | toast(error.message); |
| 1067 | } |
| 1068 | }; |
| 1069 | |
| 1070 | $("btn-copy").onclick = () => { clipboard = selected() ? structuredClone(selected()) : clipboard; }; |
| 1071 | $("btn-paste").onclick = () => |
| 1072 | { |
| 1073 | if (!clipboard) return; |
| 1074 | const copy = structuredClone(clipboard); |
| 1075 | copy.id = crypto.randomUUID(); |
| 1076 | copy.x += 8; |
| 1077 | copy.y += 8; |
| 1078 | objects.push(copy); |
| 1079 | selectedId = copy.id; |
| 1080 | renderList(); |
| 1081 | fillForm(); |
| 1082 | schedulePreview(); |
| 1083 | }; |
| 1084 | $("btn-dup").onclick = () => cloneSelected(8); |
| 1085 | $("btn-delete").onclick = () => |
| 1086 | { |
| 1087 | objects = objects.filter((obj) => obj.id !== selectedId); |
| 1088 | selectedId = null; |
| 1089 | renderList(); |
| 1090 | fillForm(); |
| 1091 | schedulePreview(); |
| 1092 | }; |
| 1093 | $("btn-front").onclick = () => moveLayer(1); |
| 1094 | $("btn-back").onclick = () => moveLayer(-1); |
| 1095 | |
| 1096 | function moveLayer (dir) |
| 1097 | { |
| 1098 | const index = objects.findIndex((obj) => obj.id === selectedId); |
| 1099 | const next = index + dir; |
| 1100 | if (index < 0 || next < 0 || next >= objects.length) return; |
| 1101 | const [item] = objects.splice(index, 1); |
| 1102 | objects.splice(next, 0, item); |
| 1103 | renderList(); |
| 1104 | schedulePreview(); |
| 1105 | } |
| 1106 | |
| 1107 | $("btn-fit").onclick = () => { zoom = 1; panX = 0; panY = 0; draw(); persist(); }; |
| 1108 | $("show-travel").onchange = () => { draw(); persist(); }; |
| 1109 | $("per-object").addEventListener("change", schedulePreview); |
| 1110 | $("jog-step").addEventListener("change", persist); |
| 1111 | $("new-text").addEventListener("input", persist); |
| 1112 | $("new-font").addEventListener("change", persist); |
| 1113 | $("new-size").addEventListener("change", persist); |
| 1114 | |
| 1115 | ["draw-speed", "travel-speed", "pen-up", "pen-down", "dwell", "origin"].forEach((id) => |
| 1116 | { |
| 1117 | $(id).addEventListener("change", schedulePreview); |
| 1118 | }); |
| 1119 | |
| 1120 | async function machineCall (path, body, confirmText) |
| 1121 | { |
| 1122 | if (confirmText && !confirm(confirmText)) return; |
| 1123 | try |
| 1124 | { |
| 1125 | toast(""); |
| 1126 | const result = await api(path, body || {}); |
| 1127 | if (result && result.wpos) paintStatus(result); |
| 1128 | if (result && result.notice) toast(result.notice, 5000); |
| 1129 | } catch (error) |
| 1130 | { |
| 1131 | toast(error.message); |
| 1132 | $("machine-error").hidden = false; |
| 1133 | $("machine-error").textContent = error.message; |
| 1134 | } |
| 1135 | } |
| 1136 | |
| 1137 | $("btn-connect").onclick = () => |
| 1138 | { |
| 1139 | if ($("btn-connect").dataset.on === "1") |
| 1140 | { |
| 1141 | userDisconnected = true; |
| 1142 | machineCall("/api/disconnect"); |
| 1143 | } |
| 1144 | else |
| 1145 | { |
| 1146 | userDisconnected = false; |
| 1147 | autoTried = ""; |
| 1148 | machineCall("/api/connect", { port: $("port").value }); |
| 1149 | } |
| 1150 | }; |
| 1151 | document.querySelectorAll(".jog button").forEach((button) => |
| 1152 | { |
| 1153 | button.onclick = () => |
| 1154 | { |
| 1155 | const step = Number($("jog-step").value); |
| 1156 | machineCall("/api/jog", { |
| 1157 | x: Number(button.dataset.x) * step, |
| 1158 | y: Number(button.dataset.y) * step, |
| 1159 | feed: Number($("travel-speed").value), |
| 1160 | origin: $("origin").value, |
| 1161 | }); |
| 1162 | }; |
| 1163 | }); |
| 1164 | $("btn-pen-up").onclick = () => machineCall("/api/pen", { down: false, ...readSettings() }); |
| 1165 | $("btn-pen-down").onclick = () => machineCall("/api/pen", { down: true, ...readSettings() }); |
| 1166 | $("btn-unlock").onclick = () => machineCall("/api/unlock"); |
| 1167 | $("btn-home").onclick = () => machineCall("/api/home", {}, "Homen beweegt naar de eindschakelaars. Doorgaan?"); |
| 1168 | $("btn-release").onclick = () => machineCall("/api/release"); |
| 1169 | async function rememberPath (trace) |
| 1170 | { |
| 1171 | const settings = readSettings(); |
| 1172 | if (trace) settings.trace = true; |
| 1173 | try |
| 1174 | { |
| 1175 | const planned = await api("/api/preview", { objects, settings }); |
| 1176 | penDraw = planned.draw || []; |
| 1177 | } |
| 1178 | catch |
| 1179 | { |
| 1180 | penDraw = (preview && preview.draw) || []; |
| 1181 | } |
| 1182 | } |
| 1183 | |
| 1184 | $("btn-plot").onclick = async () => |
| 1185 | { |
| 1186 | await rememberPath(false); |
| 1187 | machineCall("/api/plot", { objects, settings: readSettings() }); |
| 1188 | }; |
| 1189 | $("btn-trace").onclick = async () => |
| 1190 | { |
| 1191 | await rememberPath(true); |
| 1192 | machineCall("/api/trace", { objects, settings: readSettings() }); |
| 1193 | }; |
| 1194 | $("btn-pause").onclick = async () => |
| 1195 | { |
| 1196 | const path = $("btn-pause").dataset.paused === "1" ? "/api/resume" : "/api/pause"; |
| 1197 | machineCall(path); |
| 1198 | }; |
| 1199 | $("btn-stop").onclick = () => machineCall("/api/stop"); |
| 1200 | let connectOpen = false; |
| 1201 | |
| 1202 | $("machine-name").onclick = () => |
| 1203 | { |
| 1204 | connectOpen = true; |
| 1205 | syncConnectModal(); |
| 1206 | }; |
| 1207 | |
| 1208 | $("connect-close").onclick = () => |
| 1209 | { |
| 1210 | if ($("btn-connect").dataset.on !== "1") return; |
| 1211 | connectOpen = false; |
| 1212 | syncConnectModal(); |
| 1213 | }; |
| 1214 | |
| 1215 | $("connect-modal").addEventListener("cancel", (event) => |
| 1216 | { |
| 1217 | if ($("btn-connect").dataset.on !== "1") |
| 1218 | { |
| 1219 | event.preventDefault(); |
| 1220 | return; |
| 1221 | } |
| 1222 | connectOpen = false; |
| 1223 | }); |
| 1224 | |
| 1225 | $("connect-modal").addEventListener("click", (event) => |
| 1226 | { |
| 1227 | if (event.target !== $("connect-modal") || $("btn-connect").dataset.on !== "1") return; |
| 1228 | connectOpen = false; |
| 1229 | syncConnectModal(); |
| 1230 | }); |
| 1231 | |
| 1232 | function syncConnectModal () |
| 1233 | { |
| 1234 | const modal = $("connect-modal"); |
| 1235 | const connected = $("btn-connect").dataset.on === "1"; |
| 1236 | $("connect-close").hidden = !connected; |
| 1237 | const show = !connected || connectOpen; |
| 1238 | if (show && !modal.open) modal.showModal(); |
| 1239 | if (!show && modal.open) modal.close(); |
| 1240 | } |
| 1241 | |
| 1242 | function paintStatus (status) |
| 1243 | { |
| 1244 | const lamp = $("lamp"); |
| 1245 | const state = (status.state || "").toLowerCase(); |
| 1246 | lamp.className = "lamp"; |
| 1247 | if (!status.connected) lamp.classList.add("bad"); |
| 1248 | else if (state.startsWith("run") || state.startsWith("hold") || status.jobActive) lamp.classList.add("busy"); |
| 1249 | else if (state.startsWith("alarm")) lamp.classList.add("bad"); |
| 1250 | else lamp.classList.add("on"); |
| 1251 | $("machine-state").textContent = status.connecting |
| 1252 | ? "Verbinden…" |
| 1253 | : (status.connected ? (status.state || "Verbonden") : "Niet verbonden"); |
| 1254 | $("firmware").textContent = status.firmware || ""; |
| 1255 | $("btn-connect").textContent = status.connected ? "Verbreek" : (status.connecting ? "Verbinden…" : "Verbinden"); |
| 1256 | $("btn-connect").dataset.on = status.connected ? "1" : "0"; |
| 1257 | if (!status.connected) connectOpen = false; |
| 1258 | syncConnectModal(); |
| 1259 | if (status.localUrl) |
| 1260 | { |
| 1261 | $("local-url").href = status.localUrl; |
| 1262 | $("local-url").textContent = status.localUrl.replace(/^https?:\/\//, "").replace(/\/$/, ""); |
| 1263 | } |
| 1264 | $("btn-pause").textContent = status.jobPaused ? "Verder" : "Pauze"; |
| 1265 | $("btn-pause").dataset.paused = status.jobPaused ? "1" : "0"; |
| 1266 | const w = status.wpos || [0, 0, 0]; |
| 1267 | $("position").textContent = status.connected |
| 1268 | ? `X ${w[0].toFixed(2)} Y ${w[1].toFixed(2)} Z ${w[2].toFixed(2)}` |
| 1269 | : "X — Y — Z —"; |
| 1270 | if (status.error) |
| 1271 | { |
| 1272 | $("machine-error").hidden = false; |
| 1273 | $("machine-error").textContent = status.error; |
| 1274 | } else if (status.connected) |
| 1275 | { |
| 1276 | $("machine-error").hidden = true; |
| 1277 | } |
| 1278 | if (!drag) |
| 1279 | { |
| 1280 | const ports = status.ports || []; |
| 1281 | const current = $("port").value; |
| 1282 | const remembered = status.lastPort || localStorage.getItem(PORT_KEY) || ""; |
| 1283 | const preferred = (status.connected && status.port) || remembered; |
| 1284 | if ($("port").dataset.list !== ports.join(",")) |
| 1285 | { |
| 1286 | $("port").innerHTML = ports.map((port) => `<option value="${port}">${portLabel(port)}</option>`).join("") |
| 1287 | || "<option value=''>—</option>"; |
| 1288 | if (current && ports.includes(current)) $("port").value = current; |
| 1289 | else if (preferred && ports.includes(preferred)) $("port").value = preferred; |
| 1290 | else if (status.port && ports.includes(status.port)) $("port").value = status.port; |
| 1291 | $("port").dataset.list = ports.join(","); |
| 1292 | } |
| 1293 | if (status.connected && status.port) localStorage.setItem(PORT_KEY, status.port); |
| 1294 | } |
| 1295 | const progress = status.jobActive ? (status.progress || 0) : (status.progress === 1 ? 1 : 0); |
| 1296 | $("bar").style.width = `${Math.round((progress || 0) * 100)}%`; |
| 1297 | if (status.connected && status.wpos) |
| 1298 | { |
| 1299 | const xy = !status.jobActive && status.target ? status.target : status.wpos; |
| 1300 | const page = pageFromMachine(xy[0], xy[1]); |
| 1301 | if (status.jobActive) |
| 1302 | { |
| 1303 | const down = Number($("pen-down").value); |
| 1304 | const up = Number($("pen-up").value); |
| 1305 | const drawing = Math.abs(status.wpos[2] - down) <= Math.abs(status.wpos[2] - up); |
| 1306 | const speed = drawing ? Number($("draw-speed").value) : Number($("travel-speed").value); |
| 1307 | if (!penJob) startPenJob(page, speed); |
| 1308 | else showPen(page, speed); |
| 1309 | if (!drag) draw(); |
| 1310 | } |
| 1311 | else if (placePen(page) && !drag) |
| 1312 | { |
| 1313 | draw(); |
| 1314 | } |
| 1315 | } |
| 1316 | else if (penJob || pen) |
| 1317 | { |
| 1318 | stopPenJob(); |
| 1319 | } |
| 1320 | if (status.message && status.jobActive) toast(status.message); |
| 1321 | } |
| 1322 | |
| 1323 | function portLabel (port) |
| 1324 | { |
| 1325 | return String(port).split("/").pop() |
| 1326 | .replace(/^usb-/, "") |
| 1327 | .replace(/-if\d+-port\d+$/, "") |
| 1328 | .replaceAll("_", " "); |
| 1329 | } |
| 1330 | |
| 1331 | async function maybeAutoConnect (status) |
| 1332 | { |
| 1333 | if (userDisconnected || status.connected || status.connecting) return; |
| 1334 | const port = status.lastPort || localStorage.getItem(PORT_KEY) || ""; |
| 1335 | if (!port || !(status.ports || []).includes(port) || autoTried === port) return; |
| 1336 | autoTried = port; |
| 1337 | try |
| 1338 | { |
| 1339 | await api("/api/connect", { port }); |
| 1340 | } catch (error) |
| 1341 | { |
| 1342 | toast(error.message); |
| 1343 | $("machine-error").hidden = false; |
| 1344 | $("machine-error").textContent = error.message; |
| 1345 | } |
| 1346 | } |
| 1347 | |
| 1348 | async function poll () |
| 1349 | { |
| 1350 | try |
| 1351 | { |
| 1352 | const status = await api("/api/status"); |
| 1353 | paintStatus(status); |
| 1354 | await maybeAutoConnect(status); |
| 1355 | } catch (error) |
| 1356 | { |
| 1357 | $("machine-error").hidden = false; |
| 1358 | $("machine-error").textContent = error.message; |
| 1359 | } |
| 1360 | } |
| 1361 | |
| 1362 | async function boot () |
| 1363 | { |
| 1364 | try |
| 1365 | { |
| 1366 | const saved = JSON.parse(localStorage.getItem(SETTINGS_KEY) || "null") |
| 1367 | || JSON.parse(localStorage.getItem("timdraw-doc") || "null"); |
| 1368 | applySaved(saved); |
| 1369 | } catch { /* lege start */ } |
| 1370 | fillForm(); |
| 1371 | renderList(); |
| 1372 | resize(); |
| 1373 | schedulePreview(); |
| 1374 | try |
| 1375 | { |
| 1376 | const demos = await api("/api/demos"); |
| 1377 | for (const name of demos.demos || []) |
| 1378 | { |
| 1379 | const option = document.createElement("option"); |
| 1380 | option.value = name; |
| 1381 | option.textContent = name; |
| 1382 | $("demos").appendChild(option); |
| 1383 | } |
| 1384 | } catch { /* geen demomap */ } |
| 1385 | poll(); |
| 1386 | setInterval(poll, 700); |
| 1387 | } |
| 1388 | |
| 1389 | window.addEventListener("resize", resize); |
| 1390 | boot(); |