Desktop D3 UI: studios and store accounts (health checks with fixes, import apps), one card per app across studios (automatic iOS / Android pairing, manual pair / unpair, links, studio moves), store-only apps read-only, ignore list, portfolio search / studio filter / sort / grouping, collapsible studio sidebar, complete Settings, notifications, fixtures with 3 studios and 5 accounts

This commit is contained in:
CRTkafa 2026-10-11 04:15:30 +08:00
parent e058d09683
commit 7b2cc8da0a
24 changed files with 2225 additions and 312 deletions

View file

@ -15,11 +15,14 @@ const only = arg('only', '').split(',').filter(Boolean);
const themes = arg('themes', 'light,dark').split(','); const themes = arg('themes', 'light,dark').split(',');
const lang = arg('lang', 'en'); const lang = arg('lang', 'en');
const suffix = arg('suffix', ''); const suffix = arg('suffix', '');
const prefix = arg('prefix', 'd3');
export const SCREENS: [string, string][] = [ export const SCREENS: [string, string][] = [
['portfolio', 'portfolio'], ['releases', 'app:releases'], ['releases-2', 'app:releases:2'], ['catalog', 'app:catalog'], ['listings', 'app:listings'], ['portfolio', 'portfolio'], ['releases', 'app:releases'], ['releases-2', 'app:releases:2'], ['catalog', 'app:catalog'], ['listings', 'app:listings'],
['health', 'app:health'], ['reviews', 'app:reviews'], ['testflight', 'app:testflight'], ['checks', 'app:checks'], ['health', 'app:health'], ['reviews', 'app:reviews'], ['testflight', 'app:testflight'], ['checks', 'app:checks'],
['apps', 'apps'], ['accounts', 'accounts'], ['dependencies', 'dependencies'], ['settings', 'settings'], ['apps', 'apps'], ['accounts', 'accounts'], ['dependencies', 'dependencies'], ['settings', 'settings'],
['ignored', 'ignored'], ['store-app', 'app:releases:3'], ['store-app-reviews', 'app:reviews:3'], ['store-app-single', 'app:releases:7'],
['settings-pairing', 'settings:pairing'], ['settings-refresh', 'settings:refresh'], ['settings-privacy', 'settings:privacy'],
['palette', 'palette'], ['welcome-1', 'welcome:1'], ['welcome-2', 'welcome:2'], ['welcome-3', 'welcome:3'], ['welcome-4', 'welcome:4'], ['welcome-5', 'welcome:5'], ['palette', 'palette'], ['welcome-1', 'welcome:1'], ['welcome-2', 'welcome:2'], ['welcome-3', 'welcome:3'], ['welcome-4', 'welcome:4'], ['welcome-5', 'welcome:5'],
]; ];
@ -41,7 +44,7 @@ for (const theme of themes) {
if (only.length && !only.includes(name)) continue; if (only.length && !only.includes(name)) continue;
await page.goto(`${base}/?start=${encodeURIComponent(start)}&theme=${theme}&lang=${lang}`); await page.goto(`${base}/?start=${encodeURIComponent(start)}&theme=${theme}&lang=${lang}`);
await settle(page); await settle(page);
const f = join(out, `d2-${name}${suffix}-${theme}${lang === 'en' ? '' : `-${lang}`}.png`); const f = join(out, `${prefix}-${name}${suffix}-${theme}${lang === 'en' ? '' : `-${lang}`}.png`);
await page.screenshot({ path: f }); await page.screenshot({ path: f });
files.push(f); files.push(f);
} }
@ -51,10 +54,45 @@ for (const theme of themes) {
await settle(page); await settle(page);
await page.getByRole('button', { name: /Read the stores|Mağazaları oku/ }).first().click(); await page.getByRole('button', { name: /Read the stores|Mağazaları oku/ }).first().click();
await page.waitForTimeout(900); await page.waitForTimeout(900);
const f = join(out, `d2-toast${suffix}-${theme}${lang === 'en' ? '' : `-${lang}`}.png`); const f = join(out, `${prefix}-toast${suffix}-${theme}${lang === 'en' ? '' : `-${lang}`}.png`);
await page.screenshot({ path: f }); await page.screenshot({ path: f });
files.push(f); files.push(f);
} }
const shot = async (name: string) => {
const f = join(out, `${prefix}-${name}${suffix}-${theme}${lang === 'en' ? '' : `-${lang}`}.png`);
await page.screenshot({ path: f });
files.push(f);
};
if (!only.length || only.includes('accounts-tested')) {
// every account checked: one Play service account was never invited (permission missing, with the fix)
await page.goto(`${base}/?start=accounts&theme=${theme}&lang=${lang}`);
await settle(page);
await page.getByRole('button', { name: /Test all accounts|Tüm hesapları sına/ }).click();
await page.waitForTimeout(900);
await page.getByText(/Sample Labs · Play/).first().scrollIntoViewIfNeeded();
await page.evaluate(() => document.getElementById('content')?.scrollBy({ top: 260 }));
await page.waitForTimeout(200);
await shot('accounts-tested');
}
if (!only.length || only.includes('portfolio-filter')) {
// one studio, sorted by name, no grouping, with a search
await page.goto(`${base}/?start=portfolio&theme=${theme}&lang=${lang}`);
await settle(page);
await page.locator('.fchip', { hasText: 'Example Games' }).click();
await page.getByPlaceholder(/Search apps|Uygulama, bundle/).fill('o');
await page.waitForTimeout(300);
await shot('portfolio-filter');
await page.locator('.fchip').first().click();
await page.getByPlaceholder(/Search apps|Uygulama, bundle/).fill('');
}
if (!only.length || only.includes('import')) {
// Import apps running, with its progress toast
await page.goto(`${base}/?start=accounts&theme=${theme}&lang=${lang}`);
await settle(page);
await page.getByRole('button', { name: /^Import apps$|^Uygulamaları içe aktar$/ }).first().click();
await page.waitForTimeout(700);
await shot('import');
}
if (errors.length) console.error(`${theme}: page errors:\n ${[...new Set(errors)].join('\n ')}`); if (errors.length) console.error(`${theme}: page errors:\n ${[...new Set(errors)].join('\n ')}`);
await ctx.close(); await ctx.close();
} }

View file

@ -113,6 +113,8 @@ pub const EXTERNAL_HOSTS: &[&str] = &[
"ffmpeg.org", "ffmpeg.org",
"googlechromelabs.github.io", "googlechromelabs.github.io",
"git-scm.com", "git-scm.com",
// account health fixes (enable an API in the service account's Google Cloud project)
"console.cloud.google.com",
]; ];
/// Executable of a Chrome for Testing download, relative to its unpacked folder (app data `tools/chrome/`). /// Executable of a Chrome for Testing download, relative to its unpacked folder (app data `tools/chrome/`).

View file

