From 266c0d1d25452b12a13335b711381eff192fe437 Mon Sep 17 00:00:00 2001 From: Lightning Pixel Date: Sat, 14 Nov 2026 21:49:48 +0100 Subject: [PATCH] feat(home): add a Home page with recent creations and quick start The app now opens on a Home page, first in the sidebar: - the Modly logo above a centred welcome - a drop zone that hands the image to Generate and opens it; Generate's workflow panel puts it in the first image input it shows, as if it had been browsed there - quick actions: open a workflow, import a mesh, browse the library - the six newest openable assets with thumbnails, reopened in Generate Settings > Application gets a Start page choice (Home or Generate) so users can keep the old behaviour; it lives in localStorage and is read by navStore at init. The imported-mesh job moves to a shared helper (meshJob.ts) used by Generate and Home, the setup wizard's logo becomes a shared ModlyLogo component, and LibraryGrid exports its Thumbnail. Closes #416 --- package.json | 2 +- src/areas/generate/GeneratePage.tsx | 15 +- .../generate/components/WorkflowPanel.tsx | 31 ++- src/areas/home/HomePage.tsx | 211 ++++++++++++++++++ src/areas/home/recents.test.ts | 44 ++++ src/areas/home/recents.ts | 38 ++++ src/areas/library/LibraryGrid.tsx | 2 +- .../components/ApplicationSection.tsx | 21 +- src/areas/setup/FirstRunSetup.tsx | 20 +- .../components/agent/clientTools.test.ts | 2 +- src/shared/components/ui/ModlyLogo.tsx | 19 ++ src/shared/pages/pageRegistry.test.ts | 1 + src/shared/pages/pageRegistry.ts | 11 + src/shared/pages/startPage.test.ts | 33 +++ src/shared/pages/startPage.ts | 28 +++ src/shared/stores/navStore.ts | 3 +- src/shared/utils/imageInput.ts | 30 +++ src/shared/utils/meshJob.ts | 21 ++ 18 files changed, 494 insertions(+), 38 deletions(-) create mode 100644 src/areas/home/HomePage.tsx create mode 100644 src/areas/home/recents.test.ts create mode 100644 src/areas/home/recents.ts create mode 100644 src/shared/components/ui/ModlyLogo.tsx create mode 100644 src/shared/pages/startPage.test.ts create mode 100644 src/shared/pages/startPage.ts create mode 100644 src/shared/utils/imageInput.ts create mode 100644 src/shared/utils/meshJob.ts diff --git a/package.json b/package.json index f7c15b511..41881a139 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "prepare-resources": "node scripts/download-python-embed.js", "test": "npm run test:py && npm run test:node", "test:py": "node scripts/run-pytests.mjs", - "test:node": "node --test --experimental-strip-types --experimental-loader ./scripts/node-ts-extensionless-loader.mjs src/shared/types/assetLibrary.test.ts src/areas/generate/assetLibraryProjection.test.ts src/areas/generate/assetLibraryService.test.ts src/areas/generate/assetLibraryUi.test.ts src/areas/library/libraryView.test.ts src/areas/library/gridWindow.test.ts src/areas/generate/orcaSlicerLink.test.ts src/shared/utils/agentStream.test.ts src/shared/thumbnails/assetThumbnailQueue.test.ts src/shared/thumbnails/assetThumbnailStore.test.ts src/shared/components/agent/clientTools.test.ts src/shared/components/agent/agentContext.test.ts src/shared/utils/ollamaHealth.test.ts src/shared/utils/notification.test.ts src/shared/utils/agentConversations.test.ts electron/main/artifact-registry-service.test.ts electron/main/asset-thumbnail-cache.test.ts electron/main/extension-path-guard.test.ts electron/main/storage-directory-guard.test.ts electron/main/storage-ownership.test.ts electron/main/startup-error.test.ts electron/main/api-port.test.ts electron/main/agent-conversations.test.ts electron/preload/artifact-registry-preload.test.ts src/shared/stores/meshHistory.test.ts src/areas/generate/meshEditPanel.test.ts src/areas/generate/sculpt/SculptMesh.test.ts src/areas/generate/sculpt/SculptMesh.perf.test.ts src/areas/generate/sculpt/sculptLogic.test.ts src/shared/pages/pageRegistry.test.ts src/areas/workflows/workflowRunRecord.test.ts && node --test electron/main/*.test.mjs src/**/*.test.mjs", + "test:node": "node --test --experimental-strip-types --experimental-loader ./scripts/node-ts-extensionless-loader.mjs src/shared/types/assetLibrary.test.ts src/areas/generate/assetLibraryProjection.test.ts src/areas/generate/assetLibraryService.test.ts src/areas/generate/assetLibraryUi.test.ts src/areas/library/libraryView.test.ts src/areas/library/gridWindow.test.ts src/areas/generate/orcaSlicerLink.test.ts src/shared/utils/agentStream.test.ts src/shared/thumbnails/assetThumbnailQueue.test.ts src/shared/thumbnails/assetThumbnailStore.test.ts src/shared/components/agent/clientTools.test.ts src/shared/components/agent/agentContext.test.ts src/shared/utils/ollamaHealth.test.ts src/shared/utils/notification.test.ts src/shared/utils/agentConversations.test.ts electron/main/artifact-registry-service.test.ts electron/main/asset-thumbnail-cache.test.ts electron/main/extension-path-guard.test.ts electron/main/storage-directory-guard.test.ts electron/main/storage-ownership.test.ts electron/main/startup-error.test.ts electron/main/api-port.test.ts electron/main/agent-conversations.test.ts electron/preload/artifact-registry-preload.test.ts src/shared/stores/meshHistory.test.ts src/areas/generate/meshEditPanel.test.ts src/areas/generate/sculpt/SculptMesh.test.ts src/areas/generate/sculpt/SculptMesh.perf.test.ts src/areas/generate/sculpt/sculptLogic.test.ts src/shared/pages/pageRegistry.test.ts src/shared/pages/startPage.test.ts src/areas/home/recents.test.ts src/areas/workflows/workflowRunRecord.test.ts && node --test electron/main/*.test.mjs src/**/*.test.mjs", "package": "cross-env CSC_IDENTITY_AUTO_DISCOVERY=false npm run build && npm run prepare-resources && electron-builder", "package:mac": "cross-env CSC_IDENTITY_AUTO_DISCOVERY=false npm run build && npm run prepare-resources && electron-builder --mac --arm64", "lint": "eslint ." diff --git a/src/areas/generate/GeneratePage.tsx b/src/areas/generate/GeneratePage.tsx index 759fb2bd9..b546ef3a2 100644 --- a/src/areas/generate/GeneratePage.tsx +++ b/src/areas/generate/GeneratePage.tsx @@ -1,7 +1,8 @@ import { useState, useRef, useCallback, useEffect, useMemo } from 'react' import type { ReactNode } from 'react' import { useAppStore, DEFAULT_LIGHT_SETTINGS } from '@shared/stores/appStore' -import type { GenerationJob, LightSettings, PointLight } from '@shared/stores/appStore' +import type { LightSettings, PointLight } from '@shared/stores/appStore' +import { showImportedMesh } from '@shared/utils/meshJob' import { redoDepth, undoDepth } from '@shared/stores/meshHistory' import { useApi } from '@shared/hooks/useApi' import { ColorPicker } from '@shared/components/ui' @@ -872,17 +873,7 @@ export default function GeneratePage(): JSX.Element { setImporting(true) try { const { url } = await importMesh(filePath) - const job: GenerationJob = { - id: `import-${Date.now()}`, - imageFile: '', - status: 'done', - progress: 100, - outputUrl: url, - originalOutputUrl: url, - createdAt: Date.now(), - } - setCurrentJob(job) - pushMeshUrl(url) + showImportedMesh(url) } finally { setImporting(false) } diff --git a/src/areas/generate/components/WorkflowPanel.tsx b/src/areas/generate/components/WorkflowPanel.tsx index d1be5e9f7..493bf42c6 100644 --- a/src/areas/generate/components/WorkflowPanel.tsx +++ b/src/areas/generate/components/WorkflowPanel.tsx @@ -14,6 +14,7 @@ import { useWaitButton } from '@areas/workflows/useWaitButton' import { buildAllWorkflowExtensions, getWorkflowExtension } from '@areas/workflows/mockExtensions' import { validateWorkflowPreflight } from '@areas/workflows/preflight' import { mimeFromPath } from '@areas/workflows/nodes/imageUtils' +import { SUPPORTED_IMAGE_TYPES, useImageHandoff } from '@shared/utils/imageInput' import type { WorkflowExtension } from '@areas/workflows/mockExtensions' import type { Workflow, WFNode, WFEdge, ParamSchema } from '@shared/types/electron.d' import { PICKER_LABELS, openParamPicker, resolvePickerIntent } from '@shared/utils/paramPicker' @@ -28,8 +29,6 @@ const TYPE_COLOR: Record = { text: '#fbbf24', } -const SUPPORTED_IMAGE_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp']) - // ─── Helpers ────────────────────────────────────────────────────────────────── function topoSortNodes(nodes: Workflow['nodes'], edges: Workflow['edges']): WFNode[] { @@ -155,6 +154,12 @@ function WorkflowDropdown({ workflows, value, onChange }: { type PatchFn = (nodeId: string, patch: Record) => void +/** The image node params for a file on disk: its path and an inline preview. */ +async function readImageParams(path: string): Promise<{ filePath: string, preview: string }> { + const base64 = await window.electron.fs.readFileBase64(path) + return { filePath: path, preview: `data:${mimeFromPath(path)};base64,${base64}` } +} + function ImageParamRow({ nodeId, nodes, onPatch }: { nodeId: string; nodes: FlowNode[]; onPatch: PatchFn }) { const node = nodes.find((n) => n.id === nodeId) const data = node?.data as { params: Record } | undefined @@ -166,10 +171,9 @@ function ImageParamRow({ nodeId, nodes, onPatch }: { nodeId: string; nodes: Flow const request = ++loadRequest.current if (!path) return try { - const base64 = await window.electron.fs.readFileBase64(path) + const image = await readImageParams(path) if (request !== loadRequest.current) return - const src = `data:${mimeFromPath(path)};base64,${base64}` - onPatch(nodeId, { params: { ...(data?.params ?? {}), filePath: path, preview: src } }) + onPatch(nodeId, { params: { ...(data?.params ?? {}), ...image } }) } catch { if (request === loadRequest.current) showToast('Unable to load the selected image') } @@ -519,6 +523,23 @@ function EmbeddedCanvas({ workflow, allExtensions }: { && (n.data as { showInGenerate?: boolean }).showInGenerate === true, ) + // An image handed over by another page (Home) goes into the first image input + // shown here, exactly as if it had been browsed in this panel. + const pendingImage = useImageHandoff((s) => s.pendingPath) + useEffect(() => { + const path = useImageHandoff.getState().take() + if (!path) return + const target = paramNodes.find((n) => n.type === 'imageNode') + if (!target) { + showToast('This workflow has no image input. Pick a workflow with one.') + return + } + readImageParams(path) + .then((image) => patchNode(target.id, { params: { ...(target.data.params ?? {}), ...image } })) + .catch(() => showToast('Unable to load the selected image')) + // eslint-disable-next-line react-hooks/exhaustive-deps -- runs when an image is handed over; nodes are read at that point + }, [pendingImage]) + const handleGenerate = useCallback(() => { if (firstPreflightIssue) { showToast(firstPreflightIssue) diff --git a/src/areas/home/HomePage.tsx b/src/areas/home/HomePage.tsx new file mode 100644 index 000000000..f0cf5b26c --- /dev/null +++ b/src/areas/home/HomePage.tsx @@ -0,0 +1,211 @@ +import { useCallback, useEffect, useMemo, useState } from 'react' +import { useAppStore } from '@shared/stores/appStore' +import { useNavStore } from '@shared/stores/navStore' +import { useApi } from '@shared/hooks/useApi' +import { droppedImagePath, useImageHandoff } from '@shared/utils/imageInput' +import { showImportedMesh } from '@shared/utils/meshJob' +import { requestLibraryThumbnails } from '@shared/thumbnails/assetThumbnailService' +import type { ProjectedAssetLibraryEntry } from '@areas/generate/assetLibraryProjection' +import { getDefaultAssetLibraryService } from '@areas/generate/assetLibraryService' +import { openAssetLibraryEntry } from '@areas/generate/assetLibraryUi' +import { Thumbnail } from '@areas/library/LibraryGrid' +import ModlyLogo from '@shared/components/ui/ModlyLogo' +import { formatRelativeDate, selectRecentAssets } from './recents' + +function Icon({ d, size = 16 }: { d: string, size?: number }): JSX.Element { + return ( + + ) +} + +const ICONS = { + upload: 'M12 16V4m0 0-4.5 4.5M12 4l4.5 4.5M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3', + workflow: 'M4 5h5v5H4zM15 14h5v5h-5zM9 7.5h3.5a2 2 0 0 1 2 2V14', + mesh: 'M12 2 3 7v10l9 5 9-5V7zM3 7l9 5 9-5M12 12v10', + library: 'M4 4h6.5v6.5H4zM13.5 4H20v6.5h-6.5zM4 13.5h6.5V20H4zM13.5 13.5H20V20h-6.5z', +} + +function SectionHeader({ title, action }: { title: string, action?: { label: string, onClick: () => void } }): JSX.Element { + return ( +
+

