aboutsummaryrefslogtreecommitdiff
path: root/build/js/core/document.js
blob: ea50963f5fd9b9d52e16eb362e476d654ecc26cf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
// An open image: layers (bottom -> top), selection, history and view state.
import { Emitter } from './emitter.js';
import { History, StateEntry } from './history.js';
import { Layer } from './layer.js';
import { uid } from './util.js';

export class ImageDocument extends Emitter {
  constructor({ width = 1200, height = 800, name = 'Untitled', background = '#ffffff', empty = false } = {}) {
    super();
    this.id = uid('doc');
    this.name = name;
    this.width = width;
    this.height = height;
    this.layers = [];
    this.activeLayerId = null;
    this.selection = null;
    this.editMask = false; // when true, painting targets the active layer's mask
    this.history = new History(this);
    this.view = { zoom: 1, panX: 0, panY: 0, needsFit: true };
    this.version = 0; // bumps on any visual change
    this.structureVersion = 0; // bumps on layer list / property changes
    this.stroke = null; // live stroke (see tools/paint.js)
    this.floating = null; // live floating pixels {canvas, layer, dx, dy}
    this.guides = { show: false, grid: 32 }; // the grid (View ▸ Grid)
    this.guideLines = []; // [{axis: 'x' | 'y', pos}], replaced (never mutated) so undo can keep references

    if (!empty) {
      const bg = new Layer(width, height, { name: background ? 'Background' : 'Layer 1' });
      if (background) {
        const ctx = bg.ctx;
        ctx.fillStyle = background;
        ctx.fillRect(0, 0, width, height);
      }
      this.layers.push(bg);
      this.activeLayerId = bg.id;
    }
    this.history.onChange(() => this.emit('history'));
  }

  get activeLayer() { return this.layers.find((l) => l.id === this.activeLayerId) || this.layers[this.layers.length - 1] || null; }
  get activeIndex() { return this.layers.indexOf(this.activeLayer); }
  layerById(id) { return this.layers.find((l) => l.id === id) || null; }
  get isModified() { return this.history.isModified; }

  /** Where paint goes: { layer, key: 'canvas' | 'mask' }. */
  get editTarget() {
    const layer = this.activeLayer;
    if (!layer) return null;
    if (this.editMask && layer.mask) return { layer, key: 'mask' };
    return { layer, key: 'canvas' };
  }

  markDirty(structure = false) {
    this.version++;
    if (structure) this.structureVersion++;
    this.emit('change', { structure });
  }

  nextLayerName(base = 'Layer') {
    let n = this.layers.length + 1;
    const names = new Set(this.layers.map((l) => l.name));
    while (names.has(`${base} ${n}`)) n++;
    return `${base} ${n}`;
  }

  captureState() {
    return {
      width: this.width,
      height: this.height,
      activeLayerId: this.activeLayerId,
      selection: this.selection,
      editMask: this.editMask,
      guideLines: this.guideLines,
      layers: this.layers.map((layer) => ({ layer, props: layer.captureProps(), canvas: layer.canvas, mask: layer.mask })),
    };
  }

  restoreState(s) {
    this.width = s.width;
    this.height = s.height;
    this.selection = s.selection;
    this.activeLayerId = s.activeLayerId;
    this.editMask = s.editMask;
    this.guideLines = s.guideLines || [];
    this.layers = s.layers.map(({ layer, props, canvas, mask }) => {
      layer.applyProps(props);
      layer.canvas = canvas;
      layer.mask = mask;
      if (layer.isText) layer.renderText();
      layer.touch();
      layer.touchMask();
      return layer;
    });
    this.markDirty(true);
  }

  /**
   * Run a structural change as one undoable step. `fn` may mutate layer lists and
   * properties; pixel content must be changed by *replacing* canvases.
   */
  change(label, fn, { coalesceKey = null } = {}) {
    const before = this.captureState();
    const result = fn();
    const after = this.captureState();
    const entry = new StateEntry(label, before, after, coalesceKey);
    if (coalesceKey) this.history.pushCoalesced(entry);
    else this.history.push(entry);
    this.markDirty(true);
    return result;
  }

  /** Record a change whose "before" state was captured earlier (interactive edits). */
  commitChange(label, before) {
    this.history.push(new StateEntry(label, before, this.captureState()));
    this.markDirty(true);
  }

  setSelection(sel, label = 'Selection') {
    if (sel === this.selection) return;
    if (!sel && !this.selection) return;
    this.change(label, () => { this.selection = sel; });
  }

  setActiveLayer(id) {
    if (this.activeLayerId === id) return;
    this.activeLayerId = id;
    const l = this.activeLayer;
    if (this.editMask && !l?.mask) this.editMask = false;
    this.markDirty(true);
  }
}