import { create } from 'zustand' import { api, type ItemBody } from './api' import { tellHost, type NodeState } from './bridge' import type { FontMatch, Item, Look, Mode, Model, Options, Point, Recipe, SessionInfo, Shape, Status, Stroke, Variants, View, Models, Search, } from './types' const FALLBACK_LOOK: Look = { font: 'Arial Bold', color: '#ffffff', ownColor: true, size: 1, fill: 0.6, matchWeight: true, weight: 0, uneven: 0, seed: 0, shading: 0.6, opacity: 1, soften: 0.7, shiftX: 0, shiftY: 0, twoColors: false, color2: '#ff5a3c', split: 1, outline: 0, outlineColor: '#000000', shadow: 0, shadowColor: '#000000', shadowX: 0.06, shadowY: 0.08, shadowBlur: 0.04, effect: 'none', effectStrength: 1, relief: 0, } const FALLBACK_MODEL: Model = { strength: 0.3, steps: 24, cfg: 5, sampler: 'Euler a', resolution: 1024, padding: 64, variants: 1, cleanPrompt: true, guide: '', guideWeight: 0.6, } const HINT = 'Click the text to replace. Yellow outlines are what the search found.' let nextKey = 1 let previewTicket = 0 function bodyOf(items: Item[]): ItemBody[] { return items.map((item) => ({ recipe: item.recipe, text: item.text, erase: item.erase || undefined })) } /** A recipe without the parts that belong to it as one whole line: what goes into a block. */ function bare(recipe: Recipe): Recipe { const { shape: _shape, paint: _paint, path: _path, warp: _warp, ...rest } = recipe return rest } function sameShape(a: Shape, b: Shape) { return a.quad.length === b.quad.length && a.quad.every((point, i) => point[0] === b.quad[i][0] && point[1] === b.quad[i][1]) } interface State { options: Options | null theme: 'dark' | 'light' tab: string node: string | null session: SessionInfo | null items: Item[] mode: Mode reach: number showFound: boolean look: Look model: Model prompt: string negative: string view: View resultVersion: number | null /** The variants of the last model pass, to choose from. */ variants: Variants | null loading: boolean picking: boolean blending: boolean blended: boolean status: Status /** The line the handles and the brush work on. */ active: string | null /** The brush's radius, in screen pixels. */ brush: number /** The fonts most like the old letters of a line, once asked for. */ matches: { key: string; fonts: FontMatch[] } | null matching: boolean /** Looks saved under a name, and the one last chosen or saved. */ presets: Record preset: string search: Search readOld: boolean models: Models | null init: (options: Options) => void setTheme: (theme: 'dark' | 'light') => void setTab: (tab: string) => void openFile: (file: Blob, name: string) => Promise openUrl: (url: string, name: string) => Promise openNode: (node: string, state: NodeState) => Promise pick: (x: number, y: number) => Promise setText: (key: string, text: string) => void removeItem: (key: string) => void clearItems: () => void findAgain: () => Promise setMode: (mode: Mode) => void setReach: (reach: number) => void setShowFound: (show: boolean) => void setLook: (patch: Partial) => void setModel: (patch: Partial) => void setPrompt: (prompt: string) => void setNegative: (negative: string) => void setView: (view: View) => void choose: (index: number) => Promise preview: () => Promise blend: () => Promise apply: () => Promise undo: () => Promise save: () => Promise toGallery: () => void setStatus: (text: string, tone?: Status['tone']) => void setActive: (key: string | null) => void setBrush: (radius: number) => void setErase: (key: string, erase: boolean) => void setShape: (key: string, corners: Point[], bend: number) => Promise resetShape: (key: string) => Promise addStroke: (key: string, stroke: Stroke) => Promise clearStrokes: (key: string) => Promise joinItems: () => Promise splitItem: (key: string) => Promise setPath: (key: string, points: Point[]) => Promise clearPath: (key: string) => Promise setWarp: (key: string, warp: Point[][]) => Promise clearWarp: (key: string) => Promise matchFonts: (key: string) => Promise setSearch: (search: Search) => Promise setReadOld: (readOld: boolean) => void downloadModels: (choice: 'light' | 'full') => Promise applyPreset: (name: string) => void savePreset: (name: string) => Promise deletePreset: (name: string) => Promise } export const useStore = create((set, get) => { const fail = (error: unknown) => set({ status: { text: error instanceof Error ? error.message : String(error), tone: 'error' } }) /** A new image (or the same one after "Use as the image" or "Undo"): nothing is selected on it. */ const opened = (session: SessionInfo, keepPrompt = false) => { set((state) => ({ session, items: [], active: null, matches: null, view: 'result', resultVersion: null, variants: null, blended: false, prompt: keepPrompt ? state.prompt : session.prompt, negative: keepPrompt ? state.negative : session.negative, status: { text: session.found.length ? `Found ${session.found.length}. ${HINT}` : 'No text found by itself. Click right on a letter of the text to replace.', tone: 'info', }, })) } /** Work out a changed recipe of one line on the server, and keep it when it means something. */ const remake = async (key: string, recipe: Recipe, note?: string) => { const { session } = get() if (!session) return false try { const { selections } = await api.resolve(session.session, [{ recipe, text: '' }]) const shape = selections[0] if (!shape) { set({ status: { text: 'That leaves nothing of the line: the change is not kept.', tone: 'warning' } }) return false } set((state) => ({ items: state.items.map((item) => (item.key === key ? { ...item, recipe, shape } : item)), ...(note ? { status: { text: note, tone: 'info' as const } } : {}), })) tellNode() return true } catch (error) { fail(error) return false } } /** ComfyUI keeps the selections and the look in the node: tell it after every change. */ const tellNode = () => { const { node, items, look } = get() if (node) tellHost({ type: 'TF_STATE', state: { items: bodyOf(items), look } }) } return { options: null, theme: 'dark', tab: 'txt2img', node: null, session: null, items: [], mode: 'new', reach: 0.3, showFound: true, look: FALLBACK_LOOK, model: FALLBACK_MODEL, prompt: '', negative: '', view: 'result', resultVersion: null, variants: null, loading: false, picking: false, blending: false, blended: false, status: { text: 'Drop an image here, paste one, or open a file.', tone: 'info' }, active: null, brush: 12, matches: null, matching: false, presets: {}, preset: '', search: 'auto', readOld: true, models: null, init: (options) => set({ options, look: { ...FALLBACK_LOOK, ...options.settings.look }, model: { ...FALLBACK_MODEL, ...options.settings.model, // A ControlNet model kept from before that the host no longer has is dropped. guide: (options.controlnets ?? []).includes(options.settings.model.guide ?? '') ? options.settings.model.guide : '', }, reach: options.settings.reach, showFound: options.settings.showFound, presets: options.presets ?? {}, search: options.settings.search ?? 'auto', readOld: options.settings.readOld ?? true, models: options.models ?? null, }), setTheme: (theme) => set({ theme }), setTab: (tab) => set({ tab }), openFile: async (file, name) => { set({ loading: true, status: { text: 'Opening the image and looking for text…', tone: 'info' } }) try { opened(await api.upload(file, name)) } catch (error) { fail(error) } finally { set({ loading: false }) } }, openUrl: async (url, name) => { set({ loading: true, status: { text: 'Opening the image and looking for text…', tone: 'info' } }) try { const response = await fetch(url) if (!response.ok) throw new Error(`Could not load the image (${response.status}).`) opened(await api.upload(await response.blob(), name)) } catch (error) { fail(error) } finally { set({ loading: false }) } }, openNode: async (node, state) => { set({ node, loading: true, status: { text: 'Opening the image the node received…', tone: 'info' } }) if (state.look) set((current) => ({ look: { ...current.look, ...state.look } })) try { const session = await api.node(node) opened(session) const saved = (state.items || []).filter((item) => item && item.recipe) if (saved.length) { const { selections } = await api.resolve(session.session, saved) const items: Item[] = [] saved.forEach((item, index) => { const shape = selections[index] if (shape) items.push({ key: `i${nextKey++}`, recipe: item.recipe, shape, text: item.text || '', erase: !!item.erase }) }) set({ items, active: items.length ? items[items.length - 1].key : null }) } } catch (error) { fail(error) } finally { set({ loading: false }) } }, pick: async (x, y) => { const { session, mode, items, reach, picking, active } = get() if (!session || picking) return const last = items.find((item) => item.key === active) ?? items[items.length - 1] const extend: Recipe | undefined = mode === 'extend' && last ? last.recipe : undefined set({ picking: true }) try { const answer = await api.pick(session.session, x, y, reach, extend) if (!answer.recipe || !answer.selection) { set({ status: { text: 'No text found there. Click right on a letter, or widen the search area.', tone: 'warning' } }) return } const shape = answer.selection const recipe = answer.recipe set((state) => { let next: Item[] let active: string if (extend && last) { next = state.items.map((item) => (item.key === last.key ? { ...item, recipe, shape } : item)) active = last.key } else { const existing = state.items.find((item) => sameShape(item.shape, shape)) // A new line starts with what its old letters say, when they can be read. const fresh = existing ?? { key: `i${nextKey++}`, recipe, shape, text: answer.reading ?? '' } next = mode === 'add' ? (existing ? state.items : [...state.items, fresh]) : [fresh] active = fresh.key } return { items: next, active, status: { text: next.length > 1 ? `${next.length} lines selected. Type the new text for each.` : `Selected: ${shape.width} × ${shape.height} px. Type the new text.`, tone: 'info', }, } }) tellNode() } catch (error) { fail(error) } finally { set({ picking: false }) } }, setText: (key, text) => { set((state) => ({ items: state.items.map((item) => (item.key === key ? { ...item, text } : item)) })) tellNode() }, removeItem: (key) => { set((state) => ({ items: state.items.filter((item) => item.key !== key), active: state.active === key ? null : state.active, })) tellNode() }, clearItems: () => { set({ items: [], active: null, status: { text: HINT, tone: 'info' } }) tellNode() }, findAgain: async () => { const { session } = get() if (!session) return set({ loading: true }) try { const { found } = await api.find(session.session) set((state) => ({ session: state.session ? { ...state.session, found } : state.session, items: [], active: null, status: { text: found.length ? `Found ${found.length}. ${HINT}` : 'No text found by itself.', tone: 'info' }, })) tellNode() } catch (error) { fail(error) } finally { set({ loading: false }) } }, setMode: (mode) => set({ mode }), setReach: (reach) => set({ reach }), setShowFound: (showFound) => set({ showFound }), setLook: (patch) => { set((state) => ({ look: { ...state.look, ...patch } })) tellNode() }, setModel: (patch) => set((state) => ({ model: { ...state.model, ...patch } })), setPrompt: (prompt) => set({ prompt }), setNegative: (negative) => set({ negative }), setView: (view) => set({ view }), preview: async () => { const { session, items, look } = get() if (!session) return const ticket = ++previewTicket try { const answer = await api.preview(session.session, bodyOf(items), look) if (ticket !== previewTicket) return // a newer preview is on its way set((state) => ({ resultVersion: answer.empty ? null : answer.version, blended: false, variants: null, view: state.view === 'compare' && !answer.empty ? 'compare' : 'result', })) } catch (error) { if (ticket === previewTicket) fail(error) } }, choose: async (index) => { const { session, variants } = get() if (!session || !variants || index === variants.chosen) return try { const answer = await api.choose(session.session, index) set((state) => ({ resultVersion: answer.version, variants: state.variants ? { ...state.variants, chosen: index } : null, view: state.view === 'image' ? 'result' : state.view, status: { text: `Variant ${index + 1} (seed ${variants.seeds[index]}) is the result.`, tone: 'info' }, })) } catch (error) { fail(error) } }, blend: async () => { const { session, items, look, model, prompt, negative, blending } = get() if (!session || blending) return if (!items.some((item) => item.text.trim() || item.erase)) { set({ status: { text: 'Type the new text first, or mark a line as erase only.', tone: 'warning' } }) return } previewTicket++ // a preview still on its way must not cover the blended result set({ blending: true, status: { text: 'The model is blending the letters in…', tone: 'info' } }) try { const answer = await api.blend(session.session, bodyOf(items), look, { ...model, prompt, negative }) const count = answer.variants ?? 0 const left = answer.removed?.length ? ` Left out of the prompt: ${answer.removed.join(', ')}.` : '' const done = count > 1 ? `${count} variants. Pick the one whose letters came out right, under the image.` : 'Blended in. Save it, send it on, or use it as the image to go on.' set((state) => ({ resultVersion: answer.version, view: state.view === 'compare' ? 'compare' : 'result', blended: answer.blended, variants: count > 1 ? { count, chosen: 0, seeds: answer.seeds ?? [], version: answer.version } : null, status: answer.blended ? answer.warning ? { text: answer.warning + left, tone: 'warning' } : { text: done + left, tone: 'success' } : { text: (answer.warning || 'The model pass failed.') + left, tone: 'warning' }, })) } catch (error) { fail(error) } finally { set({ blending: false }) } }, apply: async () => { const { session, resultVersion } = get() if (!session || resultVersion === null) return try { opened(await api.apply(session.session), true) tellNode() } catch (error) { fail(error) } }, undo: async () => { const { session } = get() if (!session || !session.history) return try { opened(await api.undo(session.session), true) tellNode() } catch (error) { fail(error) } }, save: async () => { const { session, tab } = get() if (!session) return try { const { path } = await api.save(session.session, tab) set({ status: { text: `Saved: ${path}`, tone: 'success' } }) } catch (error) { fail(error) } }, toGallery: () => { const { session } = get() if (session) tellHost({ type: 'TF_TO_GALLERY', session: session.session }) }, setStatus: (text, tone = 'info') => set({ status: { text, tone } }), setActive: (active) => set({ active }), setBrush: (brush) => set({ brush }), setErase: (key, erase) => { set((state) => ({ items: state.items.map((item) => (item.key === key ? { ...item, erase } : item)) })) tellNode() }, setShape: async (key, corners, bend) => { const item = get().items.find((entry) => entry.key === key) if (!item) return await remake(key, { ...item.recipe, shape: { corners, bend: Math.round(bend * 10) / 10 } }) }, resetShape: async (key) => { const item = get().items.find((entry) => entry.key === key) if (!item || !item.recipe.shape) return const { shape: _shape, ...recipe } = item.recipe await remake(key, recipe, 'The place for the new text is the one the letters gave again.') }, addStroke: async (key, stroke) => { const item = get().items.find((entry) => entry.key === key) if (!item || !stroke.points.length) return await remake(key, { ...item.recipe, paint: [...(item.recipe.paint ?? []), stroke] }) }, clearStrokes: async (key) => { const item = get().items.find((entry) => entry.key === key) if (!item || !item.recipe.paint) return const { paint: _paint, ...recipe } = item.recipe await remake(key, recipe, 'The brush strokes of the line are gone.') }, joinItems: async () => { const { items, session } = get() if (!session || items.length < 2) return const parts = items.flatMap((item) => (item.recipe.join ? item.recipe.join : [bare(item.recipe)])) const recipe: Recipe = { join: parts } try { const { selections } = await api.resolve(session.session, [{ recipe, text: '' }]) const shape = selections[0] if (!shape) throw new Error('The lines could not be joined.') const key = `i${nextKey++}` const text = items .map((item) => item.text) .filter((line) => line.trim()) .join('\n') set({ items: [{ key, recipe, shape, text }], active: key, status: { text: `${parts.length} lines joined into one block. Type its text: a line break starts a new line.`, tone: 'info' }, }) tellNode() } catch (error) { fail(error) } }, splitItem: async (key) => { const { items, session } = get() const block = items.find((item) => item.key === key) if (!session || !block?.recipe.join) return try { const parts = block.recipe.join const { selections } = await api.resolve( session.session, parts.map((recipe) => ({ recipe, text: '' })), ) const lines = block.text.split('\n') const made: Item[] = [] parts.forEach((recipe, index) => { const shape = selections[index] if (shape) made.push({ key: `i${nextKey++}`, recipe, shape, text: lines[index] ?? '' }) }) set((state) => ({ items: state.items.flatMap((item) => (item.key === key ? made : [item])), active: made.length ? made[0].key : null, status: { text: `The block is ${made.length} lines again.`, tone: 'info' }, })) tellNode() } catch (error) { fail(error) } }, setPath: async (key, points) => { const item = get().items.find((entry) => entry.key === key) if (!item || points.length < 2) return // A new place for the text: the hand shape and the warp were made for the old one. const { shape: _shape, warp: _warp, ...recipe } = item.recipe const rounded = points.map(([x, y]) => [Math.round(x * 10) / 10, Math.round(y * 10) / 10] as Point) await remake(key, { ...recipe, path: rounded }, 'The new text follows the line you drew.') }, clearPath: async (key) => { const item = get().items.find((entry) => entry.key === key) if (!item || !item.recipe.path) return const { path: _path, warp: _warp, ...recipe } = item.recipe await remake(key, recipe, 'The new text is back where the old one was.') }, setWarp: async (key, warp) => { const item = get().items.find((entry) => entry.key === key) if (!item) return const rounded = warp.map((row) => row.map(([x, y]) => [Math.round(x * 10) / 10, Math.round(y * 10) / 10] as Point)) const moved = rounded.some((row) => row.some(([x, y]) => x !== 0 || y !== 0)) const { warp: _warp, ...recipe } = item.recipe await remake(key, moved ? { ...recipe, warp: rounded } : recipe) }, clearWarp: async (key) => { const item = get().items.find((entry) => entry.key === key) if (!item || !item.recipe.warp) return const { warp: _warp, ...recipe } = item.recipe await remake(key, recipe, 'The letters are no longer bent by hand.') }, setSearch: async (search) => { set({ search }) const { look, model, reach, showFound, readOld, session } = get() try { // The server looks by what is kept: keep it now, then look again. await api.saveSettings({ look, model, reach, showFound, search, readOld }) set({ models: await api.models('status') }) if (session) await get().findAgain() } catch (error) { fail(error) } }, setReadOld: (readOld) => { set({ readOld }) const { look, model, reach, showFound, search } = get() // The server reads the old letters by what is kept: keep it now, not a moment later. void api.saveSettings({ look, model, reach, showFound, search, readOld }).catch(() => undefined) }, downloadModels: async (choice) => { try { let state = await api.models('download', choice) set({ models: state, status: { text: 'Fetching the detector’s models…', tone: 'info' } }) while (state.download.running) { await new Promise((done) => window.setTimeout(done, 700)) state = await api.models('status') set({ models: state }) } if (state.download.error) throw new Error(`The download failed: ${state.download.error}`) set({ status: { text: 'The detector is here. Find text looks with it now.', tone: 'success' } }) if (get().session) await get().findAgain() } catch (error) { fail(error) } }, applyPreset: (name) => { const saved = get().presets[name] if (!saved) return const fonts = get().options?.fonts ?? [] // A font the preset names but this host lacks leaves the current one in place. const look = { ...FALLBACK_LOOK, ...saved, font: fonts.includes(saved.font) ? saved.font : get().look.font } set({ look, preset: name, status: { text: `The look of “${name}”.`, tone: 'info' } }) tellNode() }, savePreset: async (name) => { const clean = name.trim() if (!clean) return try { const { presets } = await api.presets('save', clean, get().look) set({ presets, preset: clean, status: { text: `The look is saved as “${clean}”.`, tone: 'success' } }) } catch (error) { fail(error) } }, deletePreset: async (name) => { try { const { presets } = await api.presets('delete', name) set((state) => ({ presets, preset: state.preset === name ? '' : state.preset, status: { text: `“${name}” is deleted.`, tone: 'info' }, })) } catch (error) { fail(error) } }, matchFonts: async (key) => { const { session, items, matching } = get() const item = items.find((entry) => entry.key === key) if (!session || !item || matching) return set({ matching: true }) try { const { fonts } = await api.match(session.session, item.recipe) set({ matches: { key, fonts }, status: fonts.length ? { text: `Closest to the old letters: ${fonts[0].name}. Pick one of the five below the font list.`, tone: 'info' } : { text: 'The old letters are too few or too blurred to tell their font.', tone: 'warning' }, }) } catch (error) { fail(error) } finally { set({ matching: false }) } }, } })