end to end app store screenshot creation using AI
TypeScript agentic-aiappleappstoreautomateclaudecursordesigngenerateiosios-appmarketingscreenshotskillsskills-shswiftswiftuiui
saves state to json
Parth Jadhav5d7d2f852962
diff --git a/skills/app-store-screenshots/SKILL.md b/skills/app-store-screenshots/SKILL.mdindex f396409..982c940 100644--- a/skills/app-store-screenshots/SKILL.md+++ b/skills/app-store-screenshots/SKILL.md@@ -11,8 +11,8 @@ Scaffold a pre-built Next.js + ShadCN editor that lets the user design and expor- Live preview at the canvas's true resolution (scaled to fit)- Drag-to-reorder slides, inline text editing, layout switcher per slide-- Drop-target screenshot picker (file → embedded data URI)-- Auto-save to `localStorage` (debounced)+- Drop-target screenshot picker (file → saved to `public/screenshots/uploaded/<hash>.png`)+- Auto-save to **`app-store-screenshots.json`** at the project root (git-trackable) + `localStorage` mirror- Easy iOS ↔ Android platform switch — separate slide decks live side by side- One-click bulk PNG export at every Apple/Google-required resolution via `html-to-image`- Light/dark variant toggle per slide, theme presets, locale select@@ -126,7 +126,7 @@ Otherwise, leave the defaults — the user can rewrite copy in the editor.bun dev # → http://localhost:3000```-Tell the user to open the URL and start editing. The editor auto-saves; they can close the tab and resume.+Tell the user to open the URL and start editing. The editor auto-saves to **`app-store-screenshots.json`** at the project root (plus a `localStorage` mirror for instant paint). Uploaded screenshots land in `public/screenshots/uploaded/<hash>.png`. Both are git-trackable — committing them means another machine can `git clone` and resume the exact deck.## Step 3: Coach the User on Copy@@ -293,9 +293,9 @@ If exports come out blank or with black screen rectangles:|---------|-----|| Edited `page.tsx` instead of using the editor | Roll back the edit; let users iterate in the browser || Tried to rebuild device frames from scratch | They're in `src/components/editor/device-frames.tsx` — modify there |-| Pasted screenshots into git directly | `public/screenshots/...` is fine to commit; data-URI uploads stored in `localStorage` aren't shareable across machines |+| Pasted screenshots into git directly | `public/screenshots/...` is fine to commit. Drop-target uploads are now also written to `public/screenshots/uploaded/<hash>.png` — commit both that folder **and** `app-store-screenshots.json` so collaborators reproduce your deck after `git clone`. || Wrong directory layout for tablet screenshots | See Step 2 — `android/tablet-7/portrait/{locale}/...` etc. |-| Reset wiped the deck | Reset clears `localStorage`; export first or back up `localStorage` JSON before resetting |+| Reset wiped the deck | Reset clears in-memory state and re-saves defaults to `app-store-screenshots.json`. Recover by `git checkout app-store-screenshots.json` if it was committed, or export first before resetting. || Export is blank | Source PNGs probably have alpha — flatten to RGB || `bun dev` port collision | Template defaults to `next dev`; let Next pick the next free port (3001+) |diff --git a/skills/app-store-screenshots/template/README.md b/skills/app-store-screenshots/template/README.mdindex 5d032bc..c81d4d9 100644--- a/skills/app-store-screenshots/template/README.md+++ b/skills/app-store-screenshots/template/README.md@@ -13,7 +13,7 @@ bun dev # http://localhost:3000- **Visual editor** (`src/components/editor/`) — drag-to-reorder, click-to-edit text, screenshot drop targets, per-slide layout switcher, dark/light toggle.- **Device frames** (`src/components/editor/device-frames.tsx`) — iPhone (PNG mockup), iPad, Android phone, Android tablet (portrait + landscape), feature graphic.-- **Auto-save** — every change is persisted to `localStorage` (key: `app-store-screenshots:project:v1`) within 400ms.+- **Auto-save (git-trackable)** — every change is persisted within ~600ms to **`app-store-screenshots.json`** at the project root (via `/api/project`) **and** mirrored to `localStorage` as an instant-paint cache. Commit `app-store-screenshots.json` and you can `git clone` to another machine and resume exactly where you left off.- **Multi-device decks** — iOS and Android slide decks live side by side; switching the platform tab preserves both.- **One-click export** — bulk PNG export at any required App Store / Play Store resolution using `html-to-image`.@@ -21,7 +21,7 @@ bun dev # http://localhost:3000Two ways:-1. **Drop a file in the inspector** — opens the image picker (drag-and-drop supported); the image is embedded as a data URI and stored in `localStorage`. No filesystem changes required.+1. **Drop a file in the inspector** — drag-and-drop or click Pick. The file is sent to `/api/upload`, hashed, and written to `public/screenshots/uploaded/<hash>.png`. The slide stores the resulting `/screenshots/uploaded/...` path, so commit those files alongside `app-store-screenshots.json` and the screenshots survive a `git clone`.2. **Reference a static file** — put PNGs under `public/screenshots/{platform}/{device}/{locale}/` and reference them by path. Default sample slides expect:- `public/screenshots/apple/iphone/en/01.png` … `05.png`- `public/screenshots/android/phone/en/01.png` … `05.png`@@ -45,4 +45,5 @@ The toolbar dropdown lists every Apple/Google-required size for the current devi- `mockup.png` is the iPhone bezel overlay; replacing it requires re-measuring the `PHONE_SCREEN` constants.- Image preloading converts every static path to a base64 data URI before exports run — this prevents the html-to-image race where some slide screenshots come out black.-- Reset via the toolbar's circular arrow icon clears `localStorage` and reloads the default slides.+- Reset via the toolbar's circular arrow icon clears in-memory state and reloads the default slides. To wipe disk state too, delete `app-store-screenshots.json`.+- **Persistence model** — the canonical state lives in `app-store-screenshots.json` (git-tracked). On load, the editor reads localStorage first for instant paint, then overwrites with the file contents if present. On save, both are written. If you ever see a conflict, the file always wins.diff --git a/skills/app-store-screenshots/template/src/app/api/project/route.ts b/skills/app-store-screenshots/template/src/app/api/project/route.tsnew file mode 100644index 0000000..8604ad2--- /dev/null+++ b/skills/app-store-screenshots/template/src/app/api/project/route.ts@@ -0,0 +1,47 @@+import { promises as fs } from "node:fs";+import path from "node:path";+import { NextResponse } from "next/server";++export const dynamic = "force-dynamic";++const PROJECT_FILE = "app-store-screenshots.json";++function filePath() {+ return path.join(process.cwd(), PROJECT_FILE);+}++export async function GET() {+ try {+ const raw = await fs.readFile(filePath(), "utf8");+ const parsed = JSON.parse(raw);+ return NextResponse.json({ ok: true, state: parsed });+ } catch (e) {+ const code = (e as NodeJS.ErrnoException).code;+ if (code === "ENOENT") {+ return NextResponse.json({ ok: true, state: null });+ }+ return NextResponse.json(+ { ok: false, error: e instanceof Error ? e.message : String(e) },+ { status: 500 },+ );+ }+}++export async function POST(req: Request) {+ let body: unknown;+ try {+ body = await req.json();+ } catch {+ return NextResponse.json({ ok: false, error: "Invalid JSON" }, { status: 400 });+ }+ try {+ const pretty = JSON.stringify(body, null, 2) + "\n";+ await fs.writeFile(filePath(), pretty, "utf8");+ return NextResponse.json({ ok: true });+ } catch (e) {+ return NextResponse.json(+ { ok: false, error: e instanceof Error ? e.message : String(e) },+ { status: 500 },+ );+ }+}diff --git a/skills/app-store-screenshots/template/src/app/api/upload/route.ts b/skills/app-store-screenshots/template/src/app/api/upload/route.tsnew file mode 100644index 0000000..aa028e7--- /dev/null+++ b/skills/app-store-screenshots/template/src/app/api/upload/route.ts@@ -0,0 +1,69 @@+import { createHash } from "node:crypto";+import { promises as fs } from "node:fs";+import path from "node:path";+import { NextResponse } from "next/server";++export const dynamic = "force-dynamic";++const UPLOAD_DIR_REL = path.join("public", "screenshots", "uploaded");+const PUBLIC_PREFIX = "/screenshots/uploaded";++const MIME_EXT: Record<string, string> = {+ "image/png": "png",+ "image/jpeg": "jpg",+ "image/jpg": "jpg",+};++function parseDataUrl(dataUrl: string): { mime: string; bytes: Buffer } | null {+ const m = /^data:([^;]+);base64,(.+)$/.exec(dataUrl);+ if (!m) return null;+ const mime = m[1].toLowerCase();+ const bytes = Buffer.from(m[2], "base64");+ return { mime, bytes };+}++export async function POST(req: Request) {+ let body: { dataUrl?: string };+ try {+ body = (await req.json()) as { dataUrl?: string };+ } catch {+ return NextResponse.json({ ok: false, error: "Invalid JSON" }, { status: 400 });+ }+ if (!body?.dataUrl || typeof body.dataUrl !== "string") {+ return NextResponse.json({ ok: false, error: "Missing dataUrl" }, { status: 400 });+ }+ const parsed = parseDataUrl(body.dataUrl);+ if (!parsed) {+ return NextResponse.json({ ok: false, error: "Unsupported data URL" }, { status: 400 });+ }+ const ext = MIME_EXT[parsed.mime];+ if (!ext) {+ return NextResponse.json(+ { ok: false, error: `Unsupported mime: ${parsed.mime}` },+ { status: 400 },+ );+ }+ if (parsed.bytes.byteLength > 8 * 1024 * 1024) {+ return NextResponse.json({ ok: false, error: "Image too large (>8MB)" }, { status: 413 });+ }++ const hash = createHash("sha1").update(parsed.bytes).digest("hex").slice(0, 16);+ const filename = `${hash}.${ext}`;+ const absDir = path.join(process.cwd(), UPLOAD_DIR_REL);+ const absFile = path.join(absDir, filename);++ try {+ await fs.mkdir(absDir, { recursive: true });+ try {+ await fs.access(absFile);+ } catch {+ await fs.writeFile(absFile, parsed.bytes);+ }+ return NextResponse.json({ ok: true, path: `${PUBLIC_PREFIX}/${filename}` });+ } catch (e) {+ return NextResponse.json(+ { ok: false, error: e instanceof Error ? e.message : String(e) },+ { status: 500 },+ );+ }+}diff --git a/skills/app-store-screenshots/template/src/components/editor/screenshot-picker.tsx b/skills/app-store-screenshots/template/src/components/editor/screenshot-picker.tsxindex 9dd28aa..e33bf5a 100644--- a/skills/app-store-screenshots/template/src/components/editor/screenshot-picker.tsx+++ b/skills/app-store-screenshots/template/src/components/editor/screenshot-picker.tsx@@ -21,10 +21,26 @@ async function fileToDataUrl(file: File): Promise<string> {});}+async function uploadDataUrl(dataUrl: string): Promise<string | null> {+ try {+ const resp = await fetch("/api/upload", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ dataUrl }),+ });+ if (!resp.ok) return null;+ const json = (await resp.json()) as { ok: boolean; path?: string };+ return json.ok && json.path ? json.path : null;+ } catch {+ return null;+ }+}+export function ScreenshotPicker({ label, value, onChange }: Props) {const inputRef = React.useRef<HTMLInputElement>(null);const [dragging, setDragging] = React.useState(false);const [error, setError] = React.useState<string | null>(null);+ const [uploading, setUploading] = React.useState(false);async function handleFile(file: File) {setError(null);@@ -36,12 +52,25 @@ export function ScreenshotPicker({ label, value, onChange }: Props) {setError("Image too large (>8MB)");return;}+ let dataUrl: string;try {- const dataUrl = await fileToDataUrl(file);- setImage(dataUrl, dataUrl);- onChange(dataUrl);+ dataUrl = await fileToDataUrl(file);} catch {setError("Failed to read file");+ return;+ }+ // Try to persist to disk so the screenshot survives a git clone.+ // If the upload endpoint is unreachable (e.g. static export), fall back+ // to the inline data URI — still works in the current session.+ setUploading(true);+ const uploadedPath = await uploadDataUrl(dataUrl);+ setUploading(false);+ if (uploadedPath) {+ setImage(uploadedPath, dataUrl);+ onChange(uploadedPath);+ } else {+ setImage(dataUrl, dataUrl);+ onChange(dataUrl);}}@@ -50,11 +79,13 @@ export function ScreenshotPicker({ label, value, onChange }: Props) {const previewSrc = isData ? value : hasValue ? img(value) : "";// Only flag "image not found" when the path is a real URL that we tried and failed.const knownMissing = hasValue && !isData && didFail(value);- const valueLabel = !hasValue- ? "drop image, or click Pick"- : isData- ? "uploaded image"- : value.replace(/^.*\/(?=[^/]+\/[^/]+$)/, "…/");+ const valueLabel = uploading+ ? "saving…"+ : !hasValue+ ? "drop image, or click Pick"+ : isData+ ? "uploaded image (not on disk)"+ : value.replace(/^.*\/(?=[^/]+\/[^/]+$)/, "…/");return (<div className="space-y-1">diff --git a/skills/app-store-screenshots/template/src/lib/storage.ts b/skills/app-store-screenshots/template/src/lib/storage.tsindex 063a990..eba095f 100644--- a/skills/app-store-screenshots/template/src/lib/storage.ts+++ b/skills/app-store-screenshots/template/src/lib/storage.ts@@ -7,35 +7,74 @@ import type { Device, ProjectState } from "./types";const HISTORY_LIMIT = 50;// Coalesce rapid edits (typing, slider drags) into a single undo step.const COALESCE_MS = 500;+// Debounce file/localStorage writes — frequent enough to feel instant, infrequent enough not to thrash disk.+const SAVE_DEBOUNCE_MS = 600;-function load(): ProjectState {- if (typeof window === "undefined") return DEFAULT_PROJECT;+function mergeWithDefaults(parsed: Partial<ProjectState>): ProjectState {+ return {+ ...DEFAULT_PROJECT,+ ...parsed,+ slidesByDevice: {+ ...DEFAULT_PROJECT.slidesByDevice,+ ...(parsed.slidesByDevice || {}),+ },+ };+}++function loadFromLocalStorage(): ProjectState | null {+ if (typeof window === "undefined") return null;try {const raw = window.localStorage.getItem(STORAGE_KEY);- if (!raw) return DEFAULT_PROJECT;- const parsed = JSON.parse(raw) as ProjectState;- return {- ...DEFAULT_PROJECT,- ...parsed,- slidesByDevice: { ...DEFAULT_PROJECT.slidesByDevice, ...parsed.slidesByDevice },- };+ if (!raw) return null;+ return mergeWithDefaults(JSON.parse(raw) as Partial<ProjectState>);} catch {- return DEFAULT_PROJECT;+ return null;}}-function save(state: ProjectState): { ok: true } | { ok: false; error: string } {+async function loadFromFile(): Promise<ProjectState | null> {+ if (typeof window === "undefined") return null;+ try {+ const resp = await fetch("/api/project", { cache: "no-store" });+ if (!resp.ok) return null;+ const json = (await resp.json()) as { ok: boolean; state: Partial<ProjectState> | null };+ if (!json.ok || !json.state) return null;+ return mergeWithDefaults(json.state);+ } catch {+ return null;+ }+}++function saveToLocalStorage(state: ProjectState): { ok: true } | { ok: false; error: string } {if (typeof window === "undefined") return { ok: true };try {window.localStorage.setItem(STORAGE_KEY, JSON.stringify(state));return { ok: true };} catch (e) {const msg = e instanceof Error ? e.message : String(e);- console.warn("Autosave failed", e);return { ok: false, error: msg };}}+async function saveToFile(state: ProjectState): Promise<{ ok: true } | { ok: false; error: string }> {+ if (typeof window === "undefined") return { ok: true };+ try {+ const resp = await fetch("/api/project", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(state),+ });+ if (!resp.ok) {+ return { ok: false, error: `HTTP ${resp.status}` };+ }+ const json = (await resp.json()) as { ok: boolean; error?: string };+ if (!json.ok) return { ok: false, error: json.error || "Unknown error" };+ return { ok: true };+ } catch (e) {+ return { ok: false, error: e instanceof Error ? e.message : String(e) };+ }+}+type Updater = ProjectState | ((prev: ProjectState) => ProjectState);function applyUpdater(updater: Updater, prev: ProjectState): ProjectState {@@ -55,29 +94,52 @@ export function useProject() {const futureRef = useRef<ProjectState[]>([]);const lastPushAt = useRef(0);- // Hydrate once from localStorage+ // Hydrate: prefer file (git-tracked) → localStorage (cache) → defaults.+ // localStorage is consulted first for instant paint, then file overwrites if present.useEffect(() => {- const loaded = load();- _setState(loaded);- pastRef.current = [];- futureRef.current = [];- lastPushAt.current = 0;- setHydrated(true);+ let cancelled = false;+ const cached = loadFromLocalStorage();+ if (cached) _setState(cached);++ void (async () => {+ const fromFile = await loadFromFile();+ if (cancelled) return;+ if (fromFile) {+ _setState(fromFile);+ }+ pastRef.current = [];+ futureRef.current = [];+ lastPushAt.current = 0;+ setHydrated(true);+ })();++ return () => {+ cancelled = true;+ };}, []);- // Debounced autosave+ // Debounced autosave to BOTH localStorage (fast, offline) and file (git-trackable).useEffect(() => {if (!hydrated) return;if (timer.current) clearTimeout(timer.current);timer.current = setTimeout(() => {- const result = save(state);- if (result.ok) {- setSavedAt(Date.now());- setSaveError(null);- } else {- setSaveError(result.error);- }- }, 400);+ const localResult = saveToLocalStorage(state);+ void saveToFile(state).then((fileResult) => {+ if (fileResult.ok && localResult.ok) {+ setSavedAt(Date.now());+ setSaveError(null);+ } else if (!fileResult.ok && !localResult.ok) {+ setSaveError(fileResult.error);+ } else if (!fileResult.ok) {+ // Local cache succeeded but file save failed — work isn't git-portable yet.+ setSavedAt(Date.now());+ setSaveError(`File save failed: ${fileResult.error}`);+ } else {+ setSavedAt(Date.now());+ setSaveError(localResult.ok ? null : localResult.error);+ }+ });+ }, SAVE_DEBOUNCE_MS);return () => {if (timer.current) clearTimeout(timer.current);};