end to end app store screenshot creation using AI
TypeScript agentic-aiappleappstoreautomateclaudecursordesigngenerateiosios-appmarketingscreenshotskillsskills-shswiftswiftuiui
Fix editor/export bugs found in bug bash; export 24-bit RGB PNGs
Parth Jadhav94724257f84b
diff --git a/scripts/bug-bash.cjs b/scripts/bug-bash.cjsindex e422e30..f78d425 100644--- a/scripts/bug-bash.cjs+++ b/scripts/bug-bash.cjs@@ -101,6 +101,7 @@ const fixture = (extra = {}) => ({schemaVersion:2,appName:'Bug bash',themeId:'clfor(const png of pngs) {const bytes=await png.async('nodebuffer'); const [,w,h]=png.name.match(/\/(\d+)x(\d+)\//);assert.equal(bytes.readUInt32BE(16),Number(w)); assert.equal(bytes.readUInt32BE(20),Number(h));+ assert.equal(bytes[25],2,'stores need opaque 24-bit RGB PNGs, not RGBA');}await page.getByRole('button',{name:'Export bundle',exact:true}).waitFor();assert.equal(await page.locator('[inert]').count(),0); assert.equal(downloadCount,1); await page.close();@@ -133,10 +134,10 @@ const fixture = (extra = {}) => ({schemaVersion:2,appName:'Bug bash',themeId:'clawait inspector.getByRole('combobox').nth(1).click();await page.getByRole('option',{name:'Custom color',exact:true}).click();await page.getByRole('textbox',{name:'Custom background hex color',exact:true}).fill('#FFFFFF');- const caption=page.locator('main [contenteditable=true]').first();+ const caption=page.locator('main [contenteditable=plaintext-only]').first();assert.equal(await caption.evaluate(el=>getComputedStyle(el).color),'rgb(23, 23, 23)');assert.equal(await caption.evaluate(el=>getComputedStyle(el.parentElement.parentElement.parentElement).backgroundColor),'rgb(255, 255, 255)');- await page.locator('main [contenteditable=true]').nth(1).focus();+ await page.locator('main [contenteditable=plaintext-only]').nth(1).focus();assert.match(await page.locator('main').innerText(),/Screen 2/);assert.equal(await page.locator('textarea').first().inputValue(),'banner two');await page.close();@@ -199,6 +200,94 @@ const fixture = (extra = {}) => ({schemaVersion:2,appName:'Bug bash',themeId:'clconst roundTrip=await request.get(baseURL+'/api/project');assert.deepEqual((await roundTrip.json()).state,payload.state);await context.close();});+ await check('out-of-bounds elements export where the editor shows them',async()=>{+ const {page}=await open(fixture({connectedCanvas:false,slidesByDevice:{watchos:[slide('a',{textElements:[{id:'t1',text:{en:'WIDE'},transform:{x:300,y:10,width:300,height:80,zIndex:6}}]})]}}));+ const editorX=await page.locator('main .rnd-editable').last().evaluate(el=>new DOMMatrix(getComputedStyle(el).transform).m41);+ const exportX=await page.locator('[aria-hidden] [contenteditable=false]').filter({hasText:'WIDE'}).last().evaluate(el=>parseFloat(el.closest('div[style*="z-index"]').style.left));+ assert.equal(exportX,editorX); await page.close();+ });+ await check('clearing inline copy saves nothing and shows the fallback after blur',async()=>{+ const {page,latest}=await open(fixture({locales:['en','de'],locale:'de',slidesByDevice:{watchos:[slide('a',{headline:{en:'English',de:'Deutsch'}})]}}));+ const headline=page.locator('main [contenteditable=plaintext-only]').nth(1);+ await headline.click(); await page.keyboard.press('ControlOrMeta+A'); await page.keyboard.press('Backspace');+ await page.locator('textarea').first().click(); await pause(900);+ assert.equal(latest().slidesByDevice.watchos[0].headline.de,undefined);+ assert.equal(await headline.textContent(),'English'); await page.close();+ });+ await check('overlay text can be cleared and retyped in a non-default locale',async()=>{+ const {page,latest}=await open(fixture({locales:['en','de'],locale:'de',slidesByDevice:{watchos:[slide('a',{textElements:[{id:'t1',text:{en:'Hello'},transform:{x:10,y:10,width:300,height:80,zIndex:6}}]})]}}));+ await page.locator('main [contenteditable=plaintext-only]').nth(2).focus();+ const text=page.getByRole('textbox',{name:'Overlay text',exact:true});+ assert.equal(await text.inputValue(),''); assert.equal(await text.getAttribute('placeholder'),'Hello');+ await text.fill('Hallo'); await pause(900);+ assert.deepEqual(latest().slidesByDevice.watchos[0].textElements[0].text,{en:'Hello',de:'Hallo'}); await page.close();+ });+ await check('RTL copy gets its own base direction',async()=>{+ const {page}=await open(fixture({locales:['en','he'],locale:'he',slidesByDevice:{watchos:[slide('a',{headline:{en:'Hi',he:'שלום עולם!'}})]}}));+ const headline=page.locator('main [contenteditable=plaintext-only]').nth(1);+ assert.equal(await headline.evaluate(el=>getComputedStyle(el).direction),'rtl');+ assert.equal(await page.locator('main [contenteditable=plaintext-only]').first().evaluate(el=>getComputedStyle(el).direction),'ltr'); await page.close();+ });+ await check('generated feature-graphic decks normalise without an undo step',async()=>{+ const {page,latest}=await open(fixture({device:'feature-graphic',slidesByDevice:{'feature-graphic':[slide('one',{layout:'hero'}),slide('two',{layout:'hero'})]}}));+ await pause(1000);+ assert.equal(await page.getByRole('button',{name:'Undo',exact:true}).isEnabled(),false);+ assert.deepEqual(latest().slidesByDevice['feature-graphic'].map(s=>s.layout),['feature-graphic','feature-graphic']); await page.close();+ });+ await check('feature graphic app icon can be picked and exports',async()=>{+ const JSZip=require('../skills/app-store-screenshots/template/node_modules/jszip');+ const {page,latest}=await open(fixture({device:'feature-graphic',slidesByDevice:{'feature-graphic':[slide('banner',{layout:'feature-graphic'})]}}));+ const png=await page.evaluate(()=>{const c=document.createElement('canvas');c.width=64;c.height=64;const x=c.getContext('2d');x.fillStyle='#00ff00';x.fillRect(0,0,64,64);return c.toDataURL().split(',')[1]});+ await page.route('**/api/upload',route=>route.fulfill({json:{ok:true,path:'/bugbash-icon.png'}}));+ await page.locator('aside').last().locator('input[type=file]').setInputFiles({name:'icon.png',mimeType:'image/png',buffer:Buffer.from(png,'base64')});+ await pause(900); assert.equal(latest().appIcon,'/bugbash-icon.png');+ const downloaded=page.waitForEvent('download');+ await page.route('**/bugbash-icon.png',route=>route.fulfill({body:Buffer.from(png,'base64'),contentType:'image/png'}));+ await page.getByRole('button',{name:'Export bundle',exact:true}).click();+ const zip=await JSZip.loadAsync(await fs.readFile(await (await downloaded).path()));+ const image=await Object.values(zip.files).find(f=>f.name.endsWith('.png')).async('base64');+ const green=await page.evaluate(async data=>{const img=new Image();img.src='data:image/png;base64,'+data;await img.decode();const c=document.createElement('canvas');c.width=img.width;c.height=img.height;const x=c.getContext('2d');x.drawImage(img,0,0);const p=x.getImageData(0,0,c.width,c.height).data;let n=0;for(let i=0;i<p.length;i+=4)if(p[i]<30&&p[i+1]>225&&p[i+2]<30)n++;return n},image);+ assert.ok(green>1000,'icon missing from feature graphic export'); await page.close();+ });+ await check('reset all devices keeps project settings and locales',async()=>{+ const {page,latest}=await open(fixture({appName:'Keep me',themeId:'dark-bold',locales:['en','de'],locale:'de',connectedCanvas:false}));+ await page.getByRole('button',{name:/reset/i}).first().click();+ await page.getByRole('button',{name:'Reset all devices',exact:true}).click(); await pause(900);+ const state=latest();+ assert.equal(state.appName,'Keep me'); assert.equal(state.themeId,'dark-bold'); assert.deepEqual(state.locales,['en','de']);+ assert.equal(state.locale,'de'); assert.equal(state.connectedCanvas,false); assert.equal(state.device,'watchos');+ assert.notEqual(state.slidesByDevice.watchos[0].id,'first'); await page.close();+ });+ await check('pasted rich text stays plain on the canvas',async()=>{+ const context=await browser.newContext({viewport:{width:1600,height:1000}});+ await context.grantPermissions(['clipboard-read','clipboard-write'],{origin:new URL(baseURL).origin});+ const page=await context.newPage(); let latest=fixture();+ page.on('pageerror',error=>errors.push(error.message));+ await page.route('**/api/project',async route=>{if(route.request().method()==='POST')latest=route.request().postDataJSON();await route.fulfill({json:{ok:true,state:latest}})});+ await page.goto(baseURL); await page.getByRole('button',{name:'Export bundle',exact:true}).waitFor();+ await page.evaluate(async()=>navigator.clipboard.write([new ClipboardItem({'text/html':new Blob(['<span style="color:red;font-size:80px">Pasted</span>'],{type:'text/html'}),'text/plain':new Blob(['Pasted'],{type:'text/plain'})})]));+ const headline=page.locator('main [contenteditable=plaintext-only]').nth(1);+ await headline.click(); await page.keyboard.press('ControlOrMeta+A'); await page.keyboard.press('ControlOrMeta+V'); await pause(900);+ assert.equal(await headline.evaluate(el=>el.children.length),0); assert.equal(await headline.textContent(),'Pasted');+ assert.equal(latest.slidesByDevice.watchos[0].headline.en,'Pasted'); await context.close();+ });+ await check('export finishes inline when PNG workers fail to load',async()=>{+ const JSZip=require('../skills/app-store-screenshots/template/node_modules/jszip');+ const context=await browser.newContext({viewport:{width:1600,height:1000}});+ // A worker whose script never loads: it reports an error and never replies.+ await context.addInitScript(()=>{window.Worker=class extends EventTarget{constructor(){super();setTimeout(()=>this.onerror?.(new ErrorEvent('error',{message:'blocked'})),200)}postMessage(){}terminate(){}}});+ const page=await context.newPage(); let latest=fixture();+ page.on('pageerror',error=>errors.push(error.message));+ await page.route('**/api/project',async route=>{if(route.request().method()==='POST')latest=route.request().postDataJSON();await route.fulfill({json:{ok:true,state:latest}})});+ await page.goto(baseURL); await page.getByRole('button',{name:'Export bundle',exact:true}).waitFor();+ const downloaded=page.waitForEvent('download',{timeout:60000});+ await page.getByRole('button',{name:'Export bundle',exact:true}).click();+ const zip=await JSZip.loadAsync(await fs.readFile(await (await downloaded).path()));+ const pngs=Object.values(zip.files).filter(f=>f.name.endsWith('.png'));+ assert.equal(pngs.length,12);+ for(const png of pngs) assert.equal((await png.async('nodebuffer'))[25],2);+ await context.close();+ });assert.deepEqual(errors,[]);assert.ok(passed>0,'No matching checks');console.log(`${passed} browser regression checks passed in Google Chrome.`);diff --git a/skills/app-store-screenshots/SKILL.md b/skills/app-store-screenshots/SKILL.mdindex 5ea39d6..e0af800 100644--- a/skills/app-store-screenshots/SKILL.md+++ b/skills/app-store-screenshots/SKILL.md@@ -203,8 +203,16 @@ function firstString(...values) {return values.find((value) => typeof value === "string") || "";}-function migrateSlide(slide) {- if (!slide || typeof slide !== "object") return null;+// The editor refuses to load a deck with empty or repeated screen ids.+function uniqueId(value, used) {+ let id = typeof value === "string" && value.trim() ? value : "";+ while (!id || used.has(id)) id = `migrated-${Math.random().toString(36).slice(2, 10)}`;+ used.add(id);+ return id;+}++function migrateSlide(slide, used) {+ if (!slide || typeof slide !== "object" || Array.isArray(slide)) return null;const transforms = {};const rawTransforms = slide.transforms && typeof slide.transforms === "object" ? slide.transforms : {};for (const [id, transform] of Object.entries(rawTransforms)) {@@ -227,11 +235,12 @@ function migrateSlide(slide) {return {...slide,- id: typeof slide.id === "string" ? slide.id : `migrated-${Math.random().toString(36).slice(2, 10)}`,+ id: uniqueId(slide.id, used),layout: LAYOUTS.includes(slide.layout) ? slide.layout : "device-bottom",label: localized(slide.label),headline: localized(slide.headline || slide.title || slide.caption || slide.copy),screenshot: firstString(slide.screenshot, slide.image, slide.src, slide.path),+ screenshotSecondary: typeof slide.screenshotSecondary === "string" ? slide.screenshotSecondary : undefined,...(Object.keys(transforms).length ? { transforms } : { transforms: undefined }),...(textElements && textElements.length ? { textElements } : { textElements: undefined }),};@@ -239,14 +248,30 @@ function migrateSlide(slide) {state.schemaVersion = 2;state.connectedCanvas = hasExplicitConnectedCanvas ? existingState.connectedCanvas : false;-state.locales = Array.isArray(state.locales) && state.locales.length ? state.locales : [DEFAULT_LOCALE];+// Unique codes like "en", "pt-BR", "zh_Hans"; anything else makes the editor refuse the file.+const LOCALE_CODE = /^[a-zA-Z0-9]+(?:[-_][a-zA-Z0-9]+)*$/;+state.locales = Array.isArray(state.locales)+ ? [...new Set(state.locales.filter((locale) => typeof locale === "string" && LOCALE_CODE.test(locale)))]+ : [];+if (!state.locales.length) state.locales = [DEFAULT_LOCALE];state.locale = state.locales.includes(state.locale) ? state.locale : state.locales[0];state.device = DEVICE_KEYS.includes(state.device) ? state.device : "iphone";+if (state.orientation !== "portrait" && state.orientation !== "landscape") delete state.orientation;+for (const key of ["appName", "themeId", "appIcon"]) {+ if (state[key] !== undefined && typeof state[key] !== "string") delete state[key];+}+// The feature graphic only shows an icon that `appIcon` points at.+if (!state.appIcon && fs.existsSync(path.join("public", "app-icon.png"))) state.appIcon = "/app-icon.png";if (state.slidesByDevice && typeof state.slidesByDevice === "object") {for (const [device, slides] of Object.entries(state.slidesByDevice)) {- if (!DEVICE_KEYS.includes(device)) continue;- state.slidesByDevice[device] = Array.isArray(slides) ? slides.map(migrateSlide).filter(Boolean) : [];+ // The editor only accepts known device decks; the backup keeps the original.+ if (!DEVICE_KEYS.includes(device)) {+ delete state.slidesByDevice[device];+ continue;+ }+ const used = new Set();+ state.slidesByDevice[device] = Array.isArray(slides) ? slides.map((slide) => migrateSlide(slide, used)).filter(Boolean) : [];}}@@ -405,6 +430,7 @@ The starter project state lives in `app-store-screenshots.json`, not `src/lib/deIf the user provided headlines, edit `app-store-screenshots.json` to set:- `appName`- `themeId` (one of `"clean-light" | "dark-bold" | "warm-editorial" | "ocean-fresh" | "bloom-roast"`, a named style slug such as `"swiss-grid-bold"` when the user picked that style, or add a matching entry to `THEMES` in `src/lib/constants.ts`). Themes may set `accentAlt` for the label color on inverted slides.+- `appIcon` — public path of the app icon (e.g. `"/app-icon.png"` after copying it to `public/app-icon.png`). The Play Store feature graphic shows it; blank uses the app's initial. The icon can also be picked in the feature-graphic inspector.- `connectedCanvas` (`true` for new connected decks; migrated legacy decks should stay `false` until the user opts in)- Starter slides per device with the user's `label` + `headline` + screenshot paths- Optional per-slide `typography: { labelScale, headlineScale, appNameScale }` (0.5–2, default 1) when one headline is much longer or shorter than the rest of the deck. `appNameScale` only applies to the feature graphic, where `headlineScale` sizes the tagline.@@ -586,7 +612,7 @@ The editor stores headlines and labels per-locale on each slide — switch to a- Don't literally translate — rewrite for the target market.- Re-check line breaks per locale; German/French/Portuguese often need shorter claims.-- For RTL (`ar`, `he`, `fa`, `ur`), the template handles direction inversion through CSS — let the user verify each slide looks intentional, not just flipped.+- For RTL (`ar`, `he`, `fa`, `ur`), canvas text picks its direction from its own content (`dir="auto"`), so punctuation lands on the correct side and left-set captions align to the right edge. Layouts, devices and overlays are not mirrored — let the user verify each slide looks intentional.## Step 5: Export Timediff --git a/skills/app-store-screenshots/template/README.md b/skills/app-store-screenshots/template/README.mdindex 9f72b97..d356359 100644--- a/skills/app-store-screenshots/template/README.md+++ b/skills/app-store-screenshots/template/README.md@@ -41,7 +41,7 @@ The toolbar dropdown lists every Apple/Google-required size for the current deviExports lock the editor through preparation and bundling and render a fixed project snapshot. Referenced images that cannot be loaded stop the export with an error; empty screenshot fields still produce the existing placeholder warning.-Each screen is rendered once per locale at canvas resolution (`src/lib/export-render.ts`) and scaled to every size; slots whose aspect differs slightly are cover-scaled rather than stretched. Before saving, the exporter redraws until every visible screenshot has painted, because WebKit decodes images inside the html-to-image SVG asynchronously and a single draw can leave device screens blank. If a screenshot never appears, a toast names the screen.+Each screen is rendered once per locale at canvas resolution (`src/lib/export-render.ts`) and scaled to every size; slots whose aspect differs slightly are cover-scaled rather than stretched. Before saving, the exporter redraws until every visible screenshot has painted, because WebKit decodes images inside the html-to-image SVG asynchronously and a single draw can leave device screens blank. If a screenshot never appears, a toast names the screen. Files are written as opaque 24-bit RGB PNGs (`src/lib/png-rgb.ts`, encoded in a small worker pool) because Google Play rejects PNGs with an alpha channel and canvas can only produce RGBA.CarPlay has no App Store Connect slot of its own: the CarPlay deck is a head-unit frame on a landscape iPhone canvas and exports landscape iPhone sizes for upload into the iPhone slot.diff --git a/skills/app-store-screenshots/template/src/components/editor/inspector.tsx b/skills/app-store-screenshots/template/src/components/editor/inspector.tsxindex 4b02250..bfbad41 100644--- a/skills/app-store-screenshots/template/src/components/editor/inspector.tsx+++ b/skills/app-store-screenshots/template/src/components/editor/inspector.tsx@@ -49,6 +49,7 @@ import {toTextElementId,} from "@/lib/elements";import { pickText, writeLocalized } from "@/lib/locale";+import { slideColors } from "@/lib/contrast";import { cn } from "@/lib/utils";import {cleanTypography,@@ -82,6 +83,8 @@ type Props = {orientation: Orientation;theme: Theme;locale: string;+ appIcon?: string;+ onAppIconChange: (src: string) => void;selectedElementId: ElementId | null;onChange: (patch: Partial<Slide>) => void;/** Patch computed from the slide's latest state (safe after async work). */@@ -101,6 +104,8 @@ export function Inspector({orientation,theme,locale,+ appIcon,+ onAppIconChange,selectedElementId,onChange,onUpdate,@@ -126,12 +131,6 @@ export function Inspector({onChange({ [key]: writeLocalized(slide[key], locale, value) } as Partial<Slide>);}- React.useEffect(() => {- if (device === "feature-graphic" && slide.layout !== "feature-graphic") {- onChange({ layout: "feature-graphic", transforms: undefined, screenshotSecondary: undefined });- }- }, [device, onChange, slide.layout]);-return (<div className="flex h-full flex-col"><div className="border-b p-3">@@ -232,6 +231,7 @@ export function Inspector({{!isFeatureGraphic && (<ElementTransformControlsslide={slide}+ defaultTextColor={slideColors(theme, slide).fg}device={device}orientation={orientation}locale={locale}@@ -243,9 +243,13 @@ export function Inspector({)}{isFeatureGraphic && (- <p className="rounded-md border bg-muted/40 p-3 text-[11px] leading-relaxed text-muted-foreground">- Shows app icon + name + tagline. Drop an icon at <span className="rounded bg-background px-1 py-0.5 font-mono text-[10px] text-foreground">/public/app-icon.png</span> (or leave blank — the app initial will be used). Name is set in the toolbar.- </p>+ <div className="space-y-1.5">+ <Label className="text-xs">App icon</Label>+ <ScreenshotPicker label="Icon (shared by every banner)" value={appIcon || ""} onChange={onAppIconChange} />+ <p className="text-[11px] leading-relaxed text-muted-foreground">+ Shows app icon + name + tagline. Leave the icon blank to use the app's initial. Name is set in the toolbar.+ </p>+ </div>)}</div></div>@@ -293,6 +297,7 @@ function CopyIdeasMenu({ onPick }: { onPick: (formula: string) => void }) {function ElementTransformControls({slide,+ defaultTextColor,device,orientation,locale,@@ -302,6 +307,7 @@ function ElementTransformControls({onSelectElement,}: {slide: Slide;+ defaultTextColor: string;device: Device;orientation: Orientation;locale: string;@@ -554,6 +560,7 @@ function ElementTransformControls({imageElement={activeImageElement || undefined}locale={locale}canvas={{ cW, cH }}+ defaultTextColor={defaultTextColor}onRotate={(rotation) => patchElement(activeId, { rotation })}onReorder={(dir) => reorder(activeId, dir)}onTextChange={(value) => {@@ -591,6 +598,7 @@ function ActiveElementPanel({imageElement,locale,canvas,+ defaultTextColor,onRotate,onReorder,onTextChange,@@ -606,6 +614,7 @@ function ActiveElementPanel({imageElement?: ImageElement;locale: string;canvas: { cW: number; cH: number };+ defaultTextColor: string;onRotate: (rotation: number) => void;onReorder: (dir: "front" | "back" | "up" | "down") => void;onTextChange: (value: string) => void;@@ -649,6 +658,7 @@ function ActiveElementPanel({element={textElement}locale={locale}canvas={canvas}+ defaultColor={defaultTextColor}onTextChange={onTextChange}onTextPatch={onTextPatch}/>@@ -773,16 +783,21 @@ function TextElementPanel({element,locale,canvas,+ defaultColor,onTextChange,onTextPatch,}: {element: TextElement;locale: string;canvas: { cW: number; cH: number };+ defaultColor: string;onTextChange: (value: string) => void;onTextPatch: (patch: Partial<TextElement>) => void;}) {- const text = element.text?.[locale] ?? pickText(element.text, locale);+ // Like the headline field: the locale's own text, with the fallback shown as+ // a placeholder, so clearing a translation doesn't snap back to English.+ const text = element.text?.[locale] ?? "";+ const textPlaceholder = pickText(element.text, locale) || "Overlay text";const align = element.align ?? "center";const defaultSize = defaultTextElementFontSize(canvas.cW, canvas.cH);const range = textElementFontSizeRange(canvas.cW, canvas.cH);@@ -814,7 +829,8 @@ function TextElementPanel({value={text}rows={2}onChange={(event) => onTextChange(event.target.value)}- placeholder="Overlay text"+ placeholder={textPlaceholder}+ aria-label="Overlay text"/></div><div className="space-y-1">@@ -867,7 +883,7 @@ function TextElementPanel({<Label className="text-[11px] text-muted-foreground">Color</Label><Inputtype="color"- value={element.color || "#171717"}+ value={element.color || defaultColor}className="h-7 cursor-pointer p-0.5"onChange={(event) => onTextPatch({ color: event.target.value })}aria-label="Text color"diff --git a/skills/app-store-screenshots/template/src/components/editor/screenshot-editor.tsx b/skills/app-store-screenshots/template/src/components/editor/screenshot-editor.tsxindex f16660e..2fe005d 100644--- a/skills/app-store-screenshots/template/src/components/editor/screenshot-editor.tsx+++ b/skills/app-store-screenshots/template/src/components/editor/screenshot-editor.tsx@@ -495,7 +495,10 @@ export function ScreenshotEditor() {// Render each slide once per locale at canvas resolution, then scale that// one render to every export size. The sizes are all scalings of the same- // design, so re-rendering the DOM per size only added time.+ // design, so re-rendering the DOM per size only added time. PNG encoding+ // runs in workers, so a screen encodes while the next one renders; waiting+ // for the previous screen first keeps at most one screen's pixels queued.+ let encoding: Promise<void> = Promise.resolve();for (const locale of locales) {setExportLocaleOverride(locale);await waitForPaint();@@ -508,30 +511,45 @@ export function ScreenshotEditor() {await waitForPaint();const el = exportRef.current;if (!el) {+ await encoding;failed += sizes.length;errors.push(`${locale} screen ${i + 1}: render target missing`);continue;}const filename = `${String(i + 1).padStart(2, "0")}-${slide.layout}.png`;- let written = 0;+ const label = `${locale} screen ${i + 1}`;+ const fail = (e: unknown) => {+ const msg = e instanceof Error ? e.message : String(e);+ errors.push(`${label}: ${msg}`);+ console.error("Export failed", { slideId: slide.id, locale }, e);+ };+ let pngs: Promise<Uint8Array[]>;try {const rendered = await captureSlide(el, cW, cH);- if (rendered.missingImages > 0) incomplete.push(`${locale} screen ${i + 1}`);- for (const size of sizes) {- const base64 = rendered.toPng(size.w, size.h).split(",")[1] || "";- const path = `${platform}/${state.device}/${size.w}x${size.h}/${locale}/${filename}`;- zip.file(path, base64, { base64: true });- written += 1;- }+ if (rendered.missingImages > 0) incomplete.push(label);+ pngs = Promise.all(sizes.map((size) => rendered.toPng(size.w, size.h)));} catch (e) {- const msg = e instanceof Error ? e.message : String(e);- errors.push(`${locale} screen ${i + 1}: ${msg}`);- console.error("Export failed", { slideId: slide.id, locale }, e);+ fail(e);+ await encoding;+ failed += sizes.length;+ continue;}- okCount += written;- failed += sizes.length - written;+ await encoding;+ encoding = pngs.then(+ (files) => {+ sizes.forEach((size, index) => {+ zip.file(`${platform}/${state.device}/${size.w}x${size.h}/${locale}/${filename}`, files[index]);+ });+ okCount += sizes.length;+ },+ (e) => {+ fail(e);+ failed += sizes.length;+ },+ );}}+ await encoding;setExporting("Bundling…");@@ -722,6 +740,8 @@ export function ScreenshotEditor() {orientation={state.orientation}theme={theme}locale={state.locale}+ appIcon={state.appIcon}+ onAppIconChange={(appIcon) => setState((p) => ({ ...p, appIcon }))}selectedElementId={selectedElement?.slideId === activeSlide.id ? selectedElement.elementId : null}diff --git a/skills/app-store-screenshots/template/src/components/editor/slide-canvas.tsx b/skills/app-store-screenshots/template/src/components/editor/slide-canvas.tsxindex 70f0ca8..cb093f8 100644--- a/skills/app-store-screenshots/template/src/components/editor/slide-canvas.tsx+++ b/skills/app-store-screenshots/template/src/components/editor/slide-canvas.tsx@@ -198,18 +198,32 @@ function EditableText({const handleInput = (e: React.FormEvent<HTMLDivElement>) => {if (!onChange) return;- const text = (e.currentTarget.innerText || "").replace(/\u00a0/g, " ");+ // A cleared contenteditable keeps a placeholder <br>, which innerText+ // reports as "\n"; that would save a blank line instead of clearing.+ const raw = e.currentTarget.textContent ? e.currentTarget.innerText : "";+ const text = (raw || "").replace(/\u00a0/g, " ");onChange(multiline ? text : text.replace(/\n/g, ""));};return (<divref={ref}- contentEditable={editable}+ // Per-text base direction: RTL copy (ar, he, fa, ur) keeps its+ // punctuation on the correct side without flipping LTR locales.+ dir="auto"+ // Plain text only: pasted or dropped rich text would otherwise keep its+ // colours and fonts on the canvas while the export uses the plain copy.+ contentEditable={editable ? "plaintext-only" : false}suppressContentEditableWarningdata-placeholder={placeholder}onInput={handleInput}onFocus={() => onFocus?.()}+ onBlur={(e) => {+ // Edits skip syncing while focused; catch up so the canvas shows what+ // will export (e.g. clearing a translation falls back to English).+ const incoming = value || "";+ if (e.currentTarget.textContent !== incoming) e.currentTarget.textContent = incoming;+ }}onKeyDown={(e) => {if (!multiline && e.key === "Enter") {e.preventDefault();@@ -267,7 +281,8 @@ function Caption({// produce headlines so tall they overlap the device frame.const unit = Math.min(cW, cH);return (- <div style={{ textAlign: align, position: "relative", width: "100%" }}>+ // "start" rather than "left" so a left-set caption hugs the right edge in RTL.+ <div style={{ textAlign: align === "left" ? "start" : align, position: "relative", width: "100%" }}><EditableTextvalue={pickText(slide.label, locale)}editable={editable}@@ -1314,16 +1329,21 @@ function Movable({</div>);+ // The editor shows the clamped rect, so export and thumbnails must place the+ // element there too — an out-of-bounds saved rect would otherwise export+ // somewhere the user never saw it.+ const display = clampRect(rect, boundsW, boundsH, allowOverflow);+// Non-editable (export/thumb) path: plain absolute-positioned div, no Rnd.if (!editable) {return (<divstyle={{position: "absolute",- left: rect.x,- top: rect.y,- width: rect.width,- height: rect.height,+ left: display.x,+ top: display.y,+ width: display.width,+ height: display.height,zIndex,}}>@@ -1332,7 +1352,6 @@ function Movable({);}- const display = clampRect(rect, boundsW, boundsH, allowOverflow);const controlScale = Math.max(0.05, previewScale);return (diff --git a/skills/app-store-screenshots/template/src/lib/export-render.ts b/skills/app-store-screenshots/template/src/lib/export-render.tsindex 125d68e..0abd5a3 100644--- a/skills/app-store-screenshots/template/src/lib/export-render.ts+++ b/skills/app-store-screenshots/template/src/lib/export-render.ts@@ -24,6 +24,7 @@// If an image never shows up within the timeout, report it instead of// silently shipping a blank device.import { toSvg } from "html-to-image";+import { encodeCanvasPng } from "./png-encode";const SETTLE_POLL_MS = 50;const SETTLE_TIMEOUT_MS = 8000;@@ -34,8 +35,8 @@ const SVG_PREFIX = "data:image/svg+xml;charset=utf-8,";type Box = { x: number; y: number; w: number; h: number };export type RenderedSlide = {- /** Draw the settled slide at the given export size and return a PNG data URL. */- toPng: (w: number, h: number) => string;+ /** Draw the settled slide at the given export size as opaque 24-bit PNG bytes. */+ toPng: (w: number, h: number) => Promise<Uint8Array>;/** Visible images that never appeared in the render. 0 when all is well. */missingImages: number;};@@ -200,7 +201,7 @@ export async function renderSlide(return {missingImages,toPng: (w, h) => {- if (w === width && h === height) return canvas.toDataURL("image/png");+ if (w === width && h === height) return encodeCanvasPng(canvas);const { canvas: out, ctx: octx } = createContext(w, h);octx.imageSmoothingEnabled = true;octx.imageSmoothingQuality = "high";@@ -211,7 +212,7 @@ export async function renderSlide(const dw = width * scale;const dh = height * scale;octx.drawImage(canvas, (w - dw) / 2, (h - dh) / 2, dw, dh);- return out.toDataURL("image/png");+ return encodeCanvasPng(out);},};}diff --git a/skills/app-store-screenshots/template/src/lib/png-encode.ts b/skills/app-store-screenshots/template/src/lib/png-encode.tsnew file mode 100644index 0000000..9964f7a--- /dev/null+++ b/skills/app-store-screenshots/template/src/lib/png-encode.ts@@ -0,0 +1,75 @@+"use client";+// Canvas → 24-bit RGB PNG bytes (see png-rgb.ts for why not toDataURL).+// Encoding a full-size export is ~100ms of filtering and deflate, so it runs+// on a small worker pool: exports keep rendering the next screen meanwhile.+// Without workers, or if one fails, the same encoder runs inline.+import { encodeRgbPixels } from "./png-rgb";++type Job = {+ worker: Worker;+ pixels: Uint8ClampedArray;+ width: number;+ height: number;+ resolve: (png: Uint8Array) => void;+ reject: (error: unknown) => void;+};+type Result = { id: number; png?: Uint8Array; error?: string };++let pool: Worker[] | null = null;+let nextWorker = 0;+let nextId = 0;+const jobs = new Map<number, Job>();++function encodeInline(job: Job) {+ encodeRgbPixels(job.pixels, job.width, job.height).then(job.resolve, job.reject);+}++function workers(): Worker[] {+ if (pool) return pool;+ pool = [];+ try {+ const size = Math.max(1, Math.min(4, (navigator.hardwareConcurrency || 2) - 1));+ for (let i = 0; i < size; i++) {+ const worker = new Worker(new URL("./png-worker.ts", import.meta.url));+ worker.onmessage = ({ data }: MessageEvent<Result>) => {+ const job = jobs.get(data.id);+ if (!job) return;+ jobs.delete(data.id);+ if (data.png) job.resolve(data.png);+ else encodeInline(job);+ };+ // A worker that fails to load or crashes leaves the pool, and its jobs+ // finish inline instead of leaving the export waiting forever.+ worker.onerror = (event) => {+ event.preventDefault();+ worker.terminate();+ pool = (pool || []).filter((w) => w !== worker);+ for (const [id, job] of jobs) {+ if (job.worker !== worker) continue;+ jobs.delete(id);+ encodeInline(job);+ }+ };+ pool.push(worker);+ }+ } catch {+ // Keep any workers that did start; an empty pool means inline encoding.+ }+ return pool;+}++export function encodeCanvasPng(canvas: HTMLCanvasElement): Promise<Uint8Array> {+ const ctx = canvas.getContext("2d");+ if (!ctx) return Promise.reject(new Error("Canvas 2D context unavailable"));+ const { width, height } = canvas;+ const pixels = ctx.getImageData(0, 0, width, height).data;+ const available = workers();+ if (!available.length) return encodeRgbPixels(pixels, width, height);+ const id = nextId++;+ const worker = available[nextWorker++ % available.length];+ return new Promise((resolve, reject) => {+ jobs.set(id, { worker, pixels, width, height, resolve, reject });+ // Copied, not transferred: the pixels stay here for the inline fallback.+ worker.postMessage({ id, pixels, width, height });+ });+}diff --git a/skills/app-store-screenshots/template/src/lib/png-rgb.ts b/skills/app-store-screenshots/template/src/lib/png-rgb.tsnew file mode 100644index 0000000..693c61f--- /dev/null+++ b/skills/app-store-screenshots/template/src/lib/png-rgb.ts@@ -0,0 +1,158 @@+// Encodes RGBA pixels as an opaque 24-bit RGB PNG. No DOM access, so it runs+// in the export worker (png-worker.ts) as well as on the main thread.+//+// canvas.toDataURL("image/png") always writes RGBA (colour type 6), even when+// every pixel is opaque. Google Play requires screenshots and the feature+// graphic to be "JPEG or 24-bit PNG (no alpha)", and RGB is also the safe+// choice for App Store Connect, so exports are re-encoded here without the+// alpha channel. Compression uses the browser's native zlib (CompressionStream+// "deflate"), with the standard per-row filter heuristic to keep files small.++const SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];++const CRC_TABLE = (() => {+ const table = new Uint32Array(256);+ for (let n = 0; n < 256; n++) {+ let c = n;+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;+ table[n] = c >>> 0;+ }+ return table;+})();++function crc32(bytes: Uint8Array, start: number, end: number) {+ let c = 0xffffffff;+ for (let i = start; i < end; i++) c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);+ return (c ^ 0xffffffff) >>> 0;+}++function chunk(type: string, data: Uint8Array) {+ const out = new Uint8Array(12 + data.length);+ const view = new DataView(out.buffer);+ view.setUint32(0, data.length);+ for (let i = 0; i < 4; i++) out[4 + i] = type.charCodeAt(i);+ out.set(data, 8);+ view.setUint32(8 + data.length, crc32(out, 4, 8 + data.length));+ return out;+}++// Writes one filtered scanline into `row` and returns its sum-of-absolute-+// values score, giving up once it reaches `limit`. `cur` and `prev` carry+// BPP leading zero bytes so the left neighbour never needs a bounds check.+// One loop per filter keeps the per-byte work branch-free; exports encode+// tens of millions of bytes.+const BPP = 3;++function applyFilter(type: number, cur: Uint8Array, prev: Uint8Array, row: Uint8Array, stride: number, limit: number) {+ let score = 0;+ let v = 0;+ switch (type) {+ case 0:+ for (let i = 0; i < stride && score < limit; i++) {+ v = cur[i + BPP];+ row[i] = v;+ score += v < 128 ? v : 256 - v;+ }+ break;+ case 1:+ for (let i = 0; i < stride && score < limit; i++) {+ v = (cur[i + BPP] - cur[i]) & 0xff;+ row[i] = v;+ score += v < 128 ? v : 256 - v;+ }+ break;+ case 2:+ for (let i = 0; i < stride && score < limit; i++) {+ v = (cur[i + BPP] - prev[i + BPP]) & 0xff;+ row[i] = v;+ score += v < 128 ? v : 256 - v;+ }+ break;+ case 3:+ for (let i = 0; i < stride && score < limit; i++) {+ v = (cur[i + BPP] - ((cur[i] + prev[i + BPP]) >> 1)) & 0xff;+ row[i] = v;+ score += v < 128 ? v : 256 - v;+ }+ break;+ default:+ for (let i = 0; i < stride && score < limit; i++) {+ const a = cur[i];+ const b = prev[i + BPP];+ const c = prev[i];+ const p = a + b - c;+ const pa = p > a ? p - a : a - p;+ const pb = p > b ? p - b : b - p;+ const pc = p > c ? p - c : c - p;+ v = (cur[i + BPP] - (pa <= pb && pa <= pc ? a : pb <= pc ? b : c)) & 0xff;+ row[i] = v;+ score += v < 128 ? v : 256 - v;+ }+ }+ return score;+}++// Filtered scanlines: each row is one filter-type byte plus the filtered RGB+// bytes, picking the filter with the smallest sum of absolute values.+function filterRows(rgba: Uint8ClampedArray, width: number, height: number): Uint8Array<ArrayBuffer> {+ const stride = width * BPP;+ const out = new Uint8Array((stride + 1) * height);+ let prev = new Uint8Array(stride + BPP);+ let cur = new Uint8Array(stride + BPP);+ const candidates = Array.from({ length: 5 }, () => new Uint8Array(stride));+ for (let y = 0; y < height; y++) {+ for (let x = 0, s = y * width * 4, d = BPP; x < width; x++, s += 4, d += BPP) {+ cur[d] = rgba[s];+ cur[d + 1] = rgba[s + 1];+ cur[d + 2] = rgba[s + 2];+ }+ let best = 0;+ let bestScore = Infinity;+ for (let type = 0; type < 5; type++) {+ const score = applyFilter(type, cur, prev, candidates[type], stride, bestScore);+ // A filter that hit the limit stopped early, but it lost, so the+ // winner's row is always complete.+ if (score < bestScore) {+ bestScore = score;+ best = type;+ }+ }+ const offset = y * (stride + 1);+ out[offset] = best;+ out.set(candidates[best], offset + 1);+ [prev, cur] = [cur, prev];+ }+ return out;+}++async function deflate(data: Uint8Array<ArrayBuffer>) {+ const stream = new Blob([data]).stream().pipeThrough(new CompressionStream("deflate"));+ return new Uint8Array(await new Response(stream).arrayBuffer());+}++export async function encodeRgbPixels(+ pixels: Uint8ClampedArray,+ width: number,+ height: number,+): Promise<Uint8Array<ArrayBuffer>> {+ const header = new Uint8Array(13);+ const view = new DataView(header.buffer);+ view.setUint32(0, width);+ view.setUint32(4, height);+ header[8] = 8; // bit depth+ header[9] = 2; // colour type: truecolour, no alpha++ const parts = [+ new Uint8Array(SIGNATURE),+ chunk("IHDR", header),+ chunk("IDAT", await deflate(filterRows(pixels, width, height))),+ chunk("IEND", new Uint8Array()),+ ];+ const png = new Uint8Array(parts.reduce((n, part) => n + part.length, 0));+ let offset = 0;+ for (const part of parts) {+ png.set(part, offset);+ offset += part.length;+ }+ return png;+}diff --git a/skills/app-store-screenshots/template/src/lib/png-worker.ts b/skills/app-store-screenshots/template/src/lib/png-worker.tsnew file mode 100644index 0000000..43ae81b--- /dev/null+++ b/skills/app-store-screenshots/template/src/lib/png-worker.ts@@ -0,0 +1,13 @@+// Export encoding worker: RGBA pixels in, 24-bit RGB PNG bytes out.+import { encodeRgbPixels } from "./png-rgb";++type Job = { id: number; pixels: Uint8ClampedArray; width: number; height: number };++self.onmessage = async ({ data }: MessageEvent<Job>) => {+ try {+ const png = await encodeRgbPixels(data.pixels, data.width, data.height);+ self.postMessage({ id: data.id, png }, { transfer: [png.buffer] });+ } catch (error) {+ self.postMessage({ id: data.id, error: error instanceof Error ? error.message : String(error) });+ }+};diff --git a/skills/app-store-screenshots/template/src/lib/storage.ts b/skills/app-store-screenshots/template/src/lib/storage.tsindex 52de8f6..df939c7 100644--- a/skills/app-store-screenshots/template/src/lib/storage.ts+++ b/skills/app-store-screenshots/template/src/lib/storage.ts@@ -142,7 +142,16 @@ function mergeWithDefaults(parsed: Partial<ProjectState>): ProjectState {? Object.fromEntries(Object.entries(parsed.slidesByDevice).map(([device, slides]) => [device,- Array.isArray(slides) ? slides.map((slide) => migrateSlide(slide as Slide)) : [],+ Array.isArray(slides)+ ? slides.map((slide) => {+ const migrated = migrateSlide(slide as Slide);+ // The Play Store banner deck only has one layout. Normalising+ // here (not while editing) keeps it out of undo history.+ return device === "feature-graphic" && migrated.layout !== "feature-graphic"+ ? { ...migrated, layout: "feature-graphic" as const, transforms: undefined, screenshotSecondary: undefined }+ : migrated;+ })+ : [],]),): {};@@ -354,8 +363,10 @@ export function useProject() {commit(next);}, [commit]);+ // "Reset all devices" resets the decks only. App name, theme, font, icon and+ // especially `locales` (which has no editor UI) are project settings.const reset = useCallback(() => {- setState(DEFAULT_PROJECT);+ setState((prev) => ({ ...prev, slidesByDevice: DEFAULT_PROJECT.slidesByDevice }));}, [setState]);const resetDevice = useCallback((device: Device) => {