import { paletteSize, paletteSlots, siteColorNames, type SiteColors, type Swatch, } from '../lib/palette'; import type { PaletteRequest, PaletteResponse } from './palette.worker'; import type { PageScope } from './page-scope'; import { fitSize } from '../lib/math'; import { cssValue } from './pixel-grid'; const percentFormat = new Intl.NumberFormat(undefined, { maximumSignificantDigits: 3 }); export function mountPaletteTool(scope: PageScope) { const element = document.querySelector('[data-palette-tool]'); if (!element) return; const root = element; const find = (selector: string) => { const element = root.querySelector(selector); if (!element) throw new Error(`Missing palette tool element: ${selector}`); return element; }; const form = find('[data-settings]'); const controls = find('[data-controls]'); const fileInput = find('[data-image-input]'); const status = find('[data-status]'); const original = find('[data-original]'); const result = find('[data-result]'); const lightbox = find('[data-lightbox]'); const enlarged = find('[data-lightbox-image]'); const zoom = find('[data-zoom-image]'); const lightboxStage = find('[data-lightbox-stage]'); const edge = find('[data-edge]'); const quality = find('[data-quality]'); const count = find('[name="count"]'); const savedFile = { link: find('[data-download]'), preview: find('[data-export-preview]'), details: find('[data-export-file]'), }; const exportButtons = [...root.querySelectorAll('[data-export]')]; const imageButtons = [...root.querySelectorAll('[data-open-image]')]; const site = Object.fromEntries( siteColorNames.map((name) => [name, cssValue(`--${name}`)]), ) as SiteColors; const worker = new Worker(new URL('./palette.worker.ts', import.meta.url), { type: 'module' }); scope.defer(() => worker.terminate()); scope.defer(() => lightbox.close()); scope.defer(clearDownload); let sequence = 0; let loadId = 0; let renderId = 0; let exportId = 0; let loaded = false; let loading = false; let rendering = false; let queued = false; let exporting = false; let ready = false; let sourceName = 'artwork'; let pendingName = sourceName; let width = 0, height = 0; let exportName = ''; const post = (request: PaletteRequest) => worker.postMessage(request); const message = (text: string, error = false) => { status.textContent = text; status.dataset.error = String(error); }; function readSize() { return paletteSize(count.valueAsNumber); } const settings = () => ({ size: readSize(), site, edge: edge.valueAsNumber }); function syncControls() { const slots = paletteSlots(readSize()); find('[data-count-value]').value = count.value; count.setAttribute('aria-valuetext', `${count.value} colors`); find('[data-budget-summary]').textContent = `${slots.site} site colors + up to ${slots.image} image colors.`; const unavailable = !ready || loading || rendering || queued; for (const button of exportButtons) button.disabled = unavailable || exporting; for (const button of imageButtons) button.disabled = unavailable; controls.disabled = exporting; fileInput.disabled = exporting; edge.disabled = !loaded || loading || exporting; quality.disabled = exporting; } function draw(canvas: HTMLCanvasElement, image: ImageBitmap) { canvas.width = image.width; canvas.height = image.height; canvas.parentElement!.style.aspectRatio = String(image.width / image.height); canvas.parentElement!.style.maxWidth = `${image.width}px`; const context = canvas.getContext('2d'); if (!context) throw new Error('This browser cannot draw an image preview.'); context.imageSmoothingEnabled = false; context.drawImage(image, 0, 0); } function swatches(element: HTMLElement, colors: Swatch[]) { element.replaceChildren( ...colors.map(({ hex }) => { const swatch = document.createElement('span'); const color = document.createElement('i'); color.style.backgroundColor = hex; const label = document.createElement('code'); label.textContent = hex; swatch.append(color, label); return swatch; }), ); } function dimensions() { if (!width) return; const size = fitSize(width, height, edge.valueAsNumber || Math.max(width, height)); find('[data-dimensions]').textContent = `${sourceName} · ${width} × ${height} → ${size.width} × ${size.height} on export`; const percent = percentFormat.format((edge.valueAsNumber / Math.max(width, height)) * 100); find('[data-edge-value]').value = `${percent}%`; find('[data-size-summary]').textContent = `${size.width} × ${size.height} pixels · ${edge.value} px longest edge`; edge.setAttribute('aria-valuetext', `${size.width} by ${size.height} pixels, ${percent}%`); } function render() { if (!loaded || loading || exporting || rendering || !queued) return; queued = false; rendering = true; renderId = ++sequence; post({ type: 'render', id: renderId, ...settings() }); syncControls(); } let debounce = 0; scope.defer(() => window.clearTimeout(debounce)); function schedule() { clearDownload(); queued = true; if (loaded && !loading) message('Updating your palette…'); window.clearTimeout(debounce); syncControls(); debounce = window.setTimeout(render, 100); } function load(file: Blob, name: string) { if (exporting) return; if (file.size > 64 * 1024 * 1024) { message('Choose an image smaller than 64 MB.', true); return; } loading = true; clearDownload(); pendingName = name; loadId = ++sequence; renderId = 0; rendering = false; queued = false; message(`Opening ${name}…`); post({ type: 'load', id: loadId, file }); syncControls(); } function clearDownload() { const { link, details, preview } = savedFile; if (link.href.startsWith('blob:')) URL.revokeObjectURL(link.href); link.removeAttribute('href'); link.hidden = true; details.hidden = true; preview.removeAttribute('src'); } function download(blob: Blob, name: string) { clearDownload(); const { link, details, preview } = savedFile; const url = URL.createObjectURL(blob); link.href = url; link.download = name; link.textContent = `Download ${name}`; link.hidden = false; link.setAttribute('data-astro-reload', ''); link.click(); preview.src = url; details.hidden = false; } const filename = () => sourceName .replace(/\.[^.]+$/, '') .normalize('NFKC') .replace(/[^\p{L}\p{N}._-]+/gu, '-') .replace(/^-+|-+$/g, '') || 'artwork'; scope.on(worker, 'message', (event) => { const response = (event as MessageEvent).data; if (response.type === 'rendered') { try { if (response.id !== renderId) return; rendering = false; if (queued) { render(); return; } const palette = response.palette; find('[data-palette-panel]').hidden = false; draw(original, response.original); draw(result, response.image); swatches(find('[data-site-swatches]'), palette.site); swatches(find('[data-companion-swatches]'), palette.companions); find('[data-half-count]').textContent = `${palette.site.length} site + ${palette.companions.length} image colors${palette.companions.length < paletteSlots(readSize()).image ? ' · fewer distinct colors in this image' : ''}`; ready = true; message('Palette ready. Save your image.'); syncControls(); } finally { response.image.close(); response.original.close(); } return; } if (response.type === 'loaded' && response.id === loadId) { loading = false; loaded = true; sourceName = pendingName; width = response.width; height = response.height; // A range input clamps values immediately, so update its limit before restoring full size. edge.max = String(Math.max(width, height)); edge.value = edge.max; find('[data-preview]').hidden = false; queued = true; message('Deriving your palette…'); dimensions(); render(); } else if (response.type === 'exported' && response.id === exportId) { exporting = false; download(response.blob, exportName); message( `Ready: ${exportName} · ${response.width} × ${response.height} · ${(response.blob.size / 1024).toFixed(1)} KB. Use the download link if it didn’t start automatically.`, ); syncControls(); } else if (response.type === 'error' && [loadId, renderId, exportId].includes(response.id)) { loading = rendering = exporting = queued = false; message(`Could not finish: ${response.message}`, true); syncControls(); } }); scope.on(worker, 'error', () => { loading = rendering = exporting = queued = false; ready = false; message('The image worker could not start. Reload this page in a current browser.', true); syncControls(); }); scope.on(form, 'submit', (event) => event.preventDefault()); scope.on(form, 'input', () => { dimensions(); schedule(); }); scope.on(fileInput, 'change', () => { const file = fileInput.files?.[0]; if (file) load(file, file.name); fileInput.value = ''; }); scope.on(document, 'paste', (event) => { if (exporting || lightbox.open) return; const target = event.target; if ( target instanceof Element && target.closest('input:not([type="file"]):not([type="range"]), textarea, [contenteditable]') ) return; const file = [...(event.clipboardData?.files ?? [])].find((file) => file.type.startsWith('image/'), ); if (!file) return; event.preventDefault(); load(file, file.name || 'pasted-image.png'); }); const dropZone = find('[data-drop-zone]'); scope.on(dropZone, 'dragover', (event) => { event.preventDefault(); dropZone.classList.add('is-dragging'); }); scope.on(dropZone, 'dragleave', () => dropZone.classList.remove('is-dragging')); scope.on(dropZone, 'drop', (event) => { event.preventDefault(); dropZone.classList.remove('is-dragging'); const file = (event as DragEvent).dataTransfer?.files[0]; if (file) load(file, file.name); }); for (const button of imageButtons) { scope.on(button, 'click', () => { const image = button.querySelector('canvas')!; enlarged.width = image.width; enlarged.height = image.height; enlarged.style.setProperty('--image-width', `${image.width}px`); enlarged.style.setProperty('--image-height', `${image.height}px`); lightboxStage.dataset.zoom = 'fit'; zoom.setAttribute('aria-pressed', 'false'); const context = enlarged.getContext('2d'); if (!context) { message('This browser cannot open an image preview.', true); return; } context.imageSmoothingEnabled = false; context.drawImage(image, 0, 0); const title = image.getAttribute('aria-label')!; find('#lab-lightbox-title').textContent = title; enlarged.setAttribute('aria-label', title); lightbox.showModal(); }); } scope.on(zoom, 'click', () => { const actual = lightboxStage.dataset.zoom !== 'actual'; lightboxStage.dataset.zoom = actual ? 'actual' : 'fit'; zoom.setAttribute('aria-pressed', String(actual)); }); scope.on(lightbox, 'close', () => { enlarged.width = enlarged.height = 0; }); for (const button of root.querySelectorAll('button[data-view]')) { scope.on(button, 'click', () => { if (exporting) return; find('[data-images]').dataset.view = button.dataset.view; for (const sibling of root.querySelectorAll('button[data-view]')) sibling.setAttribute('aria-pressed', String(sibling === button)); }); } scope.on(quality, 'input', () => { clearDownload(); find('[data-quality-value]').value = `${quality.value}%`; }); for (const button of exportButtons) { scope.on(button, 'click', () => { if (!ready || rendering || queued || exporting) return; const format = button.dataset.export as 'png' | 'avif'; exporting = true; exportId = ++sequence; exportName = `${filename()}-palette.${format}`; message( `Preparing ${format.toUpperCase()} at export resolution…${format === 'avif' ? ' Encoding may take a moment.' : ''}`, ); syncControls(); post({ type: 'export', id: exportId, ...settings(), format, quality: Number(quality.value) }); }); } syncControls(); }