1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
|
// Layers panel: list with thumbnails, visibility, masks, reordering, blend/opacity controls.
import { el, createCanvas } from '../../core/util.js';
import { icon } from '../icons.js';
import { selectField, rangeField } from '../widgets.js';
import { BLEND_MODES } from '../../core/layer.js';
import { setLayerProps, moveLayer } from '../../core/ops.js';
import { hasEffects, effectNames } from '../../render/effects.js';
const THUMB = 32;
export class LayersPanel {
constructor(app, container) {
this.app = app;
this.el = el('div', { class: 'panel layers-panel' });
container.appendChild(this.el);
this.thumbVersions = new Map();
this.builtFor = { doc: null, structure: -1 };
this.blend = selectField({
options: BLEND_MODES.map((m) => ({ value: m.id, label: m.label })), value: 'normal', title: 'Blend mode',
onChange: (v) => this.setProp({ blendMode: v }, 'Blend mode'),
});
this.opacity = rangeField({
label: 'Opacity', min: 0, max: 100, value: 100, unit: '%', compact: true,
onInput: (v) => this.setProp({ opacity: v / 100 }, 'Layer opacity', 'opacity'),
});
this.lockBtns = {
locked: this.toggle('lock', 'Lock layer (no edits)', 'locked'),
alphaLock: this.toggle('alphaLock', 'Lock transparent pixels', 'alphaLock'),
clip: this.toggle('clip', 'Clip to layer below (clipping mask)', 'clip'),
};
this.list = el('div', { class: 'layer-list', tabindex: 0 });
const btn = (name, title, action) => el('button', { type: 'button', class: 'btn icon-btn', title, html: icon(name, 16), onclick: () => app.run(action) });
this.el.append(
el('div', { class: 'panel-title' }, 'Layers'),
el('div', { class: 'layer-controls' },
el('div', { class: 'blend-row' }, this.blend, el('div', { class: 'lock-row' }, this.lockBtns.locked, this.lockBtns.alphaLock, this.lockBtns.clip)),
this.opacity),
this.list,
el('div', { class: 'panel-footer' },
btn('plus', 'New layer (Ctrl+Shift+N)', 'layer.new'),
btn('duplicate', 'Duplicate layer (Ctrl+J)', 'layer.duplicate'),
btn('fx', 'Layer style', 'layer.style'),
btn('mask', 'Add layer mask', 'layer.addMask'),
btn('merge', 'Merge down (Ctrl+E)', 'layer.mergeDown'),
btn('up', 'Move layer up', 'layer.raise'),
btn('down', 'Move layer down', 'layer.lower'),
btn('trash', 'Delete layer', 'layer.delete')),
);
app.on('doc', () => this.update(true));
app.on('docChange', () => this.update(false));
this.update(true);
}
toggle(iconName, title, prop) {
return el('button', {
type: 'button', class: 'btn icon-btn', title, html: icon(iconName, 15),
onclick: () => {
const l = this.app.doc?.activeLayer;
if (l) this.setProp({ [prop]: !l[prop] }, title);
},
});
}
setProp(props, label, coalesce) {
const doc = this.app.doc;
const layer = doc?.activeLayer;
if (!layer) return;
setLayerProps(doc, layer, props, label, coalesce ? `${coalesce}-${layer.id}` : null);
}
update(force) {
const doc = this.app.doc;
if (!doc) { this.list.innerHTML = ''; return; }
if (force || this.builtFor.doc !== doc || this.builtFor.structure !== doc.structureVersion) {
this.rebuild(doc);
}
this.scheduleThumbs();
const l = doc.activeLayer;
if (l) {
this.blend.setValue(l.blendMode);
if (document.activeElement?.closest?.('.range-field') !== this.opacity) this.opacity.setValue(Math.round(l.opacity * 100));
for (const [k, b] of Object.entries(this.lockBtns)) b.classList.toggle('active', !!l[k]);
}
}
rebuild(doc) {
this.builtFor = { doc, structure: doc.structureVersion };
this.thumbVersions.clear();
this.list.innerHTML = '';
this.rows = new Map();
const layers = [...doc.layers].reverse();
for (const layer of layers) {
const row = this.makeRow(doc, layer);
this.rows.set(layer.id, row);
this.list.appendChild(row);
}
}
makeRow(doc, layer) {
const active = layer.id === doc.activeLayerId;
const thumb = createCanvas(THUMB, THUMB);
thumb.className = 'thumb';
const maskThumb = layer.mask ? createCanvas(THUMB, THUMB) : null;
if (maskThumb) maskThumb.className = 'thumb mask-thumb';
if (active) {
(doc.editMask && maskThumb ? maskThumb : thumb).classList.add('target');
}
if (maskThumb && !layer.maskEnabled) maskThumb.classList.add('disabled');
const eye = el('button', {
type: 'button', class: 'btn icon-btn eye', title: 'Toggle visibility (Alt+click: solo)', html: icon(layer.visible ? 'eye' : 'eyeOff', 15),
onclick: (e) => {
e.stopPropagation();
if (e.altKey) this.solo(doc, layer);
else setLayerProps(doc, layer, { visible: !layer.visible }, layer.visible ? 'Hide layer' : 'Show layer');
},
});
const name = el('div', { class: 'layer-name' }, layer.name);
const badges = el('div', { class: 'layer-badges' },
layer.isText ? el('span', { title: 'Text layer', html: icon('textLayer', 13) }) : null,
layer.locked ? el('span', { title: 'Locked', html: icon('lock', 13) }) : null,
layer.alphaLock ? el('span', { title: 'Transparency locked', html: icon('alphaLock', 13) }) : null,
layer.blendMode !== 'normal' ? el('span', { class: 'badge-text', title: 'Blend mode' }, BLEND_MODES.find((m) => m.id === layer.blendMode)?.label || '') : null,
layer.opacity < 1 ? el('span', { class: 'badge-text' }, `${Math.round(layer.opacity * 100)}%`) : null,
hasEffects(layer) ? el('button', {
type: 'button', class: 'fx-badge', title: `Layer style: ${effectNames(layer.effects).join(', ')} (click to edit)`, html: icon('fx', 13),
onclick: (e) => { e.stopPropagation(); doc.setActiveLayer(layer.id); this.app.run('layer.style'); },
}) : null);
const row = el('div', { class: `layer-row${active ? ' active' : ''}${layer.visible ? '' : ' hidden-layer'}${layer.clip ? ' clipped' : ''}`, 'data-id': layer.id },
eye,
layer.clip ? el('span', { class: 'clip-arrow', title: 'Clipped to layer below' }, '↳') : null,
thumb, maskThumb,
el('div', { class: 'layer-meta' }, name, badges));
thumb.addEventListener('click', (e) => {
e.stopPropagation();
if (e.ctrlKey || e.metaKey) { this.app.run('select.layerAlpha', layer); return; }
doc.setActiveLayer(layer.id);
if (doc.editMask) { doc.editMask = false; doc.markDirty(true); }
});
maskThumb?.addEventListener('click', (e) => {
e.stopPropagation();
if (e.shiftKey) { setLayerProps(doc, layer, { maskEnabled: !layer.maskEnabled }, layer.maskEnabled ? 'Disable mask' : 'Enable mask'); return; }
doc.setActiveLayer(layer.id);
doc.editMask = true;
doc.markDirty(true);
});
if (maskThumb) maskThumb.title = 'Layer mask — click to edit, Shift+click to disable';
name.addEventListener('dblclick', (e) => { e.stopPropagation(); this.rename(doc, layer, name); });
row.addEventListener('contextmenu', (e) => {
e.preventDefault();
doc.setActiveLayer(layer.id);
this.app.ui.menu.showContext(e.clientX, e.clientY, this.app.ui.layerContextMenu());
});
this.attachDrag(row, doc, layer);
return row;
}
solo(doc, layer) {
const others = doc.layers.filter((l) => l !== layer);
const soloed = layer.visible && others.every((l) => !l.visible);
doc.change('Solo layer', () => {
layer.visible = true;
for (const l of others) l.visible = soloed;
});
}
rename(doc, layer, nameEl) {
const input = el('input', { type: 'text', value: layer.name, class: 'rename-input' });
nameEl.replaceWith(input);
input.focus();
input.select();
let done = false;
const finish = (ok) => {
if (done) return;
done = true;
const v = input.value.trim();
if (ok && v && v !== layer.name) setLayerProps(doc, layer, { name: v }, 'Rename layer');
else this.update(true);
};
input.addEventListener('keydown', (e) => {
e.stopPropagation();
if (e.key === 'Enter') finish(true);
if (e.key === 'Escape') finish(false);
});
input.addEventListener('blur', () => finish(true));
}
/** Pointer-based drag to reorder (no HTML5 DnD). */
attachDrag(row, doc, layer) {
row.addEventListener('pointerdown', (e) => {
// thumbnails and buttons handle their own clicks
if (e.button !== 0 || e.target.closest('button, input, .thumb')) return;
const startY = e.clientY;
let dragging = false;
let indicator = null;
let targetIndex = null;
const rows = [...this.list.children];
const move = (ev) => {
if (!dragging && Math.abs(ev.clientY - startY) > 4) {
dragging = true;
row.classList.add('dragging');
indicator = el('div', { class: 'drop-indicator' });
this.list.appendChild(indicator);
}
if (!dragging) return;
// find insertion slot in visual (top-first) order
let slot = rows.length;
for (let i = 0; i < rows.length; i++) {
const r = rows[i].getBoundingClientRect();
if (ev.clientY < r.top + r.height / 2) { slot = i; break; }
}
const listRect = this.list.getBoundingClientRect();
const refRect = slot < rows.length ? rows[slot].getBoundingClientRect() : rows[rows.length - 1].getBoundingClientRect();
const y = slot < rows.length ? refRect.top : refRect.bottom;
indicator.style.top = `${y - listRect.top + this.list.scrollTop - 1}px`;
// convert visual slot to array index (bottom-first)
const n = doc.layers.length;
const from = doc.layers.indexOf(layer);
let to = n - slot; // index of insertion in bottom-first order
if (to > from) to -= 1;
targetIndex = to;
};
const up = () => {
window.removeEventListener('pointermove', move);
window.removeEventListener('pointerup', up);
indicator?.remove();
row.classList.remove('dragging');
if (dragging && targetIndex != null) moveLayer(doc, layer, targetIndex);
else if (!dragging) {
doc.setActiveLayer(layer.id);
if (doc.editMask && !layer.mask) doc.editMask = false;
}
};
window.addEventListener('pointermove', move);
window.addEventListener('pointerup', up);
});
}
scheduleThumbs() {
if (this.thumbTimer) return;
this.thumbTimer = setTimeout(() => {
this.thumbTimer = null;
this.updateThumbs();
}, 120);
}
updateThumbs() {
const doc = this.app.doc;
if (!doc || !this.rows) return;
for (const layer of doc.layers) {
const row = this.rows.get(layer.id);
if (!row) continue;
const key = `${layer.thumbVersion}|${layer.canvas.width}x${layer.canvas.height}|${layer.preview ? 'p' : ''}`;
if (this.thumbVersions.get(layer.id) === key) continue;
this.thumbVersions.set(layer.id, key);
const [thumb, maskThumb] = row.querySelectorAll('canvas.thumb');
drawThumb(thumb, layer.preview || layer.canvas, true);
if (layer.mask && maskThumb) drawThumb(maskThumb, layer.mask, false);
}
}
}
function drawThumb(thumb, src, checker) {
const ctx = thumb.getContext('2d');
const s = THUMB;
ctx.clearRect(0, 0, s, s);
const k = Math.min(s / src.width, s / src.height);
const w = Math.max(1, Math.round(src.width * k)), h = Math.max(1, Math.round(src.height * k));
const x = Math.floor((s - w) / 2), y = Math.floor((s - h) / 2);
if (checker) {
for (let cy = 0; cy < h; cy += 6) {
for (let cx = 0; cx < w; cx += 6) {
ctx.fillStyle = ((cx + cy) / 6) % 2 ? '#cfcfcf' : '#fff';
ctx.fillRect(x + cx, y + cy, Math.min(6, w - cx), Math.min(6, h - cy));
}
}
}
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(src, x, y, w, h);
}
|