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