import { text } from '../../../shared/workspace-pages'; import { Component, createRef, Fragment, h } from 'preact'; import { compress, convert, decode, defaultCompression, defaultConverter, defaultEnhancement, enhance, inspectImage, makeZip, supportsAlpha, validateEnhancementSize, } from './pipeline'; import type { CompressionSettings, ConverterSettings, Processed } from './pipeline'; import { CompressionControls, CompressionPreprocessing, EnhancementControls, SettingsDisclosure } from './controls'; import { Footer, Guide, Home, Icon, Navigation, samplePhoto, sampleSticker } from '../../../shared/workspace-chrome'; import { embeddedModes, Preview, ProcessingHint, Queue, Settings } from './view'; import type { EmbeddedMode, Item, Progress, View } from './view'; import { currentLocale, isMode, locales, pageFromPath, pageMetadata, pagePath, siteName, socialLocale, toolsFor } from '../../../shared/workspace-pages'; import type { Locale, Mode, Page } from '../../../shared/workspace-pages'; import { assertSignal } from '../util'; import { installInstructions, requestInstall } from './install'; import type { InstallHelp } from './install'; type ExtensionMode = 'edit' | 'sticker' | 'cutout'; type ExtensionSource = 'edit' | 'sticker'; interface ProcessOptions { signal: AbortSignal; onProgress(fraction: number): void; } interface ToolLifecycle { mount(): void | Promise; snapshot(): unknown; onSelected?(item?: Item): void; onHidden?(): void; onLocaleChanged?(): void; onResultsChanged?(): void; dispose(): void; } interface Processor extends ToolLifecycle { process(item: Item, snapshot: unknown, options: ProcessOptions): Promise; onInputChanged?(): void; } interface Preprocessor extends ToolLifecycle { isEnabled(): boolean; prepare(item: Item, snapshot: unknown, options: ProcessOptions): Promise; } interface ExtensionModule { createEditMode: (host: object) => Processor; createStickerMode: (host: object) => Processor; createCutoutMode: (host: object) => Processor; createCutoutPreprocessor: (host: object) => Preprocessor; } interface ExtensionWindow extends Window { gismologLoadMode?(mode: ExtensionSource): Promise; } interface Run { controller: AbortController; mode: Mode; items: Item[]; current: Item; first: boolean; elapsedTotal: number; completed: number; started: number; fraction?: number; } interface Workspace { items: Item[]; selected?: Item; view: View; zoom: number; split: number; confirmed: boolean; message: string; summary: string; draftUrl?: string; cutoutDraft?: { id: number; file: File; url: string }; preprocessor?: Preprocessor; loadingPreprocessor?: Promise; preprocessorLoadError?: string; processor?: Processor; loadingProcessor?: Promise; loadError?: string; sampleLoading?: boolean; modeBusy?: boolean; previewController?: AbortController; } const makeWorkspace = (): Workspace => ({ items: [], view: 'original', zoom: 100, split: 52, confirmed: false, message: '', summary: '', }); const zoomSteps = [75, 100, 125, 150, 200, 300]; const imageFilename = /\.(?:avif|bmp|gif|heic|heif|ico|jpe?g|jxl|png|qoi|svg|tiff?|webp|wp2)$/i; const hasFiles = (data: DataTransfer | null) => Boolean(data && Array.from(data.types).includes('Files')); const isExtension = (mode: Page): mode is ExtensionMode => mode === 'edit' || mode === 'sticker' || mode === 'cutout'; const hasPreprocessor = (mode: Page): mode is EmbeddedMode => embeddedModes.some(value => value === mode); const errorMessage = (error: unknown) => error instanceof Error ? error.message : String(error); function legacyRoute(): Mode | undefined { if (!/^\/(?:zh\/)?(?:index\.html)?$/.test(location.pathname)) return; const hash = location.hash.slice(1); if (hash === 'batch') return 'compress'; return isMode(hash) ? hash : undefined; } function route(): Page { return legacyRoute() ?? pageFromPath(location.pathname); } function migrateLegacyRoute() { const legacy = legacyRoute(); if (legacy) history.replaceState(history.state, '', pagePath(legacy, currentLocale()) + location.search); } function updatePageMetadata(page: Page, locale: Locale) { const { title, description } = pageMetadata(page, locale); document.documentElement.lang = locale; document.title = title; const canonical = document.querySelector('link[rel="canonical"]'); if (canonical) { canonical.href = new URL(pagePath(page, locale), canonical.href).href; for (const language of [...locales, 'x-default'] as const) { const link = document.querySelector('link[rel="alternate"][hreflang="' + language + '"]'); if (link) link.href = new URL(pagePath(page, language === 'x-default' ? undefined : language), canonical.href).href; } } const imageAlt = text('绿叶间的小熊猫样图', 'A red panda among green leaves', locale); const values = { 'meta[name="description"]': description, 'meta[property="og:title"]': title, 'meta[property="og:description"]': description, 'meta[property="og:url"]': canonical?.href, 'meta[property="og:locale"]': socialLocale(locale), 'meta[property="og:locale:alternate"]': socialLocale(locale === 'en' ? 'zh-CN' : 'en'), 'meta[property="og:image:alt"]': imageAlt, 'meta[name="twitter:title"]': title, 'meta[name="twitter:description"]': description, 'meta[name="twitter:image:alt"]': imageAlt, }; for (const [selector, content] of Object.entries(values)) { const meta = document.querySelector(selector); if (meta && content) meta.content = content; } } function revoke(url?: string) { if (url) URL.revokeObjectURL(url); } function releaseResult(item: Item) { revoke(item.resultUrl); item.result = undefined; item.resultUrl = undefined; item.resultWidth = undefined; item.resultHeight = undefined; item.error = undefined; } interface State { page: Page; locale: Locale; drag: boolean; compressionPreprocessingOpen: boolean; enhancementPreprocessingOpen: boolean; enhancementAdvancedOpen: boolean; editPreprocessingOpen: boolean; installHelp?: InstallHelp; } interface InstallDialog extends HTMLDialogElement { open: boolean; showModal(): void; } function createInlineSettings(id: string, className = 'workspace-mode-settings') { // The tool keeps the same settings node when its host panel is replaced. const element = Object.assign(document.createElement('div'), { id, className }); return { element, mount: (container: HTMLDivElement | null) => { if (container) container.append(element); }, }; } function createInlinePreprocessorSettings(mode: EmbeddedMode) { return createInlineSettings('mode-settings-pre-' + mode, 'workspace-mode-settings workspace-preprocessor-settings'); } export default class WorkspaceApp extends Component<{}, State> { state: State = { page: route(), locale: currentLocale(), drag: false, compressionPreprocessingOpen: false, enhancementPreprocessingOpen: false, enhancementAdvancedOpen: false, editPreprocessingOpen: false, }; private workspaces = { convert: makeWorkspace(), compress: makeWorkspace(), enhance: makeWorkspace(), edit: makeWorkspace(), sticker: makeWorkspace(), cutout: makeWorkspace(), }; private converter = defaultConverter(); private compression = defaultCompression(); private enhancement = defaultEnhancement(); private input = createRef(); private pan = createRef(); private scrollSettings = createRef(); private installDialog = createRef(); private inlinePreprocessorSettings = { compress: createInlinePreprocessorSettings('compress'), enhance: createInlinePreprocessorSettings('enhance'), edit: createInlinePreprocessorSettings('edit'), }; private editSettings = createInlineSettings('mode-settings-edit'); private fileId = 0; private run?: Run; private exporting = false; private dragDepth = 0; componentDidMount() { migrateLegacyRoute(); window.addEventListener('hashchange', this.onLocationChange); window.addEventListener('popstate', this.onLocationChange); document.addEventListener('paste', this.onPaste); window.addEventListener('dragenter', this.onDragEnter); window.addEventListener('dragover', this.onDragOver); window.addEventListener('dragleave', this.onDragLeave); window.addEventListener('drop', this.onDrop); this.updatePage(); if ('serviceWorker' in navigator && new URLSearchParams(location.search).has('share-target')) { navigator.serviceWorker.addEventListener('message', this.onShare); navigator.serviceWorker.controller?.postMessage('share-ready'); } } componentWillUnmount() { window.removeEventListener('hashchange', this.onLocationChange); window.removeEventListener('popstate', this.onLocationChange); document.removeEventListener('paste', this.onPaste); window.removeEventListener('dragenter', this.onDragEnter); window.removeEventListener('dragover', this.onDragOver); window.removeEventListener('dragleave', this.onDragLeave); window.removeEventListener('drop', this.onDrop); if ('serviceWorker' in navigator) navigator.serviceWorker.removeEventListener('message', this.onShare); this.run?.controller.abort(); for (const workspace of Object.values(this.workspaces)) { workspace.previewController?.abort(); workspace.processor?.dispose(); workspace.preprocessor?.dispose(); revoke(workspace.draftUrl); revoke(workspace.cutoutDraft?.url); for (const item of workspace.items) { releaseResult(item); revoke(item.originalUrl); } } } private onShare = (event: MessageEvent) => { if (event.data?.action === 'load-image' && event.data.file instanceof File) { this.addToActive([event.data.file]); history.replaceState(history.state, '', location.pathname + location.hash); } }; private onLocationChange = () => { migrateLegacyRoute(); const page = route(); const locale = currentLocale(); const { page: previous, locale: previousLocale } = this.state; if (previous === page && previousLocale === locale) return; if (previous !== 'home' && previous !== page) { const workspace = this.workspaces[previous]; workspace.processor?.onHidden?.(); workspace.preprocessor?.onHidden?.(); } this.setState({ page, locale, drag: false }, () => { if (previousLocale !== locale) { for (const workspace of Object.values(this.workspaces)) { workspace.processor?.onLocaleChanged?.(); workspace.preprocessor?.onLocaleChanged?.(); } } if (previous === page) updatePageMetadata(page, locale); else this.updatePage(true); }); }; private open = (page: Page) => { if (this.state.page === page) return; history.pushState(null, '', pagePath(page, this.state.locale)); this.onLocationChange(); }; private changeLanguage = (locale: Locale) => { if (this.state.locale === locale) return; history.pushState(null, '', pagePath(this.state.page, locale) + location.search); this.onLocationChange(); }; private updatePage(focus = false) { const { page, locale } = this.state; updatePageMetadata(page, locale); if (focus) { this.pan.current?.scrollTo(0, 0); this.scrollSettings.current?.scrollTo(0, 0); window.scrollTo(0, 0); document.getElementById(page === 'home' ? 'home-title' : 'desk-title')?.focus({ preventScroll: true }); } if (isExtension(page)) void this.loadProcessor(page); if (hasPreprocessor(page)) void this.loadPreprocessor(page); } private importMode(source: ExtensionSource) { const runtime = window as ExtensionWindow; return runtime.gismologLoadMode?.(source) ?? Promise.reject(new Error(text('模块加载器不可用。', 'The tool loader is unavailable.'))); } private modeHost(mode: Mode, preprocessor: boolean) { const workspace = this.workspaces[mode]; const key = preprocessor ? 'pre-' + mode : mode; const settingsElement = preprocessor && hasPreprocessor(mode) ? this.inlinePreprocessorSettings[mode].element : mode === 'edit' ? this.editSettings.element : document.getElementById('mode-settings-' + key); const previewElement = document.getElementById('mode-preview-' + key); if (!settingsElement || (key !== 'edit' && !previewElement)) return; return { settingsElement, previewElement, getSelectedItem: () => preprocessor ? workspace.selected : this.processorInput(mode), getItems: () => workspace.items, keepAlpha: () => Boolean(workspace.preprocessor?.isEnabled()), canPreviewInput: () => !workspace.preprocessor?.isEnabled() || Boolean(workspace.cutoutDraft && workspace.cutoutDraft.id === workspace.selected?.id), markDirty: () => { if (this.run?.mode === mode) return; if (preprocessor) { this.clearCutoutDraft(workspace); revoke(workspace.draftUrl); workspace.draftUrl = undefined; workspace.processor?.onInputChanged?.(); } this.invalidate(mode, !preprocessor); }, showNotice: (message: string) => { workspace.message = message; this.forceUpdate(); }, setDraft: (blob?: Blob) => preprocessor ? this.setCutoutDraft(mode, blob) : this.setDraft(mode, blob), setModeBusy: (busy: boolean) => { if (workspace.modeBusy === busy) return; workspace.modeBusy = busy; this.forceUpdate(); }, decode, download: this.download, }; } private async mountTool(tool: T) { try { await tool.mount(); } catch (error) { tool.dispose(); throw error; } return tool; } private loadProcessor(mode: ExtensionMode) { const workspace = this.workspaces[mode]; if (workspace.processor) { if (this.run?.mode !== mode) { workspace.processor.onSelected?.(workspace.selected?.previewReady ? this.processorInput(mode) : undefined); } return; } if (workspace.loadingProcessor) return; const host = this.modeHost(mode, false); if (!host) return; workspace.loadError = undefined; workspace.loadingProcessor = this.importMode(mode === 'edit' ? 'edit' : 'sticker').then(async module => { const create = mode === 'edit' ? module.createEditMode : mode === 'cutout' ? module.createCutoutMode : module.createStickerMode; const processor = await this.mountTool(create(host)); workspace.processor = processor; if (workspace.selected?.previewReady && this.state.page === mode) processor.onSelected?.(this.processorInput(mode)); }).catch(error => { workspace.loadError = text('工作区加载失败。', 'The workspace could not load. ') + errorMessage(error); }).finally(() => { workspace.loadingProcessor = undefined; this.forceUpdate(); }); this.forceUpdate(); } private loadPreprocessor(mode: EmbeddedMode) { const workspace = this.workspaces[mode]; if (workspace.preprocessor) { if (this.run?.mode !== mode) workspace.preprocessor.onSelected?.(workspace.selected?.previewReady ? workspace.selected : undefined); return; } if (workspace.loadingPreprocessor) return; const host = this.modeHost(mode, true); if (!host) return; workspace.preprocessorLoadError = undefined; workspace.loadingPreprocessor = this.importMode('sticker').then(async module => { const preprocessor = await this.mountTool(module.createCutoutPreprocessor(host)); workspace.preprocessor = preprocessor; if (workspace.selected?.previewReady && this.state.page === mode) preprocessor.onSelected?.(workspace.selected); workspace.processor?.onInputChanged?.(); }).catch(error => { workspace.preprocessorLoadError = text('前置抠图加载失败。', 'The background removal preprocessor could not load. ') + errorMessage(error); }).finally(() => { workspace.loadingPreprocessor = undefined; this.forceUpdate(); }); this.forceUpdate(); } private processorInput(mode: Mode) { const { selected, cutoutDraft, preprocessor } = this.workspaces[mode]; return selected && cutoutDraft && cutoutDraft.id === selected.id && preprocessor?.isEnabled() ? { ...selected, file: cutoutDraft.file, originalUrl: cutoutDraft.url, previewFallback: false } : selected; } private clearCutoutDraft(workspace: Workspace) { revoke(workspace.cutoutDraft?.url); workspace.cutoutDraft = undefined; if (workspace.view === 'cutout') workspace.view = workspace.selected?.resultUrl ? 'compare' : 'original'; } private setCutoutDraft(mode: Mode, blob?: Blob) { const workspace = this.workspaces[mode]; if (this.run?.mode === mode && blob) return; const item = workspace.selected; this.clearCutoutDraft(workspace); if (blob && item && workspace.preprocessor?.isEnabled()) { const file = new File([blob], item.file.name, { type: 'image/png' }); workspace.cutoutDraft = { id: item.id, file, url: URL.createObjectURL(file) }; workspace.view = 'cutout'; } workspace.processor?.onInputChanged?.(); this.forceUpdate(); } private notifySelected(mode: Mode, item?: Item) { if (this.run?.mode === mode) return; const workspace = this.workspaces[mode]; workspace.preprocessor?.onSelected?.(item); workspace.processor?.onSelected?.(item ? this.processorInput(mode) : undefined); } private setDraft(mode: Mode, blob?: Blob) { const workspace = this.workspaces[mode]; if (this.run?.mode === mode && blob) return; revoke(workspace.draftUrl); workspace.draftUrl = blob && URL.createObjectURL(blob); if (blob) workspace.view = 'draft'; else if (workspace.view === 'draft') workspace.view = workspace.selected?.resultUrl ? 'compare' : 'original'; this.forceUpdate(); } private onPaste = (event: ClipboardEvent) => { const target = event.target; if (target instanceof Element && target.closest('input, textarea, [contenteditable]:not([contenteditable=false])')) return; const files = Array.from(event.clipboardData?.files || []); if (!files.length) return; event.preventDefault(); if (document.querySelector('dialog[open]')) return; this.addToActive(files); }; private onDragEnter = (event: DragEvent) => { if (!hasFiles(event.dataTransfer) || document.querySelector('dialog[open]')) return; event.preventDefault(); this.dragDepth += 1; if (!this.state.drag && !this.busyFor(this.state.page) && this.state.page !== 'home') this.setState({ drag: true }); }; private onDragOver = (event: DragEvent) => { if (!hasFiles(event.dataTransfer) || document.querySelector('dialog[open]')) return; event.preventDefault(); if (event.dataTransfer) event.dataTransfer.dropEffect = this.busyFor(this.state.page) ? 'none' : 'copy'; }; private onDragLeave = () => { this.dragDepth = Math.max(0, this.dragDepth - 1); if (this.dragDepth === 0 && this.state.drag) this.setState({ drag: false }); }; private onDrop = (event: DragEvent) => { const files = Array.from(event.dataTransfer?.files || []); if (!files.length || document.querySelector('dialog[open]')) return; event.preventDefault(); this.dragDepth = 0; this.setState({ drag: false }); this.addToActive(files); }; private busyFor(page: Page) { return Boolean(this.run || (page !== 'home' && this.workspaces[page].modeBusy)); } private addToActive(files: File[]) { const { page } = this.state; if (this.busyFor(page)) return; const mode = page === 'home' ? 'compress' : page; if (page === 'home') this.open(mode); this.addFiles(mode, files); } private addFiles(mode: Mode, files: File[]) { if (this.busyFor(mode)) return; const workspace = this.workspaces[mode]; const accepted = files.filter(file => file.type.startsWith('image/') || imageFilename.test(file.name)); const skipped = files.length - accepted.length; workspace.message = skipped ? text(`已跳过 ${skipped} 个非图片文件。`, `Skipped ${skipped} non-image ${skipped === 1 ? 'file' : 'files'}.`) : ''; if (workspace.items.length + accepted.length > 65_535) { workspace.message = text('队列最多可包含 65,535 张图片。', 'The queue can contain up to 65,535 images.'); this.forceUpdate(); return; } const added = accepted.map(file => ({ id: ++this.fileId, file, originalUrl: URL.createObjectURL(file), width: 0, height: 0, previewReady: false, })); workspace.items.push(...added); if (!workspace.selected && added.length) this.select(mode, added[0]); else this.forceUpdate(); } private openSample = async (mode: Mode, photo = false) => { const workspace = this.workspaces[mode]; if (this.busyFor(mode) || workspace.sampleLoading) return; this.open(mode); workspace.sampleLoading = true; this.forceUpdate(); try { const sticker = mode === 'sticker' && !photo; const response = await fetch(sticker ? sampleSticker : samplePhoto); if (!response.ok) throw new Error(text('无法加载样图。', 'The sample image could not load.')); const blob = await response.blob(); this.addFiles(mode, [new File([blob], sticker ? 'red-panda-sticker.png' : 'red-panda.jpg', { type: blob.type })]); } catch (error) { workspace.message = errorMessage(error); } finally { workspace.sampleLoading = false; this.forceUpdate(); } }; private select(mode: Mode, item: Item | undefined, forceOriginal = false) { const workspace = this.workspaces[mode]; workspace.previewController?.abort(); workspace.selected = item; workspace.view = !forceOriginal && item?.resultUrl ? 'compare' : 'original'; workspace.split = 52; this.clearCutoutDraft(workspace); this.setDraft(mode); if (item?.previewReady) { this.notifySelected(mode, item); return; } this.notifySelected(mode); if (!item || item.previewError) return; const controller = new AbortController(); workspace.previewController = controller; void this.inspectSource(item, controller.signal, mode).then(() => { if (controller.signal.aborted) return; this.notifySelected(mode, item); this.forceUpdate(); }).catch(error => { if (controller.signal.aborted) return; item.previewError = errorMessage(error); this.forceUpdate(); }); } private async inspectSource(item: Item, signal: AbortSignal, mode?: Mode) { if (item.previewReady) return; const dimensions = await inspectImage(item.file, item.originalUrl, signal, false, mode === 'convert'); assertSignal(signal); if (item.previewReady) return; item.width = dimensions.width; item.height = dimensions.height; if (dimensions.fallback) { revoke(item.originalUrl); item.originalUrl = URL.createObjectURL(dimensions.fallback); item.previewFallback = true; } item.previewReady = true; item.previewError = undefined; } private remove(mode: Mode, item: Item) { if (this.busyFor(mode)) return; const workspace = this.workspaces[mode]; const index = workspace.items.indexOf(item); workspace.items.splice(index, 1); if (workspace.selected === item) this.select(mode, workspace.items[Math.min(index, workspace.items.length - 1)]); releaseResult(item); revoke(item.originalUrl); if (!workspace.items.some(entry => entry.result)) workspace.confirmed = false; if (!workspace.items.length) workspace.summary = ''; workspace.preprocessor?.onResultsChanged?.(); workspace.processor?.onResultsChanged?.(); this.forceUpdate(); } private invalidate(mode: Mode, keepDraft = false) { const workspace = this.workspaces[mode]; const stale = workspace.items.some(entry => entry.result); for (const item of workspace.items) releaseResult(item); workspace.confirmed = false; delete this.firstDuration[mode]; workspace.summary = ''; workspace.message = stale ? text('设置已更改,请重新处理首张。', 'Settings changed. Process the first image again.') : ''; if (!keepDraft || (workspace.view === 'draft' && !workspace.draftUrl) || (workspace.view === 'cutout' && !workspace.cutoutDraft) || workspace.view === 'compare' || workspace.view === 'result') workspace.view = 'original'; workspace.preprocessor?.onResultsChanged?.(); workspace.processor?.onResultsChanged?.(); this.forceUpdate(); } private reset(mode: Mode) { if (this.busyFor(mode)) return; const workspace = this.workspaces[mode]; if (hasPreprocessor(mode)) { workspace.preprocessor?.dispose(); workspace.preprocessor = undefined; this.clearCutoutDraft(workspace); this.loadPreprocessor(mode); } if (mode === 'convert') this.converter = defaultConverter(); else if (mode === 'compress') this.compression = defaultCompression(); else if (mode === 'enhance') this.enhancement = defaultEnhancement(); else { workspace.processor?.dispose(); workspace.processor = undefined; this.setDraft(mode); this.loadProcessor(mode); } this.invalidate(mode); this.scrollSettings.current?.scrollTo(0, 0); } private jobQueue(workspace: Workspace) { const unprocessed = workspace.items.filter(item => !item.result && !item.error); const failed = workspace.items.filter(item => !item.result && item.error); const candidates = unprocessed.length ? unprocessed : failed; return workspace.confirmed ? candidates : candidates.slice(0, 1); } private async process(mode: Mode, run: Run, processor?: Processor) { const workspace = this.workspaces[mode]; const signal = run.controller.signal; const preprocessor = workspace.preprocessor; const cutout = preprocessor?.isEnabled() ? preprocessor : undefined; const cutoutSettings = cutout?.snapshot(); const compression = cutout && !supportsAlpha(this.compression.encoder) ? { ...this.compression, encoder: 'browserPNG' as const } : this.compression; const enhancement = cutout && !supportsAlpha(this.enhancement.format) ? { ...this.enhancement, format: 'browserPNG' as const } : this.enhancement; const processorSettings = processor?.snapshot(); for (const item of run.items) { assertSignal(signal); run.current = item; run.started = performance.now(); run.fraction = undefined; item.error = undefined; this.forceUpdate(); const progress = (value: number) => { if (this.run !== run || signal.aborted) return; run.fraction = Math.max(0, Math.min(1, value)); this.forceUpdate(); }; try { let input = item.file; if (cutout) { await this.inspectSource(item, signal); if (mode === 'enhance') validateEnhancementSize(item.width, item.height); input = await cutout.prepare(item, cutoutSettings, { signal, onProgress: value => progress(value * .65) }); progress(.65); } const processProgress = cutout ? (value: number) => progress(.65 + value * .35) : progress; let output: Processed; if (mode === 'convert') output = await convert(input, this.converter, signal); else if (mode === 'compress') output = await compress(input, compression, signal); else if (mode === 'enhance') output = await enhance(input, enhancement, signal, processProgress); else { await this.inspectSource(item, signal); const preparedUrl = input !== item.file ? URL.createObjectURL(input) : undefined; const prepared = preparedUrl ? { ...item, file: input, originalUrl: preparedUrl, previewFallback: false } : item; try { const file = await processor!.process(prepared, processorSettings, { signal, onProgress: processProgress }); output = { file, width: 0, height: 0 }; } finally { revoke(preparedUrl); } } assertSignal(signal); if (!output.file.size) throw new Error(text('处理没有生成文件。', 'Processing produced an empty file.')); await this.prepareResult(item, output, signal); } catch (error) { assertSignal(signal); item.error = errorMessage(error); } if (item.result) { if (run.first) this.firstDuration[mode] = performance.now() - run.started; workspace.confirmed = true; if (workspace.selected === item) workspace.view = item.resultUrl ? 'compare' : 'original'; } run.elapsedTotal += performance.now() - run.started; run.completed += 1; this.forceUpdate(); } } private async prepareResult(item: Item, output: Processed, signal: AbortSignal) { const url = URL.createObjectURL(output.file); let retained = false; try { const dimensions = await inspectImage(output.file, url, signal, true); assertSignal(signal); item.resultUrl = dimensions.fallback ? URL.createObjectURL(dimensions.fallback) : url; retained = !dimensions.fallback; item.resultWidth = dimensions.width; item.resultHeight = dimensions.height; } catch { assertSignal(signal); item.resultWidth = output.width || undefined; item.resultHeight = output.height || undefined; } finally { if (!retained) revoke(url); } item.result = output.file; } private start = async (mode: Mode) => { if (this.run) { if (this.run.mode === mode) this.run.controller.abort(); return; } const workspace = this.workspaces[mode]; const items = this.jobQueue(workspace); if (workspace.modeBusy || workspace.loadingPreprocessor || !items.length || (isExtension(mode) && !workspace.processor)) return; const run: Run = { controller: new AbortController(), mode, items, current: items[0], first: !workspace.confirmed, elapsedTotal: 0, completed: 0, started: performance.now(), }; this.run = run; workspace.message = ''; workspace.summary = ''; if (run.first && workspace.selected !== run.current) this.select(mode, run.current, true); else if (run.first) workspace.view = 'original'; const clock = window.setInterval(() => this.forceUpdate(), 250); try { await this.process(mode, run, workspace.processor); const failures = workspace.items.filter(item => item.error).length; workspace.summary = failures ? text(`有 ${failures} 张处理失败`, `${failures} ${failures === 1 ? 'image' : 'images'} failed`) : text('本轮处理完成', 'Processing complete'); } catch (error) { workspace.summary = run.controller.signal.aborted ? text('已停止处理', 'Processing stopped') : errorMessage(error); } finally { window.clearInterval(clock); const restoreFocus = this.state.page === mode && document.activeElement?.id === 'start-button'; this.run = undefined; workspace.preprocessor?.onResultsChanged?.(); workspace.processor?.onResultsChanged?.(); this.forceUpdate(() => { if (restoreFocus && this.state.page === mode && !document.getElementById('start-button')) { document.getElementById('export-button')?.focus({ preventScroll: true }); } }); } }; private download = (file: Blob, name?: string) => { const url = URL.createObjectURL(file); const link = document.createElement('a'); link.href = url; link.download = name || (file instanceof File ? file.name : 'tianspark-images'); document.body.append(link); link.click(); link.remove(); window.setTimeout(() => revoke(url), 60_000); }; private export = async (mode: Mode, selectedOnly = false) => { if (this.exporting || this.busyFor(mode)) return; const workspace = this.workspaces[mode]; const files = selectedOnly ? [workspace.selected?.result] : workspace.items.map(item => item.result); const results = files.filter((file): file is File => Boolean(file)); if (!results.length) return; if (results.length === 1) { this.download(results[0]); return; } this.exporting = true; this.forceUpdate(); try { const archive = await makeZip(results); this.download(archive, 'tianspark-' + mode + '.zip'); } catch (error) { workspace.message = errorMessage(error); } finally { this.exporting = false; this.forceUpdate(); } }; private zoom(mode: Mode, direction: 'in' | 'out' | 'fit') { const workspace = this.workspaces[mode]; const index = zoomSteps.indexOf(workspace.zoom); workspace.zoom = direction === 'fit' ? 100 : zoomSteps[index + (direction === 'in' ? 1 : -1)] ?? workspace.zoom; if (direction === 'fit') this.pan.current?.scrollTo(0, 0); this.forceUpdate(); } private progress(mode: Mode, workspace: Workspace): Progress | undefined { const done = workspace.items.filter(item => item.result).length; const total = workspace.items.length; const run = this.run?.mode === mode ? this.run : undefined; if (run) { const elapsed = performance.now() - run.started; const remainingCount = run.items.length - run.completed; const average = run.completed ? run.elapsedTotal / run.completed : undefined; const estimatedFallback = average ?? (run.first ? undefined : this.firstDuration[mode]); const fraction = run.fraction; const remainingTime = estimatedFallback === undefined ? fraction && elapsed ? elapsed / fraction - elapsed : undefined : Math.max(0, estimatedFallback - elapsed) + Math.max(0, remainingCount - 1) * estimatedFallback; return { title: run.first ? text('正在处理首张', 'Processing the first image') : text('正在处理剩余队列', 'Processing the remaining queue'), name: run.current.file.name, done, total, percent: fraction === undefined && run.completed === 0 ? undefined : ((run.completed + (fraction ?? 0)) / run.items.length) * 100, eta: remainingTime === undefined ? undefined : Math.ceil(remainingTime / 1000), status: text('计算剩余时间…', 'Estimating time left…'), }; } if (!workspace.summary || !total) return undefined; return { title: workspace.summary, done, total, percent: done / total * 100, status: text(`已完成 ${done} 张`, `Completed ${done} ${done === 1 ? 'image' : 'images'}`), }; } private firstDuration: Partial> = {}; private changeCompression = (settings: CompressionSettings) => { this.compression = settings; this.invalidate('compress'); }; private handleInstall = async () => { const installHelp = await requestInstall(); if (installHelp && this.state.page === 'home') { this.setState({ installHelp }, () => { const dialog = this.installDialog.current; if (!dialog || dialog.open) return; dialog.addEventListener('close', () => this.setState({ installHelp: undefined }), { once: true }); dialog.showModal(); }); } }; render({}, { page, locale, drag, compressionPreprocessingOpen, enhancementPreprocessingOpen, enhancementAdvancedOpen, editPreprocessingOpen, installHelp, }: State) { const mode = page === 'home' ? 'compress' : page; const tools = toolsFor(locale); const work = this.workspaces[mode]; const { selected: item, view } = work; const running = this.run?.mode === mode ? this.run : undefined; const busy = Boolean(this.run); const modeBusy = Boolean(work.modeBusy); const keepAlpha = Boolean(work.preprocessor?.isEnabled()); const cutoutUrl = keepAlpha && work.cutoutDraft?.id === item?.id ? work.cutoutDraft?.url : undefined; const successful = work.items.filter(file => file.result).length; const pending = work.items.filter(file => !file.result && !file.error).length; const failed = work.items.filter(file => file.error).length; const title = running ? text('停止处理', 'Stop processing') : work.confirmed && pending ? text(`处理剩余 ${pending} 张`, `Process ${pending} remaining ${pending === 1 ? 'image' : 'images'}`) : !pending && failed ? text('重试', 'Retry') + (work.confirmed ? text('失败项', ' failed items') : text('首张', ' first image')) : !work.confirmed && failed ? text('处理下一张', 'Process next image') : text('开始处理首张', 'Process first image'); const status = running && running.current === item ? text('正在处理这张图片…', 'Processing this image…') : item?.error || work.loadError || work.preprocessorLoadError || work.message || item?.previewError || (view === 'cutout' ? text('抠图预览', 'Cutout preview') : view === 'draft' ? text('操作草稿', 'Edit preview') : item?.result ? text('已生成结果', 'Result ready') : item ? item.previewReady ? text('处理后可查看对比与结果', 'Process the image to see and compare the result') : text('正在加载图片…', 'Loading image…') : text('选择文件、拖入或粘贴图片', 'Choose, drop, or paste an image')); const retryPreprocessor = hasPreprocessor(mode) && work.preprocessorLoadError && ; return ( { const input = event.currentTarget; this.addToActive(Array.from(input.files || [])); input.value = ''; }} />
{page === 'home' && }
{installHelp && (

{text(`安装 ${siteName}`, `Install ${siteName}`)}

{installHelp === 'installed' ? text(`已安装 ${siteName}。`, `${siteName} is already installed.`) : installInstructions()}

)}