azulejeria 1.1.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +33 -3
  2. package/package.json +1 -1
  3. package/src/azulejeria.js +272 -166
package/README.md CHANGED
@@ -15,8 +15,12 @@ presets, and, if the tile is not glazed, a material. Three walls built on
15
15
  it: [Azulejería](https://stepinto.dev/art/azulejeria.html) (Talavera
16
16
  rosettes and Mudéjar strapwork), [Jerez](https://stepinto.dev/art/jerez.html)
17
17
  (vines, horses and sherry) and [Hidráulico](https://stepinto.dev/art/hidraulico.html)
18
- (pigmented cement, pressed rather than painted). The design is written up
19
- [here](https://stepinto.dev/posts/tiles-painted-by-rule/).
18
+ (pigmented cement, pressed rather than painted). Underneath the wall is a
19
+ viewer, a canvas you paint any world into, with the drag, the pinch, the
20
+ wheel and the page chrome; [Alicatado](https://stepinto.dev/art/alicatado.html)
21
+ (cut tile set in lime) is the viewer with its own paint. The design is
22
+ written up [here](https://stepinto.dev/posts/tiles-painted-by-rule/) and
23
+ [here](https://stepinto.dev/posts/cut-tile-and-poured-cement/).
20
24
 
21
25
  ```
22
26
  npm install azulejeria
@@ -105,7 +109,8 @@ W, H, state, pal)` is drawn over the whole wall last. None of the hooks
105
109
  read the design's rng, so a material never moves a design.
106
110
 
107
111
  **`mountPanel(wall, { fileName, defaultPreset })`** wires the standard
108
- panel, which is a handful of elements found by id: selects `repeat`,
112
+ panel for a wall. It is `mountChrome` (below) with the wall's controls,
113
+ which are a handful of elements found by id: selects `repeat`,
109
114
  `motif` and `palette`; ranges `density`, `hand`, `brush` and `zoom` with
110
115
  `densityVal`, `handVal`, `brushVal` and `zoomVal` spans beside them;
111
116
  checkboxes `bands`, `grout` and `age`; buttons `newDesign` and `save`;
@@ -117,6 +122,31 @@ reads the query string, so `?preset=talavera` or
117
122
  `?seed=4242&repeat=rotate&pal=talavera&motif=rosette&density=5&age=1` is a
118
123
  shareable wall. Copy the markup from either of the two pages above.
119
124
 
125
+ **`createViewer(canvas, { paint, scale, minZoom, maxZoom, margin })`**
126
+ is what a wall is built on, and what any other world can be. `paint(g,
127
+ state, w, h, dpr, ox, oy)` paints the world into `g`, `w` by `h` css
128
+ pixels at `dpr`, with the world's origin at `(ox, oy)`. The viewer fills
129
+ the window, pans on drag, zooms on pinch or wheel, and calls
130
+ `onDoubleTap()` on a double tap. With a `margin` it paints into a buffer
131
+ that much larger than the window and only blits while you drag, which is
132
+ what a slow paint wants. `viewer.state` has `scale`, `panX` and `panY`;
133
+ add your own fields to it. Call `viewer.repaint()` when the world
134
+ changes and `viewer.moved()` when only the pan did.
135
+
136
+ **`mountChrome(viewer, spec)`** wires the same chrome around any viewer:
137
+ the panel, the tabs, the preset cards, the title that fades, the save
138
+ button, the query string. The spec names the presets, `applyPreset(name)`,
139
+ `thumb(ctx, settings)` to paint a card, and the `controls`: a list of
140
+ `{ id, key, q, kind, fmt, valId, keep, change }`, where `kind` is
141
+ `select`, `range` or `check`, `key` is the field of `viewer.state` (the
142
+ id by default), `q` its name in the query string (the key by default),
143
+ `fmt` renders a range's value beside it, `keep` leaves the preset marked
144
+ when the query string sets it, and `change(value)` is what to do after.
145
+ Then `newId` and `onNew` for the button that starts over, `mood(state)`
146
+ for the line under it, `query(q)` for anything else in the query string,
147
+ `fileName` and `suffix(state)` for the saved png, and `ready()` once
148
+ everything is applied. Alicatado is the worked example.
149
+
120
150
  **`azulejeria.css`** styles that markup. Colour it with the custom
121
151
  properties at the top of the file: `--az-bg`, `--az-title`,
122
152
  `--az-whisper`, `--az-hint`, `--az-glow`, `--az-glow-far`, `--az-panel`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "azulejeria",
3
- "version": "1.1.0",
3
+ "version": "2.0.0",
4
4
  "description": "Tin-glazed tiles painted by rule. A seeded canvas engine for Spanish azulejo walls: a diagonal-symmetric design, brushwork that drifts, washes that pool, and four ways to repeat the tile.",
5
5
  "keywords": ["canvas", "generative", "tiles", "azulejo", "mudejar", "sevilla", "pattern", "procedural", "art", "wallpaper"],
6
6
  "license": "MIT",
package/src/azulejeria.js CHANGED
@@ -9,10 +9,12 @@
9
9
  // This module is the engine: the seeded random, the brushwork (every
10
10
  // line a polyline with a slow wobble along its normal, washes laid
11
11
  // thin twice so the glaze pools), the tile (mottled glaze, the design
12
- // laid once or four times), the wall (tiles repeated with a symmetry,
13
- // each turned and shifted a little, some crazed) and the standard
14
- // control panel. Motifs, palettes and presets belong to the page that
15
- // uses it. See README.md for the shape of each.
12
+ // laid once or four times), the viewer (a canvas you paint a world
13
+ // into, with drag, pinch, wheel and the double tap), the wall (a
14
+ // viewer painting tiles repeated with a symmetry, each turned and
15
+ // shifted a little, some crazed) and the standard chrome. Motifs,
16
+ // palettes and presets belong to the page that uses it. See README.md
17
+ // for the shape of each.
16
18
  //
17
19
  // A material, optionally, changes what the tile is made of without
18
20
  // touching what is drawn on it: how the ground is laid, how a shape
@@ -342,10 +344,133 @@ export function paintThumb(cfg, p, g, T, k) {
342
344
  }
343
345
  }
344
346
 
347
+ // ------------------------------------------------------------- viewer ---
348
+ // createViewer(canvas, { paint, scale, minZoom, maxZoom, margin }) is
349
+ // a canvas you paint a world into. It fills the window, and handles
350
+ // drag, pinch, wheel and the double tap. `paint(g, state, w, h, dpr,
351
+ // ox, oy)` paints the world into g, w by h css pixels at dpr, with
352
+ // the world's origin at (ox, oy). With a `margin` the world is painted
353
+ // into a buffer that much larger than the window and only blitted
354
+ // while you drag, which is what a slow paint wants; without one it is
355
+ // painted straight to the canvas every time. `state` carries `scale`,
356
+ // `panX` and `panY`, plus whatever the page adds. Call `repaint()`
357
+ // when the world changes and `moved()` when only the pan did. Set
358
+ // `onChange(kind)` to hear 'zoom', `onInteract()` to hear the first
359
+ // touch, `onDoubleTap()` for the double tap and `onZoom()` for the end
360
+ // of a zoom.
361
+ export function createViewer(canvas, opts) {
362
+ opts = opts || {};
363
+ const ctx = canvas.getContext('2d');
364
+ const DPR = Math.min(window.devicePixelRatio || 1, 2);
365
+ const state = { scale: opts.scale || 120, panX: 0, panY: 0 };
366
+ const viewer = { canvas, ctx, state, W: 0, H: 0, DPR, paint: opts.paint,
367
+ minZoom: opts.minZoom || 40, maxZoom: opts.maxZoom || 260, margin: opts.margin || 0,
368
+ preset: '', onChange: null, onInteract: null, onDoubleTap: null, onZoom: null };
369
+ let dirty = true, needPaint = true, buf = null, bg = null, bufPan = null;
370
+
371
+ function render() {
372
+ const W = viewer.W, H = viewer.H, M = viewer.margin;
373
+ if (!M) { viewer.paint(ctx, state, W, H, DPR, W / 2 + state.panX, H / 2 + state.panY); return; }
374
+ if (needPaint || !bufPan) {
375
+ if (!buf) { buf = document.createElement('canvas'); bg = buf.getContext('2d'); }
376
+ buf.width = Math.ceil((W + 2 * M) * DPR); buf.height = Math.ceil((H + 2 * M) * DPR);
377
+ viewer.paint(bg, state, W + 2 * M, H + 2 * M, DPR, W / 2 + M + state.panX, H / 2 + M + state.panY);
378
+ bufPan = [state.panX, state.panY];
379
+ needPaint = false;
380
+ }
381
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
382
+ ctx.drawImage(buf, (state.panX - bufPan[0] - M) * DPR, (state.panY - bufPan[1] - M) * DPR);
383
+ }
384
+ function repaint() { needPaint = true; dirty = true; }
385
+ function moved() {
386
+ const M = viewer.margin;
387
+ if (M && bufPan && (Math.abs(state.panX - bufPan[0]) > M * 0.9 || Math.abs(state.panY - bufPan[1]) > M * 0.9)) needPaint = true;
388
+ dirty = true;
389
+ }
390
+ function frame() {
391
+ if (dirty) { dirty = false; render(); }
392
+ requestAnimationFrame(frame);
393
+ }
394
+ function resize() {
395
+ viewer.W = window.innerWidth; viewer.H = window.innerHeight;
396
+ canvas.width = Math.round(viewer.W * DPR); canvas.height = Math.round(viewer.H * DPR);
397
+ repaint();
398
+ }
399
+ window.addEventListener('resize', resize);
400
+
401
+ const changed = kind => { if (viewer.onChange) viewer.onChange(kind); };
402
+
403
+ function zoomAt(sx, sy, factor) {
404
+ const next = Math.max(viewer.minZoom, Math.min(viewer.maxZoom, state.scale * factor));
405
+ factor = next / state.scale;
406
+ // keep the world point under (sx, sy) fixed while the scale changes
407
+ state.panX = sx - viewer.W / 2 - (sx - viewer.W / 2 - state.panX) * factor;
408
+ state.panY = sy - viewer.H / 2 - (sy - viewer.H / 2 - state.panY) * factor;
409
+ state.scale = next;
410
+ repaint();
411
+ if (viewer.onZoom) viewer.onZoom();
412
+ changed('zoom');
413
+ }
414
+
415
+ // drag to pan, pinch or wheel to zoom, double-tap for whatever the page wants
416
+ const pointers = new Map();
417
+ let pinchDist = 0, pinchMid = null, lastTap = 0, lastTapX = 0, lastTapY = 0;
418
+
419
+ canvas.addEventListener('pointerdown', e => {
420
+ canvas.setPointerCapture(e.pointerId);
421
+ pointers.set(e.pointerId, [e.clientX, e.clientY]);
422
+ if (pointers.size === 1) {
423
+ const now = performance.now();
424
+ if (now - lastTap < 320 && Math.hypot(e.clientX - lastTapX, e.clientY - lastTapY) < 40) {
425
+ if (viewer.onDoubleTap) viewer.onDoubleTap();
426
+ lastTap = 0;
427
+ } else { lastTap = now; lastTapX = e.clientX; lastTapY = e.clientY; }
428
+ } else if (pointers.size === 2) {
429
+ const [a, b] = [...pointers.values()];
430
+ pinchDist = Math.hypot(a[0] - b[0], a[1] - b[1]);
431
+ pinchMid = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
432
+ }
433
+ if (viewer.onInteract) viewer.onInteract();
434
+ });
435
+ canvas.addEventListener('pointermove', e => {
436
+ if (!pointers.has(e.pointerId)) return;
437
+ const prev = pointers.get(e.pointerId);
438
+ pointers.set(e.pointerId, [e.clientX, e.clientY]);
439
+ if (pointers.size === 1) {
440
+ state.panX += e.clientX - prev[0];
441
+ state.panY += e.clientY - prev[1];
442
+ moved();
443
+ } else if (pointers.size === 2) {
444
+ const [a, b] = [...pointers.values()];
445
+ const dist = Math.hypot(a[0] - b[0], a[1] - b[1]);
446
+ const mid = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
447
+ if (pinchMid) { state.panX += mid[0] - pinchMid[0]; state.panY += mid[1] - pinchMid[1]; }
448
+ if (pinchDist > 0) zoomAt(mid[0], mid[1], dist / pinchDist);
449
+ else moved();
450
+ pinchDist = dist; pinchMid = mid;
451
+ }
452
+ });
453
+ const endPointer = e => {
454
+ pointers.delete(e.pointerId);
455
+ if (pointers.size < 2) { pinchDist = 0; pinchMid = null; }
456
+ };
457
+ canvas.addEventListener('pointerup', endPointer);
458
+ canvas.addEventListener('pointercancel', endPointer);
459
+ canvas.addEventListener('wheel', e => {
460
+ e.preventDefault();
461
+ zoomAt(e.clientX, e.clientY, e.deltaY < 0 ? 1.08 : 1 / 1.08);
462
+ }, { passive: false });
463
+
464
+ Object.assign(viewer, { render, repaint, moved, zoomAt, resize });
465
+ resize();
466
+ requestAnimationFrame(frame);
467
+ return viewer;
468
+ }
469
+
345
470
  // --------------------------------------------------------------- wall ---
346
- // createWall(canvas, { palettes, motifs, painters, presets }) paints a
347
- // wall that fills the canvas, and handles drag, pinch, wheel and the
348
- // double tap. It returns the wall: `state` to read or change, then
471
+ // createWall(canvas, { palettes, motifs, painters, presets, material })
472
+ // is a viewer that paints a wall of tiles. It returns the wall, which
473
+ // is the viewer with more on it: `state` to read or change, then
349
474
  // `rebuild(true)` to repaint the tiles or `rebuild(false)` to redraw
350
475
  // the wall with the tiles it has. `applyPreset(name)`, `newDesign()`
351
476
  // and `zoomAt(x, y, factor)` do the usual things. Set `onChange(kind)`
@@ -356,8 +481,6 @@ export function paintThumb(cfg, p, g, T, k) {
356
481
  // `age(ctx, t)` (what age does to one tile, drawn over it in the
357
482
  // tile's own frame) and `finish(ctx, W, H, state, pal)` (over the wall).
358
483
  export function createWall(canvas, cfg) {
359
- const ctx = canvas.getContext('2d');
360
- const DPR = Math.min(window.devicePixelRatio || 1, 2);
361
484
  const palettes = cfg.palettes, motifs = cfg.motifs, presets = cfg.presets || {};
362
485
  const painters = cfg.painters || PAINTERS;
363
486
  const material = cfg.material || null, m = material || {};
@@ -365,7 +488,8 @@ export function createWall(canvas, cfg) {
365
488
  const firstMotif = Object.keys(motifs)[0];
366
489
  for (const p of Object.values(presets)) if (!p.motif) p.motif = firstMotif;
367
490
 
368
- const state = {
491
+ const wall = createViewer(canvas, { paint, scale: 120, minZoom: 40, maxZoom: 260 });
492
+ const state = Object.assign(wall.state, {
369
493
  seed: 1,
370
494
  repeat: 'module', // module | rotate | single | checker
371
495
  pal: Object.keys(palettes)[0],
@@ -373,16 +497,15 @@ export function createWall(canvas, cfg) {
373
497
  density: 3, // how much of the design is drawn, 1..5
374
498
  hand: 0.5, // wobble of the brush
375
499
  brush: 1, // line weight
376
- scale: 120, // pixels per tile
377
- panX: 0, panY: 0,
378
500
  bands: true,
379
501
  grout: true,
380
502
  age: false,
381
- };
382
- const wall = { canvas, ctx, state, palettes, motifs, painters, material, presets, preset: '', W: 0, H: 0, onChange: null, onInteract: null };
503
+ });
504
+ Object.assign(wall, { palettes, motifs, painters, material, presets });
383
505
  const tcfg = { palettes, motifs, painters, material };
506
+ const DPR = wall.DPR;
384
507
 
385
- let tiles = { A: [], B: [] }, needTiles = true, dirty = true;
508
+ let tiles = { A: [], B: [] }, needTiles = true;
386
509
 
387
510
  function buildTiles() {
388
511
  const o = tileOpts(tcfg, state);
@@ -394,18 +517,15 @@ export function createWall(canvas, cfg) {
394
517
  needTiles = false;
395
518
  }
396
519
 
397
- function render() {
520
+ function paint(ctx, st, W, H, dpr, ox, oy) {
398
521
  if (needTiles) buildTiles();
399
522
  const pal = palettes[state.pal];
400
- const W = wall.W, H = wall.H;
401
- ctx.setTransform(1, 0, 0, 1, 0, 0);
523
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
402
524
  ctx.fillStyle = pal.grout;
403
- ctx.fillRect(0, 0, canvas.width, canvas.height);
404
- ctx.setTransform(DPR, 0, 0, DPR, 0, 0);
525
+ ctx.fillRect(0, 0, W, H);
405
526
 
406
527
  const S = state.scale;
407
528
  const gap = state.grout ? (m.gapOf ? m.gapOf(S, state) : Math.max(1.2, S * 0.022)) : 0;
408
- const ox = W / 2 + state.panX, oy = H / 2 + state.panY;
409
529
  const i0 = Math.floor(-ox / S) - 1, i1 = Math.ceil((W - ox) / S) + 1;
410
530
  const j0 = Math.floor(-oy / S) - 1, j1 = Math.ceil((H - oy) / S) + 1;
411
531
  const s = S - gap;
@@ -459,20 +579,7 @@ export function createWall(canvas, cfg) {
459
579
  }
460
580
  }
461
581
 
462
- function rebuild(rebuildTiles) { if (rebuildTiles) needTiles = true; dirty = true; }
463
- function frame() {
464
- if (dirty) { dirty = false; render(); }
465
- requestAnimationFrame(frame);
466
- }
467
- function resize() {
468
- wall.W = window.innerWidth; wall.H = window.innerHeight;
469
- canvas.width = Math.round(wall.W * DPR); canvas.height = Math.round(wall.H * DPR);
470
- rebuild(false);
471
- }
472
- window.addEventListener('resize', resize);
473
- resize();
474
- requestAnimationFrame(frame);
475
-
582
+ function rebuild(rebuildTiles) { if (rebuildTiles) needTiles = true; wall.repaint(); }
476
583
  const changed = kind => { if (wall.onChange) wall.onChange(kind); };
477
584
 
478
585
  function applyPreset(name) {
@@ -491,118 +598,70 @@ export function createWall(canvas, cfg) {
491
598
  rebuild(true);
492
599
  changed('design');
493
600
  }
601
+ // tiles are cached at a pixel size: repaint them once the zoom settles
602
+ let zoomTimer = 0;
603
+ wall.onZoom = () => { clearTimeout(zoomTimer); zoomTimer = setTimeout(() => rebuild(true), 160); };
604
+ wall.onDoubleTap = newDesign;
494
605
 
495
- // drag to pan, pinch or wheel to zoom, double-tap for a new design
496
- const pointers = new Map();
497
- let pinchDist = 0, pinchMid = null, lastTap = 0, lastTapX = 0, lastTapY = 0, zoomTimer = 0;
498
-
499
- function zoomAt(sx, sy, factor) {
500
- const next = Math.max(40, Math.min(260, state.scale * factor));
501
- factor = next / state.scale;
502
- state.panX = sx - wall.W / 2 - (sx - wall.W / 2 - state.panX) * factor;
503
- state.panY = sy - wall.H / 2 - (sy - wall.H / 2 - state.panY) * factor;
504
- state.scale = next;
505
- // tiles are cached at a pixel size: repaint them once the zoom settles
506
- clearTimeout(zoomTimer);
507
- zoomTimer = setTimeout(() => rebuild(true), 160);
508
- rebuild(false);
509
- changed('zoom');
510
- }
511
-
512
- canvas.addEventListener('pointerdown', e => {
513
- canvas.setPointerCapture(e.pointerId);
514
- pointers.set(e.pointerId, [e.clientX, e.clientY]);
515
- if (pointers.size === 1) {
516
- const now = performance.now();
517
- if (now - lastTap < 320 && Math.hypot(e.clientX - lastTapX, e.clientY - lastTapY) < 40) {
518
- newDesign();
519
- lastTap = 0;
520
- } else { lastTap = now; lastTapX = e.clientX; lastTapY = e.clientY; }
521
- } else if (pointers.size === 2) {
522
- const [a, b] = [...pointers.values()];
523
- pinchDist = Math.hypot(a[0] - b[0], a[1] - b[1]);
524
- pinchMid = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
525
- }
526
- if (wall.onInteract) wall.onInteract();
527
- });
528
- canvas.addEventListener('pointermove', e => {
529
- if (!pointers.has(e.pointerId)) return;
530
- const prev = pointers.get(e.pointerId);
531
- pointers.set(e.pointerId, [e.clientX, e.clientY]);
532
- if (pointers.size === 1) {
533
- state.panX += e.clientX - prev[0];
534
- state.panY += e.clientY - prev[1];
535
- rebuild(false);
536
- } else if (pointers.size === 2) {
537
- const [a, b] = [...pointers.values()];
538
- const dist = Math.hypot(a[0] - b[0], a[1] - b[1]);
539
- const mid = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
540
- if (pinchMid) { state.panX += mid[0] - pinchMid[0]; state.panY += mid[1] - pinchMid[1]; }
541
- if (pinchDist > 0) zoomAt(mid[0], mid[1], dist / pinchDist);
542
- else rebuild(false);
543
- pinchDist = dist; pinchMid = mid;
544
- }
545
- });
546
- const endPointer = e => {
547
- pointers.delete(e.pointerId);
548
- if (pointers.size < 2) { pinchDist = 0; pinchMid = null; }
549
- };
550
- canvas.addEventListener('pointerup', endPointer);
551
- canvas.addEventListener('pointercancel', endPointer);
552
- canvas.addEventListener('wheel', e => {
553
- e.preventDefault();
554
- zoomAt(e.clientX, e.clientY, e.deltaY < 0 ? 1.08 : 1 / 1.08);
555
- }, { passive: false });
556
-
557
- Object.assign(wall, { rebuild, render, applyPreset, newDesign, zoomAt, resize, DPR });
606
+ Object.assign(wall, { rebuild, applyPreset, newDesign });
607
+ wall.rebuild(false);
558
608
  return wall;
559
609
  }
560
610
 
561
- // -------------------------------------------------------------- panel ---
562
- // mountPanel(wall, { fileName, defaultPreset }) wires the standard
563
- // control panel: the elements with the ids repeat, motif, palette,
564
- // density, hand, brush, zoom, bands, grout, age, newDesign, mood,
565
- // save, panel, panelHead, panelToggle, presetsBody, panelBody, the
566
- // `.tab` buttons, the `.card[data-preset]` cards (each with a canvas
567
- // for its thumbnail) and the `#title` overlay. It reads the query
568
- // string (?preset=, ?seed=, ?repeat=, ?pal=, ?motif=, ?density=,
569
- // ?hand=, ?zoom=, ?bands=0, ?age=1) and applies it. Anything missing
570
- // from the page is skipped.
571
- export function mountPanel(wall, opts) {
572
- opts = opts || {};
573
- const doc = opts.document || document;
611
+ // ------------------------------------------------------------- chrome ---
612
+ // mountChrome(viewer, spec) wires the standard page chrome around any
613
+ // viewer: the `#panel` with `#panelHead` and `#panelToggle`, the `.tab`
614
+ // buttons switching `#presetsBody` and `#panelBody`, the
615
+ // `.card[data-preset]` cards (each holding a canvas for its thumbnail),
616
+ // the `#title` overlay that fades on first touch, the `#save` button,
617
+ // the `#mood` line, and the controls the spec lists. It reads the
618
+ // query string and applies it. Anything missing from the page is
619
+ // skipped.
620
+ //
621
+ // The spec: `presets` (name -> settings), `applyPreset(name)`,
622
+ // `thumb(ctx, settings)` to paint a 52px card, `controls`, a list of
623
+ // `{ id, key, q, kind, fmt, valId, keep, change }`: `kind` is 'select',
624
+ // 'range' or 'check'; `key` is the field of `viewer.state` (the id by
625
+ // default); `q` is its name in the query string (the key by default);
626
+ // `fmt` renders the value beside a range; `valId` is where
627
+ // (`<id>Val` by default); `keep` leaves the preset marked when the
628
+ // query string sets it; `change(value)` is what to do after. Then
629
+ // `newId` and `onNew` for the button that starts over, `mood(state)`
630
+ // for the line under it, `query(q)` for anything else in the query
631
+ // string, `fileName` and `suffix(state)` for the saved png, and
632
+ // `ready()` once everything is applied.
633
+ export function mountChrome(viewer, spec) {
634
+ const doc = spec.document || document;
574
635
  const $ = id => doc.getElementById(id);
575
- const { state, presets } = wall;
636
+ const { state } = viewer;
637
+ const presets = spec.presets || {};
638
+ const controls = spec.controls || [];
576
639
  const presetCards = doc.querySelectorAll('.card[data-preset]');
577
640
  const markPreset = name => presetCards.forEach(c => c.classList.toggle('on', c.dataset.preset === name));
578
- const set = (id, v) => { const el = $(id); if (el) el.value = v; };
579
641
  const text = (id, v) => { const el = $(id); if (el) el.textContent = v; };
580
- const check = (id, v) => { const el = $(id); if (el) el.checked = v; };
581
-
582
- function syncZoom() {
583
- set('zoom', Math.round(state.scale)); text('zoomVal', Math.round(state.scale) + 'px');
584
- }
585
- function syncControls() {
586
- set('repeat', state.repeat);
587
- set('palette', state.pal);
588
- set('motif', state.motif);
589
- set('density', state.density); text('densityVal', state.density);
590
- set('hand', state.hand); text('handVal', Number(state.hand).toFixed(2));
591
- set('brush', state.brush); text('brushVal', Number(state.brush).toFixed(1));
592
- syncZoom();
593
- check('bands', state.bands); check('grout', state.grout); check('age', state.age);
594
- text('mood', 'design nº ' + state.seed);
595
- markPreset(wall.preset);
642
+ const valId = c => c.valId || c.id + 'Val';
643
+ const keyOf = c => c.key || c.id;
644
+
645
+ function sync() {
646
+ for (const c of controls) {
647
+ const el = $(c.id), v = state[keyOf(c)];
648
+ if (!el) continue;
649
+ if (c.kind === 'check') el.checked = !!v;
650
+ else el.value = v;
651
+ if (c.kind === 'range') text(valId(c), c.fmt ? c.fmt(v) : String(v));
652
+ }
653
+ if (spec.mood) text('mood', spec.mood(state));
654
+ markPreset(viewer.preset);
596
655
  }
597
- wall.onChange = kind => { if (kind === 'zoom') syncZoom(); else syncControls(); };
656
+ viewer.onChange = () => sync();
598
657
 
599
- presetCards.forEach(c => c.addEventListener('click', () => wall.applyPreset(c.dataset.preset)));
658
+ presetCards.forEach(c => c.addEventListener('click', () => { spec.applyPreset(c.dataset.preset); sync(); }));
600
659
 
601
- // each preset card shows its own wall, four tiles of it
602
- for (const card of presetCards) {
660
+ // each preset card shows its own small piece of wall
661
+ if (spec.thumb) for (const card of presetCards) {
603
662
  const p = presets[card.dataset.preset], tc = card.querySelector('canvas');
604
663
  if (!p || !tc) continue;
605
- paintThumb(wall, p, tc.getContext('2d'), 52, 2);
664
+ spec.thumb(tc.getContext('2d'), p);
606
665
  }
607
666
 
608
667
  // tabs
@@ -616,25 +675,27 @@ export function mountPanel(wall, opts) {
616
675
  });
617
676
  }
618
677
 
619
- const edited = () => { wall.preset = ''; markPreset(''); };
678
+ const edited = () => { viewer.preset = ''; markPreset(''); };
679
+ const parse = (c, el) => c.kind === 'check' ? el.checked : c.kind === 'range' ? (c.int ? parseInt(el.value, 10) : parseFloat(el.value)) : el.value;
680
+ for (const c of controls) {
681
+ const el = $(c.id);
682
+ if (!el) continue;
683
+ el.addEventListener(c.kind === 'range' ? 'input' : 'change', () => {
684
+ const v = parse(c, el);
685
+ state[keyOf(c)] = v;
686
+ if (c.kind === 'range') text(valId(c), c.fmt ? c.fmt(v) : String(v));
687
+ if (!c.keep) edited();
688
+ if (c.change) c.change(v);
689
+ });
690
+ }
620
691
  const on = (id, ev, fn) => { const el = $(id); if (el) el.addEventListener(ev, fn); };
621
- on('repeat', 'change', e => { state.repeat = e.target.value; edited(); wall.rebuild(true); });
622
- on('palette', 'change', e => { state.pal = e.target.value; edited(); wall.rebuild(true); });
623
- on('motif', 'change', e => { state.motif = e.target.value; edited(); wall.rebuild(true); });
624
- on('density', 'input', e => { state.density = parseInt(e.target.value, 10); text('densityVal', state.density); edited(); wall.rebuild(true); });
625
- on('hand', 'input', e => { state.hand = parseFloat(e.target.value); text('handVal', state.hand.toFixed(2)); edited(); wall.rebuild(true); });
626
- on('brush', 'input', e => { state.brush = parseFloat(e.target.value); text('brushVal', state.brush.toFixed(1)); edited(); wall.rebuild(true); });
627
- on('zoom', 'input', e => { state.scale = parseInt(e.target.value, 10); text('zoomVal', state.scale + 'px'); edited(); wall.rebuild(true); });
628
- on('bands', 'change', e => { state.bands = e.target.checked; edited(); wall.rebuild(true); });
629
- on('grout', 'change', e => { state.grout = e.target.checked; wall.rebuild(false); });
630
- on('age', 'change', e => { state.age = e.target.checked; wall.rebuild(false); });
631
- on('newDesign', 'click', () => wall.newDesign());
692
+ if (spec.onNew) on(spec.newId || 'newDesign', 'click', () => { spec.onNew(); sync(); });
632
693
 
633
694
  on('save', 'click', () => {
634
- wall.canvas.toBlob(blob => {
695
+ viewer.canvas.toBlob(blob => {
635
696
  const a = doc.createElement('a');
636
697
  a.href = URL.createObjectURL(blob);
637
- a.download = (opts.fileName || 'wall') + '-' + state.seed + '.png';
698
+ a.download = (spec.fileName || 'wall') + '-' + (spec.suffix ? spec.suffix(state) : state.seed) + '.png';
638
699
  a.click();
639
700
  setTimeout(() => URL.revokeObjectURL(a.href), 4000);
640
701
  });
@@ -646,6 +707,7 @@ export function mountPanel(wall, opts) {
646
707
  panel.classList.toggle('closed');
647
708
  text('panelToggle', panel.classList.contains('closed') ? '+' : '−');
648
709
  });
710
+ // on a phone the open panel would cover the art; start it folded
649
711
  if (window.innerWidth < 520) {
650
712
  panel.classList.add('closed');
651
713
  text('panelToggle', '+');
@@ -659,25 +721,69 @@ export function mountPanel(wall, opts) {
659
721
  titleGone = true;
660
722
  if (titleEl) titleEl.classList.add('gone');
661
723
  }
662
- wall.onInteract = dismissTitle;
724
+ viewer.onInteract = dismissTitle;
663
725
  setTimeout(dismissTitle, 7000);
664
726
 
665
- // shareable settings, e.g. ?preset=triana or ?seed=4242&repeat=rotate&pal=coimbra&motif=laceria
727
+ // the query string: a preset, then any control by its key, within
728
+ // what the page's own element allows
666
729
  const q = new URLSearchParams(location.search);
667
- wall.applyPreset(q.get('preset') || opts.defaultPreset || Object.keys(presets)[0]);
668
- if (q.has('seed')) { state.seed = parseInt(q.get('seed'), 10) || state.seed; wall.preset = ''; }
669
- if (q.has('repeat') && REPEATS.includes(q.get('repeat'))) state.repeat = q.get('repeat');
670
- if (q.has('pal') && wall.palettes[q.get('pal')]) state.pal = q.get('pal');
671
- if (q.has('motif') && wall.motifs[q.get('motif')]) state.motif = q.get('motif');
672
- const de = parseInt(q.get('density'), 10);
673
- if (de >= 1 && de <= 5) state.density = de;
674
- const ha = parseFloat(q.get('hand'));
675
- if (ha >= 0 && ha <= 1) state.hand = ha;
676
- const z = parseInt(q.get('zoom'), 10);
677
- if (z >= 40 && z <= 260) state.scale = z;
678
- if (q.get('bands') === '0') state.bands = false;
679
- if (q.get('age') === '1') state.age = true;
680
- syncControls();
681
- wall.rebuild(true);
682
- return { syncControls, dismissTitle };
730
+ spec.applyPreset(q.get('preset') || spec.defaultPreset || Object.keys(presets)[0]);
731
+ for (const c of controls) {
732
+ const k = keyOf(c), qn = c.q || k;
733
+ if (!q.has(qn)) continue;
734
+ const el = $(c.id), raw = q.get(qn);
735
+ let v;
736
+ if (c.kind === 'check') { if (raw !== '0' && raw !== '1') continue; v = raw === '1'; }
737
+ else if (c.kind === 'range') {
738
+ v = c.int ? parseInt(raw, 10) : parseFloat(raw);
739
+ if (!(v >= parseFloat(el ? el.min : -Infinity) && v <= parseFloat(el ? el.max : Infinity))) continue;
740
+ } else {
741
+ if (el && ![...el.options].some(o => o.value === raw)) continue;
742
+ v = raw;
743
+ }
744
+ state[k] = v;
745
+ if (!c.keep) viewer.preset = '';
746
+ }
747
+ if (spec.query) spec.query(q);
748
+ sync();
749
+ if (spec.ready) spec.ready();
750
+ return { sync, dismissTitle, markPreset };
751
+ }
752
+
753
+ // -------------------------------------------------------------- panel ---
754
+ // mountPanel(wall, { fileName, defaultPreset }) is mountChrome with the
755
+ // tile wall's controls: selects `repeat`, `motif` and `palette`; ranges
756
+ // `density`, `hand`, `brush` and `zoom` with `densityVal`, `handVal`,
757
+ // `brushVal` and `zoomVal` beside them; checkboxes `bands`, `grout` and
758
+ // `age`; the `newDesign` button. The query string takes ?preset=,
759
+ // ?seed=, ?repeat=, ?pal=, ?motif=, ?density=, ?hand=, ?zoom=, ?bands=0
760
+ // and ?age=1.
761
+ export function mountPanel(wall, opts) {
762
+ opts = opts || {};
763
+ const { state } = wall;
764
+ const tiles = () => wall.rebuild(true), face = () => wall.rebuild(false);
765
+ return mountChrome(wall, {
766
+ document: opts.document,
767
+ presets: wall.presets,
768
+ defaultPreset: opts.defaultPreset,
769
+ applyPreset: name => wall.applyPreset(name),
770
+ thumb: (g, p) => paintThumb(wall, p, g, 52, 2),
771
+ controls: [
772
+ { id: 'repeat', kind: 'select', change: tiles },
773
+ { id: 'palette', key: 'pal', kind: 'select', change: tiles },
774
+ { id: 'motif', kind: 'select', change: tiles },
775
+ { id: 'density', kind: 'range', int: true, change: tiles },
776
+ { id: 'hand', kind: 'range', fmt: v => Number(v).toFixed(2), change: tiles },
777
+ { id: 'brush', kind: 'range', fmt: v => Number(v).toFixed(1), change: tiles },
778
+ { id: 'zoom', key: 'scale', q: 'zoom', kind: 'range', int: true, fmt: v => Math.round(v) + 'px', keep: true, change: tiles },
779
+ { id: 'bands', kind: 'check', keep: true, change: tiles },
780
+ { id: 'grout', kind: 'check', keep: true, change: face },
781
+ { id: 'age', kind: 'check', keep: true, change: face },
782
+ ],
783
+ newId: 'newDesign', onNew: () => wall.newDesign(),
784
+ mood: s => 'design nº ' + s.seed,
785
+ query: q => { if (q.has('seed')) { state.seed = parseInt(q.get('seed'), 10) || state.seed; wall.preset = ''; } },
786
+ fileName: opts.fileName,
787
+ ready: tiles,
788
+ });
683
789
  }