@ -1,27 +1,34 @@
// Shell: sidebar (apps with their icons, workspace), top bar (breadcrumbs, last read, refresh), the screen, the // Shell: sidebar (studios, collapsible, with their apps; the workspace), top bar (breadcrumbs, last read, refresh),
// command palette (Cmd/Ctrl+K), toasts and the first-run welcome guide. // the screen, the command palette (Cmd/Ctrl+K), toasts and the first-run welcome guide.
import { useCallback, useEffect, useMemo, useState } from 'react'; import { useCallback, useEffect, useMemo, useState } from 'react';
import { FIXTURES, onDeepLink } from './api'; import { FIXTURES, onDeepLink } from './api';
import { devSwitch } from './dev/switches'; import { devSwitch } from './dev/switches';
import { type Key, t } from './i18n'; import { type Key, t } from './i18n';
import { ago } from './lib/format'; import { ago } from './lib/format';
import { APP_TABS, NavCtx, parseStart, type Route, sameRoute, TAB_ICON, TAB_KEY, WORKSPACE, type WorkspaceScreen } from './nav'; import { groupByStudio, type UnifiedApp } from './lib/identity';
import { NavCtx, parseStart, type Route, sameRoute, TAB_ICON, TAB_KEY, tabsFor, WORKSPACE, type WorkspaceScreen } from './nav';
import { usePrefs } from './prefs-ctx'; import { usePrefs } from './prefs-ctx';
import { Accounts } from './screens/Accounts'; import { Accounts } from './screens/Accounts';
import { AppFolders } from './screens/AppFolders'; import { AppFolders } from './screens/AppFolders';
import { AppView } from './screens/AppView'; import { AppView } from './screens/AppView';
import { Dependencies } from './screens/Dependencies'; import { Dependencies } from './screens/Dependencies';
import { Ignored } from './screens/Ignored';
import { Onboarding } from './screens/Onboarding'; import { Onboarding } from './screens/Onboarding';
import { Portfolio } from './screens/Portfolio'; import { Portfolio } from './screens/Portfolio';
import { Settings } from './screens/Settings'; import { Settings } from './screens/Settings';
import { useData } from './store'; import { useData } from './store';
import { Icon, type IconName, Mark } from './ui/icons'; import { Icon, type IconName, Mark } from './ui/icons';
import { AppIcon, Kbd, MOD } from './ui/kit'; import { AppIcon, Kbd, MOD, StudioMark } from './ui/kit';
import { type Command, Palette } from './ui/Palette'; import { type Command, Palette } from './ui/Palette';
import { Toasts } from './ui/Toasts'; import { Toasts } from './ui/Toasts';
const WS_ICON: Record<WorkspaceScreen, IconName> = { apps: 'folder', accounts: 'key', dependencies: 'package', settings: 'settings' }; const WS_ICON: Record<WorkspaceScreen, IconName> = { apps: 'folder', accounts: 'building', ignored: 'eyeOff', dependencies: 'package', settings: 'settings' };
const WS_KEY: Record<WorkspaceScreen, Key> = { apps: 'nav.apps', accounts: 'nav.accounts', dependencies: 'nav.dependencies', settings: 'nav.settings' }; export const WS_KEY: Record<WorkspaceScreen, Key> = { apps: 'nav.apps', accounts: 'nav.accounts', ignored: 'nav.ignored', dependencies: 'nav.dependencies', settings: 'nav.settings' };
const SIDE_KEY = 'storebound.side.v1';
function loadCollapsed(): string[] {
try { const v = JSON.parse(localStorage.getItem(SIDE_KEY) ?? '[]') as unknown; return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []; } catch { return []; }
}
export function App({ onTheme }: { onTheme: () => void }) { export function App({ onTheme }: { onTheme: () => void }) {
const d = useData(); const d = useData();
@ -30,8 +37,15 @@ export function App({ onTheme }: { onTheme: () => void }) {
const [palette, setPalette] = useState(false); const [palette, setPalette] = useState(false);
const [welcome, setWelcome] = useState(false); const [welcome, setWelcome] = useState(false);
const [started, setStarted] = useState(false); const [started, setStarted] = useState(false);
const [collapsed, setCollapsed] = useState<string[]>(loadCollapsed);
const go = useCallback((r: Route) => { setRoute(r); document.getElementById('content')?.scrollTo({ top: 0 }); }, []); const go = useCallback((r: Route) => { setRoute(r); document.getElementById('content')?.scrollTo({ top: 0 }); }, []);
const visible = useMemo(() => d.apps.filter(a => !a.ignored).sort((a, b) => a.name.localeCompare(b.name)), [d.apps]);
const toggleGroup = (id: string) => setCollapsed(c => {
const next = c.includes(id) ? c.filter(x => x !== id) : [...c, id];
try { localStorage.setItem(SIDE_KEY, JSON.stringify(next)); } catch { /* private mode */ }
return next;
});
// first screen: dev switch (VITE_START), else the welcome guide on a first run // first screen: dev switch (VITE_START), else the welcome guide on a first run
useEffect(() => { useEffect(() => {
@ -40,69 +54,92 @@ export function App({ onTheme }: { onTheme: () => void }) {
const v = devSwitch('start'); const v = devSwitch('start');
if (v === 'welcome' || v.startsWith('welcome:')) { setWelcome(true); return; } if (v === 'welcome' || v.startsWith('welcome:')) { setWelcome(true); return; }
if (v === 'palette') setPalette(true); if (v === 'palette') setPalette(true);
const r = parseStart(v, d.projects.map(p => p.id)); const r = parseStart(v, d.apps.filter(a => !a.ignored).map(a => a.key));
if (r) { go(r); return; } if (r) { go(r); return; }
if (!d.projects.length && !prefs.onboarded) setWelcome(true); if (!d.projects.length && !d.accounts.length && !prefs.onboarded) setWelcome(true);
}, [d.ready, d.projects, started, go, prefs.onboarded]); }, [d.ready, d.apps, d.projects, d.accounts, started, go, prefs.onboarded]);
useEffect(() => { useEffect(() => {
const un = onDeepLink(s => { const r = parseStart(s, []); if (r) go(r); }); const un = onDeepLink(s => { const r = parseStart(s, []); if (r) go(r); });
return () => { un.then(f => f()); }; return () => { un.then(f => f()); };
}, [d.projects, go]); }, [go]);
// keyboard: Cmd/Ctrl+K palette, Cmd/Ctrl+1 portfolio, 2-5 workspace, Cmd/Ctrl+Shift+[ ] app tabs const app = route.screen === 'app' ? d.appByKey(route.appId) : undefined;
const tabs = app ? tabsFor(!!app.project) : [];
// keyboard: Cmd/Ctrl+K palette, Cmd/Ctrl+1 portfolio, 2-6 workspace, Cmd/Ctrl+Shift+[ ] app tabs
useEffect(() => { useEffect(() => {
const onKey = (e: KeyboardEvent) => { const onKey = (e: KeyboardEvent) => {
const mod = e.metaKey || e.ctrlKey; const mod = e.metaKey || e.ctrlKey;
if (mod && !e.shiftKey && !e.altKey && e.key.toLowerCase() === 'k') { e.preventDefault(); setPalette(p => !p); return; } if (mod && !e.shiftKey && !e.altKey && e.key.toLowerCase() === 'k') { e.preventDefault(); setPalette(p => !p); return; }
if (palette || welcome) return; if (palette || welcome) return;
if (mod && !e.shiftKey && !e.altKey && /^[1-5]$/.test(e.key)) { if (mod && !e.shiftKey && !e.altKey && /^[1-6]$/.test(e.key)) {
e.preventDefault(); e.preventDefault();
const n = Number(e.key); const n = Number(e.key);
go(n === 1 ? { screen: 'portfolio' } : { screen: WORKSPACE[n - 2]! }); go(n === 1 ? { screen: 'portfolio' } : { screen: WORKSPACE[n - 2]! });
return; return;
} }
if (mod && e.shiftKey && (e.key === '[' || e.key === ']' || e.key === '{' || e.key === '}') && route.screen === 'app') { if (mod && e.shiftKey && (e.key === '[' || e.key === ']' || e.key === '{' || e.key === '}') && route.screen === 'app' && tabs.length) {
e.preventDefault(); e.preventDefault();
const i = APP_TABS.indexOf(route.tab) + (e.key === ']' || e.key === '}' ? 1 : -1); const i = tabs.indexOf(route.tab) + (e.key === ']' || e.key === '}' ? 1 : -1);
go({ ...route, tab: APP_TABS[(i + APP_TABS.length) % APP_TABS.length]! }); go({ ...route, tab: tabs[(i + tabs.length) % tabs.length]! });
} }
}; };
window.addEventListener('keydown', onKey); window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey);
}, [palette, welcome, route, go]); }, [palette, welcome, route, go, tabs]);
const closeWelcome = useCallback(() => { const closeWelcome = useCallback(() => {
setWelcome(false); setWelcome(false);
if (!prefs.onboarded) update({ ...prefs, onboarded: true }); if (!prefs.onboarded) update({ ...prefs, onboarded: true });
}, [prefs, update]); }, [prefs, update]);
const app = route.screen === 'app' ? d.projects.find(p => p.id === route.appId) : undefined; useEffect(() => { if (route.screen === 'app' && d.ready && d.apps.length && !app) go({ screen: 'portfolio' }); }, [route, app, d.ready, d.apps.length, go]);
useEffect(() => { if (route.screen === 'app' && d.ready && !app) go({ screen: 'portfolio' }); }, [route, app, d.ready, go]);
const commands = useMemo<Command[]>(() => { const commands = useMemo<Command[]>(() => {
const c: Command[] = []; const c: Command[] = [];
const G = { apps: t('palette.gApps'), go: t('palette.gGo'), tabs: t('palette.gTabs'), act: t('palette.gActions') }; const G = { apps: t('palette.gApps'), go: t('palette.gGo'), tabs: t('palette.gTabs'), act: t('palette.gActions') };
for (const p of d.projects) c.push({ id: `app-${p.id}`, group: G.apps, title: d.statusOf(p)?.app?.name ?? p.name, hint: t('palette.openApp'), app: { name: p.name, icon: d.icons[p.id] }, run: () => go({ screen: 'app', appId: p.id, tab: route.screen === 'app' ? route.tab : 'releases' }) }); const studioName = (a: UnifiedApp) => d.studios.find(s => s.id === a.studio)?.name;
for (const a of visible) c.push({ id: `app-${a.key}`, group: G.apps, title: a.name, hint: studioName(a) ?? t('palette.openApp'), keywords: `${a.ios?.app.bundleId ?? ''} ${a.android?.app.id ?? ''} ${a.project?.name ?? ''}`, app: { name: a.name, icon: d.iconFor(a) },
run: () => go({ screen: 'app', appId: a.key, tab: route.screen === 'app' && tabsFor(!!a.project).includes(route.tab) ? route.tab : 'releases' }) });
c.push({ id: 'go-portfolio', group: G.go, title: t('nav.portfolio'), icon: 'portfolio', hint: `${MOD} 1`, run: () => go({ screen: 'portfolio' }) }); c.push({ id: 'go-portfolio', group: G.go, title: t('nav.portfolio'), icon: 'portfolio', hint: `${MOD} 1`, run: () => go({ screen: 'portfolio' }) });
WORKSPACE.forEach((s, i) => c.push({ id: `go-${s}`, group: G.go, title: t(WS_KEY[s]), icon: WS_ICON[s], hint: `${MOD} ${i + 2}`, run: () => go({ screen: s }) })); WORKSPACE.forEach((s, i) => c.push({ id: `go-${s}`, group: G.go, title: t(WS_KEY[s]), icon: WS_ICON[s], hint: `${MOD} ${i + 2}`, run: () => go({ screen: s }) }));
if (app) for (const tab of APP_TABS) c.push({ id: `tab-${tab}`, group: G.tabs, title: `${app.name} · ${t(TAB_KEY[tab])}`, icon: TAB_ICON[tab], run: () => go({ screen: 'app', appId: app.id, tab }) }); for (const s of d.studios) c.push({ id: `studio-${s.id}`, group: G.go, title: s.name, icon: 'building', keywords: 'studio', hint: t('palette.studio'), run: () => go({ screen: 'accounts', section: s.id }) });
else if (d.projects[0]) for (const p of d.projects) for (const tab of APP_TABS) c.push({ id: `tab-${p.id}-${tab}`, group: G.tabs, title: `${p.name} · ${t(TAB_KEY[tab])}`, icon: TAB_ICON[tab], keywords: 'tab', run: () => go({ screen: 'app', appId: p.id, tab }) }); if (app) for (const tab of tabs) c.push({ id: `tab-${tab}`, group: G.tabs, title: `${app.name} · ${t(TAB_KEY[tab])}`, icon: TAB_ICON[tab], run: () => go({ screen: 'app', appId: app.key, tab }) });
c.push({ id: 'act-live', group: G.act, title: t('action.readStores'), icon: 'refresh', keywords: 'refresh sync', run: () => { d.refreshPortfolio(true); } }); c.push({ id: 'act-live', group: G.act, title: t('action.readStores'), icon: 'refresh', keywords: 'refresh sync', run: () => { d.refreshPortfolio(true); } });
c.push({ id: 'act-import', group: G.act, title: t('action.importApps'), icon: 'download', keywords: 'import sync accounts', run: () => { d.importApps(); } });
c.push({ id: 'act-check', group: G.act, title: t('action.checkConfigs'), icon: 'shield', run: () => { d.refreshPortfolio(false); } }); c.push({ id: 'act-check', group: G.act, title: t('action.checkConfigs'), icon: 'shield', run: () => { d.refreshPortfolio(false); } });
c.push({ id: 'act-add', group: G.act, title: t('action.addFolder'), icon: 'folderPlus', run: () => go({ screen: 'apps' }) }); c.push({ id: 'act-add', group: G.act, title: t('action.addFolder'), icon: 'folderPlus', run: () => go({ screen: 'apps' }) });
c.push({ id: 'act-account', group: G.act, title: t('action.addAccount'), icon: 'key', run: () => go({ screen: 'accounts' }) }); c.push({ id: 'act-account', group: G.act, title: t('action.addAccount'), icon: 'key', run: () => go({ screen: 'accounts' }) });
c.push({ id: 'act-theme', group: G.act, title: t('action.toggleTheme'), icon: 'moon', keywords: 'dark light', run: onTheme }); c.push({ id: 'act-theme', group: G.act, title: t('action.toggleTheme'), icon: 'moon', keywords: 'dark light', run: onTheme });
c.push({ id: 'act-welcome', group: G.act, title: t('action.welcome'), icon: 'sparkle', keywords: 'onboarding start guide', run: () => setWelcome(true) }); c.push({ id: 'act-welcome', group: G.act, title: t('action.welcome'), icon: 'sparkle', keywords: 'onboarding start guide', run: () => setWelcome(true) });
return c; return c;
}, [d, app, route, go, onTheme]); }, [d, visible, app, tabs, route, go, onTheme]);
const crumbs: { label: string; to?: Route }[] = route.screen === 'portfolio' ? [{ label: t('nav.portfolio') }] const crumbs: { label: string; to?: Route }[] = route.screen === 'portfolio' ? [{ label: t('nav.portfolio') }]
: route.screen === 'app' ? [{ label: t('nav.portfolio'), to: { screen: 'portfolio' } }, { label: app?.name ?? '', to: app ? { screen: 'app', appId: app.id, tab: 'releases' } : undefined }, { label: t(TAB_KEY[route.tab]) }] : route.screen === 'app' ? [{ label: t('nav.portfolio'), to: { screen: 'portfolio' } }, { label: app?.name ?? '', to: app ? { screen: 'app', appId: app.key, tab: 'releases' } : undefined }, { label: t(TAB_KEY[route.tab]) }]
: [{ label: t('nav.workspace') }, { label: t(WS_KEY[route.screen]) }]; : [{ label: t('nav.workspace') }, { label: t(WS_KEY[route.screen]) }];
const lastRead = d.live?.at ?? null; const lastRead = d.live?.at ?? null;
const nav = useMemo(() => ({ route, go, openPalette: () => setPalette(true), openWelcome: () => setWelcome(true) }), [route, go]); const nav = useMemo(() => ({ route, go, openPalette: () => setPalette(true), openWelcome: () => setWelcome(true) }), [route, go]);
const current = (r: Route) => (sameRoute(r, route) || (r.screen === 'app' && route.screen === 'app' && r.appId === route.appId) ? 'page' : undefined); const current = (r: Route) => (sameRoute(r, route) || (r.screen === 'app' && route.screen === 'app' && r.appId === route.appId) || (r.screen !== 'app' && r.screen !== 'portfolio' && r.screen === route.screen) ? 'page' : undefined);
const groups = d.studios.length ? groupByStudio(visible.map(a => ({ app: a })), d.studios) : [{ studio: null as string | null, rows: visible.map(a => ({ app: a })) }];
const ignoredCount = d.apps.filter(a => a.ignored).length + d.overrides.ignored.filter(i => i.startsWith('account:')).length;
const appItem = (a: UnifiedApp) => {
const e = d.statusFor(a);
const bad = (e?.errors.length ?? 0) + (e?.check?.problems.length ?? 0);
return (
<div role="listitem" key={a.key}>
<button className="nav nav-app" aria-current={current({ screen: 'app', appId: a.key, tab: 'releases' })}
onClick={() => go({ screen: 'app', appId: a.key, tab: route.screen === 'app' && tabsFor(!!a.project).includes(route.tab) ? route.tab : 'releases' })}>
<AppIcon name={a.name} src={d.iconFor(a)} />
<span className="grow">{a.name}</span>
{!a.project && <span className="so-dot" title={t('apps.storeOnlyHint')}><Icon name="cloud" /></span>}
{bad > 0 && <span className="tag-count bad" aria-label={t('nav.problems', { count: bad })}>{bad}</span>}
</button>
</div>
);
};
return ( return (
<NavCtx.Provider value={nav}> <NavCtx.Provider value={nav}>
@ -117,32 +154,32 @@ export function App({ onTheme }: { onTheme: () => void }) {
</div> </div>
<div className="side-scroll"> <div className="side-scroll">
<button className="nav" aria-current={current({ screen: 'portfolio' })} onClick={() => go({ screen: 'portfolio' })}> <button className="nav" aria-current={current({ screen: 'portfolio' })} onClick={() => go({ screen: 'portfolio' })}>
<Icon name="portfolio" /><span className="grow">{t('nav.portfolio')}</span> <Icon name="portfolio" /><span className="grow">{t('nav.portfolio')}</span><span className="count">{visible.length}</span>
</button> </button>
<div className="side-label" id="apps-label"><span>{t('nav.appsLabel')}</span> <div className="side-label" id="apps-label"><span>{d.studios.length ? t('nav.studiosLabel') : t('nav.appsLabel')}</span>
<button onClick={() => go({ screen: 'apps' })} aria-label={t('action.addFolder')} title={t('action.addFolder')}><Icon name="plus" /></button> <button onClick={() => go({ screen: 'apps' })} aria-label={t('action.addFolder')} title={t('action.addFolder')}><Icon name="plus" /></button>
</div> </div>
<div role="list" aria-labelledby="apps-label"> {groups.map(g => {
{d.projects.map(p => { const s = d.studios.find(x => x.id === g.studio) ?? null;
const e = d.statusOf(p); const gid = g.studio ?? 'none';
const bad = (e?.errors.length ?? 0) + (e?.check?.problems.length ?? 0); const open = !collapsed.includes(gid);
return ( if (!d.studios.length) return <div role="list" aria-labelledby="apps-label" key={gid}>{g.rows.map(r => appItem(r.app))}</div>;
<div role="listitem" key={p.id}> return (
<button className="nav nav-app" aria-current={current({ screen: 'app', appId: p.id, tab: 'releases' })} onClick={() => go({ screen: 'app', appId: p.id, tab: route.screen === 'app' ? route.tab : 'releases' })}> <div className="side-group" key={gid}>
<AppIcon name={p.name} src={d.icons[p.id]} /> <button className="side-group-head" aria-expanded={open} aria-controls={`sg-${gid}`} onClick={() => toggleGroup(gid)}>
<span className="grow">{e?.app?.name ?? p.name}</span> <Icon name="chevronRight" className="chev" /><StudioMark studio={s} size="sm" /><span className="grow">{s?.name ?? t('studio.none')}</span><span className="count">{g.rows.length}</span>
{bad > 0 && <span className="tag-count bad" aria-label={t('nav.problems', { count: bad })}>{bad}</span>} </button>
</button> {open && <div role="list" id={`sg-${gid}`} aria-label={s?.name ?? t('studio.none')}>{g.rows.map(r => appItem(r.app))}</div>}
</div> </div>
); );
})} })}
{!d.projects.length && <p className="side-empty">{t('nav.noApps')}</p>} {!visible.length && <p className="side-empty">{t('nav.noApps')}</p>}
</div>
<div className="side-label"><span>{t('nav.workspace')}</span></div> <div className="side-label"><span>{t('nav.workspace')}</span></div>
{WORKSPACE.map((s, i) => ( {WORKSPACE.map((s, i) => (
<button key={s} className="nav" aria-current={current({ screen: s })} onClick={() => go({ screen: s })} title={`${t(WS_KEY[s])} (${MOD} ${i + 2})`}> <button key={s} className="nav" aria-current={current({ screen: s })} onClick={() => go({ screen: s })} title={`${t(WS_KEY[s])} (${MOD} ${i + 2})`}>
<Icon name={WS_ICON[s]} /><span className="grow">{t(WS_KEY[s])}</span> <Icon name={WS_ICON[s]} /><span className="grow">{t(WS_KEY[s])}</span>
{s === 'accounts' && <span className="count">{d.accounts.length}</span>} {s === 'accounts' && <span className="count">{d.accounts.length}</span>}
{s === 'ignored' && ignoredCount > 0 && <span className="count">{ignoredCount}</span>}
</button> </button>
))} ))}
</div> </div>
@ -165,17 +202,18 @@ export function App({ onTheme }: { onTheme: () => void }) {
<span className="spacer" /> <span className="spacer" />
{FIXTURES && <span className="dev-pill" title={t('dev.fixturesHint')}>{t('dev.fixtures')}</span>} {FIXTURES && <span className="dev-pill" title={t('dev.fixturesHint')}>{t('dev.fixtures')}</span>}
<span className="stamp"><Icon name="clock" />{lastRead ? t('top.storesRead', { when: ago(lastRead) }) : t('top.storesNotRead')}</span> <span className="stamp"><Icon name="clock" />{lastRead ? t('top.storesRead', { when: ago(lastRead) }) : t('top.storesNotRead')}</span>
<button className="btn btn-sm" onClick={() => d.refreshPortfolio(true)} disabled={!!d.portfolioBusy || !d.projects.length} title={t('action.readStoresHint')}> <button className="btn btn-sm" onClick={() => d.refreshPortfolio(true)} disabled={!!d.portfolioBusy || !visible.length} title={t('action.readStoresHint')}>
<Icon name="refresh" className={d.portfolioBusy === 'live' ? 'spin' : undefined} />{d.portfolioBusy === 'live' ? t('action.reading') : t('action.readStores')} <Icon name="refresh" className={d.portfolioBusy === 'live' ? 'spin' : undefined} />{d.portfolioBusy === 'live' ? t('action.reading') : t('action.readStores')}
</button> </button>
</header> </header>
<main className="content" id="content" tabIndex={-1}> <main className="content" id="content" tabIndex={-1}>
{route.screen === 'portfolio' && <Portfolio />} {route.screen === 'portfolio' && <Portfolio />}
{route.screen === 'app' && app && <AppView key={app.id} project={app} tab={route.tab} />} {route.screen === 'app' && app && <AppView key={app.key} app={app} tab={tabs.includes(route.tab) ? route.tab : 'releases'} />}
{route.screen === 'apps' && <AppFolders />} {route.screen === 'apps' && <AppFolders />}
{route.screen === 'accounts' && <Accounts />} {route.screen === 'accounts' && <Accounts focus={route.section} />}
{route.screen === 'ignored' && <Ignored />}
{route.screen === 'dependencies' && <Dependencies />} {route.screen === 'dependencies' && <Dependencies />}
{route.screen === 'settings' && <Settings onTheme={onTheme} />} {route.screen === 'settings' && <Settings onTheme={onTheme} section={route.section} />}
</main> </main>
</div> </div>
</div> </div>

View file

@ -3,10 +3,11 @@
// release builds, so that branch and the fixture module are dropped from them (tests/webview.test.ts checks dist/). // release builds, so that branch and the fixture module are dropped from them (tests/webview.test.ts checks dist/).
import { invoke as tauriInvoke } from '@tauri-apps/api/core'; import { invoke as tauriInvoke } from '@tauri-apps/api/core';
import { listen as tauriListen, type UnlistenFn } from '@tauri-apps/api/event'; import { listen as tauriListen, type UnlistenFn } from '@tauri-apps/api/event';
import type { DraftsResult, IconResult, ListingsResult, MethodDescriptor, PortfolioResult, ProgressParams, ToolResult } from '../../../cli/lib/desktop-protocol'; import type { AccountCheck, AppsListResult, DraftsResult, IconResult, ListingsResult, MethodDescriptor, PortfolioResult, ProgressParams, ToolResult } from '../../../cli/lib/desktop-protocol';
import type { Overrides } from './lib/identity';
export type { export type {
AppIdentity, AppStatus, CatalogParity, DraftsResult, IconResult, ListingField, ListingLocale, ListingsResult, MethodDescriptor, PortfolioResult, AccountCheck, AppIdentity, AppsListResult, AppStatus, CatalogParity, DraftsResult, StoreApp, IconResult, ListingField, ListingLocale, ListingsResult, MethodDescriptor, PortfolioResult,
ProgressParams, ProjectSummary, ReleasePhase, ReleaseTrain, ReplyDraft, StoreRelease, ToolResult, ProgressParams, ProjectSummary, ReleasePhase, ReleaseTrain, ReplyDraft, StoreRelease, ToolResult,
} from '../../../cli/lib/desktop-protocol'; } from '../../../cli/lib/desktop-protocol';
@ -17,7 +18,21 @@ export interface SidecarStatus { running: boolean; version: string; protocol: st
/** An app folder (one storebound.config.ts = one app on iOS and / or Android) and the accounts it uses. */ /** An app folder (one storebound.config.ts = one app on iOS and / or Android) and the accounts it uses. */
export interface Project { id: string; path: string; name: string; playAccount: string | null; appleAccount: string | null; added: string } export interface Project { id: string; path: string; name: string; playAccount: string | null; appleAccount: string | null; added: string }
export type AccountKind = 'play' | 'apple'; export type AccountKind = 'play' | 'apple';
export interface Account { id: string; label: string; kind: AccountKind; created: string } export interface Account { id: string; label: string; kind: AccountKind; created: string; studio?: string | null }
export const STUDIO_COLORS = ['indigo', 'violet', 'rose', 'amber', 'emerald', 'teal', 'sky', 'slate'] as const;
export type StudioColor = (typeof STUDIO_COLORS)[number];
/** A user-named group of store accounts (and so of apps). */
export interface Studio { id: string; name: string; color: StudioColor; logo: string | null; created: string }
export interface Settings {
refresh: { autoMinutes: 0 | 15 | 30 | 60 | 180 | 720; onLaunch: boolean; parallel: number; icons: boolean };
cache: { keepDays: 0 | 7 | 30 | 90 | 365 };
notify: { reviewState: boolean; lowReviews: boolean; crash: boolean };
channel: 'stable' | 'beta';
}
export const DEFAULT_SETTINGS: Settings = { refresh: { autoMinutes: 0, onLaunch: false, parallel: 4, icons: true }, cache: { keepDays: 30 }, notify: { reviewState: true, lowReviews: true, crash: true }, channel: 'stable' };
export interface Workspace { studios: Studio[]; overrides: Overrides; settings: Settings }
export interface AccountApps { account: string; entry: CacheEntry<AppsListResult> | null }
export interface CacheInfo { rows: number; bytes: number; oldest: string | null; file_bytes: number }
export interface WriteOutcome { confirmed: boolean; stage: 'dry-run' | 'dialog' | 'done'; dryRun: ToolResult; result?: ToolResult } export interface WriteOutcome { confirmed: boolean; stage: 'dry-run' | 'dialog' | 'done'; dryRun: ToolResult; result?: ToolResult }
export interface CacheEntry<T = unknown> { value: T; at: string } export interface CacheEntry<T = unknown> { value: T; at: string }
export interface DownloadInfo { tool: 'ffmpeg' | 'chrome'; available: boolean; version: string | null; size: number | null; license: string; licenseUrl: string; source: string; installed: boolean; folder: string } export interface DownloadInfo { tool: 'ffmpeg' | 'chrome'; available: boolean; version: string | null; size: number | null; license: string; licenseUrl: string; source: string; installed: boolean; folder: string }
@ -70,10 +85,28 @@ export const api = {
removeProject: (id: string) => invoke<void>('project_remove', { id }), removeProject: (id: string) => invoke<void>('project_remove', { id }),
setProjectAccounts: (id: string, play: string | null, apple: string | null) => invoke<Project>('project_set_accounts', { id, play, apple }), setProjectAccounts: (id: string, play: string | null, apple: string | null) => invoke<Project>('project_set_accounts', { id, play, apple }),
accounts: () => invoke<Account[]>('accounts_list'), accounts: () => invoke<Account[]>('accounts_list'),
addPlayAccount: (label: string) => invoke<Account | null>('account_add_play', { label }), addPlayAccount: (label: string, studio: string | null = null) => invoke<Account | null>('account_add_play', { label, studio }),
addAppleAccount: (label: string, keyId: string, issuerId: string) => invoke<Account | null>('account_add_apple', { label, keyId, issuerId }), addAppleAccount: (label: string, keyId: string, issuerId: string, studio: string | null = null) => invoke<Account | null>('account_add_apple', { label, keyId, issuerId, studio }),
removeAccount: (id: string) => invoke<void>('account_remove', { id }), removeAccount: (id: string) => invoke<void>('account_remove', { id }),
portfolio: (live = false, job?: string) => invoke<PortfolioResult>('portfolio_status', { live, job: job ?? null }), updateAccount: (id: string, label: string, studio: string | null) => invoke<Account>('account_update', { id, label, studio }),
/** Does the key work, can it see apps (live, not cached). */
checkAccount: (id: string, job?: string) => invoke<AccountCheck>('account_check', { id, job: job ?? null }),
/** Reads the apps an account can see from its store and keeps the list. */
refreshStoreApps: (id: string, job?: string) => invoke<CacheEntry<AppsListResult>>('store_apps_refresh', { id, job: job ?? null }),
storeAppsCached: () => invoke<AccountApps[]>('store_apps_cached'),
workspace: () => invoke<Workspace>('workspace_get'),
saveStudio: (id: string | null, name: string, color: StudioColor) => invoke<Studio>('studio_save', { id, name, color }),
removeStudio: (id: string) => invoke<void>('studio_remove', { id }),
studioLogo: (id: string, clear = false) => invoke<Studio | null>('studio_logo', { id, clear }),
setOverrides: (overrides: Overrides) => invoke<Overrides>('overrides_set', { overrides }),
setSettings: (settings: Settings) => invoke<Settings>('settings_set', { settings }),
cacheInfo: () => invoke<CacheInfo>('cache_info'),
revealData: () => invoke<void>('data_reveal'),
notify: (title: string, body: string) => invoke<void>('notify', { title, body }),
/** Native confirmation first; true when everything was forgotten. */
reset: () => invoke<boolean>('app_reset'),
/** Offline (folders) or live; live also reads the given store-only apps (store targets). */
portfolio: (live = false, job?: string, stores: string[] = []) => invoke<PortfolioResult>('portfolio_status', { live, stores, job: job ?? null }),
openExternal: (url: string) => invoke<void>('open_external', { url }), openExternal: (url: string) => invoke<void>('open_external', { url }),
toolsInfo: () => invoke<DownloadInfo[]>('tools_info'), toolsInfo: () => invoke<DownloadInfo[]>('tools_info'),
installTool: (tool: 'ffmpeg' | 'chrome', job: string) => invoke<string>('tools_install', { tool, job }), installTool: (tool: 'ffmpeg' | 'chrome', job: string) => invoke<string>('tools_install', { tool, job }),

View file

@ -3,7 +3,9 @@
// screenshotted without store accounts, in a browser or in `tauri dev`. Nothing here is real store data; the window // screenshotted without store accounts, in a browser or in `tauri dev`. Nothing here is real store data; the window
// shows a "DEV FIXTURES" badge. src/api.ts only imports this module behind import.meta.env.DEV, so release builds do // shows a "DEV FIXTURES" badge. src/api.ts only imports this module behind import.meta.env.DEV, so release builds do
// not contain it (tests/webview.test.ts checks the built files for FIXTURE_MARKER). // not contain it (tests/webview.test.ts checks the built files for FIXTURE_MARKER).
import type { Account, AppStatus, CacheEntry, DownloadEvent, DraftsResult, ListingField, ListingsResult, PortfolioResult, Project, ProjectSummary, StoreRelease, ToolResult } from '../api'; import { type Account, type AccountCheck, type AppsListResult, type AppStatus, type CacheEntry, DEFAULT_SETTINGS, type DownloadEvent, type DraftsResult, type ListingField, type ListingsResult,
type PortfolioResult, type Project, type ProjectSummary, type Settings, type StoreApp, type StoreRelease, type Studio, type ToolResult } from '../api';
import { buildApps, type Overrides } from '../lib/identity';
import type { CatalogDiff, HealthSnapshot, MetricRow, Review, TestFlightStatus, ValidateResult } from '../lib/model'; import type { CatalogDiff, HealthSnapshot, MetricRow, Review, TestFlightStatus, ValidateResult } from '../lib/model';
export const FIXTURE_MARKER = 'storebound-dev-fixtures'; export const FIXTURE_MARKER = 'storebound-dev-fixtures';
@ -32,16 +34,88 @@ const ICONS: Record<string, string> = {
'p-tidy': svg(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><defs><linearGradient id="g" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#2fd18b"/><stop offset="1" stop-color="#0f9d74"/></linearGradient></defs><rect width="64" height="64" fill="url(#g)"/><rect x="14" y="13" width="36" height="40" rx="7" fill="#fff"/><path d="M20 25l3 3 6-6M20 37l3 3 6-6" stroke="#0f9d74" stroke-width="3" fill="none" stroke-linecap="round" stroke-linejoin="round"/><path d="M33 26h11M33 38h11" stroke="#b6e8d4" stroke-width="3" stroke-linecap="round"/></svg>`), 'p-tidy': svg(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><defs><linearGradient id="g" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#2fd18b"/><stop offset="1" stop-color="#0f9d74"/></linearGradient></defs><rect width="64" height="64" fill="url(#g)"/><rect x="14" y="13" width="36" height="40" rx="7" fill="#fff"/><path d="M20 25l3 3 6-6M20 37l3 3 6-6" stroke="#0f9d74" stroke-width="3" fill="none" stroke-linecap="round" stroke-linejoin="round"/><path d="M33 26h11M33 38h11" stroke="#b6e8d4" stroke-width="3" stroke-linecap="round"/></svg>`),
}; };
// ---- workspace ---- // ---- workspace: 3 studios, 2 Play service accounts + 3 App Store Connect teams, 2 app folders, store-only apps ----
// Placeholder names only (example.com style): no real studio, person, team or id.
const P1 = '0a1b2c3d4e5f6071', P2 = '1b2c3d4e5f607182', A1 = '2c3d4e5f60718293', A2 = '3d4e5f6071829304', A3 = '4e5f607182930415';
const S1 = 's-example', S2 = 's-sample', S3 = 's-demo';
let studios: Studio[] = [
{ id: S1, name: 'Example Games', color: 'indigo', logo: null, created: iso(60 * 24 * 30) },
{ id: S2, name: 'Sample Labs', color: 'emerald', logo: null, created: iso(60 * 24 * 20) },
{ id: S3, name: 'Demo Indie', color: 'amber', logo: null, created: iso(60 * 24 * 9) },
];
let projects: Project[] = [ let projects: Project[] = [
{ id: 'p-prism', path: `${HOME}/apps/prism-puddle`, name: 'Prism Puddle', playAccount: 'a-play', appleAccount: 'a-apple', added: iso(60 * 24 * 12) }, { id: 'p-prism', path: `${HOME}/apps/prism-puddle`, name: 'Prism Puddle', playAccount: P1, appleAccount: A1, added: iso(60 * 24 * 12) },
{ id: 'p-tidy', path: `${HOME}/apps/tidy-lists`, name: 'Tidy Lists', playAccount: 'a-play', appleAccount: 'a-apple', added: iso(60 * 24 * 5) }, { id: 'p-tidy', path: `${HOME}/apps/tidy-lists`, name: 'Tidy Lists', playAccount: P1, appleAccount: A2, added: iso(60 * 24 * 5) },
]; ];
let accounts: Account[] = [ let accounts: Account[] = [
{ id: 'a-play', label: 'Example Studio · Play', kind: 'play', created: iso(60 * 24 * 12) }, { id: P1, label: 'Example Games · Play', kind: 'play', created: iso(60 * 24 * 30), studio: S1 },
{ id: 'a-apple', label: 'Example Studio · App Store', kind: 'apple', created: iso(60 * 24 * 12) }, { id: A1, label: 'Example Games · App Store (company)', kind: 'apple', created: iso(60 * 24 * 30), studio: S1 },
{ id: P2, label: 'Sample Labs · Play', kind: 'play', created: iso(60 * 24 * 20), studio: S2 },
{ id: A2, label: 'Sample Labs · App Store', kind: 'apple', created: iso(60 * 24 * 20), studio: S2 },
{ id: A3, label: 'Demo Indie · App Store (individual)', kind: 'apple', created: iso(60 * 24 * 9), studio: S3 },
]; ];
if (import.meta.env.VITE_FIXTURES === 'empty') { projects = []; accounts = []; } if (import.meta.env.VITE_FIXTURES === 'empty') { projects = []; accounts = []; studios = []; }
/** Small drawn icons for the store apps (fixture art). */
const glyph = (a: string, b: string, inner: string) => `data:image/svg+xml;base64,${btoa(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="${a}"/><stop offset="1" stop-color="${b}"/></linearGradient></defs><rect width="64" height="64" fill="url(#g)"/>${inner}</svg>`)}`;
const G = {
orbit: glyph('#0ea5e9', '#6366f1', '<circle cx="32" cy="32" r="9" fill="#fff"/><ellipse cx="32" cy="32" rx="22" ry="9" fill="none" stroke="#fff" stroke-width="3" transform="rotate(-25 32 32)"/>'),
block: glyph('#22c55e', '#15803d', '<rect x="14" y="30" width="16" height="16" rx="3" fill="#fff"/><rect x="34" y="30" width="16" height="16" rx="3" fill="#bbf7d0"/><rect x="24" y="12" width="16" height="16" rx="3" fill="#fff"/>'),
lantern: glyph('#f59e0b', '#b45309', '<path d="M24 18h16l4 8v16l-4 6H24l-4-6V26z" fill="#fff"/><text x="32" y="41" font-family="Georgia" font-size="16" font-weight="700" text-anchor="middle" fill="#b45309">W</text>'),
tycoon: glyph('#a855f7', '#6d28d9', '<circle cx="32" cy="32" r="16" fill="#fde68a"/><text x="32" y="39" font-family="Arial" font-size="18" font-weight="800" text-anchor="middle" fill="#92400e">$</text>'),
racer: glyph('#ef4444', '#991b1b', '<path d="M14 38l6-12h24l6 12v6H14z" fill="#fff"/><circle cx="22" cy="44" r="4" fill="#111"/><circle cx="42" cy="44" r="4" fill="#111"/>'),
habit: glyph('#14b8a6', '#0f766e', '<ellipse cx="32" cy="36" rx="13" ry="16" fill="#fff"/><path d="M24 34l5 5 11-11" stroke="#0f766e" stroke-width="4" fill="none" stroke-linecap="round"/>'),
focus: glyph('#f43f5e', '#be123c', '<circle cx="32" cy="34" r="15" fill="#fff"/><path d="M32 34V24M32 34l7 4" stroke="#be123c" stroke-width="3.5" stroke-linecap="round"/>'),
sketch: glyph('#fb923c', '#ea580c', '<path d="M32 13l5 11 12 1-9 8 3 12-11-7-11 7 3-12-9-8 12-1z" fill="#fff"/>'),
night: glyph('#1e293b', '#4338ca', '<path d="M38 16a16 16 0 1 0 10 28 13 13 0 0 1-10-28z" fill="#fde68a"/><rect x="18" y="40" width="20" height="3" rx="1.5" fill="#c7d2fe"/>'),
mood: glyph('#ec4899', '#8b5cf6', '<rect x="14" y="14" width="10" height="10" rx="3" fill="#fff"/><rect x="27" y="14" width="10" height="10" rx="3" fill="#fbcfe8"/><rect x="40" y="14" width="10" height="10" rx="3" fill="#fff"/><rect x="14" y="27" width="10" height="10" rx="3" fill="#ddd6fe"/><rect x="27" y="27" width="10" height="10" rx="3" fill="#fff"/><rect x="40" y="27" width="10" height="10" rx="3" fill="#fbcfe8"/><rect x="14" y="40" width="10" height="10" rx="3" fill="#fff"/><rect x="27" y="40" width="10" height="10" rx="3" fill="#ddd6fe"/><rect x="40" y="40" width="10" height="10" rx="3" fill="#fff"/>'),
};
const ios = (id: string, bundleId: string, name: string, icon: string | null, latest: [string, string] | null): StoreApp =>
({ store: 'ios', id, bundleId, name, platforms: ['IOS'], sku: null, primaryLocale: 'en-US', latest: latest ? { version: latest[0], state: latest[1], platform: 'IOS' } : null, icon });
const droid = (pkg: string, name: string, icon: string | null): StoreApp => ({ store: 'android', id: pkg, bundleId: pkg, name, platforms: ['ANDROID'], sku: null, primaryLocale: null, latest: null, icon });
const STORE_APPS: Record<string, StoreApp[]> = {
// one Play service account invited to two developer accounts: it sees Example Games' and Sample Labs' Play apps
[P1]: [
droid('com.example.prismpuddle', 'Prism Puddle', null), droid('com.example.tidylists', 'Tidy Lists', null), droid('com.example.orbithop', 'Orbit Hop', G.orbit),
droid('com.example.blockgarden', 'Block Garden', G.block), droid('com.example.lantern.words', 'Word Lantern', G.lantern), droid('com.example.pockettycoon', 'Pocket Tycoon', G.tycoon),
droid('com.example.nightnotes.free', 'Nightnotes Free', G.night), droid('com.example.moodgrid', 'Mood Grid', G.mood),
],
[A1]: [
ios('6400000001', 'com.example.prismpuddle', 'Prism Puddle', null, ['2.4.0', 'WAITING_FOR_REVIEW']), ios('6400000011', 'com.example.orbithop', 'Orbit Hop', G.orbit, ['3.1.0', 'READY_FOR_SALE']),
ios('6400000012', 'com.example.blockgarden.ios', 'Block Garden', G.block, ['1.2.0', 'IN_REVIEW']), ios('6400000013', 'com.example.wordlantern', 'Word Lantern', G.lantern, ['2.0.1', 'READY_FOR_SALE']),
ios('6400000014', 'com.example.oldracer', 'Old Racer', G.racer, ['1.9.3', 'REMOVED_FROM_SALE']),
],
[A2]: [
ios('6400000002', 'com.example.tidylists', 'Tidy Lists', null, ['1.5.0', 'PREPARE_FOR_SUBMISSION']), ios('6400000021', 'com.example.habithatch', 'Habit Hatch', G.habit, ['1.0.4', 'READY_FOR_SALE']),
ios('6400000022', 'com.example.focustimer', 'Focus Timer Mini', G.focus, ['2.2.0', 'READY_FOR_SALE']),
],
[A3]: [ios('6400000031', 'com.example.starsketch', 'Star Sketch', G.sketch, ['1.1.0', 'READY_FOR_SALE']), ios('6400000032', 'com.example.nightnotes', 'Night Notes', G.night, ['4.0.0', 'READY_FOR_SALE'])],
};
// Sample Labs' Play service account was never invited: no app list, and its check says what to do
const IMPORTED: Record<string, number> = { [P1]: 60 * 3, [A1]: 60 * 3, [A2]: 60 * 3, [A3]: 60 * 26 };
let overrides: Overrides = {
pairs: [{ ios: `ios:${A3}:6400000032`, android: `android:${P1}:com.example.nightnotes.free` }],
unpairs: [], links: [],
appStudio: [{ key: `android:${P1}:com.example.moodgrid`, studio: S3 }],
ignored: [`app:ios:${A1}:6400000014`],
};
if (import.meta.env.VITE_FIXTURES === 'empty') overrides = { pairs: [], unpairs: [], links: [], appStudio: [], ignored: [] };
let settings: Settings = { ...DEFAULT_SETTINGS, refresh: { ...DEFAULT_SETTINGS.refresh, autoMinutes: 60 } };
const PLAY_INVITE = (who: string) => `Play Console > Users and permissions > Invite new users: add ${who}. Account permissions: "View app information and download bulk reports (read-only)"; per app, as needed: "Manage store presence", "Manage testing tracks", "Release to production, exclude devices and use Play App Signing" (rollouts), "Reply to reviews", "Manage orders and subscriptions". One service account can be invited to several developer accounts.`;
const CHECKS: Record<string, AccountCheck> = {
[P1]: { store: 'android', status: 'ok', principal: 'storebound@example-games-123.iam.gserviceaccount.com', apps: 8, message: 'The service account can see 8 apps.', fix: null, docs: null },
[P2]: { store: 'android', status: 'permission', principal: 'storebound@sample-labs-456.iam.gserviceaccount.com', apps: 0, message: 'The key works, but no developer account has invited this service account (it sees no apps).', fix: PLAY_INVITE('storebound@sample-labs-456.iam.gserviceaccount.com'), docs: 'https://play.google.com/console/developers/users-and-permissions' },
[A1]: { store: 'ios', status: 'ok', principal: null, apps: 5, message: 'The key works and can read the team\'s apps.', fix: null, docs: null },
[A2]: { store: 'ios', status: 'ok', principal: null, apps: 3, message: 'The key works and can read the team\'s apps.', fix: null, docs: null },
[A3]: { store: 'ios', status: 'ok', principal: null, apps: 2, message: 'The key works and can read the team\'s apps.', fix: null, docs: null },
};
const appsEntry = (id: string): CacheEntry<AppsListResult> | null => (STORE_APPS[id] && IMPORTED[id] !== undefined && import.meta.env.VITE_FIXTURES !== 'cold'
? { value: { store: accounts.find(a => a.id === id)?.kind === 'play' ? 'android' : 'ios', apps: STORE_APPS[id]!, warnings: [], at: iso(IMPORTED[id]!) }, at: iso(IMPORTED[id]!) } : null);
/** Store-only apps as the window pairs them (so the cached live read covers them too). */
const storeTargets = () => buildApps({
projects, accounts, overrides, summaryOf: p => SUMMARY[p.id],
storeApps: accounts.map(a => ({ account: a.id, apps: appsEntry(a.id)?.value.apps ?? [] })),
}).filter(a => !a.project && !a.ignored);
const SUMMARY: Record<string, ProjectSummary> = { const SUMMARY: Record<string, ProjectSummary> = {
'p-prism': { 'p-prism': {
@ -98,7 +172,39 @@ function status(id: string, live: boolean): AppStatus {
storeErrors: {}, errors: [], storeErrors: {}, errors: [],
}; };
} }
const portfolio = (live: boolean): PortfolioResult => ({ apps: projects.map(p => status(p.id, live)), at: live ? iso(14) : iso(0) }); /** Store-only app releases (fixture), by bundle id / package name. */
const STORE_RELEASES: Record<string, StoreRelease[]> = {
'com.example.orbithop': [rel('ios', '3.1.0', 'live', { build: '88', state: 'READY_FOR_SALE', date: iso(60 * 24 * 6) }), rel('android', '3.1.0', 'rollout', { build: '310', state: 'inProgress', fraction: 0.5 })],
'com.example.blockgarden.ios': [rel('ios', '1.2.0', 'review', { build: '17', state: 'IN_REVIEW', date: iso(60 * 5) }), rel('ios', '1.1.2', 'live', { build: '15', state: 'READY_FOR_SALE', date: iso(60 * 24 * 40) })],
'com.example.blockgarden': [rel('android', '1.2.0', 'live', { build: '120', state: 'completed' })],
'com.example.wordlantern': [rel('ios', '2.0.1', 'live', { build: '41', state: 'READY_FOR_SALE', date: iso(60 * 24 * 18) })],
'com.example.lantern.words': [rel('android', '2.0.1', 'halted', { build: '201', state: 'halted', fraction: 0.1 })],
'com.example.pockettycoon': [rel('android', '5.4.0', 'live', { build: '540', state: 'completed' })],
'com.example.habithatch': [rel('ios', '1.0.4', 'live', { build: '9', state: 'READY_FOR_SALE', date: iso(60 * 24 * 60) })],
'com.example.focustimer': [rel('ios', '2.2.0', 'live', { build: '30', state: 'READY_FOR_SALE', date: iso(60 * 24 * 3) }), rel('ios', '2.3.0', 'rejected', { build: '31', state: 'REJECTED', date: iso(60 * 10) })],
'com.example.starsketch': [rel('ios', '1.1.0', 'live', { build: '12', state: 'READY_FOR_SALE', date: iso(60 * 24 * 12) })],
'com.example.nightnotes': [rel('ios', '4.0.0', 'live', { build: '77', state: 'READY_FOR_SALE', date: iso(60 * 24 * 2) })],
'com.example.nightnotes.free': [rel('android', '4.0.0', 'rollout', { build: '400', state: 'inProgress', fraction: 0.2 })],
'com.example.moodgrid': [rel('android', '0.9.0', 'testing', { build: '9', state: 'completed', track: 'beta' })],
};
function storeStatus(target: string, live: boolean): AppStatus {
const ios = /ios:[^:]+:(\d+):([^;]+)/.exec(target), android = /android:[^:]+:([^;]+)/.exec(target);
const bundle = ios?.[2] ?? null, pkg = android?.[1] ?? null;
const all = [...(bundle ? STORE_RELEASES[bundle] ?? [] : []), ...(pkg ? STORE_RELEASES[pkg] ?? [] : [])];
const name = Object.values(STORE_APPS).flat().find(a => a.bundleId === (bundle ?? pkg))?.name ?? bundle ?? pkg ?? '?';
const versions = [...new Set(all.map(r => r.version!))].sort().reverse();
const live1 = versions.find(v => all.some(r => r.version === v && ['live', 'rollout', 'halted'].includes(r.phase))) ?? null;
const next1 = versions.find(v => !live1 || v > live1) ?? null;
const s: ProjectSummary = { dir: '', config: '', name, languages: ['en'], play: pkg ? { packageName: pkg } : null, apple: bundle ? { bundleId: bundle, appId: ios![1]! } : null,
platforms: [...(bundle ? ['ios' as const] : []), ...(pkg ? ['android' as const] : [])], products: 0, productIds: [], subscriptions: 0, subscriptionIds: [], catalog: { ios: [], android: [] }, shots: false, testflightGroups: 0 };
return {
project: target, ok: true, virtual: true, summary: s, check: { ok: true, problems: [], warnings: [] },
app: { id: target, name, platforms: { ios: bundle ? { bundleId: bundle, ascAppId: ios![1]! } : null, android: pkg ? { packageName: pkg } : null } },
release: live ? { source: 'live', current: live1 ? train(all, live1) : null, next: next1 && next1 !== live1 ? train(all, next1) : null, all } : { source: 'none', current: null, next: null },
catalog: { checked: 'config', products: 0, subscriptions: 0, onlyIos: [], onlyAndroid: [], missingIos: [], missingAndroid: [], ok: true }, storeErrors: {}, errors: [],
};
}
const portfolio = (live: boolean, stores: string[] = []): PortfolioResult => ({ apps: [...projects.map(p => status(p.id, live)), ...(live ? stores.map(s => storeStatus(s, true)) : [])], at: live ? iso(14) : iso(0) });
// ---- per-app store reads ---- // ---- per-app store reads ----
const series = (n: number, base: number, drift: number, seed: number): number[] => const series = (n: number, base: number, drift: number, seed: number): number[] =>
@ -282,7 +388,23 @@ let chromeInstalled = false;
const ok = (method: string, data: unknown): ToolResult => ({ method, ok: true, exitCode: 0, dryRun: false, command: `storebound ${method.replace('.', ' ')} --json`, output: '', data }); const ok = (method: string, data: unknown): ToolResult => ({ method, ok: true, exitCode: 0, dryRun: false, command: `storebound ${method.replace('.', ' ')} --json`, output: '', data });
const STORE_REVIEWS: Review[] = [
R('apple', 's-a1', 5, 'Lovely', 'Simple and quick, does exactly what it says.', 'USA', 1),
R('play', 's-p1', 1, 'Stuck on loading', 'Since the last update it stays on the loading screen on my tablet.', 'en', 1),
R('apple', 's-a2', 4, 'Nice update', 'The new widgets are great. Please add a dark icon.', 'GBR', 3),
R('play', 's-p2', 2, 'Too many ads', 'An ad after every round is too much.', 'en', 5),
R('apple', 's-a3', 5, 'Harika', 'Her gün kullanıyorum, çok sade.', 'TUR', 7),
];
function read(method: string, id: string): ToolResult { function read(method: string, id: string): ToolResult {
if (id.startsWith('store:')) {
const play = /android:/.test(id);
switch (method) {
case 'health': return ok(method, play ? HEALTH['p-tidy'] : { date: day(0), apple: HEALTH['p-tidy']!.apple });
case 'reviews.list': return ok(method, STORE_REVIEWS.filter(r => (play || r.store === 'apple') && (/ios:/.test(id) || r.store === 'play')));
case 'apple.testflight_status': return ok(method, TF['p-tidy']);
default: return { method, ok: false, exitCode: 1, dryRun: false, command: `storebound ${method}`, output: `fixture: ${method} needs an app folder` };
}
}
switch (method) { switch (method) {
case 'project.icon': return ok(method, { path: SUMMARY[id]?.icon ?? null, dataUrl: ICONS[id] ?? null }); case 'project.icon': return ok(method, { path: SUMMARY[id]?.icon ?? null, dataUrl: ICONS[id] ?? null });
case 'project.listings': return ok(method, LISTINGS[id]); case 'project.listings': return ok(method, LISTINGS[id]);
@ -316,21 +438,48 @@ async function answer(cmd: string, a: Record<string, unknown>): Promise<unknown>
case 'sidecar_status': return { running: true, version: '0.5.0', protocol: 'storebound-desktop/1', methods: Array.from({ length: 64 }, (_, i) => ({ method: `m${i}` })), tools: { tools: TOOLS.map(x => (x.id === 'chrome' && chromeInstalled ? { ...x, found: true, name: 'Chrome for Testing', version: '141.0.7390.54', source: 'app' } : x)) } }; case 'sidecar_status': return { running: true, version: '0.5.0', protocol: 'storebound-desktop/1', methods: Array.from({ length: 64 }, (_, i) => ({ method: `m${i}` })), tools: { tools: TOOLS.map(x => (x.id === 'chrome' && chromeInstalled ? { ...x, found: true, name: 'Chrome for Testing', version: '141.0.7390.54', source: 'app' } : x)) } };
case 'projects_list': return projects; case 'projects_list': return projects;
case 'accounts_list': return accounts; case 'accounts_list': return accounts;
case 'workspace_get': return { studios, overrides, settings };
case 'store_apps_cached': return accounts.map(x => ({ account: x.id, entry: appsEntry(x.id) }));
case 'store_apps_refresh': {
const id = a.id as string;
await progressLines(job, ['[apps] reading the account\'s apps', '[apps] icons']);
if (job && cancelled.has(job)) throw { code: -32800, message: 'Request cancelled' };
if (!STORE_APPS[id]) throw { code: -32603, message: `Google Play: ${CHECKS[id]?.message ?? 'no apps'}` };
IMPORTED[id] = 0;
return appsEntry(id);
}
case 'account_check': await sleep(350); return CHECKS[a.id as string];
case 'studio_save': {
const s = a.id ? studios.find(x => x.id === a.id)! : { id: `s-${studios.length + 1}`, logo: null, created: iso(0) } as Studio;
Object.assign(s, { name: a.name, color: a.color });
if (!a.id) studios = [...studios, s];
return s;
}
case 'studio_remove': studios = studios.filter(s => s.id !== a.id); accounts = accounts.map(x => (x.studio === a.id ? { ...x, studio: null } : x)); return null;
case 'studio_logo': return null;
case 'account_update': { const x = accounts.find(y => y.id === a.id)!; x.label = a.label as string; x.studio = (a.studio as string | null) ?? null; return x; }
case 'overrides_set': overrides = a.overrides as Overrides; return overrides;
case 'settings_set': settings = a.settings as Settings; return settings;
case 'cache_info': return { rows: 214, bytes: 3_412_000, oldest: iso(60 * 24 * 26), file_bytes: 4_718_592 };
case 'data_reveal': case 'notify': return null;
case 'app_reset': return false;
case 'portfolio_status': { case 'portfolio_status': {
const stores = (a.stores as string[] | undefined) ?? [];
if (a.live) { if (a.live) {
for (let n = 1; n <= projects.length; n++) { const total = projects.length + stores.length;
await sleep(700); for (let n = 1; n <= total; n++) {
await sleep(total > 6 ? 180 : 700);
if (job && cancelled.has(job)) throw { code: -32800, message: 'Request cancelled' }; if (job && cancelled.has(job)) throw { code: -32800, message: 'Request cancelled' };
emit('sidecar-progress', { params: { requestId: 0, n, total: projects.length, project: projects[n - 1]!.path }, job }); emit('sidecar-progress', { params: { requestId: 0, n, total, project: projects[n - 1]?.path ?? stores[n - 1 - projects.length] }, job });
} }
return portfolio(true); return portfolio(true, stores);
} }
await sleep(120); await sleep(120);
return portfolio(false); return portfolio(false);
} }
case 'cache_get': { case 'cache_get': {
const method = a.method as string, id = a.projectId as string; const method = a.method as string, id = a.projectId as string;
if (id === '*' && method === 'portfolio.status') return projects.length ? { value: portfolio(true), at: iso(14) } satisfies CacheEntry<PortfolioResult> : null; if (id === '*' && method === 'portfolio.status') return projects.length ? { value: portfolio(true, storeTargets().map(x => x.target)), at: iso(14) } satisfies CacheEntry<PortfolioResult> : null;
if (method === 'project.icon') return ICONS[id] ? { value: read(method, id), at: iso(60) } : null; if (method === 'project.icon') return ICONS[id] ? { value: read(method, id), at: iso(60) } : null;
if (CACHED_AGO[method] !== undefined && import.meta.env.VITE_FIXTURES !== 'cold') return { value: read(method, id), at: iso(CACHED_AGO[method]!) }; if (CACHED_AGO[method] !== undefined && import.meta.env.VITE_FIXTURES !== 'cold') return { value: read(method, id), at: iso(CACHED_AGO[method]!) };
return null; return null;

View file

@ -8,7 +8,7 @@ export const en = {
'nav.appsLabel': 'Apps', 'nav.appsLabel': 'Apps',
'nav.workspace': 'Workspace', 'nav.workspace': 'Workspace',
'nav.apps': 'App folders', 'nav.apps': 'App folders',
'nav.accounts': 'Accounts', 'nav.accounts': 'Studios & accounts',
'nav.dependencies': 'Dependencies', 'nav.dependencies': 'Dependencies',
'nav.settings': 'Settings', 'nav.settings': 'Settings',
'nav.noApps': 'No apps yet', 'nav.noApps': 'No apps yet',
@ -557,4 +557,221 @@ export const en = {
'wz.back': 'Back', 'wz.back': 'Back',
'wz.next': 'Next', 'wz.next': 'Next',
'wz.finish': 'Finish', 'wz.finish': 'Finish',
'nav.ignored': 'Ignored',
'nav.studios': 'Studios',
'nav.studiosLabel': 'Studios',
'palette.studio': 'Studio',
'action.importApps': 'Import apps',
'action.importAppsHint': 'Read-only: every app each store account can see, from App Store Connect and Google Play',
'apps.storeOnly': 'Store only',
'apps.storeOnlyHint': 'On a store account, no app folder yet: store data only (read-only)',
'common.save': 'Save',
'studio.studio': 'Studio',
'studio.none': 'No studio',
'studio.noneSub': 'Accounts not in a studio yet',
'studio.new': 'New studio',
'studio.newSub': 'A studio groups store accounts, and with them their apps',
'studio.name': 'Name',
'studio.namePlaceholder': 'Example Games',
'studio.color': 'Colour',
'studio.add': 'Add a studio',
'studio.added': 'Studio {name} added',
'studio.edit': 'Edit',
'studio.logo': 'Logo',
'studio.logoClear': 'Remove logo',
'studio.remove': 'Remove',
'studio.removeHint': 'Removes the studio only: its accounts and apps stay, without a studio',
'studio.counts': '{count} accounts · {apps} apps · {store} store only',
'studio.noAccounts': 'No store account in this studio yet: add one below and pick this studio.',
'studio.allAssigned': 'Every account is in a studio.',
'color.indigo': 'Indigo',
'color.violet': 'Violet',
'color.rose': 'Rose',
'color.amber': 'Amber',
'color.emerald': 'Emerald',
'color.teal': 'Teal',
'color.sky': 'Sky',
'color.slate': 'Slate',
'accounts.leadStudios': 'Studios group your store accounts: Google Play service accounts and App Store Connect team keys. Keys stay in the system keychain; apps come in with Import apps.',
'accounts.emptyTextStudios': 'Add a studio, then its Google Play service account and App Store Connect keys. Import apps then lists every app those keys can see.',
'accounts.playSubMany': 'Service account JSON key. One service account can be invited to several Play developer accounts: it sees all their apps.',
'accounts.appleSubMany': 'One API key per team (company or individual): key id, issuer id and the .p8 file.',
'accounts.safetyStudios': 'Keys are read once from the file you pick, stored in the system keychain and never shown again. storebound gets one account\'s key in memory for one call. Studio names, labels and app lists stay on this computer.',
'acct.ok': 'Works',
'acct.noApps': 'No apps',
'acct.permission': 'Permission missing',
'acct.revoked': 'Key revoked',
'acct.apiDisabled': 'API off',
'acct.error': 'Not reachable',
'acct.notTested': 'Not tested',
'acct.kindPlay': 'Google Play service account',
'acct.kindApple': 'App Store Connect team key',
'acct.appsRead': '{count} apps, read {when}',
'acct.appsRead_one': '1 app, read {when}',
'acct.notImported': 'apps not imported yet',
'acct.folders': 'used by {count} folders',
'acct.folders_one': 'used by 1 folder',
'acct.test': 'Test',
'acct.testAll': 'Test all accounts',
'acct.import': 'Import apps',
'acct.edit': 'Rename or move to a studio',
'acct.editAria': 'Edit {label}',
'acct.ignore': 'Ignore this account',
'acct.ignoreHint': 'Ignore: leave this account\'s apps out of the portfolio and store reads',
'acct.unignore': 'Show this account again',
'acct.ignored': 'Ignored',
'acct.openFix': 'Open',
'ignored.lead': 'Apps and accounts left out of the portfolio, the sidebar and store reads. Nothing on the stores changes.',
'ignored.restoreAll': 'Restore all',
'ignored.restore': 'Restore',
'ignored.emptyTitle': 'Nothing is ignored',
'ignored.emptyText': 'Ignore an app from its page (or a whole account in Studios & accounts) to keep test apps and old titles out of the way.',
'ignored.apps': 'Apps',
'ignored.appsSub': '{count} ignored',
'ignored.accounts': 'Accounts',
'ignored.accountsSub': 'Every app of these accounts is left out',
'ignored.accountApps': '{count} apps',
'ignored.accountApps_one': '1 app',
'ignored.noApps': 'No ignored app.',
'ignored.noAccounts': 'No ignored account.',
'ignored.howTo': 'Pairing and single-store apps:',
'ignored.toPairing': 'Settings > App pairing',
'pair.folder': 'From its app folder',
'pair.manual': 'Paired by hand',
'pair.id': 'Paired: same bundle id and package name',
'pair.close': 'Paired: close ids',
'pair.name': 'Paired: same name',
'pair.single': 'One store only',
'app.moveStudio': 'Move to a studio',
'app.pairWith': 'Pair with',
'app.pairWithName': 'Pair {name} with',
'app.pick': 'Pick an app',
'app.unpair': 'Unpair',
'app.ignore': 'Ignore',
'app.ignoreHint': 'Leave this app out of the portfolio and store reads (Ignored lists it to restore)',
'app.studioHint': 'Open the studio',
'app.storeOnlyTitle': 'Store only.',
'app.storeOnlyText': 'This app is on your store accounts but has no app folder: releases, reviews, health and TestFlight are shown read-only. Link its folder, or start one, to manage listings, products and checks.',
'app.linkFolder': 'Link a folder',
'app.initHere': 'Start an app folder here',
'app.linked': '{name} is linked',
'app.linkFailed': 'Could not link the folder',
'portfolio.subStudios': '{count} apps · {stores} store listings · {studios} studios',
'portfolio.emptyAccounts': 'Add a studio and its accounts',
'portfolio.notImported': 'Apps of {count} accounts are not imported yet: Import apps lists everything those keys can see.',
'portfolio.notImported_one': 'Apps of 1 account are not imported yet: Import apps lists everything its key can see.',
'portfolio.toolbar': 'Filter and sort the apps',
'portfolio.search': 'Search apps, bundle ids, packages',
'portfolio.studioFilter': 'Studio',
'portfolio.allStudios': 'All studios',
'portfolio.sort': 'Sort',
'portfolio.sortAttention': 'Needs attention',
'portfolio.sortRecent': 'Recently updated',
'portfolio.sortName': 'Name',
'portfolio.group': 'Group by studio',
'portfolio.groupCount': '{count} apps',
'portfolio.noConfig': 'No config',
'portfolio.storeOnlyCheck': 'Store only',
'portfolio.noMatch': 'No app matches',
'portfolio.noMatchText': 'Clear the search or pick another studio.',
'portfolio.studiosN': '{count} studios',
'portfolio.studiosN_one': '1 studio',
'portfolio.folders': 'App folders',
'portfolio.foldersN': '{count} folders · {store} store only',
'portfolio.ignoredN': '{count} apps',
'portfolio.ignoredN_one': '1 app',
'kpi.appsSubStore': 'iOS {ios} · Android {android} · {store} store only',
'toast.importing': 'Importing apps',
'toast.importingDetail': 'Every app each account can see (read-only)',
'toast.importDone': '{count} apps on your accounts',
'toast.importDone_one': '1 app on your accounts',
'toast.importDoneDetail': 'from {count} accounts',
'toast.importDoneDetail_one': 'from 1 account',
'toast.importPartial': '{count} accounts could not be read',
'toast.importPartial_one': '1 account could not be read',
'toast.saveFailed': 'Not saved',
'notify.releaseTitle': '{name}: store state changed',
'notify.releaseBody': '{store} {version}: {phase}',
'notify.lowTitle': '{name}: {count} new low ratings',
'notify.lowTitle_one': '{name}: a new low rating',
'notify.crashTitle': '{name}: over the Play threshold',
'set.lead': 'Studios, accounts, store reads, the offline cache, language, theme, notifications and more. Everything stays on this computer.',
'set.sections': 'Settings sections',
'set.studios': 'Studios & accounts',
'set.studiosSub': 'Which accounts belong to which studio',
'set.studioLine': 'Play {play} · App Store {apple} · {apps} apps',
'set.noStudios': 'No studio yet. Studios group accounts and their apps in the portfolio and the sidebar.',
'set.manage': 'Manage',
'set.pairing': 'App pairing & ignore list',
'set.pairingSub': 'An iOS and an Android app become one card when their ids or names match; pair or split them by hand here',
'set.pairedHow': 'Pairing',
'set.noCandidates': 'Nothing to pair with',
'set.noStoreOnly': 'Every app has its folder: pairing comes from the configs.',
'set.ignoredLine': 'Ignored: {count} apps, {accounts} accounts.',
'set.openIgnored': 'Open the list',
'set.refresh': 'Store reads',
'set.refreshSub': 'Reads use each account\'s API quota: they run when you ask, or on the schedule here',
'set.autoRefresh': 'Read the stores automatically',
'set.autoHint': 'While the app is open. Off by default.',
'set.off': 'Off',
'set.min': '{n} min',
'set.hour': '{n} h',
'set.onLaunch': 'Read when the app starts',
'set.onLaunchHint': 'Imports the apps of every account, then reads every app\'s store status',
'set.icons': 'Store icons on import',
'set.iconsHint': 'One extra request per app; folders use their own icon',
'set.parallel': 'Apps read at the same time',
'set.parallelHint': 'Fewer is gentler on rate limits',
'set.cache': 'Offline cache',
'set.cacheSub': 'The last store reads, shown with their time when you are offline',
'set.cacheSize': 'On disk',
'set.cacheRows': '{count} saved reads',
'set.cacheRows_one': '1 saved read',
'set.cacheOldest': 'Oldest',
'set.keep': 'Keep saved reads',
'set.days': '{n} days',
'set.year': '1 year',
'set.always': 'Always',
'set.notifications': 'Notifications',
'set.notificationsSub': 'After a read, when something changed since the previous one',
'set.nReview': 'Review and release state changes',
'set.nReviewHint': 'In review, approved, rejected, live, halted',
'set.nLow': 'New 1 or 2 star reviews',
'set.nLowHint': 'When the Reviews tab reads new ones',
'set.nCrash': 'Crash or ANR rate over the threshold',
'set.nCrashHint': 'Google Play bad behavior thresholds',
'set.testNotify': 'Send a test notification',
'set.testTitle': 'storebound',
'set.testBody': 'Notifications work.',
'set.appCopy': 'app copy',
'set.depsText': 'Store work needs no local tool. Screenshots, previews and icons use ffmpeg and Chrome: one click on the Dependencies screen.',
'set.cli': 'CLI sidecar',
'set.protocol': 'Protocol',
'set.state': 'State',
'set.running': 'Running',
'set.writes': 'Writes',
'set.writesText': 'Dry run first, then your Apply in a system dialog. Submit, release and publish stay in the consoles.',
'set.privacy': 'Privacy',
'set.p1': 'No telemetry, no analytics, no crash reports: the app talks only to the stores, with your keys, when you ask.',
'set.p2': 'Store keys live in the system keychain; the app data folder holds names, settings and saved reads, never keys.',
'set.p3': 'Nothing is written into your app folders unless you confirm it in a system dialog.',
'set.p4': 'Tester emails stay masked; review drafts stay in each app folder\'s .storebound/ (gitignored).',
'set.reveal': 'Show the data folder',
'set.scQuit': 'Quit',
'set.updates': 'Updates',
'set.channel': 'Channel',
'set.stable': 'Stable',
'set.beta': 'Beta',
'set.updatesText': 'Signed updates from storebound.dev arrive with the first public desktop release; the channel is kept for then.',
'set.reset': 'Reset',
'set.resetText': 'Forgets {accounts} accounts (their keys are removed from the keychain), {studios} studios, {folders} app folders (the folders stay on disk), pairing, the ignore list, settings and saved reads. A system dialog asks first.',
'set.resetButton': 'Reset the app',
'set.resetDone': 'storebound desktop was reset',
'set.footer': '{n} apps known to this computer',
'studio.counts_one': '1 account · {apps} apps · {store} store only',
'portfolio.groupCount_one': '1 app',
'portfolio.groupAccounts': '{count} accounts',
'portfolio.groupAccounts_one': '1 account',
} as const; } as const;

View file

@ -10,7 +10,7 @@ export const tr: Record<keyof typeof en, string> = {
'nav.appsLabel': 'Uygulamalar', 'nav.appsLabel': 'Uygulamalar',
'nav.workspace': 'Çalışma alanı', 'nav.workspace': 'Çalışma alanı',
'nav.apps': 'Uygulama klasörleri', 'nav.apps': 'Uygulama klasörleri',
'nav.accounts': 'Hesaplar', 'nav.accounts': 'Stüdyolar ve hesaplar',
'nav.dependencies': 'Bağımlılıklar', 'nav.dependencies': 'Bağımlılıklar',
'nav.settings': 'Ayarlar', 'nav.settings': 'Ayarlar',
'nav.noApps': 'Henüz uygulama yok', 'nav.noApps': 'Henüz uygulama yok',
@ -559,4 +559,221 @@ export const tr: Record<keyof typeof en, string> = {
'wz.back': 'Geri', 'wz.back': 'Geri',
'wz.next': 'İleri', 'wz.next': 'İleri',
'wz.finish': 'Bitir', 'wz.finish': 'Bitir',
'nav.ignored': 'Yok sayılanlar',
'nav.studios': 'Stüdyolar',
'nav.studiosLabel': 'Stüdyolar',
'palette.studio': 'Stüdyo',
'action.importApps': 'Uygulamaları içe aktar',
'action.importAppsHint': 'Salt okunur: her mağaza hesabının gördüğü tüm uygulamalar, App Store Connect ve Google Play\'den',
'apps.storeOnly': 'Yalnızca mağaza',
'apps.storeOnlyHint': 'Bir mağaza hesabında, henüz uygulama klasörü yok: yalnızca mağaza verisi (salt okunur)',
'common.save': 'Kaydet',
'studio.studio': 'Stüdyo',
'studio.none': 'Stüdyosuz',
'studio.noneSub': 'Henüz bir stüdyoda olmayan hesaplar',
'studio.new': 'Yeni stüdyo',
'studio.newSub': 'Stüdyo mağaza hesaplarını, onlarla birlikte uygulamalarını gruplar',
'studio.name': 'Ad',
'studio.namePlaceholder': 'Örnek Oyunlar',
'studio.color': 'Renk',
'studio.add': 'Stüdyo ekle',
'studio.added': '{name} stüdyosu eklendi',
'studio.edit': 'Düzenle',
'studio.logo': 'Logo',
'studio.logoClear': 'Logoyu kaldır',
'studio.remove': 'Kaldır',
'studio.removeHint': 'Yalnızca stüdyoyu kaldırır: hesapları ve uygulamaları stüdyosuz kalır',
'studio.counts': '{count} hesap · {apps} uygulama · {store} yalnızca mağazada',
'studio.noAccounts': 'Bu stüdyoda henüz mağaza hesabı yok: aşağıdan bir hesap ekleyip bu stüdyoyu seçin.',
'studio.allAssigned': 'Her hesap bir stüdyoda.',
'color.indigo': 'Çivit',
'color.violet': 'Mor',
'color.rose': 'Gül',
'color.amber': 'Kehribar',
'color.emerald': 'Zümrüt',
'color.teal': 'Deniz mavisi',
'color.sky': 'Gök mavisi',
'color.slate': 'Arduvaz',
'accounts.leadStudios': 'Stüdyolar mağaza hesaplarınızı gruplar: Google Play hizmet hesapları ve App Store Connect ekip anahtarları. Anahtarlar sistem anahtar zincirinde kalır; uygulamalar "Uygulamaları içe aktar" ile gelir.',
'accounts.emptyTextStudios': 'Bir stüdyo, sonra onun Google Play hizmet hesabını ve App Store Connect anahtarlarını ekleyin. "Uygulamaları içe aktar" bu anahtarların gördüğü tüm uygulamaları listeler.',
'accounts.playSubMany': 'Hizmet hesabı JSON anahtarı. Bir hizmet hesabı birden çok Play geliştirici hesabına davet edilebilir: hepsinin uygulamalarını görür.',
'accounts.appleSubMany': 'Ekip başına bir API anahtarı (şirket ya da bireysel): anahtar kimliği, issuer kimliği ve .p8 dosyası.',
'accounts.safetyStudios': 'Anahtarlar seçtiğiniz dosyadan bir kez okunur, sistem anahtar zincirine kaydedilir ve bir daha gösterilmez. storebound bir hesabın anahtarını tek bir çağrı için bellekte alır. Stüdyo adları, etiketler ve uygulama listeleri bu bilgisayarda kalır.',
'acct.ok': 'Çalışıyor',
'acct.noApps': 'Uygulama yok',
'acct.permission': 'İzin eksik',
'acct.revoked': 'Anahtar iptal',
'acct.apiDisabled': 'API kapalı',
'acct.error': 'Ulaşılamadı',
'acct.notTested': 'Sınanmadı',
'acct.kindPlay': 'Google Play hizmet hesabı',
'acct.kindApple': 'App Store Connect ekip anahtarı',
'acct.appsRead': '{count} uygulama, {when} okundu',
'acct.appsRead_one': '1 uygulama, {when} okundu',
'acct.notImported': 'uygulamalar henüz içe aktarılmadı',
'acct.folders': '{count} klasör kullanıyor',
'acct.folders_one': '1 klasör kullanıyor',
'acct.test': 'Sına',
'acct.testAll': 'Tüm hesapları sına',
'acct.import': 'Uygulamaları al',
'acct.edit': 'Yeniden adlandır ya da stüdyoya taşı',
'acct.editAria': '{label} düzenle',
'acct.ignore': 'Bu hesabı yok say',
'acct.ignoreHint': 'Yok say: bu hesabın uygulamalarını portföy ve mağaza okumalarının dışında bırak',
'acct.unignore': 'Bu hesabı yeniden göster',
'acct.ignored': 'Yok sayıldı',
'acct.openFix': 'Aç',
'ignored.lead': 'Portföy, kenar çubuğu ve mağaza okumalarının dışında bırakılan uygulamalar ve hesaplar. Mağazalarda hiçbir şey değişmez.',
'ignored.restoreAll': 'Tümünü geri getir',
'ignored.restore': 'Geri getir',
'ignored.emptyTitle': 'Yok sayılan bir şey yok',
'ignored.emptyText': 'Test uygulamalarını ve eski başlıkları uzak tutmak için bir uygulamayı kendi sayfasından (ya da bütün bir hesabı Stüdyolar ve hesaplar\'dan) yok sayın.',
'ignored.apps': 'Uygulamalar',
'ignored.appsSub': '{count} yok sayıldı',
'ignored.accounts': 'Hesaplar',
'ignored.accountsSub': 'Bu hesapların tüm uygulamaları dışarıda',
'ignored.accountApps': '{count} uygulama',
'ignored.accountApps_one': '1 uygulama',
'ignored.noApps': 'Yok sayılan uygulama yok.',
'ignored.noAccounts': 'Yok sayılan hesap yok.',
'ignored.howTo': 'Eşleştirme ve tek mağazalı uygulamalar:',
'ignored.toPairing': 'Ayarlar > Uygulama eşleştirme',
'pair.folder': 'Uygulama klasöründen',
'pair.manual': 'Elle eşleştirildi',
'pair.id': 'Eşleşti: aynı bundle id ve paket adı',
'pair.close': 'Eşleşti: benzer kimlikler',
'pair.name': 'Eşleşti: aynı ad',
'pair.single': 'Tek mağaza',
'app.moveStudio': 'Bir stüdyoya taşı',
'app.pairWith': 'Şununla eşleştir',
'app.pairWithName': '{name} uygulamasını şununla eşleştir',
'app.pick': 'Bir uygulama seçin',
'app.unpair': 'Eşleşmeyi ayır',
'app.ignore': 'Yok say',
'app.ignoreHint': 'Bu uygulamayı portföy ve mağaza okumalarının dışında bırak (Yok sayılanlar ekranından geri getirilir)',
'app.studioHint': 'Stüdyoyu aç',
'app.storeOnlyTitle': 'Yalnızca mağaza.',
'app.storeOnlyText': 'Bu uygulama mağaza hesaplarınızda ama uygulama klasörü yok: sürümler, yorumlar, sağlık ve TestFlight salt okunur gösterilir. Mağaza metinlerini, ürünleri ve denetimleri yönetmek için klasörünü bağlayın ya da yeni bir klasör başlatın.',
'app.linkFolder': 'Klasör bağla',
'app.initHere': 'Burada uygulama klasörü başlat',
'app.linked': '{name} bağlandı',
'app.linkFailed': 'Klasör bağlanamadı',
'portfolio.subStudios': '{count} uygulama · {stores} mağaza kaydı · {studios} stüdyo',
'portfolio.emptyAccounts': 'Stüdyo ve hesaplarını ekle',
'portfolio.notImported': '{count} hesabın uygulamaları henüz içe aktarılmadı: "Uygulamaları içe aktar" bu anahtarların gördüğü her şeyi listeler.',
'portfolio.notImported_one': '1 hesabın uygulamaları henüz içe aktarılmadı: "Uygulamaları içe aktar" anahtarının gördüğü her şeyi listeler.',
'portfolio.toolbar': 'Uygulamaları süz ve sırala',
'portfolio.search': 'Uygulama, bundle id, paket ara',
'portfolio.studioFilter': 'Stüdyo',
'portfolio.allStudios': 'Tüm stüdyolar',
'portfolio.sort': 'Sırala',
'portfolio.sortAttention': 'Dikkat isteyen',
'portfolio.sortRecent': 'Son güncellenen',
'portfolio.sortName': 'Ad',
'portfolio.group': 'Stüdyoya göre grupla',
'portfolio.groupCount': '{count} uygulama',
'portfolio.noConfig': 'Yapılandırma yok',
'portfolio.storeOnlyCheck': 'Yalnızca mağaza',
'portfolio.noMatch': 'Eşleşen uygulama yok',
'portfolio.noMatchText': 'Aramayı temizleyin ya da başka bir stüdyo seçin.',
'portfolio.studiosN': '{count} stüdyo',
'portfolio.studiosN_one': '1 stüdyo',
'portfolio.folders': 'Uygulama klasörleri',
'portfolio.foldersN': '{count} klasör · {store} yalnızca mağazada',
'portfolio.ignoredN': '{count} uygulama',
'portfolio.ignoredN_one': '1 uygulama',
'kpi.appsSubStore': 'iOS {ios} · Android {android} · {store} yalnızca mağazada',
'toast.importing': 'Uygulamalar içe aktarılıyor',
'toast.importingDetail': 'Her hesabın gördüğü tüm uygulamalar (salt okunur)',
'toast.importDone': 'Hesaplarınızda {count} uygulama',
'toast.importDone_one': 'Hesaplarınızda 1 uygulama',
'toast.importDoneDetail': '{count} hesaptan',
'toast.importDoneDetail_one': '1 hesaptan',
'toast.importPartial': '{count} hesap okunamadı',
'toast.importPartial_one': '1 hesap okunamadı',
'toast.saveFailed': 'Kaydedilmedi',
'notify.releaseTitle': '{name}: mağaza durumu değişti',
'notify.releaseBody': '{store} {version}: {phase}',
'notify.lowTitle': '{name}: {count} yeni düşük puan',
'notify.lowTitle_one': '{name}: yeni bir düşük puan',
'notify.crashTitle': '{name}: Play eşiğinin üstünde',
'set.lead': 'Stüdyolar, hesaplar, mağaza okumaları, çevrimdışı önbellek, dil, tema, bildirimler ve dahası. Hepsi bu bilgisayarda kalır.',
'set.sections': 'Ayar bölümleri',
'set.studios': 'Stüdyolar ve hesaplar',
'set.studiosSub': 'Hangi hesap hangi stüdyoya ait',
'set.studioLine': 'Play {play} · App Store {apple} · {apps} uygulama',
'set.noStudios': 'Henüz stüdyo yok. Stüdyolar hesapları ve uygulamalarını portföyde ve kenar çubuğunda gruplar.',
'set.manage': 'Yönet',
'set.pairing': 'Uygulama eşleştirme ve yok sayılanlar',
'set.pairingSub': 'Bir iOS ve bir Android uygulaması kimlikleri ya da adları eşleşince tek kart olur; burada elle eşleştirin ya da ayırın',
'set.pairedHow': 'Eşleştirme',
'set.noCandidates': 'Eşleştirilecek bir şey yok',
'set.noStoreOnly': 'Her uygulamanın klasörü var: eşleştirme yapılandırmalardan gelir.',
'set.ignoredLine': 'Yok sayılan: {count} uygulama, {accounts} hesap.',
'set.openIgnored': 'Listeyi aç',
'set.refresh': 'Mağaza okumaları',
'set.refreshSub': 'Okumalar her hesabın API kotasını kullanır: siz istediğinizde ya da buradaki zamanlamayla çalışır',
'set.autoRefresh': 'Mağazaları otomatik oku',
'set.autoHint': 'Uygulama açıkken. Varsayılan olarak kapalı.',
'set.off': 'Kapalı',
'set.min': '{n} dk',
'set.hour': '{n} sa',
'set.onLaunch': 'Uygulama açılınca oku',
'set.onLaunchHint': 'Her hesabın uygulamalarını içe aktarır, sonra her uygulamanın mağaza durumunu okur',
'set.icons': 'İçe aktarırken mağaza simgeleri',
'set.iconsHint': 'Uygulama başına bir ek istek; klasörler kendi simgelerini kullanır',
'set.parallel': 'Aynı anda okunan uygulama',
'set.parallelHint': 'Daha az, hız sınırlarına daha nazik',
'set.cache': 'Çevrimdışı önbellek',
'set.cacheSub': 'Son mağaza okumaları, çevrimdışıyken zamanlarıyla gösterilir',
'set.cacheSize': 'Diskte',
'set.cacheRows': '{count} kayıtlı okuma',
'set.cacheRows_one': '1 kayıtlı okuma',
'set.cacheOldest': 'En eski',
'set.keep': 'Kayıtlı okumaları sakla',
'set.days': '{n} gün',
'set.year': '1 yıl',
'set.always': 'Her zaman',
'set.notifications': 'Bildirimler',
'set.notificationsSub': 'Bir okumadan sonra, öncekinden beri bir şey değiştiyse',
'set.nReview': 'İnceleme ve yayın durumu değişiklikleri',
'set.nReviewHint': 'İncelemede, onaylandı, reddedildi, yayında, durduruldu',
'set.nLow': 'Yeni 1 ya da 2 yıldızlı yorumlar',
'set.nLowHint': 'Yorumlar sekmesi yenilerini okuduğunda',
'set.nCrash': 'Çökme ya da ANR oranı eşiğin üstünde',
'set.nCrashHint': 'Google Play kötü davranış eşikleri',
'set.testNotify': 'Deneme bildirimi gönder',
'set.testTitle': 'storebound',
'set.testBody': 'Bildirimler çalışıyor.',
'set.appCopy': 'uygulama kopyası',
'set.depsText': 'Mağaza işleri yerel araç gerektirmez. Ekran görüntüleri, önizlemeler ve simgeler ffmpeg ve Chrome kullanır: Bağımlılıklar ekranında tek tık.',
'set.cli': 'CLI yardımcısı',
'set.protocol': 'Protokol',
'set.state': 'Durum',
'set.running': 'Çalışıyor',
'set.writes': 'Yazmalar',
'set.writesText': 'Önce deneme, sonra sistem penceresinde sizin Uygula onayınız. Gönderme, yayınlama ve yayımlama konsollarda kalır.',
'set.privacy': 'Gizlilik',
'set.p1': 'Telemetri, analiz ya da çökme raporu yok: uygulama yalnızca siz istediğinizde, anahtarlarınızla mağazalarla konuşur.',
'set.p2': 'Mağaza anahtarları sistem anahtar zincirinde durur; uygulama veri klasöründe adlar, ayarlar ve kayıtlı okumalar vardır, anahtar asla.',
'set.p3': 'Siz bir sistem penceresinde onaylamadıkça uygulama klasörlerinize hiçbir şey yazılmaz.',
'set.p4': 'Test kullanıcısı e-postaları maskeli kalır; yorum taslakları her uygulama klasörünün .storebound/ klasöründe (gitignore) kalır.',
'set.reveal': 'Veri klasörünü göster',
'set.scQuit': 'Çık',
'set.updates': 'Güncellemeler',
'set.channel': 'Kanal',
'set.stable': 'Kararlı',
'set.beta': 'Beta',
'set.updatesText': 'storebound.dev\'den imzalı güncellemeler ilk herkese açık masaüstü sürümüyle gelir; kanal o zaman için saklanır.',
'set.reset': 'Sıfırla',
'set.resetText': '{accounts} hesabı (anahtarları anahtar zincirinden silinir), {studios} stüdyoyu, {folders} uygulama klasörünü (klasörler diskte kalır), eşleştirmeyi, yok sayılanları, ayarları ve kayıtlı okumaları unutur. Önce bir sistem penceresi sorar.',
'set.resetButton': 'Uygulamayı sıfırla',
'set.resetDone': 'storebound masaüstü sıfırlandı',
'set.footer': 'Bu bilgisayarın bildiği {n} uygulama',
'studio.counts_one': '1 hesap · {apps} uygulama · {store} yalnızca mağazada',
'portfolio.groupCount_one': '1 uygulama',
'portfolio.groupAccounts': '{count} hesap',
'portfolio.groupAccounts_one': '1 hesap',
}; };

View file

@ -0,0 +1,225 @@
// One app card per product, across studios and store accounts. Pure, so tests/identity.test.ts pins every rule.
//
// Inputs: app folders (with the store ids of their config), the apps each store account can see (`apps list`), and
// the owner's overrides (manual pairs / unpairs, links of a store app to a folder, studio moves, the ignore list).
// Order of matching:
// 1. a folder takes the store apps its config names (explicit link > App Store app id > bundle id / package name),
// preferring the accounts mapped to the folder;
// 2. the remaining store apps pair iOS + Android: manual pairs, then the same bundle id and package name, then a
// close id (".ios" / ".android" suffixes, case, punctuation) or the same name; unpairs block an automatic pair;
// 3. what is left is a single-platform store-only app.
// A store-only app is read through a "store target" (store:ios:<account>:<app id>:<bundle>;android:<account>:<package>).
import type { Account, AppStatus, Project, StoreApp } from '../api';
export interface Pair { ios: string; android: string }
export interface Overrides {
pairs: Pair[];
unpairs: Pair[];
links: { key: string; project: string }[];
appStudio: { key: string; studio: string }[];
ignored: string[];
}
export const NO_OVERRIDES: Overrides = { pairs: [], unpairs: [], links: [], appStudio: [], ignored: [] };
/** One app record of one store account. */
export interface StoreRef { key: string; account: string; store: 'ios' | 'android'; app: StoreApp }
export type Pairing = 'folder' | 'manual' | 'id' | 'close' | 'name' | 'single';
export interface UnifiedApp {
/** Route and list key: the project id, else the store target. */
key: string;
/** What reads use: the project id, else the store target ("store:..."). */
target: string;
name: string;
project: Project | null;
ios: StoreRef | null;
android: StoreRef | null;
studio: string | null;
pairing: Pairing;
/** The keys an "ignore" puts on the list ("project:<id>" or "app:<store key>"). */
ignoreKeys: string[];
ignored: boolean;
/** Store icon (data URL) when the folder has none. */
storeIcon: string | null;
}
export const refKey = (account: string, a: StoreApp): string => `${a.store}:${account}:${a.id}`;
/** Store target of a store-only app. */
export function storeTarget(ios: StoreRef | null, android: StoreRef | null): string {
const parts: string[] = [];
if (ios) parts.push(`ios:${ios.account}:${ios.app.id}:${ios.app.bundleId}`);
if (android) parts.push(`android:${android.account}:${android.app.id}`);
return `store:${parts.join(';')}`;
}
/** "com.example.Puzzle.ios" -> "comexamplepuzzle": ids that differ only by a platform suffix, case or punctuation. */
export function normId(id: string): string {
return id.toLowerCase().replace(/[._-](ios|iphone|android|droid|app)$/g, '').replace(/[^a-z0-9]/g, '');
}
export const normName = (n: string): string => n.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]/g, '');
const samePair = (p: Pair, ios: string, android: string) => p.ios === ios && p.android === android;
export interface BuildInput {
projects: Project[];
/** Store ids of each folder's config (from the offline portfolio read). */
summaryOf: (p: Project) => AppStatus['summary'] | undefined;
accounts: Account[];
/** The last app list of each account. */
storeApps: { account: string; apps: StoreApp[] }[];
overrides: Overrides;
}
export function buildApps(i: BuildInput): UnifiedApp[] {
const o = i.overrides;
const ignoredAccounts = new Set(o.ignored.filter(x => x.startsWith('account:')).map(x => x.slice(8)));
const accountStudio = new Map(i.accounts.map(a => [a.id, a.studio ?? null] as const));
const known = new Set(i.accounts.map(a => a.id));
// every store app of every (not ignored) account
const refs: StoreRef[] = [];
for (const s of i.storeApps) {
if (!known.has(s.account) || ignoredAccounts.has(s.account)) continue;
for (const app of s.apps) refs.push({ key: refKey(s.account, app), account: s.account, store: app.store, app });
}
const used = new Set<string>();
const take = (r: StoreRef | null | undefined): StoreRef | null => { if (!r || used.has(r.key)) return null; used.add(r.key); return r; };
const studioOverride = new Map(o.appStudio.map(x => [x.key, x.studio] as const));
const ignored = new Set(o.ignored);
const out: UnifiedApp[] = [];
// 1. folders
for (const p of i.projects) {
const s = i.summaryOf(p);
const mine = (r: StoreRef) => r.account === (r.store === 'ios' ? p.appleAccount : p.playAccount);
const rank = (rs: StoreRef[]) => [...rs].sort((a, b) => Number(mine(b)) - Number(mine(a)));
const linked = o.links.filter(l => l.project === p.id).map(l => refs.find(r => r.key === l.key)).filter((r): r is StoreRef => !!r && !used.has(r.key));
let ios = take(linked.find(r => r.store === 'ios'));
let android = take(linked.find(r => r.store === 'android'));
if (!ios && s?.apple) {
const free = refs.filter(r => r.store === 'ios' && !used.has(r.key) && !o.links.some(l => l.key === r.key));
ios = take(rank(free.filter(r => s.apple!.appId && r.app.id === s.apple!.appId))[0] ?? rank(free.filter(r => r.app.bundleId === s.apple!.bundleId))[0]);
}
if (!android && s?.play) {
const free = refs.filter(r => r.store === 'android' && !used.has(r.key) && !o.links.some(l => l.key === r.key));
android = take(rank(free.filter(r => r.app.id === s.play!.packageName))[0]);
}
const studio = studioOverride.get(`project:${p.id}`)
?? (p.appleAccount && accountStudio.get(p.appleAccount)) ?? (p.playAccount && accountStudio.get(p.playAccount))
?? (ios && accountStudio.get(ios.account)) ?? (android && accountStudio.get(android.account)) ?? null;
out.push({
key: p.id, target: p.id, name: p.name, project: p, ios, android, studio, pairing: 'folder',
ignoreKeys: [`project:${p.id}`], ignored: ignored.has(`project:${p.id}`), storeIcon: ios?.app.icon ?? android?.app.icon ?? null,
});
}
// 2. pairs among the remaining store apps
const freeIos = () => refs.filter(r => r.store === 'ios' && !used.has(r.key));
const freeAndroid = () => refs.filter(r => r.store === 'android' && !used.has(r.key));
const blocked = (a: StoreRef, b: StoreRef) => o.unpairs.some(p => samePair(p, a.key, b.key));
const sameStudio = (a: StoreRef, b: StoreRef) => (accountStudio.get(a.account) ?? null) === (accountStudio.get(b.account) ?? null);
const pairs: [StoreRef, StoreRef, Pairing][] = [];
for (const m of o.pairs) {
const a = freeIos().find(r => r.key === m.ios), b = freeAndroid().find(r => r.key === m.android);
if (a && b) { take(a); take(b); pairs.push([a, b, 'manual']); }
}
const auto = (how: Pairing, match: (a: StoreRef, b: StoreRef) => boolean) => {
for (const a of freeIos()) {
const cands = freeAndroid().filter(b => !blocked(a, b) && match(a, b)).sort((x, y) => Number(sameStudio(a, y)) - Number(sameStudio(a, x)));
const b = cands[0];
if (b) { take(a); take(b); pairs.push([a, b, how]); }
}
};
auto('id', (a, b) => a.app.bundleId === b.app.id);
auto('close', (a, b) => normId(a.app.bundleId) !== '' && normId(a.app.bundleId) === normId(b.app.id));
auto('name', (a, b) => normName(a.app.name) !== '' && normName(a.app.name) === normName(b.app.name));
const storeOnly = (ios: StoreRef | null, android: StoreRef | null, pairing: Pairing) => {
const target = storeTarget(ios, android);
const keys = [ios, android].filter((r): r is StoreRef => !!r).map(r => r.key);
const studio = keys.map(k => studioOverride.get(k)).find(Boolean)
?? (ios && accountStudio.get(ios.account)) ?? (android && accountStudio.get(android.account)) ?? null;
out.push({
key: target, target, name: ios?.app.name ?? android?.app.name ?? '?', project: null, ios, android, studio, pairing,
ignoreKeys: keys.map(k => `app:${k}`), ignored: keys.some(k => ignored.has(`app:${k}`)), storeIcon: ios?.app.icon ?? android?.app.icon ?? null,
});
};
for (const [a, b, how] of pairs) storeOnly(a, b, how);
// 3. singles
for (const r of refs) if (!used.has(r.key)) { used.add(r.key); storeOnly(r.store === 'ios' ? r : null, r.store === 'android' ? r : null, 'single'); }
return out;
}
/** Candidates to pair a single-platform app with (the other store's single apps), closest first. */
export function pairCandidates(app: UnifiedApp, all: UnifiedApp[]): UnifiedApp[] {
if (app.project || (app.ios && app.android)) return [];
const want = app.ios ? 'android' : 'ios';
const me = (app.ios ?? app.android)!;
const score = (x: UnifiedApp) => {
const r = (want === 'ios' ? x.ios : x.android)!;
return (normId(r.app.bundleId) === normId(me.app.bundleId) ? 4 : 0) + (normName(r.app.name) === normName(me.app.name) ? 2 : 0) + (x.studio === app.studio ? 1 : 0);
};
return all.filter(x => !x.project && !x.ignored && (want === 'ios' ? x.ios && !x.android : x.android && !x.ios)).sort((a, b) => score(b) - score(a) || a.name.localeCompare(b.name));
}
/** Overrides after pairing two single store apps by hand (drops an unpair of the same two). */
export function withPair(o: Overrides, ios: string, android: string): Overrides {
return { ...o, pairs: [...o.pairs.filter(p => p.ios !== ios && p.android !== android), { ios, android }], unpairs: o.unpairs.filter(p => !samePair(p, ios, android)) };
}
/** Overrides after splitting a paired app (keeps it apart from now on). */
export function withUnpair(o: Overrides, ios: string, android: string): Overrides {
return { ...o, pairs: o.pairs.filter(p => !samePair(p, ios, android)), unpairs: [...o.unpairs.filter(p => !samePair(p, ios, android)), { ios, android }] };
}
export function withIgnored(o: Overrides, keys: string[], on: boolean): Overrides {
const set = new Set(o.ignored);
for (const k of keys) { if (on) set.add(k); else set.delete(k); }
return { ...o, ignored: [...set] };
}
/** Moves an app to a studio (null: back to its accounts' studio). */
export function withStudio(o: Overrides, app: UnifiedApp, studio: string | null): Overrides {
const keys = app.project ? [`project:${app.project.id}`] : [app.ios?.key, app.android?.key].filter((k): k is string => !!k);
const rest = o.appStudio.filter(x => !keys.includes(x.key));
return { ...o, appStudio: studio ? [...rest, ...keys.map(key => ({ key, studio }))] : rest };
}
/** Links the store apps of a store-only app to a folder. */
export function withLink(o: Overrides, app: UnifiedApp, project: string): Overrides {
const keys = [app.ios?.key, app.android?.key].filter((k): k is string => !!k);
return { ...o, links: [...o.links.filter(l => !keys.includes(l.key)), ...keys.map(key => ({ key, project }))] };
}
// ---- Portfolio list: filter, search, sort, group ----
export type SortBy = 'attention' | 'recent' | 'name';
export interface ListRow { app: UnifiedApp; attention: number; blockers: number; updated: string | null }
export function filterSort(rows: ListRow[], o: { studio: string | 'all' | 'none'; query: string; sort: SortBy }): ListRow[] {
const q = o.query.trim().toLowerCase();
const hit = (r: ListRow) => !q || [r.app.name, r.app.ios?.app.bundleId, r.app.android?.app.id, r.app.project?.path.split(/[\\/]/).pop()]
.some(s => s && s.toLowerCase().includes(q));
const inStudio = (r: ListRow) => o.studio === 'all' || (o.studio === 'none' ? !r.app.studio : r.app.studio === o.studio);
const by = {
attention: (a: ListRow, b: ListRow) => b.blockers - a.blockers || b.attention - a.attention || a.app.name.localeCompare(b.app.name),
recent: (a: ListRow, b: ListRow) => (b.updated ?? '').localeCompare(a.updated ?? '') || a.app.name.localeCompare(b.app.name),
name: (a: ListRow, b: ListRow) => a.app.name.localeCompare(b.app.name),
}[o.sort];
return rows.filter(r => !r.app.ignored && inStudio(r) && hit(r)).sort(by);
}
/** Groups by studio in the studios' order, apps without a studio last. */
export function groupByStudio<T extends { app: UnifiedApp }>(rows: T[], studios: { id: string }[]): { studio: string | null; rows: T[] }[] {
const order = [...studios.map(s => s.id as string | null), null];
const known = new Set(studios.map(s => s.id));
return order.map(id => ({ studio: id, rows: rows.filter(r => (id === null ? !r.app.studio || !known.has(r.app.studio) : r.app.studio === id)) })).filter(g => g.rows.length);
}
/** Per studio: visible apps (not ignored). */
export function studioCounts(apps: UnifiedApp[]): Record<string, number> {
const m: Record<string, number> = {};
for (const a of apps) if (!a.ignored) m[a.studio ?? ''] = (m[a.studio ?? ''] ?? 0) + 1;
return m;
}

View file

@ -0,0 +1,41 @@
// What deserves a desktop notification after a read (Settings > Notifications). Pure: compares the previous read with
// the new one and never fires on a first read (nothing to compare with = no flood).
import type { PortfolioResult } from '../api';
import { healthSeries, type HealthSnapshot, isError, PLAY_THRESHOLDS, type Review } from './model';
export interface ReleaseChange { project: string; name: string; store: 'ios' | 'android'; version: string; from: string; to: string }
/** Phase changes of the same version on the same store that the owner waits for: review in / out, approved, rejected, live, halted. */
export function releaseChanges(prev: PortfolioResult | null | undefined, next: PortfolioResult): ReleaseChange[] {
if (!prev) return [];
const WATCH = new Set(['review', 'approved', 'rejected', 'live', 'halted']);
const out: ReleaseChange[] = [];
for (const a of next.apps) {
const before = prev.apps.find(p => p.project === a.project);
if (!before || before.release.source !== 'live' || a.release.source !== 'live') continue;
for (const r of a.release.all ?? []) {
if (!r.version) continue;
const old = (before.release.all ?? []).find(x => x.store === r.store && x.version === r.version);
if (!old || old.phase === r.phase) continue;
if (WATCH.has(r.phase) || WATCH.has(old.phase)) out.push({ project: a.project, name: a.app?.name ?? a.project, store: r.store, version: r.version, from: old.phase, to: r.phase });
}
}
return out;
}
/** New 1-2 star reviews since the previous read. */
export function newLowReviews(prev: Review[] | null | undefined, next: Review[]): Review[] {
if (!prev) return [];
const seen = new Set(prev.map(r => `${r.store}:${r.id}`));
return next.filter(r => r.rating <= 2 && !seen.has(`${r.store}:${r.id}`));
}
/** Crash or ANR rate that went over the Play bad behavior threshold since the previous read. */
export function crashCrossed(prev: HealthSnapshot | null | undefined, next: HealthSnapshot): ('crash' | 'anr')[] {
if (!prev?.play || isError(prev.play) || !next.play || isError(next.play)) return [];
const out: ('crash' | 'anr')[] = [];
const was = { crash: healthSeries(prev.play.crash, 'userPerceivedCrashRate', PLAY_THRESHOLDS.crash), anr: healthSeries(prev.play.anr, 'userPerceivedAnrRate', PLAY_THRESHOLDS.anr) };
const now = { crash: healthSeries(next.play.crash, 'userPerceivedCrashRate', PLAY_THRESHOLDS.crash), anr: healthSeries(next.play.anr, 'userPerceivedAnrRate', PLAY_THRESHOLDS.anr) };
for (const k of ['crash', 'anr'] as const) if (now[k].tone === 'bad' && was[k].tone !== 'bad') out.push(k);
return out;
}

View file

@ -1,25 +1,30 @@
// Routes: Portfolio -> one App (tabs) plus the workspace screens. Pure, so tests can check the deep links. // Routes: Portfolio -> one App (tabs) plus the workspace screens. Pure, so tests can check the deep links.
// An app is keyed by its project id, or (store-only apps, no folder) by its store target ("store:...").
import { createContext, useContext } from 'react'; import { createContext, useContext } from 'react';
import type { Key } from './i18n'; import type { Key } from './i18n';
import type { IconName } from './ui/icons'; import type { IconName } from './ui/icons';
export const APP_TABS = ['releases', 'catalog', 'listings', 'health', 'reviews', 'testflight', 'checks'] as const; export const APP_TABS = ['releases', 'catalog', 'listings', 'health', 'reviews', 'testflight', 'checks'] as const;
export type AppTab = (typeof APP_TABS)[number]; export type AppTab = (typeof APP_TABS)[number];
/** Tabs of a store-only app: store reads only (catalog, listings and checks need the app folder). */
export const STORE_TABS: readonly AppTab[] = ['releases', 'health', 'reviews', 'testflight'];
export const tabsFor = (hasFolder: boolean): readonly AppTab[] => (hasFolder ? APP_TABS : STORE_TABS);
export const TAB_KEY: Record<AppTab, Key> = { releases: 'tab.releases', catalog: 'tab.catalog', listings: 'tab.listings', health: 'tab.health', reviews: 'tab.reviews', testflight: 'tab.testflight', checks: 'tab.checks' }; export const TAB_KEY: Record<AppTab, Key> = { releases: 'tab.releases', catalog: 'tab.catalog', listings: 'tab.listings', health: 'tab.health', reviews: 'tab.reviews', testflight: 'tab.testflight', checks: 'tab.checks' };
export const TAB_ICON: Record<AppTab, IconName> = { releases: 'rocket', catalog: 'tag', listings: 'text', health: 'activity', reviews: 'message', testflight: 'plane', checks: 'shield' }; export const TAB_ICON: Record<AppTab, IconName> = { releases: 'rocket', catalog: 'tag', listings: 'text', health: 'activity', reviews: 'message', testflight: 'plane', checks: 'shield' };
export const WORKSPACE = ['apps', 'accounts', 'dependencies', 'settings'] as const; export const WORKSPACE = ['apps', 'accounts', 'ignored', 'dependencies', 'settings'] as const;
export type WorkspaceScreen = (typeof WORKSPACE)[number]; export type WorkspaceScreen = (typeof WORKSPACE)[number];
export type Route = { screen: 'portfolio' } | { screen: 'app'; appId: string; tab: AppTab } | { screen: WorkspaceScreen }; export type Route = { screen: 'portfolio' } | { screen: 'app'; appId: string; tab: AppTab } | { screen: WorkspaceScreen; section?: string };
/** storebound://<screen> deep links and the dev-only start switch ("app:health" = first app, Health tab; /** storebound://<screen> deep links and the dev-only start switch ("app:health" = first app, Health tab;
* "app:health:2" = second app). `apps` are the project ids in list order. */ * "app:health:2" = second app; "settings:refresh" = a Settings section). `apps` are the app keys in list order. */
export function parseStart(v: string, apps: string[]): Route | null { export function parseStart(v: string, apps: string[]): Route | null {
const [screen, tab, n] = v.split(':'); const [screen, tab, n] = v.split(':');
const app = apps[Math.max(0, (Number(n) || 1) - 1)]; const app = apps[Math.max(0, (Number(n) || 1) - 1)];
if (screen === 'app' && app) return { screen: 'app', appId: app, tab: APP_TABS.includes(tab as AppTab) ? tab as AppTab : 'releases' }; if (screen === 'app' && app) return { screen: 'app', appId: app, tab: APP_TABS.includes(tab as AppTab) ? tab as AppTab : 'releases' };
if (screen === 'portfolio') return { screen: 'portfolio' }; if (screen === 'portfolio') return { screen: 'portfolio' };
return (WORKSPACE as readonly string[]).includes(screen ?? '') ? { screen: screen as WorkspaceScreen } : null; if (!(WORKSPACE as readonly string[]).includes(screen ?? '')) return null;
return tab ? { screen: screen as WorkspaceScreen, section: tab } : { screen: screen as WorkspaceScreen };
} }
export const sameRoute = (a: Route, b: Route): boolean => JSON.stringify(a) === JSON.stringify(b); export const sameRoute = (a: Route, b: Route): boolean => JSON.stringify(a) === JSON.stringify(b);

View file

@ -1,88 +1,227 @@
// Store accounts: the keys live in the system keychain; the app keeps a label only and hands a key to storebound in // Studios & accounts: studios (name, colour, logo) group store accounts; each account is a Google Play service account
// memory for one call. // (one JSON key; it can be invited to several Play developer accounts) or an App Store Connect team key (key id,
import { useState } from 'react'; // issuer id, .p8). Keys live in the system keychain; the app keeps a label and the studio only. Per account: a health
import { type Account, api, errorText } from '../api'; // check (key works / permission missing / revoked, with the fix) and "Import apps" (every app the key can see).
import { t } from '../i18n'; import { type FormEvent, useEffect, useState } from 'react';
import { date } from '../lib/format'; import { type Account, type AccountCheck, api, errorText, STUDIO_COLORS, type Studio, type StudioColor } from '../api';
import { useData } from '../store'; import { type Key, t } from '../i18n';
import { ago } from '../lib/format';
import { withIgnored } from '../lib/identity';
import { type AccountHealth, useData } from '../store';
import { Icon, StoreGlyph } from '../ui/icons'; import { Icon, StoreGlyph } from '../ui/icons';
import { Card, Chip, Empty, Notice } from '../ui/kit'; import { Card, Chip, Empty, Notice, StudioMark } from '../ui/kit';
import type { Tone } from '../lib/model';
export function Accounts() { const STATUS: Record<AccountCheck['status'], [Tone, Key]> = {
ok: ['ok', 'acct.ok'], 'no-apps': ['warn', 'acct.noApps'], permission: ['warn', 'acct.permission'], revoked: ['bad', 'acct.revoked'], 'api-disabled': ['warn', 'acct.apiDisabled'], error: ['bad', 'acct.error'],
};
export function HealthChip({ h }: { h: AccountHealth | undefined }) {
if (!h) return <Chip tone="neutral">{t('acct.notTested')}</Chip>;
if (h.error || !h.check) return <span title={h.error}><Chip tone="bad">{t('acct.error')}</Chip></span>;
const [tone, key] = STATUS[h.check.status];
return <span title={h.check.message}><Chip tone={tone}>{t(key)}</Chip></span>;
}
function Swatches({ value, onChange, name }: { value: StudioColor; onChange: (c: StudioColor) => void; name: string }) {
return (
<div className="swatches" role="radiogroup" aria-label={t('studio.color')}>
{STUDIO_COLORS.map(c => (
<button key={c} type="button" role="radio" aria-checked={value === c} className={`swatch studio-${c}`} onClick={() => onChange(c)} aria-label={t(`color.${c}` as Key)} title={t(`color.${c}` as Key)}>
{value === c && <Icon name="check" />}
</button>
))}
<span className="sr">{name}</span>
</div>
);
}
function AccountRow({ a, busy, setBusy, onError }: { a: Account; busy: string | null; setBusy: (b: string | null) => void; onError: (e: string | null) => void }) {
const d = useData();
const [edit, setEdit] = useState(false);
const [label, setLabel] = useState(a.label);
const [studio, setStudio] = useState(a.studio ?? '');
const h = d.accountHealth[a.id];
const list = d.storeApps[a.id];
const ignored = d.overrides.ignored.includes(`account:${a.id}`);
const used = d.projects.filter(p => p.playAccount === a.id || p.appleAccount === a.id).length;
const run = async (key: string, fn: () => Promise<unknown>) => {
setBusy(key); onError(null);
try { await fn(); } catch (e) { onError(errorText(e)); } finally { setBusy(null); }
};
const save = (e: FormEvent) => { e.preventDefault(); run(`ed-${a.id}`, async () => { await api.updateAccount(a.id, label, studio || null); await d.reload(); setEdit(false); }); };
const check = h?.check;
return (
<div className={`acct${ignored ? ' is-ignored' : ''}`}>
<div className="acct-row">
<span className={`acct-glyph ${a.kind}`}><StoreGlyph store={a.kind === 'play' ? 'android' : 'ios'} /></span>
<div className="acct-main">
<div className="row" style={{ gap: 8 }}><span className="strong">{a.label}</span><HealthChip h={h} />{ignored && <Chip tone="neutral" icon="eyeOff">{t('acct.ignored')}</Chip>}</div>
<div className="small muted">
{a.kind === 'play' ? t('acct.kindPlay') : t('acct.kindApple')}
{' · '}{list ? t('acct.appsRead', { count: list.value.apps.length, when: ago(list.at) }) : t('acct.notImported')}
{used ? ` · ${t('acct.folders', { count: used })}` : ''}
{check?.principal ? <> · <span className="mono-id selectable">{check.principal}</span></> : null}
</div>
</div>
<div className="actions">
<button className="btn btn-sm" onClick={() => run(`ck-${a.id}`, () => d.checkAccount(a.id))} disabled={!!busy}><Icon name="shield" className={busy === `ck-${a.id}` ? 'spin' : undefined} />{t('acct.test')}</button>
<button className="btn btn-sm" onClick={() => run(`im-${a.id}`, () => d.importApps(a.id))} disabled={!!busy || d.importBusy}><Icon name="download" />{t('acct.import')}</button>
<button className="btn btn-sm btn-ghost btn-icon" onClick={() => setEdit(x => !x)} aria-expanded={edit} aria-label={t('acct.editAria', { label: a.label })} title={t('acct.edit')}><Icon name="edit" /></button>
<button className="btn btn-sm btn-ghost btn-icon" onClick={() => d.updateOverrides(o => withIgnored(o, [`account:${a.id}`], !ignored))} aria-label={ignored ? t('acct.unignore') : t('acct.ignore')} title={ignored ? t('acct.unignore') : t('acct.ignoreHint')}><Icon name={ignored ? 'eye' : 'eyeOff'} /></button>
<button className="btn btn-sm btn-ghost btn-icon btn-danger" disabled={!!busy} onClick={() => run(`rm-${a.id}`, async () => { await api.removeAccount(a.id); await d.reload(); })} aria-label={t('accounts.removeAria', { label: a.label })} title={t('accounts.remove')}><Icon name="trash" /></button>
</div>
</div>
{edit && (
<form className="acct-edit" onSubmit={save}>
<div className="field"><label htmlFor={`al-${a.id}`}>{t('accounts.label')}</label><input id={`al-${a.id}`} className="input" value={label} onChange={e => setLabel(e.target.value)} maxLength={60} /></div>
<div className="field"><label htmlFor={`as-${a.id}`}>{t('studio.studio')}</label>
<select id={`as-${a.id}`} className="input" value={studio} onChange={e => setStudio(e.target.value)}>
<option value="">{t('studio.none')}</option>
{d.studios.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
</select></div>
<div className="actions"><button className="btn btn-primary btn-sm" type="submit" disabled={!label.trim() || !!busy}><Icon name="check" />{t('common.save')}</button><button type="button" className="btn btn-sm btn-ghost" onClick={() => setEdit(false)}>{t('common.cancel')}</button></div>
</form>
)}
{check && check.status !== 'ok' && check.fix && (
<div className="acct-fix">
<Notice tone={check.status === 'revoked' ? 'bad' : 'warn'} action={check.docs ? <button className="btn btn-sm" onClick={() => api.openExternal(check.docs!).catch(e => onError(errorText(e)))}><Icon name="external" />{t('acct.openFix')}</button> : undefined}>
<b>{check.message}</b><br />{check.fix}
</Notice>
</div>
)}
{h?.error && <div className="acct-fix"><Notice tone="bad">{h.error}</Notice></div>}
</div>
);
}
function StudioCard({ s, accounts, focus }: { s: Studio | null; accounts: Account[]; focus: boolean }) {
const d = useData();
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [edit, setEdit] = useState(false);
const [name, setName] = useState(s?.name ?? '');
const [color, setColor] = useState<StudioColor>(s?.color ?? 'indigo');
const apps = d.apps.filter(a => !a.ignored && (a.studio ?? null) === (s?.id ?? null));
const storeOnly = apps.filter(a => !a.project).length;
const act = async (key: string, fn: () => Promise<unknown>) => { setBusy(key); setError(null); try { await fn(); await d.reload(); } catch (e) { setError(errorText(e)); } finally { setBusy(null); } };
const id = s ? `studio-${s.id}` : 'studio-none';
useEffect(() => { if (focus) document.getElementById(id)?.scrollIntoView({ block: 'start' }); }, [focus, id]);
return (
<section className={`card studio-card${focus ? ' focus' : ''}`} id={id} aria-labelledby={`${id}-h`}>
<div className="card-head">
<div className="row" style={{ gap: 12, minWidth: 0 }}>
<StudioMark studio={s} size="lg" />
<div className="stack" style={{ gap: 2, minWidth: 0 }}>
<h2 id={`${id}-h`}>{s?.name ?? t('studio.none')}</h2>
<div className="sub">{s ? t('studio.counts', { count: accounts.length, apps: apps.length, store: storeOnly }) : t('studio.noneSub')}</div>
</div>
</div>
{s && (
<div className="actions">
<button className="btn btn-sm btn-ghost" onClick={() => setEdit(x => !x)} aria-expanded={edit}><Icon name="edit" />{t('studio.edit')}</button>
<button className="btn btn-sm btn-ghost" onClick={() => act('logo', () => api.studioLogo(s.id))} disabled={!!busy}><Icon name="image" />{t('studio.logo')}</button>
{s.logo && <button className="btn btn-sm btn-ghost" onClick={() => act('logo', () => api.studioLogo(s.id, true))} disabled={!!busy}>{t('studio.logoClear')}</button>}
<button className="btn btn-sm btn-ghost btn-danger" onClick={() => act('rm', () => api.removeStudio(s.id))} disabled={!!busy} title={t('studio.removeHint')}><Icon name="trash" />{t('studio.remove')}</button>
</div>
)}
</div>
{s && edit && (
<form className="card-body studio-edit" onSubmit={e => { e.preventDefault(); act('save', async () => { await api.saveStudio(s.id, name, color); setEdit(false); }); }}>
<div className="field"><label htmlFor={`${id}-n`}>{t('studio.name')}</label><input id={`${id}-n`} className="input" value={name} onChange={e => setName(e.target.value)} maxLength={48} /></div>
<div className="field"><span className="legend">{t('studio.color')}</span><Swatches value={color} onChange={setColor} name={name} /></div>
<div className="actions"><button className="btn btn-primary btn-sm" type="submit" disabled={!name.trim() || !!busy}><Icon name="check" />{t('common.save')}</button></div>
</form>
)}
{error && <div className="card-body"><Notice tone="bad">{error}</Notice></div>}
{accounts.length ? <div className="acct-list">{accounts.map(a => <AccountRow key={a.id} a={a} busy={busy} setBusy={setBusy} onError={setError} />)}</div>
: <div className="card-body"><p className="small muted">{s ? t('studio.noAccounts') : t('studio.allAssigned')}</p></div>}
</section>
);
}
export function Accounts({ focus }: { focus?: string }) {
const d = useData(); const d = useData();
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState<string | null>(null); const [busy, setBusy] = useState<string | null>(null);
const [studioName, setStudioName] = useState('');
const [studioColor, setStudioColor] = useState<StudioColor>('indigo');
const [playLabel, setPlayLabel] = useState(''); const [playLabel, setPlayLabel] = useState('');
const [playStudio, setPlayStudio] = useState('');
const [appleLabel, setAppleLabel] = useState(''); const [appleLabel, setAppleLabel] = useState('');
const [appleStudio, setAppleStudio] = useState('');
const [keyId, setKeyId] = useState(''); const [keyId, setKeyId] = useState('');
const [issuerId, setIssuerId] = useState(''); const [issuerId, setIssuerId] = useState('');
const act = async (key: string, fn: () => Promise<Account | null | void>) => { const act = async (key: string, fn: () => Promise<Account | Studio | null | void>, ok?: (r: Account | Studio) => string) => {
setBusy(key); setError(null); setBusy(key); setError(null);
try { try {
const r = await fn(); const r = await fn();
if (r) d.toast({ kind: 'ok', title: t('accounts.saved', { label: r.label }), detail: t('accounts.savedDetail') }); if (r && ok) d.toast({ kind: 'ok', title: ok(r), detail: 'kind' in r ? t('accounts.savedDetail') : undefined });
await d.reload(); await d.reload();
return r;
} catch (e) { setError(errorText(e)); } finally { setBusy(null); } } catch (e) { setError(errorText(e)); } finally { setBusy(null); }
}; };
const addPlay = () => act('play', async () => { const a = await api.addPlayAccount(playLabel); if (a) setPlayLabel(''); return a; }); const addStudio = () => act('studio', async () => { const s = await api.saveStudio(null, studioName, studioColor); setStudioName(''); return s; }, r => t('studio.added', { name: (r as Studio).name }));
const addApple = () => act('apple', async () => { const a = await api.addAppleAccount(appleLabel, keyId, issuerId); if (a) { setAppleLabel(''); setKeyId(''); setIssuerId(''); } return a; }); const addPlay = () => act('play', async () => { const a = await api.addPlayAccount(playLabel, playStudio || null); if (a) setPlayLabel(''); return a; }, r => t('accounts.saved', { label: (r as Account).label }));
const used = (a: Account) => d.projects.filter(p => p.playAccount === a.id || p.appleAccount === a.id).map(p => p.name); const addApple = () => act('apple', async () => { const a = await api.addAppleAccount(appleLabel, keyId, issuerId, appleStudio || null); if (a) { setAppleLabel(''); setKeyId(''); setIssuerId(''); } return a; }, r => t('accounts.saved', { label: (r as Account).label }));
const testAll = async () => { setBusy('all'); await Promise.all(d.accounts.map(a => d.checkAccount(a.id))); setBusy(null); };
const unassigned = d.accounts.filter(a => !a.studio || !d.studios.some(s => s.id === a.studio));
const studioSelect = (id: string, value: string, set: (v: string) => void) => (
<div className="field"><label htmlFor={id}>{t('studio.studio')}</label>
<select id={id} className="input" value={value} onChange={e => set(e.target.value)}>
<option value="">{t('studio.none')}</option>
{d.studios.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
</select></div>
);
return ( return (
<div className="page"> <div className="page">
<div className="ph"><div><h1>{t('nav.accounts')}</h1><p>{t('accounts.lead')}</p></div></div> <div className="ph">
<div><h1>{t('nav.accounts')}</h1><p>{t('accounts.leadStudios')}</p></div>
<div className="actions">
<button className="btn" onClick={testAll} disabled={!!busy || !d.accounts.length}><Icon name="shield" className={busy === 'all' ? 'spin' : undefined} />{t('acct.testAll')}</button>
<button className="btn btn-primary" onClick={() => d.importApps()} disabled={d.importBusy || !d.accounts.length}><Icon name="download" className={d.importBusy ? 'spin' : undefined} />{t('action.importApps')}</button>
</div>
</div>
{error && <Notice tone="bad">{error}</Notice>} {error && <Notice tone="bad">{error}</Notice>}
<Card title={t('accounts.list')} icon="key" sub={t('accounts.listSub')} pad={false}> {!d.accounts.length && !d.studios.length && <Card pad={false}><Empty illo="key" title={t('accounts.emptyTitle')}>{t('accounts.emptyTextStudios')}</Empty></Card>}
{!d.accounts.length ? <Empty illo="key" title={t('accounts.emptyTitle')}>{t('accounts.emptyText')}</Empty> : ( {d.studios.map(s => <StudioCard key={s.id} s={s} accounts={d.accounts.filter(a => a.studio === s.id)} focus={focus === s.id} />)}
<table className="table"> {(unassigned.length > 0 || !d.studios.length) && d.accounts.length > 0 && <StudioCard s={null} accounts={unassigned} focus={focus === 'none'} />}
<thead><tr><th>{t('col.name')}</th><th>{t('col.store')}</th><th>{t('col.usedBy')}</th><th>{t('col.added')}</th><th><span className="sr">{t('col.actions')}</span></th></tr></thead>
<tbody> <div className="grid g3" style={{ alignItems: 'start' }}>
{d.accounts.map(a => ( <Card title={t('studio.new')} icon="building" sub={t('studio.newSub')}>
<tr key={a.id}> <form className="form" onSubmit={e => { e.preventDefault(); addStudio(); }}>
<td className="strong">{a.label}</td> <div className="field"><label htmlFor="studio-name">{t('studio.name')}</label><input id="studio-name" className="input" value={studioName} onChange={e => setStudioName(e.target.value)} maxLength={48} placeholder={t('studio.namePlaceholder')} autoComplete="off" /></div>
<td><span className="row" style={{ gap: 8 }}><StoreGlyph store={a.kind === 'play' ? 'android' : 'ios'} className="ic14" />{a.kind === 'play' ? 'Google Play' : 'App Store Connect'}</span></td> <div className="field"><span className="legend">{t('studio.color')}</span><Swatches value={studioColor} onChange={setStudioColor} name={studioName} /></div>
<td>{used(a).length ? used(a).join(', ') : <Chip tone="neutral">{t('accounts.unused')}</Chip>}</td> <div><button className="btn btn-primary" type="submit" disabled={!studioName.trim() || !!busy}><Icon name="plus" />{t('studio.add')}</button></div>
<td className="muted">{date(a.created)}</td> </form>
<td className="right"><button className="btn btn-sm btn-ghost btn-danger" disabled={!!busy} onClick={() => act(`rm-${a.id}`, () => api.removeAccount(a.id))} aria-label={t('accounts.removeAria', { label: a.label })}><Icon name="trash" />{t('accounts.remove')}</button></td> </Card>
</tr> <Card title="Google Play" icon="key" sub={t('accounts.playSubMany')}>
))}
</tbody>
</table>
)}
</Card>
<div className="grid g2">
<Card title="Google Play" icon="key" sub={t('accounts.playSub')}>
<form className="form" onSubmit={e => { e.preventDefault(); addPlay(); }}> <form className="form" onSubmit={e => { e.preventDefault(); addPlay(); }}>
<div className="field"> <div className="field"><label htmlFor="play-label">{t('accounts.label')}</label>
<label htmlFor="play-label">{t('accounts.label')}</label> <input id="play-label" className="input" type="text" value={playLabel} onChange={e => setPlayLabel(e.target.value)} placeholder={t('accounts.playPlaceholder')} maxLength={60} autoComplete="off" /></div>
<input id="play-label" className="input" type="text" value={playLabel} onChange={e => setPlayLabel(e.target.value)} placeholder={t('accounts.playPlaceholder')} maxLength={60} autoComplete="off" /> {studioSelect('play-studio', playStudio, setPlayStudio)}
</div>
<p className="small muted">{t('accounts.playHow')}</p> <p className="small muted">{t('accounts.playHow')}</p>
<div><button className="btn btn-primary" type="submit" disabled={!playLabel.trim() || !!busy}><Icon name="key" />{t('accounts.choosePlay')}</button></div> <div><button className="btn btn-primary" type="submit" disabled={!playLabel.trim() || !!busy}><Icon name="key" />{t('accounts.choosePlay')}</button></div>
</form> </form>
</Card> </Card>
<Card title="App Store Connect" icon="key" sub={t('accounts.appleSub')}> <Card title="App Store Connect" icon="key" sub={t('accounts.appleSubMany')}>
<form className="form" onSubmit={e => { e.preventDefault(); addApple(); }}> <form className="form" onSubmit={e => { e.preventDefault(); addApple(); }}>
<div className="field"> <div className="field"><label htmlFor="apple-label">{t('accounts.label')}</label>
<label htmlFor="apple-label">{t('accounts.label')}</label> <input id="apple-label" className="input" type="text" value={appleLabel} onChange={e => setAppleLabel(e.target.value)} placeholder={t('accounts.applePlaceholder')} maxLength={60} autoComplete="off" /></div>
<input id="apple-label" className="input" type="text" value={appleLabel} onChange={e => setAppleLabel(e.target.value)} placeholder={t('accounts.applePlaceholder')} maxLength={60} autoComplete="off" /> {studioSelect('apple-studio', appleStudio, setAppleStudio)}
</div>
<div className="grid g2" style={{ gap: 12 }}> <div className="grid g2" style={{ gap: 12 }}>
<div className="field"> <div className="field"><label htmlFor="key-id">{t('accounts.keyId')}</label>
<label htmlFor="key-id">{t('accounts.keyId')}</label> <input id="key-id" className="input mono" type="text" value={keyId} onChange={e => setKeyId(e.target.value.toUpperCase())} placeholder="ABC123DEFG" maxLength={10} autoComplete="off" spellCheck={false} /></div>
<input id="key-id" className="input mono" type="text" value={keyId} onChange={e => setKeyId(e.target.value.toUpperCase())} placeholder="ABC123DEFG" maxLength={10} autoComplete="off" spellCheck={false} /> <div className="field"><label htmlFor="issuer-id">{t('accounts.issuerId')}</label>
</div> <input id="issuer-id" className="input mono" type="text" value={issuerId} onChange={e => setIssuerId(e.target.value)} placeholder="UUID" maxLength={36} autoComplete="off" spellCheck={false} /></div>
<div className="field">
<label htmlFor="issuer-id">{t('accounts.issuerId')}</label>
<input id="issuer-id" className="input mono" type="text" value={issuerId} onChange={e => setIssuerId(e.target.value)} placeholder="UUID" maxLength={36} autoComplete="off" spellCheck={false} />
</div>
</div> </div>
<div><button className="btn btn-primary" type="submit" disabled={!appleLabel.trim() || keyId.length !== 10 || issuerId.length < 36 || !!busy}><Icon name="key" />{t('accounts.chooseApple')}</button></div> <div><button className="btn btn-primary" type="submit" disabled={!appleLabel.trim() || keyId.length !== 10 || issuerId.length < 36 || !!busy}><Icon name="key" />{t('accounts.chooseApple')}</button></div>
</form> </form>
</Card> </Card>
</div> </div>
<Notice tone="info" icon="shield">{t('accounts.safety')}</Notice> <Notice tone="info" icon="shield">{t('accounts.safetyStudios')}</Notice>
</div> </div>
); );
} }

View file

@ -1,12 +1,15 @@
// One app across both stores: header (icon, ids, store state), then the tabs. // One app across both stores: header (icon, studio, ids, store state, pairing), then the tabs. A store-only app (no
import { type KeyboardEvent, useRef } from 'react'; // app folder) shows its store reads (releases, health, reviews, TestFlight) read-only, with "Link a folder" and
import { api, type Project } from '../api'; // "Start an app folder here" to make it a full app.
import { t } from '../i18n'; import { type KeyboardEvent, useRef, useState } from 'react';
import { APP_TABS, type AppTab, TAB_ICON, TAB_KEY, useNav } from '../nav'; import { api, errorText } from '../api';
import { type Key, t } from '../i18n';
import { pairCandidates, type UnifiedApp, withIgnored, withLink, withPair, withStudio, withUnpair } from '../lib/identity';
import { storeNow } from '../lib/model'; import { storeNow } from '../lib/model';
import { type AppTab, TAB_ICON, TAB_KEY, tabsFor, useNav } from '../nav';
import { useData } from '../store'; import { useData } from '../store';
import { Icon } from '../ui/icons'; import { Icon } from '../ui/icons';
import { AppIcon, Chip, PhaseChip, StoreBadge } from '../ui/kit'; import { AppIcon, Chip, Notice, PhaseChip, StoreBadge, StoreOnlyTag, StudioMark } from '../ui/kit';
import { CatalogTab } from './tabs/Catalog'; import { CatalogTab } from './tabs/Catalog';
import { ChecksTab } from './tabs/Checks'; import { ChecksTab } from './tabs/Checks';
import { HealthTab } from './tabs/Health'; import { HealthTab } from './tabs/Health';
@ -18,23 +21,88 @@ import { TestFlightTab } from './tabs/TestFlight';
export const ascUrl = (appId: string | null | undefined): string => (appId ? `https://appstoreconnect.apple.com/apps/${encodeURIComponent(appId)}/distribution` : 'https://appstoreconnect.apple.com/apps'); export const ascUrl = (appId: string | null | undefined): string => (appId ? `https://appstoreconnect.apple.com/apps/${encodeURIComponent(appId)}/distribution` : 'https://appstoreconnect.apple.com/apps');
export const PLAY_CONSOLE = 'https://play.google.com/console/'; export const PLAY_CONSOLE = 'https://play.google.com/console/';
export function AppView({ project, tab }: { project: Project; tab: AppTab }) { const PAIRING: Record<UnifiedApp['pairing'], Key> = { folder: 'pair.folder', manual: 'pair.manual', id: 'pair.id', close: 'pair.close', name: 'pair.name', single: 'pair.single' };
/** Pairing, studio and ignore controls of one app. */
function AppControls({ app }: { app: UnifiedApp }) {
const d = useData(); const d = useData();
const nav = useNav(); const nav = useNav();
const e = d.statusOf(project); const cands = pairCandidates(app, d.apps);
const l = d.liveOf(project); const canUnpair = !app.project && !!app.ios && !!app.android;
const ios = e?.app?.platforms.ios, android = e?.app?.platforms.android; return (
const name = e?.app?.name ?? project.name; <div className="app-controls">
const tabs = useRef<(HTMLButtonElement | null)[]>([]); <span className="small muted row" style={{ gap: 6 }}><Icon name="link" className="ic13" />{t(PAIRING[app.pairing])}</span>
const setTab = (x: AppTab) => nav.go({ screen: 'app', appId: project.id, tab: x }); <label className="row small" style={{ gap: 6 }}><span className="muted">{t('studio.studio')}</span>
<select className="input input-sm" value={app.studio ?? ''} onChange={e => d.updateOverrides(o => withStudio(o, app, e.target.value || null))} aria-label={t('app.moveStudio')}>
<option value="">{t('studio.none')}</option>
{d.studios.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
</select></label>
{cands.length > 0 && (
<label className="row small" style={{ gap: 6 }}><span className="muted">{t('app.pairWith')}</span>
<select className="input input-sm" value="" onChange={e => {
const other = cands.find(c => c.key === e.target.value);
if (!other) return;
const ios = (app.ios ?? other.ios)!.key, android = (app.android ?? other.android)!.key;
d.updateOverrides(o => withPair(o, ios, android)).then(() => nav.go({ screen: 'portfolio' }));
}} aria-label={t('app.pairWith')}>
<option value="">{t('app.pick')}</option>
{cands.slice(0, 30).map(c => <option key={c.key} value={c.key}>{c.name} · {(c.ios ?? c.android)!.app.bundleId}</option>)}
</select></label>
)}
{canUnpair && <button className="btn btn-sm btn-ghost" onClick={() => d.updateOverrides(o => withUnpair(o, app.ios!.key, app.android!.key)).then(() => nav.go({ screen: 'portfolio' }))}><Icon name="unlink" />{t('app.unpair')}</button>}
<button className="btn btn-sm btn-ghost" onClick={() => d.updateOverrides(o => withIgnored(o, app.ignoreKeys, true)).then(() => nav.go({ screen: 'portfolio' }))} title={t('app.ignoreHint')}><Icon name="eyeOff" />{t('app.ignore')}</button>
</div>
);
}
function StoreOnlyBanner({ app }: { app: UnifiedApp }) {
const d = useData();
const [busy, setBusy] = useState(false);
const [profile, setProfile] = useState<'app' | 'game' | 'subscription-app'>('app');
const link = async (init: boolean) => {
setBusy(true);
try {
const p = init ? await api.initProject(profile) : await api.addProject();
if (p) {
await d.updateOverrides(o => withLink(o, app, p.id));
await d.reload();
d.toast({ kind: 'ok', title: t('app.linked', { name: p.name }), detail: init ? t('folders.startedDetail') : undefined });
}
} catch (e) { d.toast({ kind: 'bad', title: t('app.linkFailed'), detail: errorText(e) }); } finally { setBusy(false); }
};
return (
<Notice tone="info" icon="cloud" action={<div className="actions">
<button className="btn btn-sm btn-primary" onClick={() => link(false)} disabled={busy}><Icon name="link" />{t('app.linkFolder')}</button>
<select className="input input-sm" value={profile} onChange={e => setProfile(e.target.value as typeof profile)} aria-label={t('folders.profile')}>
<option value="app">{t('profile.app')}</option><option value="game">{t('profile.game')}</option><option value="subscription-app">{t('profile.subscription-app')}</option>
</select>
<button className="btn btn-sm" onClick={() => link(true)} disabled={busy}><Icon name="folderPlus" />{t('app.initHere')}</button>
</div>}>
<b>{t('app.storeOnlyTitle')}</b> {t('app.storeOnlyText')}
</Notice>
);
}
export function AppView({ app, tab }: { app: UnifiedApp; tab: AppTab }) {
const d = useData();
const nav = useNav();
const e = d.statusFor(app);
const l = d.liveFor(app);
const ios = e?.app?.platforms.ios ?? (app.ios ? { bundleId: app.ios.app.bundleId, ascAppId: app.ios.app.id } : null);
const android = e?.app?.platforms.android ?? (app.android ? { packageName: app.android.app.id } : null);
const name = (app.project && e?.app?.name) || app.name;
const tabs = tabsFor(!!app.project);
const tabRefs = useRef<(HTMLButtonElement | null)[]>([]);
const studio = d.studios.find(s => s.id === app.studio) ?? null;
const setTab = (x: AppTab) => nav.go({ screen: 'app', appId: app.key, tab: x });
const onKey = (ev: KeyboardEvent) => { const onKey = (ev: KeyboardEvent) => {
const i = APP_TABS.indexOf(tab); const i = tabs.indexOf(tab);
const j = ev.key === 'ArrowRight' ? i + 1 : ev.key === 'ArrowLeft' ? i - 1 : ev.key === 'Home' ? 0 : ev.key === 'End' ? APP_TABS.length - 1 : null; const j = ev.key === 'ArrowRight' ? i + 1 : ev.key === 'ArrowLeft' ? i - 1 : ev.key === 'Home' ? 0 : ev.key === 'End' ? tabs.length - 1 : null;
if (j === null) return; if (j === null) return;
ev.preventDefault(); ev.preventDefault();
const n = (j + APP_TABS.length) % APP_TABS.length; const n = (j + tabs.length) % tabs.length;
setTab(APP_TABS[n]!); setTab(tabs[n]!);
tabs.current[n]?.focus(); tabRefs.current[n]?.focus();
}; };
const all = l?.release.all ?? []; const all = l?.release.all ?? [];
const iosNow = l ? storeNow(all, 'ios').now : null, androidNow = l ? storeNow(all, 'android').now : null; const iosNow = l ? storeNow(all, 'ios').now : null, androidNow = l ? storeNow(all, 'android').now : null;
@ -44,15 +112,17 @@ export function AppView({ project, tab }: { project: Project; tab: AppTab }) {
<div className="page"> <div className="page">
<div className="ph"> <div className="ph">
<div className="app-head"> <div className="app-head">
<AppIcon name={name} src={d.icons[project.id]} /> <AppIcon name={name} src={d.iconFor(app)} />
<div> <div>
<div className="row" style={{ gap: 10 }}> <div className="row" style={{ gap: 10 }}>
<h1>{name}</h1> <h1>{name}</h1>
{e?.summary?.profile && <Chip tone="outline">{t(`profile.${e.summary.profile}` as 'profile.app')}</Chip>} {e?.summary?.profile && app.project && <Chip tone="outline">{t(`profile.${e.summary.profile}` as 'profile.app')}</Chip>}
{!app.project && <StoreOnlyTag />}
<button className="studio-pill" onClick={() => nav.go({ screen: 'accounts', section: app.studio ?? 'none' })} title={t('app.studioHint')}><StudioMark studio={studio} size="sm" />{studio?.name ?? t('studio.none')}</button>
</div> </div>
<div className="ids"> <div className="ids">
<StoreBadge store="ios" id={ios?.bundleId} off={!!e && !ios}>{iosNow && <><span className="num strong">{iosNow.version}</span><PhaseChip r={iosNow} /></>}</StoreBadge> <StoreBadge store="ios" id={ios?.bundleId} off={!ios && (!!e || !app.project)}>{iosNow && <><span className="num strong">{iosNow.version}</span><PhaseChip r={iosNow} /></>}</StoreBadge>
<StoreBadge store="android" id={android?.packageName} off={!!e && !android}>{androidNow && <><span className="num strong">{androidNow.version}</span><PhaseChip r={androidNow} /></>}</StoreBadge> <StoreBadge store="android" id={android?.packageName} off={!android && (!!e || !app.project)}>{androidNow && <><span className="num strong">{androidNow.version}</span><PhaseChip r={androidNow} /></>}</StoreBadge>
</div> </div>
</div> </div>
</div> </div>
@ -61,22 +131,24 @@ export function AppView({ project, tab }: { project: Project; tab: AppTab }) {
{android && <button className="btn btn-ghost" onClick={() => open(PLAY_CONSOLE)} title={t('app.consoleHint')}><Icon name="external" />Play Console</button>} {android && <button className="btn btn-ghost" onClick={() => open(PLAY_CONSOLE)} title={t('app.consoleHint')}><Icon name="external" />Play Console</button>}
</div> </div>
</div> </div>
<AppControls app={app} />
{!app.project && <StoreOnlyBanner app={app} />}
<div className="tabs" role="tablist" aria-label={t('app.sections', { name })} onKeyDown={onKey}> <div className="tabs" role="tablist" aria-label={t('app.sections', { name })} onKeyDown={onKey}>
{APP_TABS.map((x, i) => ( {tabs.map((x, i) => (
<button key={x} ref={el => { tabs.current[i] = el; }} role="tab" id={`tab-${x}`} aria-selected={tab === x} aria-controls="tabpanel" tabIndex={tab === x ? 0 : -1} className="tab" onClick={() => setTab(x)}> <button key={x} ref={el => { tabRefs.current[i] = el; }} role="tab" id={`tab-${x}`} aria-selected={tab === x} aria-controls="tabpanel" tabIndex={tab === x ? 0 : -1} className="tab" onClick={() => setTab(x)}>
<Icon name={TAB_ICON[x]} />{t(TAB_KEY[x])} <Icon name={TAB_ICON[x]} />{t(TAB_KEY[x])}
</button> </button>
))} ))}
</div> </div>
<div role="tabpanel" id="tabpanel" aria-labelledby={`tab-${tab}`} className="stack" style={{ gap: 16 }}> <div role="tabpanel" id="tabpanel" aria-labelledby={`tab-${tab}`} className="stack" style={{ gap: 16 }}>
{tab === 'releases' && <ReleasesTab project={project} />} {tab === 'releases' && <ReleasesTab app={app} />}
{tab === 'catalog' && <CatalogTab project={project} />} {tab === 'catalog' && app.project && <CatalogTab project={app.project} />}
{tab === 'listings' && <ListingsTab project={project} />} {tab === 'listings' && app.project && <ListingsTab project={app.project} />}
{tab === 'health' && <HealthTab project={project} />} {tab === 'health' && <HealthTab app={app} />}
{tab === 'reviews' && <ReviewsTab project={project} />} {tab === 'reviews' && <ReviewsTab app={app} />}
{tab === 'testflight' && <TestFlightTab project={project} />} {tab === 'testflight' && <TestFlightTab app={app} />}
{tab === 'checks' && <ChecksTab project={project} />} {tab === 'checks' && app.project && <ChecksTab project={app.project} />}
</div> </div>
</div> </div>
); );

View file

@ -0,0 +1,66 @@
// Ignored: apps and whole store accounts left out of the portfolio, the sidebar and store reads. Restore brings them
// back (nothing on the stores changes either way).
import { t } from '../i18n';
import { withIgnored } from '../lib/identity';
import { useNav } from '../nav';
import { useData } from '../store';
import { Icon, StoreGlyph } from '../ui/icons';
import { AppIcon, Card, Empty, StoreOnlyTag, StudioMark } from '../ui/kit';
export function Ignored() {
const d = useData();
const nav = useNav();
const apps = d.apps.filter(a => a.ignored).sort((a, b) => a.name.localeCompare(b.name));
const accounts = d.accounts.filter(a => d.overrides.ignored.includes(`account:${a.id}`));
const restoreAll = () => d.updateOverrides(o => ({ ...o, ignored: [] }));
const empty = !apps.length && !accounts.length;
return (
<div className="page">
<div className="ph">
<div><h1>{t('nav.ignored')}</h1><p>{t('ignored.lead')}</p></div>
{!empty && <div className="actions"><button className="btn" onClick={restoreAll}><Icon name="eye" />{t('ignored.restoreAll')}</button></div>}
</div>
{empty ? <Card pad={false}><Empty compact illo="shield" title={t('ignored.emptyTitle')}>{t('ignored.emptyText')}</Empty></Card> : (
<>
<Card title={t('ignored.apps')} icon="layers" sub={t('ignored.appsSub', { count: apps.length })} pad={false}>
{apps.length ? (
<div className="list">
{apps.map(a => {
const s = d.studios.find(x => x.id === a.studio) ?? null;
return (
<div className="li" key={a.key}>
<AppIcon name={a.name} src={d.iconFor(a)} />
<div className="li-main">
<span className="li-title row" style={{ gap: 8 }}>{a.name}{!a.project && <StoreOnlyTag />}</span>
<span className="li-sub row" style={{ gap: 8 }}>
<StudioMark studio={s} size="sm" />{s?.name ?? t('studio.none')}
{a.ios && <span className="row" style={{ gap: 4 }}><StoreGlyph store="ios" className="ic13" /><span className="mono-id">{a.ios.app.bundleId}</span></span>}
{a.android && <span className="row" style={{ gap: 4 }}><StoreGlyph store="android" className="ic13" /><span className="mono-id">{a.android.app.id}</span></span>}
</span>
</div>
<button className="btn btn-sm" onClick={() => d.updateOverrides(o => withIgnored(o, a.ignoreKeys, false))}><Icon name="eye" />{t('ignored.restore')}</button>
</div>
);
})}
</div>
) : <div className="card-body"><p className="small muted">{t('ignored.noApps')}</p></div>}
</Card>
<Card title={t('ignored.accounts')} icon="key" sub={t('ignored.accountsSub')} pad={false}>
{accounts.length ? (
<div className="list">
{accounts.map(a => (
<div className="li" key={a.id}>
<span className="li-icon tone-bg-neutral"><StoreGlyph store={a.kind === 'play' ? 'android' : 'ios'} /></span>
<div className="li-main"><span className="li-title">{a.label}</span><span className="li-sub">{a.kind === 'play' ? t('acct.kindPlay') : t('acct.kindApple')} · {t('ignored.accountApps', { count: d.storeApps[a.id]?.value.apps.length ?? 0 })}</span></div>
<button className="btn btn-sm" onClick={() => d.updateOverrides(o => withIgnored(o, [`account:${a.id}`], false))}><Icon name="eye" />{t('ignored.restore')}</button>
</div>
))}
</div>
) : <div className="card-body"><p className="small muted">{t('ignored.noAccounts')}</p></div>}
</Card>
</>
)}
<p className="small muted">{t('ignored.howTo')} <button className="link" onClick={() => nav.go({ screen: 'settings', section: 'pairing' })}>{t('ignored.toPairing')}</button></p>
</div>
);
}

View file

@ -1,14 +1,16 @@
// Portfolio: every app on both stores. KPIs, one row per app (live version and state per store with its place on // Portfolio: every app of every studio on both stores. KPIs, a toolbar (search, studio chips with counts, sort,
// the release track, next version, catalog parity, config check), what needs attention, and the workspace state. // grouping), one row per app (live version and state per store with its place on the release track, next version,
import { useEffect, useState } from 'react'; // crash rate, catalog parity, config check), grouped by studio; then what needs attention and the workspace state.
import { api, type AppStatus, type Project, type StoreRelease, type ToolResult } from '../api'; import { useEffect, useMemo, useState } from 'react';
import { api, type AppStatus, type StoreRelease, type ToolResult } from '../api';
import { type Key, t } from '../i18n'; import { type Key, t } from '../i18n';
import { ago, pct, share } from '../lib/format'; import { ago, pct, share } from '../lib/format';
import { filterSort, groupByStudio, type ListRow, type SortBy, studioCounts, type UnifiedApp } from '../lib/identity';
import { type Attention, attention, healthSeries, type HealthSnapshot, isError, laneOf, PLAY_THRESHOLDS, STAGES, storeNow, type Tone } from '../lib/model'; import { type Attention, attention, healthSeries, type HealthSnapshot, isError, laneOf, PLAY_THRESHOLDS, STAGES, storeNow, type Tone } from '../lib/model';
import { useNav } from '../nav'; import { useNav } from '../nav';
import { useData } from '../store'; import { useData } from '../store';
import { Icon, StoreGlyph } from '../ui/icons'; import { Icon, StoreGlyph } from '../ui/icons';
import { AppIcon, Card, Chip, Empty, Kpi, Notice, PhaseChip, Skeleton, Sparkline } from '../ui/kit'; import { AppIcon, Card, Chip, Empty, Kpi, Notice, PhaseChip, Seg, Skeleton, Sparkline, StudioMark } from '../ui/kit';
/** Tag of one app's offline config check. */ /** Tag of one app's offline config check. */
export function checkState(e: Pick<AppStatus, 'errors' | 'check'> | undefined): { text: string; tone: Tone } { export function checkState(e: Pick<AppStatus, 'errors' | 'check'> | undefined): { text: string; tone: Tone } {
@ -29,9 +31,8 @@ export function Pips({ r, store }: { r: StoreRelease | null; store: 'ios' | 'and
); );
} }
function StoreCell({ e, store, project }: { e: AppStatus | undefined; store: 'ios' | 'android'; project: AppStatus | undefined }) { function StoreCell({ e, store, on }: { e: AppStatus | undefined; store: 'ios' | 'android'; on: boolean }) {
const on = store === 'ios' ? project?.app?.platforms.ios : project?.app?.platforms.android; if (!on) return <span className="muted small">{t('app.notOnStore')}</span>;
if (project && !on) return <span className="muted small">{t('app.notOnStore')}</span>;
if (!e) return <span className="muted small">{t('common.unknown')}</span>; if (!e) return <span className="muted small">{t('common.unknown')}</span>;
const err = e.storeErrors[store]; const err = e.storeErrors[store];
if (err) return <span title={err}><Chip tone="warn">{t('portfolio.unreadable')}</Chip></span>; if (err) return <span title={err}><Chip tone="warn">{t('portfolio.unreadable')}</Chip></span>;
@ -64,18 +65,19 @@ function NextCell({ e }: { e: AppStatus | undefined }) {
} }
/** Last cached health read of every app (the Health tab reads it; the portfolio only shows what is saved). */ /** Last cached health read of every app (the Health tab reads it; the portfolio only shows what is saved). */
function useCachedHealth(projects: Project[]): Record<string, { h: HealthSnapshot; at: string } | null> { function useCachedHealth(targets: string[]): Record<string, { h: HealthSnapshot; at: string } | null> {
const [m, set] = useState<Record<string, { h: HealthSnapshot; at: string } | null>>({}); const [m, set] = useState<Record<string, { h: HealthSnapshot; at: string } | null>>({});
const key = projects.map(p => p.id).join(); const key = targets.join();
useEffect(() => { useEffect(() => {
for (const p of projects) { for (const id of targets) {
api.cached<ToolResult>('health', p.id).then(c => set(x => ({ ...x, [p.id]: c?.value.data ? { h: c.value.data as HealthSnapshot, at: c.at } : null })), () => {}); api.cached<ToolResult>('health', id).then(c => set(x => ({ ...x, [id]: c?.value.data ? { h: c.value.data as HealthSnapshot, at: c.at } : null })), () => {});
} }
}, [key]); // eslint-disable-line react-hooks/exhaustive-deps }, [key]); // eslint-disable-line react-hooks/exhaustive-deps
return m; return m;
} }
function HealthCell({ c }: { c: { h: HealthSnapshot; at: string } | null | undefined }) { function HealthCell({ c, android }: { c: { h: HealthSnapshot; at: string } | null | undefined; android: boolean }) {
if (!android) return <span className="muted small">{t('portfolio.healthNoPlay')}</span>;
if (!c) return <span className="muted small">{t('portfolio.healthNotRead')}</span>; if (!c) return <span className="muted small">{t('portfolio.healthNotRead')}</span>;
const play = c.h.play; const play = c.h.play;
if (!play) return <span className="muted small">{t('portfolio.healthNoPlay')}</span>; if (!play) return <span className="muted small">{t('portfolio.healthNoPlay')}</span>;
@ -105,44 +107,110 @@ function AttentionList({ items }: { items: Attention[] }) {
); );
} }
/** Newest store activity of an app (release record date), else when its folder was added. */
function updatedAt(a: UnifiedApp, l: AppStatus | undefined): string | null {
const dates = (l?.release.all ?? []).map(r => r.date).filter((x): x is string => !!x);
return dates.sort().at(-1) ?? a.project?.added ?? null;
}
const VIEW_KEY = 'storebound.portfolio.v1';
interface View { studio: string; sort: SortBy; group: boolean }
function loadView(): View {
try {
const v = JSON.parse(localStorage.getItem(VIEW_KEY) ?? '{}') as Partial<View>;
return { studio: typeof v.studio === 'string' ? v.studio : 'all', sort: v.sort === 'recent' || v.sort === 'name' ? v.sort : 'attention', group: v.group !== false };
} catch { return { studio: 'all', sort: 'attention', group: true }; }
}
export function Portfolio() { export function Portfolio() {
const d = useData(); const d = useData();
const nav = useNav(); const nav = useNav();
const open = (p: Project) => nav.go({ screen: 'app', appId: p.id, tab: 'releases' }); const [view, setViewState] = useState<View>(loadView);
const [query, setQuery] = useState('');
const setView = (v: Partial<View>) => setViewState(x => { const n = { ...x, ...v }; try { localStorage.setItem(VIEW_KEY, JSON.stringify(n)); } catch { /* private mode */ } return n; });
const visible = useMemo(() => d.apps.filter(a => !a.ignored), [d.apps]);
const health = useCachedHealth(visible.map(a => a.target));
const open = (a: UnifiedApp) => nav.go({ screen: 'app', appId: a.key, tab: 'releases' });
if (d.ready && !d.projects.length) { const all = useMemo(() => visible.map(app => {
const e = d.statusFor(app), l = d.liveFor(app);
const att = attention(app.key, app.name, e, l, health[app.target]?.h);
return { app, e, l, att, attention: att.length, blockers: att.filter(x => x.tone === 'bad').length, updated: updatedAt(app, l) };
}), [visible, d, health]);
const counts = useMemo(() => studioCounts(visible), [visible]);
const studioOk = view.studio === 'all' || view.studio === 'none' || d.studios.some(s => s.id === view.studio);
const rows = filterSort(all as (ListRow & typeof all[number])[], { studio: studioOk ? view.studio : 'all', query, sort: view.sort }) as typeof all;
const grouped = view.group && d.studios.length ? groupByStudio(rows, d.studios) : [{ studio: undefined as string | null | undefined, rows }];
if (d.ready && !visible.length) {
return ( return (
<div className="page"> <div className="page">
<div className="ph"><div><h1>{t('nav.portfolio')}</h1><p>{t('portfolio.lead')}</p></div></div> <div className="ph"><div><h1>{t('nav.portfolio')}</h1><p>{t('portfolio.lead')}</p></div></div>
<Card pad={false}> <Card pad={false}>
<Empty illo="apps" title={t('portfolio.emptyTitle')} actions={<> <Empty illo="apps" title={t('portfolio.emptyTitle')} actions={<>
<button className="btn btn-primary" onClick={() => nav.go({ screen: 'apps' })}><Icon name="folderPlus" />{t('action.addFolder')}</button> <button className="btn btn-primary" onClick={() => nav.go({ screen: 'accounts' })}><Icon name="building" />{t('portfolio.emptyAccounts')}</button>
<button className="btn" onClick={nav.openWelcome}><Icon name="sparkle" />{t('action.welcome')}</button> <button className="btn" onClick={() => nav.go({ screen: 'apps' })}><Icon name="folderPlus" />{t('action.addFolder')}</button>
<button className="btn btn-ghost" onClick={nav.openWelcome}><Icon name="sparkle" />{t('action.welcome')}</button>
</>}>{t('portfolio.emptyText')}</Empty> </>}>{t('portfolio.emptyText')}</Empty>
</Card> </Card>
</div> </div>
); );
} }
const health = useCachedHealth(d.projects); const shown = rows.map(r => r.l).filter((x): x is AppStatus => !!x);
const rows = d.projects.map(p => ({ p, e: d.statusOf(p), l: d.liveOf(p) })); const releases = shown.flatMap(l => l.release.all ?? [l.release.current?.ios, l.release.current?.android, l.release.next?.ios, l.release.next?.android].filter((x): x is StoreRelease => !!x));
const lives = rows.map(r => r.l).filter((x): x is AppStatus => !!x); const stores = rows.reduce((n, r) => n + (r.app.ios || r.e?.app?.platforms.ios ? 1 : 0) + (r.app.android || r.e?.app?.platforms.android ? 1 : 0), 0);
const all = lives.flatMap(l => l.release.all ?? [l.release.current?.ios, l.release.current?.android, l.release.next?.ios, l.release.next?.android].filter((x): x is StoreRelease => !!x)); const liveCount = shown.reduce((n, l) => n + (l.release.current?.ios ? 1 : 0) + (l.release.current?.android ? 1 : 0), 0);
const stores = rows.reduce((n, r) => n + (r.e?.app?.platforms.ios ? 1 : 0) + (r.e?.app?.platforms.android ? 1 : 0), 0); const rolling = releases.filter(r => r.phase === 'rollout');
const liveCount = lives.reduce((n, l) => n + (l.release.current?.ios ? 1 : 0) + (l.release.current?.android ? 1 : 0), 0); const review = releases.filter(r => r.phase === 'review');
const rolling = all.filter(r => r.phase === 'rollout'); const att = rows.flatMap(r => r.att);
const review = all.filter(r => r.phase === 'review');
const att = rows.flatMap(r => attention(r.p.id, r.e?.app?.name ?? r.p.name, r.e, r.l, health[r.p.id]?.h));
const blockers = att.filter(a => a.tone === 'bad').length; const blockers = att.filter(a => a.tone === 'bad').length;
const known = lives.length > 0; const known = shown.length > 0;
const iosApps = rows.filter(r => r.e?.app?.platforms.ios).length, androidApps = rows.filter(r => r.e?.app?.platforms.android).length; const iosApps = rows.filter(r => r.app.ios || r.e?.app?.platforms.ios).length, androidApps = rows.filter(r => r.app.android || r.e?.app?.platforms.android).length;
const storeOnly = rows.filter(r => !r.app.project).length;
const neverImported = d.accounts.filter(a => !d.storeApps[a.id]).length;
const row = (r: typeof all[number]) => {
const { app, e, l } = r;
const st = app.project ? checkState(e) : null;
const cat = l?.catalog ?? e?.catalog;
const ios = !!(app.ios || e?.app?.platforms.ios), android = !!(app.android || e?.app?.platforms.android);
const sub = app.ios?.app.bundleId ?? e?.app?.platforms.ios?.bundleId ?? app.android?.app.id ?? e?.app?.platforms.android?.packageName ?? '';
return (
<tr key={app.key} className="clickable" onClick={() => open(app)}>
<td>
<div className="cell-app">
<AppIcon name={app.name} src={d.iconFor(app)} />
<div className="t">
<button className="link n" onClick={ev => { ev.stopPropagation(); open(app); }}>{e?.app?.name && app.project ? e.app.name : app.name}</button>
<div className="s"><span className="mono-id">{sub}</span>{!app.project && <span className="so-inline" title={t('apps.storeOnlyHint')}><Icon name="cloud" /><span className="sr">{t('apps.storeOnly')}</span></span>}</div>
</div>
</div>
</td>
<td>{e || !app.project ? <StoreCell e={l} store="ios" on={ios} /> : <Skeleton lines={2} />}</td>
<td>{e || !app.project ? <StoreCell e={l} store="android" on={android} /> : <Skeleton lines={2} />}</td>
<td><NextCell e={l} /></td>
<td><HealthCell c={health[app.target]} android={android} /></td>
<td>
{!app.project ? <span className="small muted">{t('portfolio.noConfig')}</span> : cat ? (
<div className="mini">
<span className="num small strong">{t('portfolio.products', { count: cat.products })} · {t('portfolio.subs', { count: cat.subscriptions })}</span>
{cat.checked === 'live' ? (cat.ok ? <Chip tone="ok">{t('portfolio.inParity')}</Chip> : <Chip tone="warn">{t('portfolio.differs', { count: cat.missingIos.length + cat.missingAndroid.length + cat.onlyIos.length + cat.onlyAndroid.length })}</Chip>)
: <span className="small muted">{t('portfolio.configOnly')}</span>}
</div>
) : <span className="muted small">–</span>}
</td>
<td className="right">{st ? <Chip tone={st.tone}>{st.text}</Chip> : <span className="muted small">–</span>}</td>
</tr>
);
};
return ( return (
<div className="page"> <div className="page">
<div className="ph"> <div className="ph">
<div><h1>{t('nav.portfolio')}</h1><p>{t('portfolio.sub', { count: d.projects.length, stores })}</p></div> <div><h1>{t('nav.portfolio')}</h1><p>{t('portfolio.subStudios', { count: visible.length, stores, studios: d.studios.length })}</p></div>
<div className="actions"> <div className="actions">
<button className="btn" onClick={() => d.refreshPortfolio(false)} disabled={!!d.portfolioBusy}><Icon name="shield" />{t('action.checkConfigs')}</button> <button className="btn" onClick={() => d.importApps()} disabled={d.importBusy || !d.accounts.length} title={t('action.importAppsHint')}><Icon name="download" className={d.importBusy ? 'spin' : undefined} />{t('action.importApps')}</button>
<button className="btn btn-primary" onClick={() => d.refreshPortfolio(true)} disabled={!!d.portfolioBusy} title={t('action.readStoresHint')}> <button className="btn btn-primary" onClick={() => d.refreshPortfolio(true)} disabled={!!d.portfolioBusy} title={t('action.readStoresHint')}>
<Icon name="refresh" className={d.portfolioBusy === 'live' ? 'spin' : undefined} />{d.portfolioBusy === 'live' ? t('action.reading') : t('action.readStores')} <Icon name="refresh" className={d.portfolioBusy === 'live' ? 'spin' : undefined} />{d.portfolioBusy === 'live' ? t('action.reading') : t('action.readStores')}
</button> </button>
@ -150,67 +218,66 @@ export function Portfolio() {
</div> </div>
{d.portfolioError && <Notice tone="bad">{d.portfolioError}</Notice>} {d.portfolioError && <Notice tone="bad">{d.portfolioError}</Notice>}
{neverImported > 0 && <Notice tone="info" icon="download" action={<button className="btn btn-sm" onClick={() => d.importApps()} disabled={d.importBusy}>{t('action.importApps')}</button>}>{t('portfolio.notImported', { count: neverImported })}</Notice>}
{!known && d.ready && <Notice tone="info" action={<button className="btn btn-sm" onClick={() => d.refreshPortfolio(true)}>{t('action.readStores')}</button>}>{t('portfolio.notReadNotice')}</Notice>} {!known && d.ready && <Notice tone="info" action={<button className="btn btn-sm" onClick={() => d.refreshPortfolio(true)}>{t('action.readStores')}</button>}>{t('portfolio.notReadNotice')}</Notice>}
<div className="kpis"> <div className="kpis">
<Kpi icon="layers" label={t('kpi.apps')} value={d.projects.length} sub={t('kpi.appsSub', { ios: iosApps, android: androidApps })} /> <Kpi icon="layers" label={t('kpi.apps')} value={rows.length} sub={t('kpi.appsSubStore', { ios: iosApps, android: androidApps, store: storeOnly })} />
<Kpi icon="check" label={t('kpi.live')} value={known ? liveCount : '–'} sub={known ? t('kpi.liveSub', { count: stores }) : t('kpi.notRead')} /> <Kpi icon="check" label={t('kpi.live')} value={known ? liveCount : '–'} sub={known ? t('kpi.liveSub', { count: stores }) : t('kpi.notRead')} />
<Kpi icon="rocket" label={t('kpi.rolling')} value={known ? rolling.length : '–'} sub={!known ? t('kpi.notRead') : rolling.length ? [...new Set(rolling.map(r => r.version))].map(v => `${v}: ${rolling.filter(r => r.version === v).map(r => `${r.store === 'ios' ? 'iOS' : 'Android'}${r.fraction !== null ? ` ${share(r.fraction)}` : ''}`).join(', ')}`).join(' · ') : t('kpi.none')} /> <Kpi icon="rocket" label={t('kpi.rolling')} value={known ? rolling.length : '–'} sub={!known ? t('kpi.notRead') : rolling.length ? [...new Set(rolling.map(r => r.version))].map(v => `${v}: ${rolling.filter(r => r.version === v).map(r => `${r.store === 'ios' ? 'iOS' : 'Android'}${r.fraction !== null ? ` ${share(r.fraction)}` : ''}`).join(', ')}`).join(' · ') : t('kpi.none')} />
<Kpi icon="clock" label={t('kpi.review')} value={known ? review.length : '–'} sub={!known ? t('kpi.notRead') : review.length ? review.map(r => `${r.store === 'ios' ? 'iOS' : 'Android'} ${r.version}`).join(' · ') : t('kpi.none')} tone={review.length ? 'warn' : undefined} /> <Kpi icon="clock" label={t('kpi.review')} value={known ? review.length : '–'} sub={!known ? t('kpi.notRead') : review.length ? review.map(r => `${r.store === 'ios' ? 'iOS' : 'Android'} ${r.version}`).join(' · ') : t('kpi.none')} tone={review.length ? 'warn' : undefined} />
<Kpi icon="alert" label={t('kpi.attention')} value={att.length} sub={blockers ? t('kpi.blockers', { count: blockers }) : t('kpi.noBlockers')} tone={blockers ? 'bad' : att.length ? 'warn' : undefined} /> <Kpi icon="alert" label={t('kpi.attention')} value={att.length} sub={blockers ? t('kpi.blockers', { count: blockers }) : t('kpi.noBlockers')} tone={blockers ? 'bad' : att.length ? 'warn' : undefined} />
</div> </div>
<div className="toolbar" role="toolbar" aria-label={t('portfolio.toolbar')}>
<div className="search-input grow-0"><Icon name="search" /><input className="input" value={query} onChange={e => setQuery(e.target.value)} placeholder={t('portfolio.search')} aria-label={t('portfolio.search')} /></div>
<div className="fchips" role="group" aria-label={t('portfolio.studioFilter')}>
<button className="fchip" aria-pressed={view.studio === 'all' || !studioOk} onClick={() => setView({ studio: 'all' })}>{t('portfolio.allStudios')}<span className="n">{visible.length}</span></button>
{d.studios.map(s => (
<button key={s.id} className="fchip" aria-pressed={view.studio === s.id} onClick={() => setView({ studio: s.id })}><StudioMark studio={s} size="sm" />{s.name}<span className="n">{counts[s.id] ?? 0}</span></button>
))}
{d.studios.length > 0 && (counts[''] ?? 0) > 0 && <button className="fchip" aria-pressed={view.studio === 'none'} onClick={() => setView({ studio: 'none' })}><StudioMark studio={null} size="sm" />{t('studio.none')}<span className="n">{counts['']}</span></button>}
</div>
<span className="grow" />
<Seg value={view.sort} onChange={sort => setView({ sort })} label={t('portfolio.sort')} options={[['attention', t('portfolio.sortAttention'), 'alert'], ['recent', t('portfolio.sortRecent'), 'clock'], ['name', t('portfolio.sortName')]]} />
{d.studios.length > 0 && <label className="check"><input type="checkbox" checked={view.group} onChange={e => setView({ group: e.target.checked })} />{t('portfolio.group')}</label>}
</div>
<Card title={t('portfolio.apps')} icon="portfolio" sub={known ? t('portfolio.appsSub', { when: ago(d.live?.at) }) : t('portfolio.appsSubOffline')} pad={false} <Card title={t('portfolio.apps')} icon="portfolio" sub={known ? t('portfolio.appsSub', { when: ago(d.live?.at) }) : t('portfolio.appsSubOffline')} pad={false}
actions={<div className="legend-row"><span><span className="pips"><b className="on" /></span>{t('legend.done')}</span><span>{t('legend.stages')}</span></div>}> actions={<div className="legend-row"><span><span className="pips"><b className="on" /></span>{t('legend.done')}</span><span>{t('legend.stages')}</span></div>}>
<div className="table-wrap"> {rows.length ? (
<table className="table"> <div className="table-wrap">
<thead><tr> <table className="table">
<th>{t('col.app')}</th><th>App Store</th><th>Google Play</th><th>{t('col.next')}</th><th>{t('col.crash')}</th><th>{t('col.catalog')}</th><th className="right">{t('col.config')}</th> <thead><tr>
</tr></thead> <th>{t('col.app')}</th><th>App Store</th><th>Google Play</th><th>{t('col.next')}</th><th>{t('col.crash')}</th><th>{t('col.catalog')}</th><th className="right">{t('col.config')}</th>
<tbody> </tr></thead>
{rows.map(({ p, e, l }) => { {grouped.map(g => {
const st = checkState(e); const s = g.studio === undefined ? undefined : d.studios.find(x => x.id === g.studio) ?? null;
const cat = l?.catalog ?? e?.catalog;
return ( return (
<tr key={p.id} className="clickable" onClick={() => open(p)}> <tbody key={g.studio ?? (g.studio === null ? 'none' : 'all')}>
<td> {s !== undefined && (
<div className="cell-app"> <tr className="group-row"><td colSpan={7}>
<AppIcon name={e?.app?.name ?? p.name} src={d.icons[p.id]} /> <span className="row" style={{ gap: 10 }}><StudioMark studio={s} size="sm" /><b>{s?.name ?? t('studio.none')}</b><span className="muted small">{t('portfolio.groupCount', { count: g.rows.length })} · {t('portfolio.groupAccounts', { count: d.accounts.filter(a => (a.studio ?? null) === (g.studio ?? null)).length })}</span></span>
<div className="t"> </td></tr>
<button className="link n" onClick={ev => { ev.stopPropagation(); open(p); }}>{e?.app?.name ?? p.name}</button> )}
<div className="s mono-id">{e?.app?.platforms.ios?.bundleId ?? e?.app?.platforms.android?.packageName ?? ''}</div> {g.rows.map(row)}
</div> </tbody>
</div>
</td>
<td>{e ? <StoreCell e={l} store="ios" project={e} /> : <Skeleton lines={2} />}</td>
<td>{e ? <StoreCell e={l} store="android" project={e} /> : <Skeleton lines={2} />}</td>
<td><NextCell e={l} /></td>
<td><HealthCell c={health[p.id]} /></td>
<td>
{cat ? (
<div className="mini">
<span className="num small strong">{t('portfolio.products', { count: cat.products })} · {t('portfolio.subs', { count: cat.subscriptions })}</span>
{cat.checked === 'live' ? (cat.ok ? <Chip tone="ok">{t('portfolio.inParity')}</Chip> : <Chip tone="warn">{t('portfolio.differs', { count: cat.missingIos.length + cat.missingAndroid.length + cat.onlyIos.length + cat.onlyAndroid.length })}</Chip>)
: <span className="small muted">{t('portfolio.configOnly')}</span>}
</div>
) : <span className="muted small">–</span>}
</td>
<td className="right"><Chip tone={st.tone}>{st.text}</Chip></td>
</tr>
); );
})} })}
</tbody> </table>
</table> </div>
</div> ) : <Empty compact illo="unknown" title={t('portfolio.noMatch')}>{t('portfolio.noMatchText')}</Empty>}
</Card> </Card>
<div className="grid g-main-side"> <div className="grid g-main-side">
<Card title={t('portfolio.attention')} icon="alert" sub={t('portfolio.attentionSub')} pad={false}><AttentionList items={att} /></Card> <Card title={t('portfolio.attention')} icon="alert" sub={t('portfolio.attentionSub')} pad={false}><AttentionList items={[...att].sort((a, b) => (a.tone === 'bad' ? 0 : 1) - (b.tone === 'bad' ? 0 : 1))} /></Card>
<Card title={t('portfolio.workspace')} icon="settings"> <Card title={t('portfolio.workspace')} icon="settings">
<dl className="kv"> <dl className="kv">
<dt>{t('nav.studios')}</dt><dd>{d.studios.length ? t('portfolio.studiosN', { count: d.studios.length }) : <button className="link" onClick={() => nav.go({ screen: 'accounts' })}>{t('studio.add')}</button>}</dd>
<dt>{t('nav.accounts')}</dt><dd>{d.accounts.length ? t('portfolio.accounts', { play: d.accounts.filter(a => a.kind === 'play').length, apple: d.accounts.filter(a => a.kind === 'apple').length }) : <button className="link" onClick={() => nav.go({ screen: 'accounts' })}>{t('action.addAccount')}</button>}</dd> <dt>{t('nav.accounts')}</dt><dd>{d.accounts.length ? t('portfolio.accounts', { play: d.accounts.filter(a => a.kind === 'play').length, apple: d.accounts.filter(a => a.kind === 'apple').length }) : <button className="link" onClick={() => nav.go({ screen: 'accounts' })}>{t('action.addAccount')}</button>}</dd>
<dt>{t('portfolio.folders')}</dt><dd>{t('portfolio.foldersN', { count: d.projects.length, store: storeOnly })}</dd>
<dt>{t('nav.ignored')}</dt><dd>{d.apps.filter(a => a.ignored).length ? <button className="link" onClick={() => nav.go({ screen: 'ignored' })}>{t('portfolio.ignoredN', { count: d.apps.filter(a => a.ignored).length })}</button> : t('kpi.none')}</dd>
<dt>{t('portfolio.storesRead')}</dt><dd>{d.live ? ago(d.live.at) : t('time.never')}</dd> <dt>{t('portfolio.storesRead')}</dt><dd>{d.live ? ago(d.live.at) : t('time.never')}</dd>
<dt>{t('portfolio.tools')}</dt><dd>{d.sidecar?.tools ? t('portfolio.toolsFound', { found: d.sidecar.tools.tools.filter(x => x.found).length, total: d.sidecar.tools.tools.length }) : '–'}</dd>
<dt>CLI</dt><dd>{d.sidecar ? `storebound ${d.sidecar.version}` : d.sidecarError ?? '–'}</dd> <dt>CLI</dt><dd>{d.sidecar ? `storebound ${d.sidecar.version}` : d.sidecarError ?? '–'}</dd>
</dl> </dl>
</Card> </Card>

View file

@ -1,65 +1,241 @@
import { useState } from 'react'; // Settings, every part of the app in one place: studios and accounts, app pairing and the ignore list, store reads
import { api, errorText } from '../api'; // (on launch, every N minutes, how many apps at once, icons), the offline cache, language and theme, notifications,
import { t } from '../i18n'; // local tools, the CLI sidecar, privacy, keyboard shortcuts, updates and reset. A section list on the left jumps.
import { useEffect, useState } from 'react';
import { api, type CacheInfo, errorText, type Settings as S } from '../api';
import { type Key, t } from '../i18n';
import { ago, bytes, date, num } from '../lib/format';
import { pairCandidates, type UnifiedApp, withPair, withUnpair } from '../lib/identity';
import { useNav } from '../nav'; import { useNav } from '../nav';
import { usePrefs } from '../prefs-ctx'; import { usePrefs } from '../prefs-ctx';
import { useData } from '../store'; import { useData } from '../store';
import { Icon } from '../ui/icons'; import { Icon, type IconName, StoreGlyph } from '../ui/icons';
import { Card, Kbd, MOD, Notice, Seg } from '../ui/kit'; import { AppIcon, Card, Chip, Kbd, MOD, Notice, Seg, StudioMark } from '../ui/kit';
export function Settings({ onTheme: _onTheme }: { onTheme: () => void }) { export const SECTIONS: [string, IconName, Key][] = [
['studios', 'building', 'set.studios'], ['pairing', 'link', 'set.pairing'], ['refresh', 'refresh', 'set.refresh'], ['cache', 'database', 'set.cache'],
['appearance', 'sun', 'settings.appearance'], ['notifications', 'bell', 'set.notifications'], ['dependencies', 'package', 'nav.dependencies'], ['cli', 'terminal', 'set.cli'],
['privacy', 'shield', 'set.privacy'], ['shortcuts', 'keyboard', 'settings.shortcuts'], ['updates', 'download', 'set.updates'], ['reset', 'rotate', 'set.reset'],
];
function Toggle({ id, label, hint, checked, onChange }: { id: string; label: string; hint?: string; checked: boolean; onChange: (v: boolean) => void }) {
return (
<label className="toggle-row" htmlFor={id}>
<span className="grow"><span className="strong">{label}</span>{hint && <span className="small muted">{hint}</span>}</span>
<input id={id} type="checkbox" role="switch" className="switch" checked={checked} onChange={e => onChange(e.target.checked)} />
</label>
);
}
function PairRow({ app, all }: { app: UnifiedApp; all: UnifiedApp[] }) {
const d = useData();
const cands = pairCandidates(app, all);
const r = (app.ios ?? app.android)!;
return (
<tr>
<td><div className="cell-app"><AppIcon name={app.name} src={d.iconFor(app)} /><div className="t"><span className="n">{app.name}</span><div className="s mono-id">{r.app.bundleId}</div></div></div></td>
<td>{app.ios && app.android ? <span className="row" style={{ gap: 6 }}><StoreGlyph store="ios" className="ic13" /><StoreGlyph store="android" className="ic13" />{t(`pair.${app.pairing}` as Key)}</span>
: <span className="row" style={{ gap: 6 }}><StoreGlyph store={app.ios ? 'ios' : 'android'} className="ic13" />{t('pair.single')}</span>}</td>
<td className="right">
{app.ios && app.android ? <button className="btn btn-sm btn-ghost" onClick={() => d.updateOverrides(o => withUnpair(o, app.ios!.key, app.android!.key))}><Icon name="unlink" />{t('app.unpair')}</button>
: cands.length ? (
<select className="input input-sm" value="" aria-label={t('app.pairWithName', { name: app.name })} onChange={e => {
const other = cands.find(c => c.key === e.target.value);
if (other) d.updateOverrides(o => withPair(o, (app.ios ?? other.ios)!.key, (app.android ?? other.android)!.key));
}}>
<option value="">{t('app.pairWith')}</option>
{cands.slice(0, 30).map(c => <option key={c.key} value={c.key}>{c.name} · {(c.ios ?? c.android)!.app.bundleId}</option>)}
</select>
) : <span className="small muted">{t('set.noCandidates')}</span>}
</td>
</tr>
);
}
export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void; section?: string }) {
const d = useData(); const d = useData();
const nav = useNav(); const nav = useNav();
const { prefs, update } = usePrefs(); const { prefs, update } = usePrefs();
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [cache, setCache] = useState<CacheInfo | null>(null);
const [active, setActive] = useState(section ?? 'studios');
const s = d.settings;
const tools = d.sidecar?.tools; const tools = d.sidecar?.tools;
const clear = () => api.clearCache().then(() => d.toast({ kind: 'ok', title: t('settings.cacheCleared') }), e => setError(errorText(e))); const set = (patch: (x: S) => S) => d.updateSettings(patch(s));
const loadCache = () => api.cacheInfo().then(setCache, () => {});
useEffect(() => { loadCache(); }, []);
useEffect(() => { if (section) { setActive(section); document.getElementById(`set-${section}`)?.scrollIntoView({ block: 'start' }); } }, [section]);
const jump = (id: string) => { setActive(id); document.getElementById(`set-${id}`)?.scrollIntoView({ block: 'start', behavior: prefs.motion === 'reduce' ? 'auto' : 'smooth' }); };
const clear = () => api.clearCache().then(() => { d.toast({ kind: 'ok', title: t('settings.cacheCleared') }); loadCache(); }, e => setError(errorText(e)));
const reset = async () => {
try {
if (await api.reset()) {
try { localStorage.clear(); } catch { /* private mode */ }
await d.reload();
d.toast({ kind: 'ok', title: t('set.resetDone') });
nav.openWelcome();
}
} catch (e) { setError(errorText(e)); }
};
const storeOnly = d.apps.filter(a => !a.project && !a.ignored);
const paired = storeOnly.filter(a => a.ios && a.android);
const singles = storeOnly.filter(a => !(a.ios && a.android));
return ( return (
<div className="page"> <div className="page">
<div className="ph"><div><h1>{t('nav.settings')}</h1><p>{t('settings.lead')}</p></div></div> <div className="ph"><div><h1>{t('nav.settings')}</h1><p>{t('set.lead')}</p></div></div>
{error && <Notice tone="bad">{error}</Notice>} {error && <Notice tone="bad">{error}</Notice>}
<div className="grid g2" style={{ alignItems: 'start' }}> <div className="set-layout">
<Card title={t('settings.appearance')} icon="sun"> <nav className="set-nav" aria-label={t('set.sections')}>
<div className="form"> {SECTIONS.map(([id, icon, key]) => (
<div className="field" role="group" aria-label={t('settings.theme')}><span className="legend">{t('settings.theme')}</span> <button key={id} className="nav" aria-current={active === id ? 'true' : undefined} onClick={() => jump(id)}><Icon name={icon} /><span className="grow">{t(key)}</span></button>
<Seg value={prefs.theme} onChange={theme => update({ ...prefs, theme })} label={t('settings.theme')} options={[['system', t('settings.system'), 'settings'], ['light', t('settings.light'), 'sun'], ['dark', t('settings.dark'), 'moon']]} /></div> ))}
<div className="field" role="group" aria-label={t('settings.motion')}><span className="legend">{t('settings.motion')}</span> </nav>
<Seg value={prefs.motion} onChange={motion => update({ ...prefs, motion })} label={t('settings.motion')} options={[['system', t('settings.followSystem')], ['reduce', t('settings.reduce')]]} /></div> <div className="stack set-body" style={{ gap: 16 }}>
<div className="field" role="group" aria-label={t('settings.language')}><span className="legend">{t('settings.language')}</span> <Card id="set-studios" title={t('set.studios')} icon="building" sub={t('set.studiosSub')} className="set-card" actions={<button className="btn btn-sm" onClick={() => nav.go({ screen: 'accounts' })}>{t('set.manage')}<Icon name="arrowRight" /></button>}>
<Seg value={prefs.lang} onChange={lang => update({ ...prefs, lang })} label={t('settings.language')} options={[['system', t('settings.system')], ['en', 'English'], ['tr', 'Türkçe']]} /></div> {d.studios.length ? (
</div> <div className="studio-sum">
</Card> {d.studios.map(st => {
<Card title={t('settings.shortcuts')} icon="keyboard"> const accts = d.accounts.filter(a => a.studio === st.id);
<dl className="shortcuts"> return (
<dt>{t('settings.scPalette')}</dt><dd><Kbd keys={[MOD, 'K']} /></dd> <button key={st.id} className="studio-sum-item" onClick={() => nav.go({ screen: 'accounts', section: st.id })}>
<dt>{t('nav.portfolio')}</dt><dd><Kbd keys={[MOD, '1']} /></dd> <StudioMark studio={st} size="md" />
<dt>{t('settings.scWorkspace')}</dt><dd><Kbd keys={[MOD, '2']} /><span className="muted">–</span><Kbd keys={[MOD, '5']} /></dd> <span className="stack" style={{ gap: 2 }}><b>{st.name}</b><span className="small muted">{t('set.studioLine', { play: accts.filter(a => a.kind === 'play').length, apple: accts.filter(a => a.kind === 'apple').length, apps: d.apps.filter(a => a.studio === st.id && !a.ignored).length })}</span></span>
<dt>{t('settings.scTabs')}</dt><dd><Kbd keys={[MOD, '⇧', '[']} /><Kbd keys={[MOD, '⇧', ']']} /></dd> </button>
<dt>{t('settings.scTabArrows')}</dt><dd><Kbd keys={['←', '→']} /></dd> );
<dt>{t('settings.scClose')}</dt><dd><Kbd keys={['Esc']} /></dd> })}
</dl> </div>
</Card> ) : <p className="small muted">{t('set.noStudios')}</p>}
<Card title={t('settings.data')} icon="database"> </Card>
<div className="stack">
<p className="small muted">{t('settings.dataText')}</p> <Card id="set-pairing" title={t('set.pairing')} icon="link" sub={t('set.pairingSub')} pad={false} className="set-card">
<div className="actions"> {storeOnly.length ? (
<button className="btn btn-sm" onClick={clear}><Icon name="trash" />{t('settings.clearCache')}</button> <table className="table">
<button className="btn btn-sm" onClick={nav.openWelcome}><Icon name="sparkle" />{t('action.welcome')}</button> <thead><tr><th>{t('col.app')}</th><th>{t('set.pairedHow')}</th><th className="right"><span className="sr">{t('col.actions')}</span></th></tr></thead>
<tbody>{[...paired, ...singles].map(a => <PairRow key={a.key} app={a} all={d.apps} />)}</tbody>
</table>
) : <div className="card-body"><p className="small muted">{t('set.noStoreOnly')}</p></div>}
<div className="card-foot"><Icon name="eyeOff" />{t('set.ignoredLine', { count: d.apps.filter(a => a.ignored).length, accounts: d.overrides.ignored.filter(i => i.startsWith('account:')).length })}
<button className="link" onClick={() => nav.go({ screen: 'ignored' })}>{t('set.openIgnored')}</button></div>
</Card>
<Card id="set-refresh" title={t('set.refresh')} icon="refresh" sub={t('set.refreshSub')} className="set-card">
<div className="form">
<div className="field"><span className="legend">{t('set.autoRefresh')}</span>
<Seg value={String(s.refresh.autoMinutes) as '0'} label={t('set.autoRefresh')} onChange={v => set(x => ({ ...x, refresh: { ...x.refresh, autoMinutes: Number(v) as S['refresh']['autoMinutes'] } }))}
options={[['0', t('set.off')], ['15', t('set.min', { n: 15 })], ['30', t('set.min', { n: 30 })], ['60', t('set.hour', { n: 1 })], ['180', t('set.hour', { n: 3 })], ['720', t('set.hour', { n: 12 })]]} />
<span className="hint">{t('set.autoHint')}</span></div>
<Toggle id="on-launch" label={t('set.onLaunch')} hint={t('set.onLaunchHint')} checked={s.refresh.onLaunch} onChange={v => set(x => ({ ...x, refresh: { ...x.refresh, onLaunch: v } }))} />
<Toggle id="icons" label={t('set.icons')} hint={t('set.iconsHint')} checked={s.refresh.icons} onChange={v => set(x => ({ ...x, refresh: { ...x.refresh, icons: v } }))} />
<div className="field"><label htmlFor="parallel">{t('set.parallel')}</label>
<select id="parallel" className="input" style={{ width: 120 }} value={s.refresh.parallel} onChange={e => set(x => ({ ...x, refresh: { ...x.refresh, parallel: Number(e.target.value) } }))}>
{[1, 2, 3, 4, 6, 8].map(n => <option key={n} value={n}>{n}</option>)}
</select><span className="hint">{t('set.parallelHint')}</span></div>
<div className="actions">
<button className="btn btn-sm" onClick={() => d.importApps()} disabled={d.importBusy || !d.accounts.length}><Icon name="download" />{t('action.importApps')}</button>
<button className="btn btn-sm" onClick={() => d.refreshPortfolio(true)} disabled={!!d.portfolioBusy}><Icon name="refresh" />{t('action.readStores')}</button>
<span className="small muted">{d.live ? t('foot.lastRead', { when: ago(d.live.at) }) : t('foot.neverRead')}</span>
</div>
</div> </div>
</div> </Card>
</Card>
<Card title={t('settings.about')} icon="info"> <Card id="set-cache" title={t('set.cache')} icon="database" sub={t('set.cacheSub')} className="set-card">
<dl className="kv"> <div className="form">
<dt>{t('settings.app')}</dt><dd>{d.info ? `storebound desktop ${d.info.version}${d.info.debug ? ` (${t('settings.debug')})` : ''}` : '–'}</dd> <dl className="kv">
<dt>CLI</dt><dd>{d.sidecar ? `storebound ${d.sidecar.version} · ${d.sidecar.protocol} · ${t('settings.methods', { count: d.sidecar.methods.length })}` : d.sidecarError ?? t('foot.cliStarting')}</dd> <dt>{t('set.cacheSize')}</dt><dd>{cache ? `${bytes(cache.file_bytes)} · ${t('set.cacheRows', { count: cache.rows })}` : '–'}</dd>
<dt>{t('settings.tools')}</dt><dd>{tools ? t('portfolio.toolsFound', { found: tools.tools.filter(x => x.found).length, total: tools.tools.length }) : '–'}</dd> <dt>{t('set.cacheOldest')}</dt><dd>{cache?.oldest ? `${date(cache.oldest)} (${ago(cache.oldest)})` : '–'}</dd>
<dt>{t('settings.telemetry')}</dt><dd>{t('settings.telemetryNone')}</dd> </dl>
</dl> <div className="field"><span className="legend">{t('set.keep')}</span>
<div className="actions" style={{ marginTop: 12 }}> <Seg value={String(s.cache.keepDays) as '0'} label={t('set.keep')} onChange={v => set(x => ({ ...x, cache: { keepDays: Number(v) as S['cache']['keepDays'] } })).then(loadCache)}
<button className="btn btn-sm btn-ghost" onClick={() => api.openExternal('https://storebound.dev/').catch(e => setError(errorText(e)))}><Icon name="external" />storebound.dev</button> options={[['7', t('set.days', { n: 7 })], ['30', t('set.days', { n: 30 })], ['90', t('set.days', { n: 90 })], ['365', t('set.year')], ['0', t('set.always')]]} /></div>
</div> <div className="actions"><button className="btn btn-sm" onClick={clear}><Icon name="trash" />{t('settings.clearCache')}</button></div>
</Card> <p className="small muted">{t('settings.dataText')}</p>
</div>
</Card>
<Card id="set-appearance" title={t('settings.appearance')} icon="sun" className="set-card">
<div className="form">
<div className="field" role="group" aria-label={t('settings.language')}><span className="legend">{t('settings.language')}</span>
<Seg value={prefs.lang} onChange={lang => update({ ...prefs, lang })} label={t('settings.language')} options={[['system', t('settings.system')], ['en', 'English'], ['tr', 'Türkçe']]} /></div>
<div className="field" role="group" aria-label={t('settings.theme')}><span className="legend">{t('settings.theme')}</span>
<Seg value={prefs.theme} onChange={theme => update({ ...prefs, theme })} label={t('settings.theme')} options={[['system', t('settings.system'), 'settings'], ['light', t('settings.light'), 'sun'], ['dark', t('settings.dark'), 'moon']]} /></div>
<div className="field" role="group" aria-label={t('settings.motion')}><span className="legend">{t('settings.motion')}</span>
<Seg value={prefs.motion} onChange={motion => update({ ...prefs, motion })} label={t('settings.motion')} options={[['system', t('settings.followSystem')], ['reduce', t('settings.reduce')]]} /></div>
</div>
</Card>
<Card id="set-notifications" title={t('set.notifications')} icon="bell" sub={t('set.notificationsSub')} className="set-card">
<div className="form">
<Toggle id="n-review" label={t('set.nReview')} hint={t('set.nReviewHint')} checked={s.notify.reviewState} onChange={v => set(x => ({ ...x, notify: { ...x.notify, reviewState: v } }))} />
<Toggle id="n-low" label={t('set.nLow')} hint={t('set.nLowHint')} checked={s.notify.lowReviews} onChange={v => set(x => ({ ...x, notify: { ...x.notify, lowReviews: v } }))} />
<Toggle id="n-crash" label={t('set.nCrash')} hint={t('set.nCrashHint')} checked={s.notify.crash} onChange={v => set(x => ({ ...x, notify: { ...x.notify, crash: v } }))} />
<div className="actions"><button className="btn btn-sm" onClick={() => api.notify(t('set.testTitle'), t('set.testBody')).catch(e => setError(errorText(e)))}><Icon name="bell" />{t('set.testNotify')}</button></div>
</div>
</Card>
<Card id="set-dependencies" title={t('nav.dependencies')} icon="package" className="set-card" actions={<button className="btn btn-sm" onClick={() => nav.go({ screen: 'dependencies' })}>{t('set.manage')}<Icon name="arrowRight" /></button>}>
{tools ? (
<div className="dep-sum">
{tools.tools.map(x => <span key={x.id} className="row small" style={{ gap: 6 }}><i className={`dot ${x.found ? 'ok' : ''}`} />{x.name}{x.version ? <span className="muted num">{x.version}</span> : null}{x.source === 'app' && <Chip tone="outline">{t('set.appCopy')}</Chip>}</span>)}
</div>
) : <p className="small muted">–</p>}
<p className="small muted" style={{ marginTop: 10 }}>{t('set.depsText')}</p>
</Card>
<Card id="set-cli" title={t('set.cli')} icon="terminal" className="set-card">
<dl className="kv">
<dt>{t('settings.app')}</dt><dd>{d.info ? `storebound desktop ${d.info.version}${d.info.debug ? ` (${t('settings.debug')})` : ''} · ${d.info.platform}` : '–'}</dd>
<dt>CLI</dt><dd>{d.sidecar ? `storebound ${d.sidecar.version}` : d.sidecarError ?? t('foot.cliStarting')}</dd>
<dt>{t('set.protocol')}</dt><dd>{d.sidecar ? `${d.sidecar.protocol} · ${t('settings.methods', { count: d.sidecar.methods.length })}` : '–'}</dd>
<dt>{t('set.state')}</dt><dd><span className="row" style={{ gap: 6 }}><i className={`dot ${d.sidecar?.running ? 'ok' : d.sidecarError ? 'bad' : ''}`} />{d.sidecar?.running ? t('set.running') : d.sidecarError ? t('foot.cliDown') : t('foot.cliStarting')}</span></dd>
<dt>{t('set.writes')}</dt><dd>{t('set.writesText')}</dd>
</dl>
</Card>
<Card id="set-privacy" title={t('set.privacy')} icon="shield" className="set-card">
<ul className="plain-list">
<li><Icon name="check" />{t('set.p1')}</li>
<li><Icon name="check" />{t('set.p2')}</li>
<li><Icon name="check" />{t('set.p3')}</li>
<li><Icon name="check" />{t('set.p4')}</li>
</ul>
<div className="actions" style={{ marginTop: 12 }}>
<button className="btn btn-sm" onClick={() => api.revealData().catch(e => setError(errorText(e)))}><Icon name="folder" />{t('set.reveal')}</button>
<button className="btn btn-sm btn-ghost" onClick={() => api.openExternal('https://storebound.dev/').catch(e => setError(errorText(e)))}><Icon name="external" />storebound.dev</button>
</div>
</Card>
<Card id="set-shortcuts" title={t('settings.shortcuts')} icon="keyboard" className="set-card">
<dl className="shortcuts">
<dt>{t('settings.scPalette')}</dt><dd><Kbd keys={[MOD, 'K']} /></dd>
<dt>{t('nav.portfolio')}</dt><dd><Kbd keys={[MOD, '1']} /></dd>
<dt>{t('settings.scWorkspace')}</dt><dd><Kbd keys={[MOD, '2']} /><span className="muted">–</span><Kbd keys={[MOD, '6']} /></dd>
<dt>{t('settings.scTabs')}</dt><dd><Kbd keys={[MOD, '⇧', '[']} /><Kbd keys={[MOD, '⇧', ']']} /></dd>
<dt>{t('settings.scTabArrows')}</dt><dd><Kbd keys={['←', '→']} /></dd>
<dt>{t('settings.scClose')}</dt><dd><Kbd keys={['Esc']} /></dd>
<dt>{t('set.scQuit')}</dt><dd><Kbd keys={[MOD, 'Q']} /></dd>
</dl>
</Card>
<Card id="set-updates" title={t('set.updates')} icon="download" className="set-card">
<div className="form">
<div className="field"><span className="legend">{t('set.channel')}</span>
<Seg value={s.channel} label={t('set.channel')} onChange={channel => set(x => ({ ...x, channel }))} options={[['stable', t('set.stable')], ['beta', t('set.beta')]]} /></div>
<p className="small muted">{t('set.updatesText')}</p>
</div>
</Card>
<Card id="set-reset" title={t('set.reset')} icon="rotate" className="set-card danger-card">
<div className="stack">
<p className="small muted">{t('set.resetText', { accounts: d.accounts.length, studios: d.studios.length, folders: d.projects.length })}</p>
<div className="actions">
<button className="btn btn-sm" onClick={nav.openWelcome}><Icon name="sparkle" />{t('action.welcome')}</button>
<button className="btn btn-sm btn-danger" onClick={reset}><Icon name="rotate" />{t('set.resetButton')}</button>
</div>
</div>
</Card>
<p className="small muted">{t('set.footer', { n: num(d.apps.length) })}</p>
</div>
</div> </div>
</div> </div>
); );

View file

@ -1,6 +1,6 @@
// Health: Google Play vitals (user-perceived crash and ANR rate per day against the bad behavior thresholds, worst // Health: Google Play vitals (user-perceived crash and ANR rate per day against the bad behavior thresholds, worst
// devices, top issues) and App Store diagnostics (power and performance metrics, signatures, TestFlight crashes). // devices, top issues) and App Store diagnostics (power and performance metrics, signatures, TestFlight crashes).
import type { Project } from '../../api'; import type { UnifiedApp } from '../../lib/identity';
import { t } from '../../i18n'; import { t } from '../../i18n';
import { ago, date, num, pct } from '../../lib/format'; import { ago, date, num, pct } from '../../lib/format';
import { type AppleHealth, healthSeries, type HealthSnapshot, isError, PLAY_THRESHOLDS, type PlayHealth, type Series } from '../../lib/model'; import { type AppleHealth, healthSeries, type HealthSnapshot, isError, PLAY_THRESHOLDS, type PlayHealth, type Series } from '../../lib/model';
@ -122,8 +122,8 @@ function Apple({ h }: { h: AppleHealth }) {
); );
} }
export function HealthTab({ project }: { project: Project }) { export function HealthTab({ app }: { app: UnifiedApp }) {
const r = useRead<HealthSnapshot>(project.id, 'health', { network: true, title: t('tab.health') }); const r = useRead<HealthSnapshot>(app.target, 'health', { network: true, title: t('tab.health'), appName: app.name });
const refresh = <button className="btn btn-sm" onClick={r.refresh} disabled={r.loading}><Icon name="refresh" className={r.loading && !r.data ? 'spin' : undefined} />{r.data ? t('action.refresh') : t('health.read')}</button>; const refresh = <button className="btn btn-sm" onClick={r.refresh} disabled={r.loading}><Icon name="refresh" className={r.loading && !r.data ? 'spin' : undefined} />{r.data ? t('action.refresh') : t('health.read')}</button>;
if (!r.data) { if (!r.data) {
if (r.loading && !r.error) return <Card><Skeleton lines={4} block /></Card>; if (r.loading && !r.error) return <Card><Skeleton lines={4} block /></Card>;

View file

@ -1,6 +1,7 @@
// Releases: the release timeline (one version on both stores on one track: build -> testing -> review -> live -> // Releases: the release timeline (one version on both stores on one track: build -> testing -> review -> live ->
// rollout %), then every version read from the stores. Submit and release stay in the consoles. // rollout %), then every version read from the stores. Submit and release stay in the consoles.
import { api, type Project, type ReleaseTrain } from '../../api'; import { api, type ReleaseTrain } from '../../api';
import type { UnifiedApp } from '../../lib/identity';
import { type Key, t } from '../../i18n'; import { type Key, t } from '../../i18n';
import { ago, date, share } from '../../lib/format'; import { ago, date, share } from '../../lib/format';
import { type Lane, STAGES, type TestFlightStatus, trainLanes, versionHistory } from '../../lib/model'; import { type Lane, STAGES, type TestFlightStatus, trainLanes, versionHistory } from '../../lib/model';
@ -60,10 +61,11 @@ function Train({ title, train, tf, tone }: { title: string; train: ReleaseTrain;
); );
} }
export function ReleasesTab({ project }: { project: Project }) { export function ReleasesTab({ app }: { app: UnifiedApp }) {
const d = useData(); const d = useData();
const l = d.liveOf(project); const l = d.liveFor(app);
const tf = useRead<TestFlightStatus>(project.id, 'apple.testflight_status', { network: true, title: 'TestFlight' }); const project = app.project;
const tf = useRead<TestFlightStatus>(app.target, 'apple.testflight_status', { network: true, title: 'TestFlight', skip: !app.ios && !d.statusFor(app)?.app?.platforms.ios });
const open = (url: string) => { api.openExternal(url).catch(() => {}); }; const open = (url: string) => { api.openExternal(url).catch(() => {}); };
if (!l) { if (!l) {
@ -71,7 +73,7 @@ export function ReleasesTab({ project }: { project: Project }) {
<Card pad={false}> <Card pad={false}>
<Empty illo="cloud" title={t('releases.notReadTitle')} actions={<> <Empty illo="cloud" title={t('releases.notReadTitle')} actions={<>
<button className="btn btn-primary" onClick={() => d.refreshPortfolio(true)} disabled={!!d.portfolioBusy}><Icon name="refresh" />{t('action.readStores')}</button> <button className="btn btn-primary" onClick={() => d.refreshPortfolio(true)} disabled={!!d.portfolioBusy}><Icon name="refresh" />{t('action.readStores')}</button>
{!project.playAccount && !project.appleAccount && <span className="small muted">{t('releases.noAccounts')}</span>} {project && !project.playAccount && !project.appleAccount && <span className="small muted">{t('releases.noAccounts')}</span>}
</>}>{t('releases.notReadText')}</Empty> </>}>{t('releases.notReadText')}</Empty>
</Card> </Card>
); );

View file

@ -2,7 +2,8 @@
// (.storebound/replies) with the send checks. Approving a draft is a local, confirmed write; sending stays in the // (.storebound/replies) with the send checks. Approving a draft is a local, confirmed write; sending stays in the
// terminal (`storebound reviews send`): replies are public. // terminal (`storebound reviews send`): replies are public.
import { useMemo, useState } from 'react'; import { useMemo, useState } from 'react';
import { api, type DraftsResult, errorText, newJob, type Project, type ReplyDraft } from '../../api'; import { api, type DraftsResult, errorText, newJob, type ReplyDraft } from '../../api';
import type { UnifiedApp } from '../../lib/identity';
import { t } from '../../i18n'; import { t } from '../../i18n';
import { ago, date, num } from '../../lib/format'; import { ago, date, num } from '../../lib/format';
import { draftName, filterReviews, type Review, type ReviewFilter, starStats } from '../../lib/model'; import { draftName, filterReviews, type Review, type ReviewFilter, starStats } from '../../lib/model';
@ -56,10 +57,11 @@ function Detail({ r, draft, onApprove, busy }: { r: Review; draft: ReplyDraft |
); );
} }
export function ReviewsTab({ project }: { project: Project }) { export function ReviewsTab({ app }: { app: UnifiedApp }) {
const d = useData(); const d = useData();
const list = useRead<Review[]>(project.id, 'reviews.list', { network: true, args: { days: 30 }, title: t('tab.reviews') }); const project = app.project;
const drafts = useRead<DraftsResult>(project.id, 'reviews.drafts', { network: false }); const list = useRead<Review[]>(app.target, 'reviews.list', { network: true, args: { days: 30 }, title: t('tab.reviews'), appName: app.name });
const drafts = useRead<DraftsResult>(app.target, 'reviews.drafts', { network: false, skip: !project });
const [f, setF] = useState<ReviewFilter>({ store: 'all', stars: [], unanswered: false, query: '' }); const [f, setF] = useState<ReviewFilter>({ store: 'all', stars: [], unanswered: false, query: '' });
const [sel, setSel] = useState<string | null>(null); const [sel, setSel] = useState<string | null>(null);
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
@ -74,6 +76,7 @@ export function ReviewsTab({ project }: { project: Project }) {
setBusy(true); setBusy(true);
const job = newJob(method); const job = newJob(method);
try { try {
if (!project) return;
const o = await api.writeWithConfirm(method, project.id, args, job); const o = await api.writeWithConfirm(method, project.id, args, job);
if (o.confirmed && o.result?.ok) { d.toast({ kind: 'ok', title, detail: undefined }); await drafts.refresh(); } if (o.confirmed && o.result?.ok) { d.toast({ kind: 'ok', title, detail: undefined }); await drafts.refresh(); }
else if (o.stage === 'dry-run') d.toast({ kind: 'bad', title: t('write.dryFailed'), detail: o.dryRun.output.split('\n').filter(Boolean).at(-1) }); else if (o.stage === 'dry-run') d.toast({ kind: 'bad', title: t('write.dryFailed'), detail: o.dryRun.output.split('\n').filter(Boolean).at(-1) });

View file

@ -1,6 +1,6 @@
// TestFlight: beta groups (internal / external, testers, builds, public link) and the recent builds with their // TestFlight: beta groups (internal / external, testers, builds, public link) and the recent builds with their
// processing and beta review states. // processing and beta review states.
import type { Project } from '../../api'; import type { UnifiedApp } from '../../lib/identity';
import { t } from '../../i18n'; import { t } from '../../i18n';
import { ago, date, num } from '../../lib/format'; import { ago, date, num } from '../../lib/format';
import type { TestFlightStatus, Tone } from '../../lib/model'; import type { TestFlightStatus, Tone } from '../../lib/model';
@ -23,11 +23,11 @@ function State({ s }: { s: string | null }) {
return s ? <Chip tone={b.tone}>{b.text}</Chip> : <span className="muted small">–</span>; return s ? <Chip tone={b.tone}>{b.text}</Chip> : <span className="muted small">–</span>;
} }
export function TestFlightTab({ project }: { project: Project }) { export function TestFlightTab({ app }: { app: UnifiedApp }) {
const d = useData(); const d = useData();
const e = d.statusOf(project); const e = d.statusFor(app);
const r = useRead<TestFlightStatus>(project.id, 'apple.testflight_status', { network: true, title: 'TestFlight' }); const r = useRead<TestFlightStatus>(app.target, 'apple.testflight_status', { network: true, title: 'TestFlight' });
if (e && !e.app?.platforms.ios) return <Card pad={false}><Empty illo="plane" title={t('tf.noIos')}>{t('tf.noIosText')}</Empty></Card>; if ((e && !e.app?.platforms.ios) || (!e && !app.project && !app.ios)) return <Card pad={false}><Empty illo="plane" title={t('tf.noIos')}>{t('tf.noIosText')}</Empty></Card>;
if (!r.data) { if (!r.data) {
if (r.loading && !r.error) return <Card><Skeleton lines={4} block /></Card>; if (r.loading && !r.error) return <Card><Skeleton lines={4} block /></Card>;
return ( return (

View file

@ -1,11 +1,15 @@
// App data shared by every screen: app folders, accounts, the sidecar, the portfolio (offline check + the last live // App data shared by every screen: app folders, studios, store accounts and the apps they see, the pairing / ignore
// read from the cache), app icons, and background jobs shown as toasts with progress and cancel. // overrides, settings, the sidecar, the portfolio (offline check + the last live read from the cache), app icons, and
// background jobs shown as toasts with progress and cancel.
import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { import {
type Account, api, type AppInfo, type AppStatus, type CacheEntry, errorText, newJob, onDownload, onProgress, type PortfolioResult, type Project, reads, type Account, type AccountCheck, api, type AppInfo, type AppsListResult, type AppStatus, type CacheEntry, DEFAULT_SETTINGS, errorText, newJob, onDownload,
type SidecarStatus, type ToolResult, onProgress, type PortfolioResult, type Project, reads, type Settings, type SidecarStatus, type Studio, type ToolResult,
} from './api'; } from './api';
import { t } from './i18n'; import { t } from './i18n';
import { buildApps, NO_OVERRIDES, type Overrides, type UnifiedApp } from './lib/identity';
import { isError, type HealthSnapshot, type Review } from './lib/model';
import { crashCrossed, newLowReviews, releaseChanges } from './lib/notify';
export type ToastKind = 'job' | 'ok' | 'bad' | 'info'; export type ToastKind = 'job' | 'ok' | 'bad' | 'info';
export interface Toast { export interface Toast {
@ -19,11 +23,22 @@ export interface Toast {
job?: string; job?: string;
} }
export interface AccountHealth { check?: AccountCheck; error?: string; at: string }
export interface Data { export interface Data {
ready: boolean; ready: boolean;
info: AppInfo | null; info: AppInfo | null;
projects: Project[]; projects: Project[];
accounts: Account[]; accounts: Account[];
studios: Studio[];
overrides: Overrides;
settings: Settings;
/** Last app list read of each account (null: never read). */
storeApps: Record<string, CacheEntry<AppsListResult> | null>;
/** Last account check of this session. */
accountHealth: Record<string, AccountHealth>;
/** Every app across studios and accounts, ignored ones included (`ignored: true`). */
apps: UnifiedApp[];
sidecar: SidecarStatus | null; sidecar: SidecarStatus | null;
sidecarError: string | null; sidecarError: string | null;
/** Latest portfolio read (offline check, or live when just read). */ /** Latest portfolio read (offline check, or live when just read). */
@ -32,11 +47,21 @@ export interface Data {
live: CacheEntry<PortfolioResult> | null; live: CacheEntry<PortfolioResult> | null;
portfolioBusy: 'offline' | 'live' | null; portfolioBusy: 'offline' | 'live' | null;
portfolioError: string | null; portfolioError: string | null;
importBusy: boolean;
icons: Record<string, string | null>; icons: Record<string, string | null>;
refreshPortfolio: (live?: boolean) => Promise<void>; refreshPortfolio: (live?: boolean) => Promise<void>;
/** Reads the apps of one account (or all) from the stores. */
importApps: (account?: string) => Promise<void>;
checkAccount: (id: string) => Promise<void>;
reload: () => Promise<void>; reload: () => Promise<void>;
updateOverrides: (fn: (o: Overrides) => Overrides) => Promise<void>;
updateSettings: (s: Settings) => Promise<void>;
statusOf: (p: Project) => AppStatus | undefined; statusOf: (p: Project) => AppStatus | undefined;
liveOf: (p: Project) => AppStatus | undefined; liveOf: (p: Project) => AppStatus | undefined;
statusFor: (a: UnifiedApp) => AppStatus | undefined;
liveFor: (a: UnifiedApp) => AppStatus | undefined;
iconFor: (a: UnifiedApp) => string | null;
appByKey: (key: string) => UnifiedApp | undefined;
toasts: Toast[]; toasts: Toast[];
toast: (t: Omit<Toast, 'id'> & { id?: string }) => string; toast: (t: Omit<Toast, 'id'> & { id?: string }) => string;
updateToast: (id: string, patch: Partial<Toast>) => void; updateToast: (id: string, patch: Partial<Toast>) => void;
@ -58,15 +83,25 @@ export function DataProvider({ children }: { children: ReactNode }) {
const [info, setInfo] = useState<AppInfo | null>(null); const [info, setInfo] = useState<AppInfo | null>(null);
const [projects, setProjects] = useState<Project[]>([]); const [projects, setProjects] = useState<Project[]>([]);
const [accounts, setAccounts] = useState<Account[]>([]); const [accounts, setAccounts] = useState<Account[]>([]);
const [studios, setStudios] = useState<Studio[]>([]);
const [overrides, setOverrides] = useState<Overrides>(NO_OVERRIDES);
const [settings, setSettings] = useState<Settings>(DEFAULT_SETTINGS);
const [storeApps, setStoreApps] = useState<Record<string, CacheEntry<AppsListResult> | null>>({});
const [accountHealth, setAccountHealth] = useState<Record<string, AccountHealth>>({});
const [sidecar, setSidecar] = useState<SidecarStatus | null>(null); const [sidecar, setSidecar] = useState<SidecarStatus | null>(null);
const [sidecarError, setSidecarError] = useState<string | null>(null); const [sidecarError, setSidecarError] = useState<string | null>(null);
const [portfolio, setPortfolio] = useState<PortfolioResult | null>(null); const [portfolio, setPortfolio] = useState<PortfolioResult | null>(null);
const [live, setLive] = useState<CacheEntry<PortfolioResult> | null>(null); const [live, setLive] = useState<CacheEntry<PortfolioResult> | null>(null);
const [portfolioBusy, setBusy] = useState<Data['portfolioBusy']>(null); const [portfolioBusy, setBusy] = useState<Data['portfolioBusy']>(null);
const [portfolioError, setPortfolioError] = useState<string | null>(null); const [portfolioError, setPortfolioError] = useState<string | null>(null);
const [importBusy, setImportBusy] = useState(false);
const [icons, setIcons] = useState<Record<string, string | null>>({}); const [icons, setIcons] = useState<Record<string, string | null>>({});
const [toasts, setToasts] = useState<Toast[]>([]); const [toasts, setToasts] = useState<Toast[]>([]);
const timers = useRef(new Map<string, ReturnType<typeof setTimeout>>()); const timers = useRef(new Map<string, ReturnType<typeof setTimeout>>());
const liveRef = useRef(live);
liveRef.current = live;
const settingsRef = useRef(settings);
settingsRef.current = settings;
const dismiss = useCallback((id: string) => { const dismiss = useCallback((id: string) => {
setToasts(ts => ts.filter(x => x.id !== id)); setToasts(ts => ts.filter(x => x.id !== id));
@ -92,20 +127,36 @@ export function DataProvider({ children }: { children: ReactNode }) {
const cancelJob = useCallback((job: string) => { api.cancel(job).catch(() => {}); }, []); const cancelJob = useCallback((job: string) => { api.cancel(job).catch(() => {}); }, []);
const reload = useCallback(async () => { const reload = useCallback(async () => {
const [p, a] = await Promise.all([api.projects(), api.accounts()]); const [p, a, w, s] = await Promise.all([api.projects(), api.accounts(), api.workspace(), api.storeAppsCached()]);
setProjects(p); setProjects(p);
setAccounts(a); setAccounts(a);
setStudios(w.studios);
setOverrides(w.overrides);
setSettings(w.settings);
setStoreApps(Object.fromEntries(s.map(x => [x.account, x.entry])));
}, []); }, []);
const apps = useMemo(() => buildApps({
projects, accounts, overrides,
summaryOf: p => portfolio?.apps.find(a => a.project === p.path)?.summary ?? liveRef.current?.value.apps.find(a => a.project === p.path)?.summary,
storeApps: Object.entries(storeApps).filter(([, e]) => !!e).map(([account, e]) => ({ account, apps: e!.value.apps })),
}), [projects, accounts, overrides, portfolio, storeApps]);
const appsRef = useRef(apps);
appsRef.current = apps;
const refreshPortfolio = useCallback(async (liveRead = false) => { const refreshPortfolio = useCallback(async (liveRead = false) => {
const job = newJob(liveRead ? 'portfolio-live' : 'portfolio'); const job = newJob(liveRead ? 'portfolio-live' : 'portfolio');
setBusy(liveRead ? 'live' : 'offline'); setPortfolioError(null); setBusy(liveRead ? 'live' : 'offline'); setPortfolioError(null);
const tid = liveRead ? toast({ id: job, kind: 'job', title: t('toast.readingStores'), detail: t('toast.readingStoresDetail'), progress: null, job }) : null; const tid = liveRead ? toast({ id: job, kind: 'job', title: t('toast.readingStores'), detail: t('toast.readingStoresDetail'), progress: null, job }) : null;
try { try {
const r = await api.portfolio(liveRead, job); const stores = liveRead ? appsRef.current.filter(a => !a.project && !a.ignored).map(a => a.target) : [];
const r = await api.portfolio(liveRead, job, stores);
setPortfolio(r); setPortfolio(r);
if (liveRead) { if (liveRead) {
const changes = releaseChanges(liveRef.current?.value, r);
setLive({ value: r, at: r.at }); setLive({ value: r, at: r.at });
if (settingsRef.current.notify.reviewState) for (const c of changes.slice(0, 5))
api.notify(t('notify.releaseTitle', { name: c.name }), t('notify.releaseBody', { store: c.store === 'ios' ? 'App Store' : 'Google Play', version: c.version, phase: t(`phase.${c.to}` as 'phase.live') })).catch(() => {});
const failed = r.apps.filter(a => a.storeErrors.ios || a.storeErrors.android).length; const failed = r.apps.filter(a => a.storeErrors.ios || a.storeErrors.android).length;
if (tid) updateToast(tid, failed ? { kind: 'info', title: t('toast.readDonePartial'), detail: t('toast.readDonePartialDetail', { count: failed }), progress: undefined, job: undefined } if (tid) updateToast(tid, failed ? { kind: 'info', title: t('toast.readDonePartial'), detail: t('toast.readDonePartialDetail', { count: failed }), progress: undefined, job: undefined }
: { kind: 'ok', title: t('toast.readDone'), detail: t('toast.readDoneDetail', { count: r.apps.length }), progress: undefined, job: undefined }); : { kind: 'ok', title: t('toast.readDone'), detail: t('toast.readDoneDetail', { count: r.apps.length }), progress: undefined, job: undefined });
@ -117,7 +168,54 @@ export function DataProvider({ children }: { children: ReactNode }) {
} finally { setBusy(null); } } finally { setBusy(null); }
}, [toast, updateToast]); }, [toast, updateToast]);
// start: app info, folders, accounts, sidecar, cached live portfolio const importApps = useCallback(async (account?: string) => {
const ids = (account ? [account] : accounts.map(a => a.id)).filter(id => account || !overrides.ignored.includes(`account:${id}`));
if (!ids.length) return;
const job = newJob('import');
setImportBusy(true);
const tid = toast({ id: job, kind: 'job', title: t('toast.importing'), detail: t('toast.importingDetail'), progress: { done: 0, total: ids.length }, job });
let ok = 0, apps = 0;
const errors: string[] = [];
for (const [n, id] of ids.entries()) {
try {
const e = await api.refreshStoreApps(id, job);
setStoreApps(m => ({ ...m, [id]: e }));
ok++; apps += e.value.apps.length;
} catch (e) {
const msg = errorText(e);
if (/cancel/i.test(msg)) { updateToast(tid, { kind: 'info', title: t('toast.cancelled'), detail: undefined, progress: undefined, job: undefined }); setImportBusy(false); return; }
errors.push(`${accounts.find(a => a.id === id)?.label ?? id}: ${msg}`);
}
updateToast(tid, { progress: { done: n + 1, total: ids.length } });
}
setImportBusy(false);
updateToast(tid, errors.length ? { kind: ok ? 'info' : 'bad', title: t('toast.importPartial', { count: errors.length }), detail: errors[0], progress: undefined, job: undefined }
: { kind: 'ok', title: t('toast.importDone', { count: apps }), detail: t('toast.importDoneDetail', { count: ok }), progress: undefined, job: undefined });
}, [accounts, overrides.ignored, toast, updateToast]);
const checkAccount = useCallback(async (id: string) => {
try {
const check = await api.checkAccount(id, newJob('check'));
setAccountHealth(m => ({ ...m, [id]: { check, at: new Date().toISOString() } }));
} catch (e) { setAccountHealth(m => ({ ...m, [id]: { error: errorText(e), at: new Date().toISOString() } })); }
}, []);
const updateOverrides = useCallback(async (fn: (o: Overrides) => Overrides) => {
const next = fn(overrides);
setOverrides(next);
try { setOverrides(await api.setOverrides(next)); } catch (e) {
setOverrides(overrides);
toast({ kind: 'bad', title: t('toast.saveFailed'), detail: errorText(e) });
}
}, [overrides, toast]);
const updateSettings = useCallback(async (s: Settings) => {
const old = settings;
setSettings(s);
try { setSettings(await api.setSettings(s)); } catch (e) { setSettings(old); toast({ kind: 'bad', title: t('toast.saveFailed'), detail: errorText(e) }); }
}, [settings, toast]);
// start: app info, folders, accounts, workspace, sidecar, cached live portfolio
useEffect(() => { useEffect(() => {
api.appInfo().then(setInfo, () => {}); api.appInfo().then(setInfo, () => {});
reload().catch(() => {}).finally(() => setReady(true)); reload().catch(() => {}).finally(() => setReady(true));
@ -127,6 +225,22 @@ export function DataProvider({ children }: { children: ReactNode }) {
useEffect(() => { if (projects.length) refreshPortfolio(false); }, [projects.length, refreshPortfolio]); useEffect(() => { if (projects.length) refreshPortfolio(false); }, [projects.length, refreshPortfolio]);
// Settings > Refresh: on launch, then every N minutes (store reads use the accounts' API quota: off by default)
const launched = useRef(false);
useEffect(() => {
if (!ready || launched.current) return;
launched.current = true;
if (settings.refresh.onLaunch && (projects.length || accounts.length)) importApps().finally(() => refreshPortfolio(true));
}, [ready, settings.refresh.onLaunch, projects.length, accounts.length, importApps, refreshPortfolio]);
const busyRef = useRef(portfolioBusy);
busyRef.current = portfolioBusy;
useEffect(() => {
const m = settings.refresh.autoMinutes;
if (!m) return;
const tm = setInterval(() => { if (!busyRef.current) refreshPortfolio(true); }, m * 60_000);
return () => clearInterval(tm);
}, [settings.refresh.autoMinutes, refreshPortfolio]);
// icons: cached first, then read (offline, cheap) // icons: cached first, then read (offline, cheap)
useEffect(() => { useEffect(() => {
for (const p of projects) { for (const p of projects) {
@ -163,11 +277,18 @@ export function DataProvider({ children }: { children: ReactNode }) {
const cur = portfolio?.apps.find(a => (a.project === p.path || a.app?.id === p.path) && a.release.source === 'live'); const cur = portfolio?.apps.find(a => (a.project === p.path || a.app?.id === p.path) && a.release.source === 'live');
return cur ?? live?.value.apps.find(a => a.project === p.path || a.app?.id === p.path); return cur ?? live?.value.apps.find(a => a.project === p.path || a.app?.id === p.path);
}, [portfolio, live]); }, [portfolio, live]);
const statusFor = useCallback((a: UnifiedApp) => (a.project ? statusOf(a.project) : portfolio?.apps.find(x => x.project === a.target) ?? live?.value.apps.find(x => x.project === a.target)), [statusOf, portfolio, live]);
const liveFor = useCallback((a: UnifiedApp) => (a.project ? liveOf(a.project) : portfolio?.apps.find(x => x.project === a.target && x.release.source === 'live') ?? live?.value.apps.find(x => x.project === a.target)), [liveOf, portfolio, live]);
const iconFor = useCallback((a: UnifiedApp) => (a.project ? icons[a.project.id] ?? a.storeIcon : a.storeIcon), [icons]);
const appByKey = useCallback((key: string) => apps.find(a => a.key === key), [apps]);
const value = useMemo<Data>(() => ({ const value = useMemo<Data>(() => ({
ready, info, projects, accounts, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError, icons, ready, info, projects, accounts, studios, overrides, settings, storeApps, accountHealth, apps, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError,
refreshPortfolio, reload, statusOf, liveOf, toasts, toast, updateToast, dismiss, cancelJob, importBusy, icons, refreshPortfolio, importApps, checkAccount, reload, updateOverrides, updateSettings, statusOf, liveOf, statusFor, liveFor, iconFor, appByKey,
}), [ready, info, projects, accounts, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError, icons, refreshPortfolio, reload, statusOf, liveOf, toasts, toast, updateToast, dismiss, cancelJob]); toasts, toast, updateToast, dismiss, cancelJob,
}), [ready, info, projects, accounts, studios, overrides, settings, storeApps, accountHealth, apps, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError,
importBusy, icons, refreshPortfolio, importApps, checkAccount, reload, updateOverrides, updateSettings, statusOf, liveOf, statusFor, liveFor, iconFor, appByKey,
toasts, toast, updateToast, dismiss, cancelJob]);
return <Ctx.Provider value={value}>{children}</Ctx.Provider>; return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
} }
@ -183,16 +304,31 @@ export interface ReadState<T> {
refresh: () => Promise<void>; refresh: () => Promise<void>;
} }
/** Notifications a fresh read may trigger (Settings > Notifications), compared with the read it replaces. */
function notifyAfterRead(method: string, prev: unknown, next: unknown, settings: Settings, appName: string | undefined): void {
const name = appName ?? '';
if (method === 'reviews.list' && settings.notify.lowReviews && Array.isArray(next)) {
const fresh = newLowReviews(prev as Review[] | null, next as Review[]);
if (fresh.length) api.notify(t('notify.lowTitle', { name, count: fresh.length }), `${'★'.repeat(fresh[0]!.rating)} ${fresh[0]!.title ?? ''} ${fresh[0]!.body}`.trim()).catch(() => {});
}
if (method === 'health' && settings.notify.crash && next && typeof next === 'object') {
const crossed = crashCrossed(prev as HealthSnapshot | null, next as HealthSnapshot);
if (crossed.length && !isError((next as HealthSnapshot).play)) api.notify(t('notify.crashTitle', { name }), crossed.map(k => (k === 'crash' ? t('health.crash') : t('health.anr'))).join(', ')).catch(() => {});
}
}
/** /**
* One read method of one app. The cached value shows at once with its time; offline reads (`network: false`) then * One read method of one app (a project id, or a store-only app's store target). The cached value shows at once with
* refresh by themselves, store reads only on demand (they use the account's API quota). A failed read keeps the last * its time; offline reads (`network: false`) then refresh by themselves, store reads only on demand (they use the
* good value and says so: never an empty "all fine". * account's API quota). A failed read keeps the last good value and says so: never an empty "all fine".
*/ */
export function useRead<T>(projectId: string, method: string, o: { network: boolean; args?: Record<string, unknown>; title?: string }): ReadState<T> { export function useRead<T>(target: string, method: string, o: { network: boolean; args?: Record<string, unknown>; title?: string; appName?: string; skip?: boolean }): ReadState<T> {
const d = useData(); const d = useData();
const argsKey = JSON.stringify(o.args ?? {}); const argsKey = JSON.stringify(o.args ?? {});
const [s, set] = useState<Omit<ReadState<T>, 'refresh'>>({ data: null, at: null, fromCache: false, loading: true, error: null, command: null }); const [s, set] = useState<Omit<ReadState<T>, 'refresh'>>({ data: null, at: null, fromCache: false, loading: true, error: null, command: null });
const seq = useRef(0); const seq = useRef(0);
const dataRef = useRef<T | null>(null);
dataRef.current = s.data;
const refresh = useCallback(async () => { const refresh = useCallback(async () => {
const my = ++seq.current; const my = ++seq.current;
@ -200,9 +336,10 @@ export function useRead<T>(projectId: string, method: string, o: { network: bool
set(x => ({ ...x, loading: true, error: null })); set(x => ({ ...x, loading: true, error: null }));
const tid = o.network ? d.toast({ id: job, kind: 'job', title: o.title ?? t('toast.reading'), detail: t('toast.readingDetail'), progress: null, job }) : null; const tid = o.network ? d.toast({ id: job, kind: 'job', title: o.title ?? t('toast.reading'), detail: t('toast.readingDetail'), progress: null, job }) : null;
try { try {
const r = await api.call<ToolResult>(method, projectId, { args: JSON.parse(argsKey) as Record<string, unknown> }, job); const r = await api.call<ToolResult>(method, target, { args: JSON.parse(argsKey) as Record<string, unknown> }, job);
if (my !== seq.current) return; if (my !== seq.current) return;
if (r.ok && r.data !== undefined) { if (r.ok && r.data !== undefined) {
notifyAfterRead(method, dataRef.current, r.data, d.settings, o.appName);
set({ data: r.data as T, at: new Date().toISOString(), fromCache: false, loading: false, error: null, command: r.command }); set({ data: r.data as T, at: new Date().toISOString(), fromCache: false, loading: false, error: null, command: r.command });
if (tid) d.updateToast(tid, { kind: 'ok', title: t('toast.readOk', { what: o.title ?? method }), detail: undefined, progress: undefined, job: undefined }); if (tid) d.updateToast(tid, { kind: 'ok', title: t('toast.readOk', { what: o.title ?? method }), detail: undefined, progress: undefined, job: undefined });
} else { } else {
@ -216,19 +353,20 @@ export function useRead<T>(projectId: string, method: string, o: { network: bool
set(x => ({ ...x, loading: false, error: msg })); set(x => ({ ...x, loading: false, error: msg }));
if (tid) d.updateToast(tid, { kind: /cancel/i.test(msg) ? 'info' : 'bad', title: /cancel/i.test(msg) ? t('toast.cancelled') : t('toast.readFailedWhat', { what: o.title ?? method }), detail: msg, progress: undefined, job: undefined }); if (tid) d.updateToast(tid, { kind: /cancel/i.test(msg) ? 'info' : 'bad', title: /cancel/i.test(msg) ? t('toast.cancelled') : t('toast.readFailedWhat', { what: o.title ?? method }), detail: msg, progress: undefined, job: undefined });
} }
}, [projectId, method, argsKey, o.network, o.title]); // eslint-disable-line react-hooks/exhaustive-deps }, [target, method, argsKey, o.network, o.title, o.appName, d.settings]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => { useEffect(() => {
let alive = true; let alive = true;
if (o.skip) { set({ data: null, at: null, fromCache: false, loading: false, error: null, command: null }); return; }
set({ data: null, at: null, fromCache: false, loading: true, error: null, command: null }); set({ data: null, at: null, fromCache: false, loading: true, error: null, command: null });
api.cached<ToolResult>(method, projectId, JSON.parse(argsKey) as Record<string, unknown>).then(c => { api.cached<ToolResult>(method, target, JSON.parse(argsKey) as Record<string, unknown>).then(c => {
if (!alive) return; if (!alive) return;
if (c && c.value.data !== undefined) set({ data: c.value.data as T, at: c.at, fromCache: true, loading: !o.network, error: null, command: c.value.command }); if (c && c.value.data !== undefined) set({ data: c.value.data as T, at: c.at, fromCache: true, loading: !o.network, error: null, command: c.value.command });
else set(x => ({ ...x, loading: !o.network })); else set(x => ({ ...x, loading: !o.network }));
if (!o.network) refresh(); if (!o.network) refresh();
}, () => { if (alive) { set(x => ({ ...x, loading: !o.network })); if (!o.network) refresh(); } }); }, () => { if (alive) { set(x => ({ ...x, loading: !o.network })); if (!o.network) refresh(); } });
return () => { alive = false; }; return () => { alive = false; };
}, [projectId, method, argsKey]); // eslint-disable-line react-hooks/exhaustive-deps }, [target, method, argsKey, o.skip]); // eslint-disable-line react-hooks/exhaustive-deps
return { ...s, refresh }; return { ...s, refresh };
} }

View file

@ -632,3 +632,119 @@ h2[tabindex="-1"]:focus, h2[tabindex="-1"]:focus-visible { outline: none; }
.tbad { color: var(--bad-ink); } .twarn { color: var(--warn-ink); } .tbad { color: var(--bad-ink); } .twarn { color: var(--warn-ink); }
.table .mini, .table .mini > * { white-space: nowrap; } .table .mini, .table .mini > * { white-space: nowrap; }
.table .mini .row { flex-wrap: nowrap; } .table .mini .row { flex-wrap: nowrap; }
/* ---- D3: studios, store-only apps, toolbar, accounts, settings ---- */
:root {
--st-indigo: #4f46e5; --st-violet: #7c3aed; --st-rose: #e11d48; --st-amber: #b45309;
--st-emerald: #047857; --st-teal: #0f766e; --st-sky: #0369a1; --st-slate: #475569;
}
.studio-indigo { --st: var(--st-indigo); } .studio-violet { --st: var(--st-violet); } .studio-rose { --st: var(--st-rose); } .studio-amber { --st: var(--st-amber); }
.studio-emerald { --st: var(--st-emerald); } .studio-teal { --st: var(--st-teal); } .studio-sky { --st: var(--st-sky); } .studio-slate { --st: var(--st-slate); }
.studio-mark { display: inline-grid; place-items: center; flex: none; overflow: hidden; color: #fff; font-weight: 760; letter-spacing: .02em;
background: linear-gradient(140deg, color-mix(in srgb, var(--st, var(--st-slate)) 82%, #fff), var(--st, var(--st-slate))); box-shadow: inset 0 0 0 1px rgba(0, 0, 0, .08); }
.studio-mark img { width: 100%; height: 100%; object-fit: cover; }
.studio-mark.sm { width: 16px; height: 16px; border-radius: 5px; font-size: 7.5px; }
.studio-mark.md { width: 28px; height: 28px; border-radius: 8px; font-size: 11px; }
.studio-mark.lg { width: 40px; height: 40px; border-radius: 11px; font-size: 14px; }
.studio-mark.none { background: transparent; box-shadow: inset 0 0 0 1.5px var(--line-2); border: 0; }
.studio-mark.none.sm { box-shadow: inset 0 0 0 1.5px var(--faint); }
.so-tag { height: 20px; padding: 0 7px; font-size: 10.5px; gap: 4px; }
.so-tag svg { width: 12px; height: 12px; }
.so-dot { display: inline-grid; place-items: center; color: var(--faint); }
.so-dot svg { width: 13px; height: 13px; }
.nav[aria-current="page"] .so-dot svg { color: var(--faint); }
/* sidebar studio groups */
.side-group { margin-top: 2px; }
.side-group-head { all: unset; box-sizing: border-box; width: 100%; display: flex; align-items: center; gap: 8px; height: 28px; padding: 0 8px 0 6px; border-radius: 7px; cursor: pointer;
font-size: var(--t-meta); font-weight: 650; color: var(--ink-2); transition: background-color var(--speed) var(--ease); }
.side-group-head:hover { background: var(--hover); color: var(--ink); }
.side-group-head:focus-visible { outline: 2px solid var(--focus); outline-offset: -2px; }
.side-group-head .chev { width: 12px; height: 12px; color: var(--muted); transition: transform var(--speed) var(--ease); }
.side-group-head[aria-expanded="true"] .chev { transform: rotate(90deg); }
.side-group-head .grow { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.side-group-head .count { font-size: var(--t-micro); color: var(--muted); font-weight: 560; font-variant-numeric: tabular-nums; }
.side-group [role="list"] { padding-left: 12px; margin-left: 13px; border-left: 1px solid var(--line); }
.side-group .nav-app { height: 32px; }
/* portfolio toolbar */
.toolbar { display: flex; align-items: center; flex-wrap: wrap; gap: 10px 12px; }
.toolbar .search-input { width: 260px; }
.toolbar .search-input .input { height: 32px; }
.toolbar .grow { flex: 1; }
.fchips { display: flex; flex-wrap: wrap; gap: 6px; }
.fchip { all: unset; box-sizing: border-box; display: inline-flex; align-items: center; gap: 7px; height: 30px; padding: 0 11px 0 9px; border-radius: 999px; cursor: pointer;
background: var(--surface); border: 1px solid var(--line); color: var(--ink-2); font-size: var(--t-meta); font-weight: 600; box-shadow: var(--shadow-1);
transition: background-color var(--speed) var(--ease), border-color var(--speed) var(--ease); }
.fchip:hover { background: var(--hover); color: var(--ink); }
.fchip:focus-visible { outline: 2px solid var(--focus); outline-offset: 1px; }
.fchip .n { font-size: var(--t-micro); font-weight: 650; color: var(--muted); font-variant-numeric: tabular-nums; padding: 1px 6px; border-radius: 999px; background: var(--bg-sunken); }
.fchip[aria-pressed="true"] { background: var(--accent-soft); border-color: var(--accent-line); color: var(--accent); }
.fchip[aria-pressed="true"] .n { background: var(--surface); color: var(--accent); }
.table tbody tr.group-row td { background: var(--surface-2); padding-top: 9px; padding-bottom: 9px; border-top: 1px solid var(--line); }
.table tbody tr.group-row b { font-weight: 680; }
.table tbody tr.group-row:hover td { background: var(--surface-2); }
.table tbody + tbody tr.group-row td { border-top: 1px solid var(--line-2); }
/* studios & accounts */
.studio-card .card-head { align-items: center; }
.studio-card.focus { box-shadow: var(--shadow-2), 0 0 0 2px var(--accent-line); }
.studio-edit { display: grid; grid-template-columns: minmax(200px, 320px) 1fr auto; gap: 16px; align-items: end; border-bottom: 1px solid var(--line); }
.acct-list { display: grid; }
.acct { border-top: 1px solid var(--line); }
.acct.is-ignored .acct-row { opacity: .62; }
.acct-row { display: flex; align-items: center; gap: 14px; padding: 12px 18px; }
.acct-glyph { width: 32px; height: 32px; border-radius: 9px; display: grid; place-items: center; flex: none; background: var(--bg-sunken); border: 1px solid var(--line); }
.acct-glyph svg { width: 16px; height: 16px; }
.acct-main { flex: 1; min-width: 0; display: grid; gap: 3px; }
.acct-main .small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.acct-edit { display: grid; grid-template-columns: minmax(180px, 1fr) minmax(180px, 1fr) auto; gap: 12px; align-items: end; padding: 0 18px 14px 64px; }
.acct-fix { padding: 0 18px 14px 64px; }
.swatches { display: flex; flex-wrap: wrap; gap: 8px; }
.swatch { all: unset; box-sizing: border-box; width: 26px; height: 26px; border-radius: 8px; display: grid; place-items: center; cursor: pointer; color: #fff;
background: var(--st); box-shadow: inset 0 0 0 1px rgba(0, 0, 0, .1); transition: transform var(--speed) var(--ease); }
.swatch:hover { transform: translateY(-1px); }
.swatch:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
.swatch[aria-checked="true"] { box-shadow: 0 0 0 2px var(--surface), 0 0 0 4px var(--st); }
.swatch svg { width: 14px; height: 14px; }
/* app page: studio pill, pairing controls */
.studio-pill { all: unset; box-sizing: border-box; display: inline-flex; align-items: center; gap: 7px; height: 24px; padding: 0 10px 0 5px; border-radius: 999px; cursor: pointer;
background: var(--surface); border: 1px solid var(--line); font-size: var(--t-micro); font-weight: 650; color: var(--ink-2); }
.studio-pill:hover { background: var(--hover); color: var(--ink); }
.studio-pill:focus-visible { outline: 2px solid var(--focus); }
.app-controls { display: flex; align-items: center; flex-wrap: wrap; gap: 8px 16px; padding: 8px 12px; border: 1px solid var(--line); border-radius: var(--r); background: var(--surface-2); }
.input.input-sm, select.input.input-sm { height: 28px; padding: 0 8px; font-size: var(--t-meta); width: auto; max-width: 280px; }
/* settings */
.set-layout { display: grid; grid-template-columns: 210px minmax(0, 1fr); gap: 24px; align-items: start; }
.set-nav { position: sticky; top: 0; display: grid; gap: 1px; padding: 6px; border: 1px solid var(--line); border-radius: var(--r-lg); background: var(--surface); box-shadow: var(--shadow-1); }
.set-nav .nav { height: 30px; font-size: var(--t-meta); }
.set-nav .nav[aria-current="true"] { background: var(--accent-soft); color: var(--accent); font-weight: 650; }
.set-nav .nav[aria-current="true"] svg { color: var(--accent); }
.set-body .card { scroll-margin-top: 12px; }
.toggle-row { display: flex; align-items: center; gap: 16px; padding: 10px 0; border-top: 1px solid var(--line); cursor: pointer; }
.toggle-row:first-child { border-top: 0; padding-top: 0; }
.toggle-row .grow { display: grid; gap: 2px; }
.switch { appearance: none; -webkit-appearance: none; flex: none; width: 36px; height: 21px; border-radius: 999px; background: var(--line-2); position: relative; cursor: pointer; margin: 0;
transition: background-color var(--speed) var(--ease); }
.switch::after { content: ""; position: absolute; top: 2.5px; left: 2.5px; width: 16px; height: 16px; border-radius: 50%; background: #fff; box-shadow: 0 1px 2px rgba(0, 0, 0, .3); transition: transform var(--speed) var(--ease); }
.switch:checked { background: var(--accent-solid); }
.switch:checked::after { transform: translateX(15px); }
.switch:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
.studio-sum { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 10px; }
.studio-sum-item { all: unset; box-sizing: border-box; display: flex; align-items: center; gap: 12px; padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--r); cursor: pointer; background: var(--surface-2); }
.studio-sum-item:hover { background: var(--hover); }
.studio-sum-item:focus-visible { outline: 2px solid var(--focus); }
.dep-sum { display: flex; flex-wrap: wrap; gap: 8px 20px; }
.plain-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }
.plain-list li { display: flex; gap: 10px; align-items: flex-start; font-size: var(--t-body); color: var(--ink-2); }
.plain-list svg { width: 15px; height: 15px; color: var(--ok-solid); flex: none; margin-top: 2px; }
.danger-card { border-color: color-mix(in srgb, var(--bad-solid) 35%, var(--line)); }
.btn.btn-danger:not(.btn-ghost) { color: var(--bad-ink); background: var(--bad-bg); border-color: color-mix(in srgb, var(--bad-solid) 40%, transparent); }
@media (max-width: 1100px) { .set-layout { grid-template-columns: 1fr; } .set-nav { position: static; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); } .studio-edit, .acct-edit { grid-template-columns: 1fr; } }
.cell-app .s .so-inline { display: inline-flex; align-items: center; gap: 4px; margin-left: 8px; font-family: var(--font); font-size: var(--t-micro); font-weight: 650; color: var(--muted); }
.cell-app .s .so-inline svg { width: 12px; height: 12px; }
.toolbar .search-input { width: 240px; }

View file

@ -47,6 +47,20 @@ const P = {
keyboard: 'M3.5 6.5h17A1 1 0 0 1 21.5 7.5v9a1 1 0 0 1-1 1h-17a1 1 0 0 1-1-1v-9a1 1 0 0 1 1-1zM6.5 10h.1M10 10h.1M13.5 10h.1M17 10h.1M7.5 14h9', keyboard: 'M3.5 6.5h17A1 1 0 0 1 21.5 7.5v9a1 1 0 0 1-1 1h-17a1 1 0 0 1-1-1v-9a1 1 0 0 1 1-1zM6.5 10h.1M10 10h.1M13.5 10h.1M17 10h.1M7.5 14h9',
database: 'M12 8c4.4 0 8-1.3 8-3s-3.6-3-8-3-8 1.3-8 3 3.6 3 8 3zM4 5v14c0 1.7 3.6 3 8 3s8-1.3 8-3V5M4 12c0 1.7 3.6 3 8 3s8-1.3 8-3', database: 'M12 8c4.4 0 8-1.3 8-3s-3.6-3-8-3-8 1.3-8 3 3.6 3 8 3zM4 5v14c0 1.7 3.6 3 8 3s8-1.3 8-3V5M4 12c0 1.7 3.6 3 8 3s8-1.3 8-3',
wand: 'M14.5 6.5l3 3M4 20 17.5 6.5l-3-3L1 17zM19 2.5v3M20.5 4h-3M21 10v2M22 11h-2', wand: 'M14.5 6.5l3 3M4 20 17.5 6.5l-3-3L1 17zM19 2.5v3M20.5 4h-3M21 10v2M22 11h-2',
building: 'M4.5 20.5V5A1.5 1.5 0 0 1 6 3.5h7A1.5 1.5 0 0 1 14.5 5v15.5M14.5 9.5H18a1.5 1.5 0 0 1 1.5 1.5v9.5M3 20.5h18M8 7.5h3M8 11h3M8 14.5h3',
eye: 'M2.5 12c1-1.5 4.5-6 9.5-6s8.5 4.5 9.5 6c-1 1.5-4.5 6-9.5 6s-8.5-4.5-9.5-6zM12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z',
eyeOff: 'M3 3l18 18M10.6 6.1c.5-.1.9-.1 1.4-.1 5 0 8.5 4.5 9.5 6-.5.8-1.6 2.3-3.2 3.6M6.4 7.9C4.7 9.2 3.5 10.9 2.5 12c1 1.5 4.5 6 9.5 6 1.5 0 2.9-.4 4.1-1M9.9 9.9a3 3 0 0 0 4.2 4.2',
link: 'M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1',
unlink: 'M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1M4 4l16 16',
bell: 'M6 16.5V11a6 6 0 1 1 12 0v5.5l1.5 2h-15zM10 20.5a2 2 0 0 0 4 0',
filter: 'M4 5.5h16l-6 7.5v5.5l-4 1.5v-7z',
play: 'M8 5.5v13l10.5-6.5z',
send: 'M4 11.5 20 4l-6 16-3-6.5zM11 13.5 20 4',
edit: 'M4 20h4L19 9l-4-4L4 16zM13.5 6.5l4 4',
upload: 'M12 20V9M7.5 13.5 12 9l4.5 4.5M4.5 4.5h15',
sliders: 'M4 6.5h9M17 6.5h3M4 12h3M11 12h9M4 17.5h11M19 17.5h1M15 4.5v4M9 10v4M17 15.5v4',
rotate: 'M4 12a8 8 0 1 0 2.4-5.7L4 8.5M4 4v4.5h4.5',
cloud: 'M7 18.5h10.5a4 4 0 0 0 .6-8 6 6 0 0 0-11.6 1.6A3.3 3.3 0 0 0 7 18.5z',
} as const; } as const;
export type IconName = keyof typeof P; export type IconName = keyof typeof P;

View file

@ -137,9 +137,9 @@ export function Seg<T extends string>({ value, options, onChange, label }: { val
); );
} }
export function Card({ title, icon, sub, actions, children, foot, className = '', pad = true }: { title?: ReactNode; icon?: IconName; sub?: ReactNode; actions?: ReactNode; children: ReactNode; foot?: ReactNode; className?: string; pad?: boolean }) { export function Card({ title, icon, sub, actions, children, foot, className = '', pad = true, id }: { title?: ReactNode; icon?: IconName; sub?: ReactNode; actions?: ReactNode; children: ReactNode; foot?: ReactNode; className?: string; pad?: boolean; id?: string }) {
return ( return (
<section className={`card ${className}`}> <section className={`card ${className}`} id={id}>
{title !== undefined && ( {title !== undefined && (
<div className="card-head"> <div className="card-head">
<div className="stack" style={{ gap: 2 }}><h2>{icon && <Icon name={icon} />}{title}</h2>{sub && <div className="sub">{sub}</div>}</div> <div className="stack" style={{ gap: 2 }}><h2>{icon && <Icon name={icon} />}{title}</h2>{sub && <div className="sub">{sub}</div>}</div>
@ -158,3 +158,15 @@ export function Kbd({ keys }: { keys: string[] }) {
/** Platform modifier label (⌘ on macOS, Ctrl elsewhere). */ /** Platform modifier label (⌘ on macOS, Ctrl elsewhere). */
export const MOD = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform) ? '⌘' : 'Ctrl'; export const MOD = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform) ? '⌘' : 'Ctrl';
/** A studio's logo, or its monogram on the studio colour. `null` studio: "No studio" (dashed). */
export function StudioMark({ studio, size = 'md' }: { studio: { name: string; color: string; logo?: string | null } | null; size?: 'sm' | 'md' | 'lg' }) {
if (!studio) return <span className={`studio-mark none ${size}`} aria-hidden="true" />;
if (studio.logo) return <span className={`studio-mark ${size}`} aria-hidden="true"><img src={studio.logo} alt="" draggable={false} /></span>;
return <span className={`studio-mark studio-${studio.color} ${size}`} aria-hidden="true">{monogram(studio.name)}</span>;
}
/** Small "store only" marker (an app without an app folder). */
export function StoreOnlyTag() {
return <span className="chip outline so-tag" title={t('apps.storeOnlyHint')}><Icon name="cloud" />{t('apps.storeOnly')}</span>;
}

View file

@ -0,0 +1,143 @@
// One app card per product across studios and store accounts: folder matching, automatic pairing (same id, close id,
// same name), manual pair / unpair, links, studio moves, the ignore list, and the portfolio filter / sort / grouping.
import { describe, expect, test } from 'bun:test';
import type { Account, Project, ProjectSummary, StoreApp } from '../src/api';
import {
buildApps, filterSort, groupByStudio, type ListRow, NO_OVERRIDES, normId, normName, type Overrides, pairCandidates, storeTarget, studioCounts,
withIgnored, withLink, withPair, withStudio, withUnpair,
} from '../src/lib/identity';
import { crashCrossed, newLowReviews, releaseChanges } from '../src/lib/notify';
const P1 = '0a1b2c3d4e5f6071', A1 = '2c3d4e5f60718293', A2 = '3d4e5f6071829304';
const acc = (id: string, kind: 'play' | 'apple', studio: string | null): Account => ({ id, label: id, kind, created: '2026-10-01T00:00:00Z', studio });
const ios = (id: string, bundleId: string, name: string): StoreApp => ({ store: 'ios', id, bundleId, name, platforms: ['IOS'], icon: null });
const droid = (pkg: string, name: string): StoreApp => ({ store: 'android', id: pkg, bundleId: pkg, name, platforms: ['ANDROID'], icon: null });
const summary = (bundleId: string | null, pkg: string | null, appId: string | null = null): ProjectSummary => ({
dir: '/x', config: '/x/c', name: 'x', languages: ['en'], apple: bundleId ? { bundleId, appId } : null, play: pkg ? { packageName: pkg } : null,
platforms: [], products: 0, productIds: [], subscriptions: 0, subscriptionIds: [], catalog: { ios: [], android: [] }, shots: false, testflightGroups: 0,
});
const proj = (id: string, name: string, play: string | null, apple: string | null): Project => ({ id, path: `/apps/${id}`, name, playAccount: play, appleAccount: apple, added: '2026-10-01T00:00:00Z' });
const accounts = [acc(P1, 'play', 's1'), acc(A1, 'apple', 's1'), acc(A2, 'apple', 's2')];
const storeApps = [
{ account: P1, apps: [droid('com.example.prism', 'Prism'), droid('com.example.orbit', 'Orbit Hop'), droid('com.example.block', 'Block Garden'), droid('com.example.lantern.words', 'Word Lantern'), droid('com.example.tycoon', 'Pocket Tycoon')] },
{ account: A1, apps: [ios('101', 'com.example.prism', 'Prism'), ios('102', 'com.example.orbit', 'Orbit Hop'), ios('103', 'com.example.Block.ios', 'Block Garden HD'), ios('104', 'com.example.wordlantern', 'Word Lantern')] },
{ account: A2, apps: [ios('201', 'com.example.habit', 'Habit Hatch')] },
];
const prism = proj('p1', 'Prism Puddle', P1, A1);
const build = (o: Overrides = NO_OVERRIDES, projects = [prism]) => buildApps({ projects, accounts, storeApps, overrides: o, summaryOf: p => (p.id === 'p1' ? summary('com.example.prism', 'com.example.prism') : summary(null, null)) });
const byName = (apps: ReturnType<typeof build>, n: string) => apps.find(a => a.name === n)!;
describe('identity pairing', () => {
test('a folder takes the store apps its config names; the rest pair by id, close id, then name', () => {
const apps = build();
expect(apps.map(a => [a.name, a.pairing, !!a.ios, !!a.android])).toEqual([
['Prism Puddle', 'folder', true, true],
['Orbit Hop', 'id', true, true],
['Block Garden HD', 'close', true, true],
['Word Lantern', 'name', true, true],
['Pocket Tycoon', 'single', false, true],
['Habit Hatch', 'single', true, false],
]);
expect(byName(apps, 'Prism Puddle')).toMatchObject({ key: 'p1', target: 'p1', studio: 's1', ios: { key: `ios:${A1}:101` }, android: { key: `android:${P1}:com.example.prism` } });
const orbit = byName(apps, 'Orbit Hop');
expect(orbit.target).toBe(`store:ios:${A1}:102:com.example.orbit;android:${P1}:com.example.orbit`);
expect(orbit.key).toBe(orbit.target);
expect(orbit.ignoreKeys).toEqual([`app:ios:${A1}:102`, `app:android:${P1}:com.example.orbit`]);
expect(byName(apps, 'Habit Hatch').studio).toBe('s2');
});
test('the app id in the config wins over the bundle id; accounts mapped to the folder are preferred', () => {
const twin = [...storeApps, { account: A2, apps: [ios('999', 'com.example.prism', 'Prism (old team)')] }];
const apps = buildApps({ projects: [prism], accounts, storeApps: twin, overrides: NO_OVERRIDES, summaryOf: () => summary('com.example.prism', 'com.example.prism', '999') });
expect(apps[0]!.ios?.app.id).toBe('999');
const apps2 = buildApps({ projects: [prism], accounts, storeApps: twin, overrides: NO_OVERRIDES, summaryOf: () => summary('com.example.prism', 'com.example.prism') });
expect(apps2[0]!.ios?.account).toBe(A1);
});
test('unpair blocks the automatic pair; manual pair beats it', () => {
const o1 = withUnpair(NO_OVERRIDES, `ios:${A1}:102`, `android:${P1}:com.example.orbit`);
const apps1 = build(o1);
expect(apps1.filter(a => a.name === 'Orbit Hop').map(a => [!!a.ios, !!a.android, a.pairing])).toEqual([[false, true, 'single'], [true, false, 'single']]);
const o2 = withPair(o1, `ios:${A1}:102`, `android:${P1}:com.example.tycoon`);
expect(o2.unpairs).toHaveLength(1);
const apps2 = build(o2);
const manual = apps2.find(a => a.pairing === 'manual')!;
expect([manual.ios?.app.id, manual.android?.app.id]).toEqual(['102', 'com.example.tycoon']);
// pairing the unpaired two again drops the unpair
expect(withPair(o1, `ios:${A1}:102`, `android:${P1}:com.example.orbit`).unpairs).toEqual([]);
});
test('links: a store-only app joins a folder by hand', () => {
const orbit = byName(build(), 'Orbit Hop');
const fresh = proj('p2', 'Orbit (folder)', null, null);
const apps = build(withLink(NO_OVERRIDES, orbit, 'p2'), [prism, fresh]);
const linked = apps.find(a => a.key === 'p2')!;
expect([linked.ios?.app.id, linked.android?.app.id, linked.pairing]).toEqual(['102', 'com.example.orbit', 'folder']);
expect(apps.some(a => a.name === 'Orbit Hop' && !a.project)).toBe(false);
});
test('ignore: an app (all its store keys) or a whole account; studio moves', () => {
const tycoon = byName(build(), 'Pocket Tycoon');
const o = withIgnored(NO_OVERRIDES, tycoon.ignoreKeys, true);
expect(byName(build(o), 'Pocket Tycoon').ignored).toBe(true);
expect(withIgnored(o, tycoon.ignoreKeys, false).ignored).toEqual([]);
const noA1 = build(withIgnored(NO_OVERRIDES, [`account:${A1}`], true));
expect(noA1.some(a => a.ios?.account === A1)).toBe(false);
expect(byName(noA1, 'Orbit Hop').ios).toBeNull();
const moved = build(withStudio(NO_OVERRIDES, tycoon, 's2'));
expect(byName(moved, 'Pocket Tycoon').studio).toBe('s2');
const back = withStudio(withStudio(NO_OVERRIDES, tycoon, 's2'), tycoon, null);
expect(back.appStudio).toEqual([]);
expect(withStudio(NO_OVERRIDES, byName(build(), 'Prism Puddle'), 's9').appStudio).toEqual([{ key: 'project:p1', studio: 's9' }]);
expect(studioCounts(build(o))).toEqual({ s1: 4, s2: 1 });
});
test('accounts that are gone or never read add nothing', () => {
const apps = buildApps({ projects: [], accounts: [acc(P1, 'play', null)], storeApps: [{ account: 'deadbeefdeadbeef', apps: [droid('com.example.x', 'X')] }], overrides: NO_OVERRIDES, summaryOf: () => undefined });
expect(apps).toEqual([]);
});
test('helpers: normalised ids and names, store targets, pair candidates', () => {
expect(normId('com.Example.Block.ios')).toBe(normId('com.example.block'));
expect(normId('com.example.block-android')).toBe('comexampleblock');
expect(normName('Word Lantern!')).toBe(normName('word-lantern'));
expect(storeTarget(null, { key: 'k', account: P1, store: 'android', app: droid('com.a.b', 'B') })).toBe(`store:android:${P1}:com.a.b`);
const apps = build(withUnpair(NO_OVERRIDES, `ios:${A1}:102`, `android:${P1}:com.example.orbit`));
const lone = apps.find(a => a.name === 'Orbit Hop' && a.ios)!;
expect(pairCandidates(lone, apps)[0]!.android?.app.id).toBe('com.example.orbit');
expect(pairCandidates(byName(apps, 'Prism Puddle'), apps)).toEqual([]);
});
});
describe('portfolio list', () => {
const apps = build();
const rows: ListRow[] = apps.map((app, i) => ({ app, attention: [0, 3, 1, 0, 2, 0][i]!, blockers: [0, 1, 0, 0, 0, 0][i]!, updated: [`2026-10-0${i + 1}`, null, '2026-10-09', null, '2026-09-01', '2026-10-05'][i]! }));
test('filter by studio and search ids, sort by attention / recent / name', () => {
expect(filterSort(rows, { studio: 'all', query: '', sort: 'attention' }).map(r => r.app.name).slice(0, 3)).toEqual(['Orbit Hop', 'Pocket Tycoon', 'Block Garden HD']);
expect(filterSort(rows, { studio: 'all', query: '', sort: 'recent' }).map(r => r.app.name)[0]).toBe('Block Garden HD');
expect(filterSort(rows, { studio: 's2', query: '', sort: 'name' }).map(r => r.app.name)).toEqual(['Habit Hatch']);
expect(filterSort(rows, { studio: 'all', query: 'lantern.words', sort: 'name' }).map(r => r.app.name)).toEqual(['Word Lantern']);
expect(filterSort(rows, { studio: 'none', query: '', sort: 'name' })).toEqual([]);
});
test('groups follow the studios\' order, no studio last; ignored apps never listed', () => {
const g = groupByStudio(rows, [{ id: 's2' }, { id: 's1' }]);
expect(g.map(x => [x.studio, x.rows.length])).toEqual([['s2', 1], ['s1', 5]]);
const ignored = rows.map(r => (r.app.name === 'Habit Hatch' ? { ...r, app: { ...r.app, ignored: true } } : r));
expect(filterSort(ignored, { studio: 'all', query: '', sort: 'name' }).some(r => r.app.name === 'Habit Hatch')).toBe(false);
});
});
describe('notifications', () => {
const status = (phase: string) => ({ apps: [{ project: '/a', ok: true, app: { id: '/a', name: 'A', platforms: { ios: null, android: null } }, summary: null, check: null, catalog: null, storeErrors: {}, errors: [],
release: { source: 'live' as const, current: null, next: null, all: [{ store: 'ios' as const, version: '2.0', build: '1', state: phase, phase: phase as 'review', fraction: null, track: null }] } }], at: 'x' });
test('release phase changes, only against a previous read', () => {
expect(releaseChanges(null, status('review'))).toEqual([]);
expect(releaseChanges(status('review'), status('review'))).toEqual([]);
expect(releaseChanges(status('review'), status('approved'))).toEqual([{ project: '/a', name: 'A', store: 'ios', version: '2.0', from: 'review', to: 'approved' }]);
expect(releaseChanges(status('draft'), status('testing'))).toEqual([]);
});
test('new 1-2 star reviews and threshold crossings', () => {
const r = (id: string, rating: number) => ({ store: 'play' as const, id, rating, body: '', date: '2026-10-01' });
expect(newLowReviews(null, [r('a', 1)])).toEqual([]);
expect(newLowReviews([r('a', 1)], [r('a', 1), r('b', 2), r('c', 5)]).map(x => x.id)).toEqual(['b']);
const h = (crash: number) => ({ date: 'x', play: { window: { start: '', end: '', days: 28 }, anr: [], issues: [], crash: [{ date: '2026-10-01', dims: {}, values: { userPerceivedCrashRate: crash } }] } });
expect(crashCrossed(h(0.005), h(0.02))).toEqual(['crash']);
expect(crashCrossed(h(0.02), h(0.03))).toEqual([]);
expect(crashCrossed(null, h(0.03))).toEqual([]);
});
});