// 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); }