{title}

+ {action && ( + + )} +
+ ) +} + +function QuickAction({ icon, label, detail, busy, onClick }: { icon: string, label: string, detail: string, busy?: boolean, onClick: () => void }): JSX.Element { + return ( + + ) +} + +function DropZone({ onImage }: { onImage: (path: string) => void }): JSX.Element { + const [dragging, setDragging] = useState(false) + return ( + + ) +} + +function RecentAsset({ entry, opening, onOpen }: { entry: ProjectedAssetLibraryEntry, opening: boolean, onOpen: () => void }): JSX.Element { + const date = formatRelativeDate(entry.updatedAt ?? entry.createdAt) + return ( + + ) +} + +function Empty({ text }: { text: string }): JSX.Element { + return ( +
+

{text}

+
+ ) +} + +export default function HomePage(): JSX.Element { + const navigate = useNavStore((s) => s.navigate) + const showError = useAppStore((s) => s.showError) + const { importMesh } = useApi() + const service = useMemo(() => getDefaultAssetLibraryService(), []) + + const [assets, setAssets] = useState([]) + const [assetsLoaded, setAssetsLoaded] = useState(false) + const [openingId, setOpeningId] = useState(null) + const [importing, setImporting] = useState(false) + + const loadAssets = useCallback(async () => { + try { + const result = await service.list() + if (!result.success) return + const recent = selectRecentAssets(result.entries) + setAssets(recent) + // Render only the thumbnails this page shows. + void requestLibraryThumbnails(recent) + } finally { + setAssetsLoaded(true) + } + }, [service]) + + useEffect(() => { void loadAssets() }, [loadAssets]) + + async function openAsset(entry: ProjectedAssetLibraryEntry) { + if (openingId) return + setOpeningId(entry.id) + try { + const result = await openAssetLibraryEntry(service, entry) + if (!result.success) { + showError(result.message) + return + } + const { setCurrentJob, pushMeshUrl } = useAppStore.getState() + setCurrentJob(result.selection.job) + pushMeshUrl(result.selection.historyUrl) + navigate('generate') + } catch (err) { + showError(err instanceof Error ? err.message : String(err)) + } finally { + setOpeningId(null) + } + } + + async function importFromDisk() { + const filePath = await window.electron.fs.selectMeshFile() + if (!filePath) return + setImporting(true) + try { + const { url } = await importMesh(filePath) + showImportedMesh(url) + navigate('generate') + } catch (err) { + showError(err instanceof Error ? err.message : 'Could not import the mesh.') + } finally { + setImporting(false) + } + } + + const returning = assets.length > 0 + + return ( +
+
+ +

{returning ? 'Welcome back' : 'Welcome to Modly'}

+
+ +
+ { useImageHandoff.getState().offer(path); navigate('generate') }} /> +
+ navigate('workflows')} /> + { void importFromDisk() }} /> + navigate('library')} /> +
+
+ +
+ 0 ? { label: 'See all', onClick: () => navigate('library') } : undefined} /> + {assets.length > 0 ? ( +
+ {assets.map((entry) => ( + { void openAsset(entry) }} /> + ))} +
+ ) : assetsLoaded ? ( + + ) : ( +
+
+ ) +} diff --git a/src/areas/home/recents.test.ts b/src/areas/home/recents.test.ts new file mode 100644 index 000000000..6a1e732c0 --- /dev/null +++ b/src/areas/home/recents.test.ts @@ -0,0 +1,44 @@ +import assert from 'node:assert/strict' +import test from 'node:test' + +import type { AssetLibraryEntry } from '../../shared/types/assetLibrary' +import { projectAssetLibraryEntry, type ProjectedAssetLibraryEntry } from '../generate/assetLibraryProjection' +import { formatRelativeDate, selectRecentAssets } from './recents' + +function entry(name: string, overrides: Partial = {}): ProjectedAssetLibraryEntry { + return projectAssetLibraryEntry({ + id: `library:${name}`, + workspacePath: `Workflows/run/${name}`, + displayName: name, + sourceScope: 'workflows', + capability: 'mesh', + state: 'ready', + previewKind: '3d-model', + warnings: [], + openable: true, + ...overrides, + }) +} + +test('recent assets are the newest openable ones, newest first, capped', () => { + const entries = [ + entry('old.glb', { createdAt: '2026-01-01T00:00:00.000Z' }), + entry('new.glb', { createdAt: '2026-03-01T00:00:00.000Z' }), + entry('mid.glb', { createdAt: '2026-02-01T00:00:00.000Z' }), + entry('locked.glb', { createdAt: '2026-04-01T00:00:00.000Z', state: 'unsafe', openable: false }), + entry('notes.txt', { createdAt: '2026-05-01T00:00:00.000Z', previewKind: 'text', openable: false }), + ] + assert.deepEqual(selectRecentAssets(entries).map((e) => e.displayName), ['new.glb', 'mid.glb', 'old.glb']) + assert.deepEqual(selectRecentAssets(entries, 2).map((e) => e.displayName), ['new.glb', 'mid.glb']) + assert.deepEqual(selectRecentAssets([]), []) +}) + +test('formatRelativeDate reads ISO dates relative to now', () => { + const now = Date.parse('2026-11-14T12:00:00.000Z') + // English whatever the OS language, like the rest of the UI. + assert.equal(formatRelativeDate('2026-11-14T11:55:00.000Z', now), '5 minutes ago') + assert.equal(formatRelativeDate('2026-11-13T12:00:00.000Z', now), 'yesterday') + assert.equal(formatRelativeDate('2026-11-14T11:59:50.000Z', now), 'this minute') + assert.equal(formatRelativeDate('nope', now), null) + assert.equal(formatRelativeDate(undefined, now), null) +}) diff --git a/src/areas/home/recents.ts b/src/areas/home/recents.ts new file mode 100644 index 000000000..48ed2764c --- /dev/null +++ b/src/areas/home/recents.ts @@ -0,0 +1,38 @@ +import type { ProjectedAssetLibraryEntry } from '../generate/assetLibraryProjection' +import { isAssetLibraryEntryOpenable } from '../generate/assetLibraryUi' +import { DEFAULT_LIBRARY_QUERY, selectLibraryEntries } from '../library/libraryView' + +export const RECENT_ASSET_LIMIT = 6 + +/** The newest assets the user can reopen, by the Library's own visibility and date rules. */ +export function selectRecentAssets( + entries: ProjectedAssetLibraryEntry[], + limit = RECENT_ASSET_LIMIT, +): ProjectedAssetLibraryEntry[] { + return selectLibraryEntries(entries, DEFAULT_LIBRARY_QUERY) + .filter((entry) => isAssetLibraryEntryOpenable(entry)) + .slice(0, limit) +} + +function timeOf(value: string | undefined): number { + const time = value ? Date.parse(value) : Number.NaN + return Number.isFinite(time) ? time : Number.NEGATIVE_INFINITY +} + +// English like the rest of the UI ("yesterday"), not the OS language. +const RELATIVE = new Intl.RelativeTimeFormat('en', { numeric: 'auto' }) +const UNITS: [Intl.RelativeTimeFormatUnit, number][] = [ + ['year', 365 * 24 * 3600], ['month', 30 * 24 * 3600], ['week', 7 * 24 * 3600], + ['day', 24 * 3600], ['hour', 3600], ['minute', 60], +] + +/** "5 minutes ago", "yesterday"… for an ISO date; null when it can't be read. */ +export function formatRelativeDate(value: string | undefined, now = Date.now()): string | null { + const time = timeOf(value) + if (!Number.isFinite(time)) return null + const seconds = Math.round((time - now) / 1000) + for (const [unit, size] of UNITS) { + if (Math.abs(seconds) >= size) return RELATIVE.format(Math.round(seconds / size), unit) + } + return RELATIVE.format(0, 'minute') +} diff --git a/src/areas/library/LibraryGrid.tsx b/src/areas/library/LibraryGrid.tsx index b6d8f10f2..5feba2266 100644 --- a/src/areas/library/LibraryGrid.tsx +++ b/src/areas/library/LibraryGrid.tsx @@ -62,7 +62,7 @@ export function formatEntryDate(entry: ProjectedAssetLibraryEntry): string | nul } /** The asset's thumbnail, or its capability icon until one is rendered (or if it fails to load). */ -function Thumbnail({ entry, iconSize }: { entry: ProjectedAssetLibraryEntry, iconSize: number }): JSX.Element { +export function Thumbnail({ entry, iconSize }: { entry: ProjectedAssetLibraryEntry, iconSize: number }): JSX.Element { const url = useAssetThumbnailUrl(entry) const [failedUrl, setFailedUrl] = useState(null) if (url && url !== failedUrl) { diff --git a/src/areas/settings/components/ApplicationSection.tsx b/src/areas/settings/components/ApplicationSection.tsx index 63984cb73..22583caf3 100644 --- a/src/areas/settings/components/ApplicationSection.tsx +++ b/src/areas/settings/components/ApplicationSection.tsx @@ -1,12 +1,31 @@ +import { useState } from 'react' import { useAppStore } from '@shared/stores/appStore' -import { Section, Card, Row, Toggle } from '@shared/ui' +import { readStartPage, writeStartPage, type StartPage } from '@shared/pages/startPage' +import { Section, Card, Row, Toggle, SegmentedControl } from '@shared/ui' + +const START_PAGE_OPTIONS: { value: StartPage; label: string }[] = [ + { value: 'home', label: 'Home' }, + { value: 'generate', label: 'Generate' }, +] export function ApplicationSection(): JSX.Element { const { showRamIndicator, setShowRamIndicator } = useAppStore() + const [startPage, setStartPage] = useState(readStartPage) + + function changeStartPage(page: StartPage) { + setStartPage(page) + writeStartPage(page) + } return (
+ + + - - - - - - - - - - - - - - + ) } @@ -27,7 +15,7 @@ function ModlyLogo(): JSX.Element { function AppHeader(): JSX.Element { return ( <> - +

Modly

AI-powered 3D mesh generation

diff --git a/src/shared/components/agent/clientTools.test.ts b/src/shared/components/agent/clientTools.test.ts index b6f29acec..24a31ab45 100644 --- a/src/shared/components/agent/clientTools.test.ts +++ b/src/shared/components/agent/clientTools.test.ts @@ -337,7 +337,7 @@ test('navigate changes page and validates it', async () => { const f = fake() assert.equal(await run('navigate', { page: 'models' }, f), 'Opened the Extensions page.') assert.deepEqual(f.calls, [['navigate', 'models']]) - assert.match(await run('navigate', { page: 'home' }, f), /^Error: page must be one of: generate, workflows, library, models, settings/) + assert.match(await run('navigate', { page: 'nope' }, f), /^Error: page must be one of: home, generate, workflows, library, models, settings/) }) test('a throwing dependency comes back as an error text', async () => { diff --git a/src/shared/components/ui/ModlyLogo.tsx b/src/shared/components/ui/ModlyLogo.tsx new file mode 100644 index 000000000..8b62b221f --- /dev/null +++ b/src/shared/components/ui/ModlyLogo.tsx @@ -0,0 +1,19 @@ +/** The Modly mark, in its violet gradient. */ +export default function ModlyLogo({ size = 64, className }: { size?: number, className?: string }): JSX.Element { + return ( + + + + + + + + + + + + + + + ) +} diff --git a/src/shared/pages/pageRegistry.test.ts b/src/shared/pages/pageRegistry.test.ts index ce65055b7..eec0988bb 100644 --- a/src/shared/pages/pageRegistry.test.ts +++ b/src/shared/pages/pageRegistry.test.ts @@ -21,6 +21,7 @@ test('the pages keep their ids, labels and sidebar order', () => { assert.deepEqual( pagesByGroup().map((s) => [s.group, s.pages.map((p) => `${p.id}:${p.label}`)]), [ + ['home', ['home:Home']], ['create', ['generate:Generate', 'workflows:Workflows']], ['manage', ['library:Library']], ['system', ['models:Extensions', 'settings:Settings']], diff --git a/src/shared/pages/pageRegistry.ts b/src/shared/pages/pageRegistry.ts index 6428d0718..c886fb23c 100644 --- a/src/shared/pages/pageRegistry.ts +++ b/src/shared/pages/pageRegistry.ts @@ -30,6 +30,17 @@ export interface PageDefinition { } export const PAGES = [ + { + id: 'home', + label: 'Home', + group: 'home', + icon: [ + ['path', { d: 'M3 10.5 12 3l9 7.5' }], + ['path', { d: 'M5 9v10.5a1 1 0 0 0 1 1h4v-6h4v6h4a1 1 0 0 0 1-1V9' }], + ], + load: () => import('@areas/home/HomePage'), + wrapperClass: 'flex-1 overflow-y-auto', + }, { id: 'generate', label: 'Generate', diff --git a/src/shared/pages/startPage.test.ts b/src/shared/pages/startPage.test.ts new file mode 100644 index 000000000..eb628668d --- /dev/null +++ b/src/shared/pages/startPage.test.ts @@ -0,0 +1,33 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { DEFAULT_START_PAGE, readStartPage, writeStartPage } from './startPage' + +function memoryStorage(initial: Record = {}) { + const data = new Map(Object.entries(initial)) + return { + getItem: (key: string) => data.get(key) ?? null, + setItem: (key: string, value: string) => { data.set(key, value) }, + } +} + +test('the app starts on Home unless the user chose Generate', () => { + assert.equal(DEFAULT_START_PAGE, 'home') + assert.equal(readStartPage(memoryStorage()), 'home') + assert.equal(readStartPage(memoryStorage({ 'modly.startPage': 'generate' })), 'generate') +}) + +test('an unknown or unreadable value falls back to Home', () => { + assert.equal(readStartPage(memoryStorage({ 'modly.startPage': 'settings' })), 'home') + assert.equal(readStartPage(undefined), 'home') + const throwing = { getItem: () => { throw new Error('blocked') }, setItem: () => { throw new Error('blocked') } } + assert.equal(readStartPage(throwing), 'home') + assert.doesNotThrow(() => writeStartPage('generate', throwing)) +}) + +test('writeStartPage round-trips', () => { + const storage = memoryStorage() + writeStartPage('generate', storage) + assert.equal(readStartPage(storage), 'generate') + writeStartPage('home', storage) + assert.equal(readStartPage(storage), 'home') +}) diff --git a/src/shared/pages/startPage.ts b/src/shared/pages/startPage.ts new file mode 100644 index 000000000..23a0f117c --- /dev/null +++ b/src/shared/pages/startPage.ts @@ -0,0 +1,28 @@ +// The page the app opens on. Kept in localStorage by this module rather than in +// appStore, so navStore can read it at init and still load under `node --test`. + +export type StartPage = 'home' | 'generate' + +export const START_PAGES: readonly StartPage[] = ['home', 'generate'] +export const DEFAULT_START_PAGE: StartPage = 'home' + +const STORAGE_KEY = 'modly.startPage' + +type Storage = Pick + +function defaultStorage(): Storage | undefined { + try { return globalThis.localStorage } catch { return undefined } +} + +export function readStartPage(storage: Storage | undefined = defaultStorage()): StartPage { + try { + const value = storage?.getItem(STORAGE_KEY) + return (START_PAGES as readonly string[]).includes(value ?? '') ? value as StartPage : DEFAULT_START_PAGE + } catch { + return DEFAULT_START_PAGE + } +} + +export function writeStartPage(page: StartPage, storage: Storage | undefined = defaultStorage()): void { + try { storage?.setItem(STORAGE_KEY, page) } catch { /* private mode / quota */ } +} diff --git a/src/shared/stores/navStore.ts b/src/shared/stores/navStore.ts index 6afcdfdac..b43f304cc 100644 --- a/src/shared/stores/navStore.ts +++ b/src/shared/stores/navStore.ts @@ -1,6 +1,7 @@ import { create } from 'zustand' // Relative and type-only, so the store loads under `node --test`. import type { Page } from '../pages/pageRegistry' +import { readStartPage } from '../pages/startPage' export type { Page } @@ -18,7 +19,7 @@ interface NavState { } export const useNavStore = create((set, get) => ({ - currentPage: 'generate', + currentPage: readStartPage(), params: null, navigate: (page, params) => set({ currentPage: page, params: params ?? null }), openExtension: (extensionId) => get().navigate('models', { extension: extensionId }), diff --git a/src/shared/utils/imageInput.ts b/src/shared/utils/imageInput.ts new file mode 100644 index 000000000..2aeba8846 --- /dev/null +++ b/src/shared/utils/imageInput.ts @@ -0,0 +1,30 @@ +import { create } from 'zustand' + +// Hands an input image from another page (Home) to Generate. Generate's image +// lives in the selected workflow's image node, which only Generate's panel can +// edit, so the path waits here until that panel picks it up. + +export const SUPPORTED_IMAGE_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp']) + +interface ImageHandoff { + pendingPath: string | null + offer: (path: string) => void + /** Returns the waiting path, if any, and clears it. */ + take: () => string | null +} + +export const useImageHandoff = create((set, get) => ({ + pendingPath: null, + offer: (path) => set({ pendingPath: path }), + take: () => { + const path = get().pendingPath + if (path) set({ pendingPath: null }) + return path + }, +})) + +/** The disk path of a dropped file, or null when it is not a supported image. */ +export function droppedImagePath(file: File | undefined): string | null { + if (!file || !SUPPORTED_IMAGE_TYPES.has(file.type)) return null + return window.electron.fs.getPathForFile(file) || null +} diff --git a/src/shared/utils/meshJob.ts b/src/shared/utils/meshJob.ts new file mode 100644 index 000000000..4cf2329a2 --- /dev/null +++ b/src/shared/utils/meshJob.ts @@ -0,0 +1,21 @@ +import { useAppStore, type GenerationJob } from '@shared/stores/appStore' + +/** The viewer job for a mesh imported from disk (already converted by the API). */ +export function importedMeshJob(url: string, now = Date.now()): GenerationJob { + return { + id: `import-${now}`, + imageFile: '', + status: 'done', + progress: 100, + outputUrl: url, + originalOutputUrl: url, + createdAt: now, + } +} + +/** Shows an imported mesh in Generate's viewer, as its first undo state. */ +export function showImportedMesh(url: string): void { + const { setCurrentJob, pushMeshUrl } = useAppStore.getState() + setCurrentJob(importedMeshJob(url)) + pushMeshUrl(url) +}