diff --git a/package-lock.json b/package-lock.json index 1b6c1da..e8574ca 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,7 @@ "adm-zip": "^0.5.16", "express": "^5.2.1", "jsonwebtoken": "^9.0.3", + "multer": "^2.1.1", "react": "^18.3.1", "react-dom": "^18.3.1" }, @@ -2059,6 +2060,12 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/append-field": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz", + "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==", + "license": "MIT" + }, "node_modules/aria-query": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", @@ -2180,6 +2187,23 @@ "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", "license": "BSD-3-Clause" }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "license": "MIT" + }, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "dependencies": { + "streamsearch": "^1.1.0" + }, + "engines": { + "node": ">=10.16.0" + } + }, "node_modules/bytes": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", @@ -2272,6 +2296,21 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/concat-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz", + "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==", + "engines": [ + "node >= 6.0" + ], + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.0.2", + "typedarray": "^0.0.6" + } + }, "node_modules/content-disposition": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz", @@ -3632,6 +3671,68 @@ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "license": "MIT" }, + "node_modules/multer": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/multer/-/multer-2.1.1.tgz", + "integrity": "sha512-mo+QTzKlx8R7E5ylSXxWzGoXoZbOsRMpyitcht8By2KHvMbf3tjwosZ/Mu/XYU6UuJ3VZnODIrak5ZrPiPyB6A==", + "license": "MIT", + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.6.0", + "concat-stream": "^2.0.0", + "type-is": "^1.6.18" + }, + "engines": { + "node": ">= 10.16.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/multer/node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/multer/node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/nanoid": { "version": "3.3.11", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", @@ -3920,6 +4021,20 @@ "node": ">=0.10.0" } }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/redent": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz", @@ -4226,6 +4341,23 @@ "dev": true, "license": "MIT" }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, "node_modules/strip-indent": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz", @@ -4416,6 +4548,12 @@ "node": ">= 0.6" } }, + "node_modules/typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==", + "license": "MIT" + }, "node_modules/undici": { "version": "7.24.5", "resolved": "https://registry.npmjs.org/undici/-/undici-7.24.5.tgz", @@ -4466,6 +4604,12 @@ "browserslist": ">= 4.21.0" } }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, "node_modules/vary": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", diff --git a/package.json b/package.json index 1708578..643b19a 100644 --- a/package.json +++ b/package.json @@ -34,6 +34,7 @@ "adm-zip": "^0.5.16", "express": "^5.2.1", "jsonwebtoken": "^9.0.3", + "multer": "^2.1.1", "react": "^18.3.1", "react-dom": "^18.3.1" }, diff --git a/server/index.js b/server/index.js index 692e421..ba8bb2d 100644 --- a/server/index.js +++ b/server/index.js @@ -4,6 +4,7 @@ import appsRouter from "./routes/apps.js"; import productsRouter from "./routes/products.js"; import xcodeCloudRouter from "./routes/xcode-cloud.js"; import pricingRouter from "./routes/pricing.js"; +import screenshotsRouter from "./routes/screenshots.js"; const app = express(); @@ -14,6 +15,7 @@ app.use("/api/apps", appsRouter); app.use("/api/apps", productsRouter); app.use("/api/apps", pricingRouter); app.use("/api/apps", xcodeCloudRouter); +app.use("/api/apps", screenshotsRouter); const PORT = process.env.SERVER_PORT || 3001; app.listen(PORT, () => { diff --git a/server/routes/screenshots.js b/server/routes/screenshots.js new file mode 100644 index 0000000..2278d40 --- /dev/null +++ b/server/routes/screenshots.js @@ -0,0 +1,268 @@ +import { Router } from "express"; +import crypto from "crypto"; +import multer from "multer"; +import { getAccounts } from "../lib/account-store.js"; +import { ascFetch } from "../lib/asc-client.js"; +import { apiCache } from "../lib/cache.js"; + +const router = Router(); +const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 30 * 1024 * 1024 } }); + +function resolveAccount(accountId) { + const accounts = getAccounts(); + const account = accounts.find((a) => a.id === accountId); + if (!account) throw new Error("Account not found"); + return account; +} + +function cacheKey(locId, accountId) { + return `screenshots:sets:${locId}:${accountId || "default"}`; +} + +// ── List screenshot sets + screenshots for a localization ────────────────── + +router.get("/:appId/versions/:versionId/localizations/:locId/screenshot-sets", async (req, res) => { + const { locId } = req.params; + const { accountId } = req.query; + + const key = cacheKey(locId, accountId); + const cached = apiCache.get(key); + if (cached) return res.json(cached); + + try { + const account = resolveAccount(accountId); + + const setsData = await ascFetch( + account, + `/v1/appStoreVersionLocalizations/${locId}/appScreenshotSets?include=appScreenshots&fields[appScreenshots]=fileName,fileSize,sourceFileChecksum,assetDeliveryState,imageAsset&limit=50` + ); + + // Index included screenshots by ID + const screenshotsById = {}; + if (setsData.included) { + for (const item of setsData.included) { + if (item.type !== "appScreenshots") continue; + screenshotsById[item.id] = { + id: item.id, + fileName: item.attributes.fileName, + fileSize: item.attributes.fileSize, + sourceFileChecksum: item.attributes.sourceFileChecksum, + imageAsset: item.attributes.imageAsset, + assetDeliveryState: item.attributes.assetDeliveryState, + }; + } + } + + const sets = (setsData.data || []).map((s) => { + const refs = s.relationships?.appScreenshots?.data || []; + const screenshots = refs + .map((ref) => screenshotsById[ref.id]) + .filter(Boolean); + + return { + id: s.id, + displayType: s.attributes.screenshotDisplayType, + screenshots, + }; + }); + + apiCache.set(key, sets); + res.json(sets); + } catch (err) { + console.error(`Failed to fetch screenshot sets for localization ${locId}:`, err.message); + res.status(502).json({ error: err.message }); + } +}); + +// ── Create a screenshot set ──────────────────────────────────────────────── + +router.post("/:appId/versions/:versionId/localizations/:locId/screenshot-sets", async (req, res) => { + const { locId } = req.params; + const { accountId, displayType } = req.body; + + if (!accountId || !displayType) { + return res.status(400).json({ error: "accountId and displayType are required" }); + } + + try { + const account = resolveAccount(accountId); + + const data = await ascFetch(account, "/v1/appScreenshotSets", { + method: "POST", + body: { + data: { + type: "appScreenshotSets", + attributes: { screenshotDisplayType: displayType }, + relationships: { + appStoreVersionLocalization: { + data: { type: "appStoreVersionLocalizations", id: locId }, + }, + }, + }, + }, + }); + + apiCache.delete(cacheKey(locId, accountId)); + + res.json({ + id: data.data.id, + displayType: data.data.attributes.screenshotDisplayType, + screenshots: [], + }); + } catch (err) { + console.error(`Failed to create screenshot set for localization ${locId}:`, err.message); + res.status(502).json({ error: err.message }); + } +}); + +// ── Delete screenshot set ────────────────────────────────────────────────── + +router.delete("/screenshot-sets/:setId", async (req, res) => { + const { setId } = req.params; + const { accountId, locId } = req.query; + + try { + const account = resolveAccount(accountId); + await ascFetch(account, `/v1/appScreenshotSets/${setId}`, { method: "DELETE" }); + if (locId) apiCache.delete(cacheKey(locId, accountId)); + res.json({ success: true }); + } catch (err) { + console.error(`Failed to delete screenshot set ${setId}:`, err.message); + res.status(502).json({ error: err.message }); + } +}); + +// ── Upload a screenshot (3-step: reserve -> upload chunks -> commit) ─────── + +router.post("/screenshot-sets/:setId/screenshots/upload", upload.single("file"), async (req, res) => { + const { setId } = req.params; + const { accountId, locId } = req.body; + + if (!req.file) { + return res.status(400).json({ error: "No file provided" }); + } + + try { + const account = resolveAccount(accountId); + const buffer = req.file.buffer; + const checksum = crypto.createHash("md5").update(buffer).digest("base64"); + + // Step 1: Reserve + const reserveData = await ascFetch(account, "/v1/appScreenshots", { + method: "POST", + body: { + data: { + type: "appScreenshots", + attributes: { + fileName: req.file.originalname, + fileSize: buffer.length, + sourceFileChecksum: checksum, + }, + relationships: { + appScreenshotSet: { + data: { type: "appScreenshotSets", id: setId }, + }, + }, + }, + }, + }); + + const screenshotId = reserveData.data.id; + const uploadOps = reserveData.data.attributes.uploadOperations || []; + + // Step 2: Upload chunks to CDN + for (const op of uploadOps) { + const chunk = buffer.slice(op.offset, op.offset + op.length); + const headers = {}; + for (const h of op.requestHeaders) { + headers[h.name] = h.value; + } + + const cdnRes = await fetch(op.url, { + method: op.method, + headers, + body: chunk, + }); + + if (!cdnRes.ok) { + throw new Error(`CDN upload failed: ${cdnRes.status} ${cdnRes.statusText}`); + } + } + + // Step 3: Commit + const commitData = await ascFetch(account, `/v1/appScreenshots/${screenshotId}`, { + method: "PATCH", + body: { + data: { + type: "appScreenshots", + id: screenshotId, + attributes: { + uploaded: true, + sourceFileChecksum: checksum, + }, + }, + }, + }); + + if (locId) apiCache.delete(cacheKey(locId, accountId)); + + res.json({ + id: commitData.data.id, + fileName: commitData.data.attributes.fileName, + fileSize: commitData.data.attributes.fileSize, + sourceFileChecksum: commitData.data.attributes.sourceFileChecksum, + imageAsset: commitData.data.attributes.imageAsset, + assetDeliveryState: commitData.data.attributes.assetDeliveryState, + }); + } catch (err) { + console.error(`Failed to upload screenshot to set ${setId}:`, err.message); + res.status(502).json({ error: err.message }); + } +}); + +// ── Delete a single screenshot ───────────────────────────────────────────── + +router.delete("/screenshots/:screenshotId", async (req, res) => { + const { screenshotId } = req.params; + const { accountId, locId } = req.query; + + try { + const account = resolveAccount(accountId); + await ascFetch(account, `/v1/appScreenshots/${screenshotId}`, { method: "DELETE" }); + if (locId) apiCache.delete(cacheKey(locId, accountId)); + res.json({ success: true }); + } catch (err) { + console.error(`Failed to delete screenshot ${screenshotId}:`, err.message); + res.status(502).json({ error: err.message }); + } +}); + +// ── Reorder screenshots within a set ─────────────────────────────────────── + +router.patch("/screenshot-sets/:setId/screenshots/reorder", async (req, res) => { + const { setId } = req.params; + const { accountId, locId, screenshotIds } = req.body; + + if (!accountId || !Array.isArray(screenshotIds)) { + return res.status(400).json({ error: "accountId and screenshotIds array are required" }); + } + + try { + const account = resolveAccount(accountId); + + await ascFetch(account, `/v1/appScreenshotSets/${setId}/relationships/appScreenshots`, { + method: "PATCH", + body: { + data: screenshotIds.map((id) => ({ type: "appScreenshots", id })), + }, + }); + + if (locId) apiCache.delete(cacheKey(locId, accountId)); + res.json({ success: true }); + } catch (err) { + console.error(`Failed to reorder screenshots in set ${setId}:`, err.message); + res.status(502).json({ error: err.message }); + } +}); + +export default router; diff --git a/src/api/index.js b/src/api/index.js index 9d6aafb..f668280 100644 --- a/src/api/index.js +++ b/src/api/index.js @@ -430,6 +430,78 @@ export async function setSubscriptionPrices(appId, groupId, subId, { accountId, return res.json(); } +// ── Screenshots ───────────────────────────────────────────────────────────── + +export async function fetchScreenshotSets(appId, versionId, locId, accountId) { + const params = new URLSearchParams({ accountId }); + const res = await fetch(`/api/apps/${appId}/versions/${versionId}/localizations/${locId}/screenshot-sets?${params}`); + if (!res.ok) throw new Error(`Failed to fetch screenshot sets: ${res.status}`); + return res.json(); +} + +export async function createScreenshotSet(appId, versionId, locId, { accountId, displayType }) { + const res = await fetch(`/api/apps/${appId}/versions/${versionId}/localizations/${locId}/screenshot-sets`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ accountId, displayType }), + }); + if (!res.ok) { + const err = await res.json().catch(() => ({})); + throw new Error(err.error || `Failed to create screenshot set: ${res.status}`); + } + return res.json(); +} + +export async function deleteScreenshotSet(setId, accountId, locId) { + const params = new URLSearchParams({ accountId, locId }); + const res = await fetch(`/api/apps/screenshot-sets/${setId}?${params}`, { method: "DELETE" }); + if (!res.ok) { + const err = await res.json().catch(() => ({})); + throw new Error(err.error || `Failed to delete screenshot set: ${res.status}`); + } + return res.json(); +} + +export async function uploadScreenshot(setId, accountId, locId, file) { + const formData = new FormData(); + formData.append("file", file); + formData.append("accountId", accountId); + formData.append("locId", locId); + + const res = await fetch(`/api/apps/screenshot-sets/${setId}/screenshots/upload`, { + method: "POST", + body: formData, + }); + if (!res.ok) { + const err = await res.json().catch(() => ({})); + throw new Error(err.error || `Failed to upload screenshot: ${res.status}`); + } + return res.json(); +} + +export async function deleteScreenshot(screenshotId, accountId, locId) { + const params = new URLSearchParams({ accountId, locId }); + const res = await fetch(`/api/apps/screenshots/${screenshotId}?${params}`, { method: "DELETE" }); + if (!res.ok) { + const err = await res.json().catch(() => ({})); + throw new Error(err.error || `Failed to delete screenshot: ${res.status}`); + } + return res.json(); +} + +export async function reorderScreenshots(setId, accountId, locId, screenshotIds) { + const res = await fetch(`/api/apps/screenshot-sets/${setId}/screenshots/reorder`, { + method: "PATCH", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ accountId, locId, screenshotIds }), + }); + if (!res.ok) { + const err = await res.json().catch(() => ({})); + throw new Error(err.error || `Failed to reorder screenshots: ${res.status}`); + } + return res.json(); +} + // ── Xcode Cloud ───────────────────────────────────────────────────────────── export async function fetchBuildActions(appId, buildId, accountId) { diff --git a/src/components/ScreenshotsSection.jsx b/src/components/ScreenshotsSection.jsx new file mode 100644 index 0000000..e77ed2b --- /dev/null +++ b/src/components/ScreenshotsSection.jsx @@ -0,0 +1,459 @@ +import { useState, useEffect, useRef, useCallback } from "react"; +import { + fetchVersionLocalizations, + fetchScreenshotSets, + createScreenshotSet, + deleteScreenshotSet, + uploadScreenshot, + deleteScreenshot, + reorderScreenshots, +} from "../api/index.js"; +import { SCREENSHOT_DISPLAY_TYPES, SCREENSHOT_MAX_COUNT } from "../constants/index.js"; + +const CATEGORIES = ["iPhone", "iPad", "Apple Watch"]; + +function getDisplayTypesByCategory(category) { + return Object.entries(SCREENSHOT_DISPLAY_TYPES) + .filter(([, v]) => v.category === category) + .map(([key, v]) => ({ key, label: v.label })); +} + +function screenshotUrl(imageAsset, width = 400) { + if (!imageAsset?.templateUrl) return null; + const height = Math.round(width * 2.16); + return imageAsset.templateUrl + .replace("{w}", String(width)) + .replace("{h}", String(height)) + .replace("{f}", "png"); +} + +export default function ScreenshotsSection({ appId, versionId, accountId, isMobile }) { + const [expanded, setExpanded] = useState(false); + + // Localizations (reused for locale tabs) + const [localizations, setLocalizations] = useState([]); + const [locsLoading, setLocsLoading] = useState(false); + const [locsError, setLocsError] = useState(null); + + const [selectedLocId, setSelectedLocId] = useState(null); + const [selectedCategory, setSelectedCategory] = useState("iPhone"); + + // Screenshot sets for selected locale + const [sets, setSets] = useState([]); + const [setsLoading, setSetsLoading] = useState(false); + const [setsError, setSetsError] = useState(null); + + // Per-operation states + const [uploadingSetId, setUploadingSetId] = useState(null); + const [deletingId, setDeletingId] = useState(null); + const [creatingSetType, setCreatingSetType] = useState(null); + const [error, setError] = useState(null); + + // Drag state + const [dragSetId, setDragSetId] = useState(null); + const [dragIndex, setDragIndex] = useState(null); + const [dragOverIndex, setDragOverIndex] = useState(null); + + const fileInputRef = useRef(null); + const uploadSetIdRef = useRef(null); + + // Load localizations when expanded + useEffect(() => { + if (!expanded) return; + let cancelled = false; + setLocsLoading(true); + setLocsError(null); + + fetchVersionLocalizations(appId, versionId, accountId) + .then((data) => { + if (cancelled) return; + setLocalizations(data); + if (data.length > 0 && !selectedLocId) { + const enUS = data.find((l) => l.locale.toLowerCase() === "en-us"); + setSelectedLocId(enUS ? enUS.id : data[0].id); + } + }) + .catch((err) => { if (!cancelled) setLocsError(err.message); }) + .finally(() => { if (!cancelled) setLocsLoading(false); }); + + return () => { cancelled = true; }; + }, [expanded, appId, versionId, accountId]); + + // Load screenshot sets when locale changes + useEffect(() => { + if (!selectedLocId) return; + let cancelled = false; + setSetsLoading(true); + setSetsError(null); + + fetchScreenshotSets(appId, versionId, selectedLocId, accountId) + .then((data) => { if (!cancelled) setSets(data); }) + .catch((err) => { if (!cancelled) setSetsError(err.message); }) + .finally(() => { if (!cancelled) setSetsLoading(false); }); + + return () => { cancelled = true; }; + }, [selectedLocId, appId, versionId, accountId]); + + const selectedLocale = localizations.find((l) => l.id === selectedLocId)?.locale; + + // Filter sets for current category + const categoryTypes = getDisplayTypesByCategory(selectedCategory); + const categoryTypeKeys = new Set(categoryTypes.map((t) => t.key)); + const filteredSets = sets.filter((s) => categoryTypeKeys.has(s.displayType)); + + // Display types that don't have sets yet (for creating new ones) + const existingTypes = new Set(sets.map((s) => s.displayType)); + const availableTypes = categoryTypes.filter((t) => !existingTypes.has(t.key)); + + // ── Handlers ───────────────────────────────────────────────────────────── + + async function handleCreateSet(displayType) { + setCreatingSetType(displayType); + setError(null); + try { + const newSet = await createScreenshotSet(appId, versionId, selectedLocId, { accountId, displayType }); + setSets((prev) => [...prev, newSet]); + } catch (err) { + setError(err.message); + } finally { + setCreatingSetType(null); + } + } + + function triggerUpload(setId) { + uploadSetIdRef.current = setId; + fileInputRef.current?.click(); + } + + async function handleFileSelected(e) { + const file = e.target.files?.[0]; + if (!file) return; + e.target.value = ""; + + const setId = uploadSetIdRef.current; + if (!setId) return; + + setUploadingSetId(setId); + setError(null); + try { + const newScreenshot = await uploadScreenshot(setId, accountId, selectedLocId, file); + setSets((prev) => + prev.map((s) => + s.id === setId + ? { ...s, screenshots: [...s.screenshots, newScreenshot] } + : s + ) + ); + } catch (err) { + setError(err.message); + } finally { + setUploadingSetId(null); + } + } + + async function handleDeleteScreenshot(setId, screenshotId) { + setDeletingId(screenshotId); + setError(null); + try { + await deleteScreenshot(screenshotId, accountId, selectedLocId); + setSets((prev) => + prev.map((s) => + s.id === setId + ? { ...s, screenshots: s.screenshots.filter((sc) => sc.id !== screenshotId) } + : s + ) + ); + } catch (err) { + setError(err.message); + } finally { + setDeletingId(null); + } + } + + async function handleDeleteSet(setId) { + setDeletingId(`set-${setId}`); + setError(null); + try { + await deleteScreenshotSet(setId, accountId, selectedLocId); + setSets((prev) => prev.filter((s) => s.id !== setId)); + } catch (err) { + setError(err.message); + } finally { + setDeletingId(null); + } + } + + // ── Drag-and-drop reorder ──────────────────────────────────────────────── + + function handleDragStart(setId, index) { + setDragSetId(setId); + setDragIndex(index); + } + + function handleDragOver(e, index) { + e.preventDefault(); + setDragOverIndex(index); + } + + const handleDrop = useCallback(async (setId) => { + if (dragSetId !== setId || dragIndex === null || dragOverIndex === null || dragIndex === dragOverIndex) { + setDragSetId(null); + setDragIndex(null); + setDragOverIndex(null); + return; + } + + const set = sets.find((s) => s.id === setId); + if (!set) return; + + const newScreenshots = [...set.screenshots]; + const [moved] = newScreenshots.splice(dragIndex, 1); + newScreenshots.splice(dragOverIndex, 0, moved); + + // Optimistic update + setSets((prev) => + prev.map((s) => (s.id === setId ? { ...s, screenshots: newScreenshots } : s)) + ); + + setDragSetId(null); + setDragIndex(null); + setDragOverIndex(null); + + try { + await reorderScreenshots(setId, accountId, selectedLocId, newScreenshots.map((s) => s.id)); + } catch (err) { + setError(err.message); + // Revert on failure + setSets((prev) => + prev.map((s) => (s.id === setId ? { ...s, screenshots: set.screenshots } : s)) + ); + } + }, [dragSetId, dragIndex, dragOverIndex, sets, accountId, selectedLocId]); + + // ── Render ─────────────────────────────────────────────────────────────── + + return ( +
+ {/* Hidden file input */} + + + {/* Collapsible header */} +
+ +
+ + {expanded && ( + <> + {locsLoading ? ( +
+
{"\u21bb"}
+
Loading localizations...
+
+ ) : locsError ? ( +
+
Failed to load localizations
+
{locsError}
+
+ ) : localizations.length === 0 ? ( +
+
No localizations available
+
Add a localization first to manage screenshots
+
+ ) : ( + <> + {/* Locale tabs */} +
+ {localizations.map((loc) => ( + + ))} +
+ + {/* Device category tabs */} +
+ {CATEGORIES.map((cat) => ( + + ))} +
+ + {error && ( +
{error}
+ )} + + {setsLoading ? ( +
+
{"\u21bb"}
+
Loading screenshots...
+
+ ) : setsError ? ( +
+
Failed to load screenshots
+
{setsError}
+
+ ) : ( +
+ {/* Existing sets */} + {filteredSets.map((set) => { + const typeInfo = SCREENSHOT_DISPLAY_TYPES[set.displayType]; + const isUploading = uploadingSetId === set.id; + const isDeletingSet = deletingId === `set-${set.id}`; + const atMax = set.screenshots.length >= SCREENSHOT_MAX_COUNT; + + return ( +
+ {/* Set header */} +
+ + {typeInfo?.label || set.displayType} + +
+ + {set.screenshots.length} of {SCREENSHOT_MAX_COUNT} + + +
+
+ + {/* Screenshot grid */} +
+ {set.screenshots.map((sc, idx) => { + const isDeleting = deletingId === sc.id; + const isProcessing = sc.assetDeliveryState?.state !== "COMPLETE"; + const url = screenshotUrl(sc.imageAsset); + const isDragging = dragSetId === set.id && dragIndex === idx; + const isDragOver = dragSetId === set.id && dragOverIndex === idx; + + return ( +
handleDragStart(set.id, idx)} + onDragOver={(e) => handleDragOver(e, idx)} + onDrop={() => handleDrop(set.id)} + onDragEnd={() => { setDragSetId(null); setDragIndex(null); setDragOverIndex(null); }} + className={`relative group rounded-lg overflow-hidden cursor-grab shrink-0 ${ + isDragging ? "opacity-40" : "" + } ${isDragOver ? "ring-2 ring-accent" : ""}`} + style={{ width: isMobile ? 64 : 80, height: isMobile ? 138 : 173 }} + > + {isProcessing ? ( +
+
{"\u21bb"}
+
+ ) : url ? ( + {sc.fileName} + ) : ( +
+ No preview +
+ )} + + {/* Delete overlay */} + +
+ ); + })} + + {/* Upload button */} + {!atMax && ( + + )} +
+
+ ); + })} + + {/* Create new set for display types that don't have one */} + {availableTypes.length > 0 && ( +
+
Add Display Type
+
+ {availableTypes.map((t) => ( + + ))} +
+
+ )} + + {filteredSets.length === 0 && availableTypes.length === 0 && ( +
+
No display types for {selectedCategory}
+
+ )} +
+ )} + + )} + + )} +
+ ); +} diff --git a/src/components/VersionDetailPage.jsx b/src/components/VersionDetailPage.jsx index 86815c6..2c8e3a3 100644 --- a/src/components/VersionDetailPage.jsx +++ b/src/components/VersionDetailPage.jsx @@ -2,6 +2,7 @@ import { useState, useEffect } from "react"; import { fetchVersionDetail, fetchVersionBuilds, fetchAttachedBuild, attachBuild } from "../api/index.js"; import Badge from "./Badge.jsx"; import BuildSelector from "./BuildSelector.jsx"; +import ScreenshotsSection from "./ScreenshotsSection.jsx"; import VersionLocalizationsSection from "./VersionLocalizationsSection.jsx"; export default function VersionDetailPage({ app, version, accounts, isMobile }) { @@ -172,6 +173,14 @@ export default function VersionDetailPage({ app, version, accounts, isMobile }) /> + {/* Screenshots Section */} + + {/* Localizations Section */}