Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions apps/web/src/components/project-controls.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { useRef, useState } from 'react'
import { Download, Upload } from 'lucide-react'

import { Button } from '@/components/ui/button'
import { downloadProject, importProject } from '@/lib/project'
import { usePhotoStore } from '@/stores/photo-store'
import { settingsSnapshot, useSettingsStore } from '@/stores/settings-store'

export function ProjectControls() {
const photos = usePhotoStore((state) => state.photos)
const replaceAll = usePhotoStore((state) => state.replaceAll)
const inputRef = useRef<HTMLInputElement>(null)
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)

const handleSave = async () => {
setBusy(true)
try {
await downloadProject(
photos,
settingsSnapshot(useSettingsStore.getState()),
)
} finally {
setBusy(false)
}
}

const handleOpen = async (file: File) => {
setBusy(true)
setError(null)
try {
const { photos: imported, settings } = await importProject(file)
replaceAll(imported)
useSettingsStore.setState(settings)
} catch {
setError('Could not open that project file.')
} finally {
setBusy(false)
}
}

return (
<div className="flex flex-col items-end gap-1">
<div className="flex items-center gap-2">
<input
ref={inputRef}
type="file"
accept="application/json,.json"
hidden
onChange={(event) => {
const file = event.target.files?.[0]
if (file) void handleOpen(file)
event.target.value = ''
}}
/>
<Button
variant="outline"
size="sm"
disabled={busy}
onClick={() => inputRef.current?.click()}
>
<Upload className="size-3.5" />
Open
</Button>
<Button
variant="outline"
size="sm"
disabled={busy || photos.length === 0}
onClick={() => void handleSave()}
>
<Download className="size-3.5" />
Save
</Button>
</div>
{error && <span className="text-destructive text-xs">{error}</span>}
</div>
)
}
112 changes: 112 additions & 0 deletions apps/web/src/lib/project.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import {
type Crop,
DEFAULT_CROP,
DEFAULT_ORIENTATION,
type Orientation,
} from '@/lib/crop'
import { type Photo } from '@/lib/photos'
import { type SettingsSnapshot } from '@/stores/settings-store'

// A portable project file: the layout, captions, settings and the images
// themselves, all in one self-contained JSON. No account, no cloud — just a
// file you own, that re-opens the exact same sheet anywhere.

const PROJECT_VERSION = 1

interface ProjectPhoto {
name: string
captionTop: string
captionBottom: string
place?: { city: string; country: string }
takenAt?: number
cameraLine?: string
crop: Crop
orientation: Orientation
/** The image embedded as a data URL (base64). */
dataUrl: string
}

interface ProjectFile {
version: number
settings: SettingsSnapshot
photos: ProjectPhoto[]
}

function fileToDataUrl(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => resolve(reader.result as string)
reader.onerror = () => reject(reader.error)
reader.readAsDataURL(file)
})
}

export async function buildProjectFile(
photos: Photo[],
settings: SettingsSnapshot,
): Promise<ProjectFile> {
const projectPhotos = await Promise.all(
photos.map(async (photo) => ({
name: photo.name,
captionTop: photo.captionTop,
captionBottom: photo.captionBottom,
place: photo.place,
takenAt: photo.takenAt,
cameraLine: photo.cameraLine,
crop: photo.crop,
orientation: photo.orientation,
dataUrl: await fileToDataUrl(photo.file),
})),
)
return { version: PROJECT_VERSION, settings, photos: projectPhotos }
}

export async function downloadProject(
photos: Photo[],
settings: SettingsSnapshot,
filename = 'polaroid-project.json',
): Promise<void> {
const project = await buildProjectFile(photos, settings)
const blob = new Blob([JSON.stringify(project)], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = filename
link.click()
URL.revokeObjectURL(url)
}

/** Parses a project file back into live photos (new ids, fresh object URLs). */
export async function importProject(file: File): Promise<{
photos: Photo[]
settings: Partial<SettingsSnapshot>
}> {
const parsed = JSON.parse(await file.text()) as ProjectFile
if (!parsed || !Array.isArray(parsed.photos)) {
throw new Error('Invalid project file')
}
const photos = await Promise.all(
parsed.photos.map(async (entry) => {
const blob = await (await fetch(entry.dataUrl)).blob()
const rebuilt = new File([blob], entry.name || 'photo', {
type: blob.type,
})
return {
id: crypto.randomUUID(),
file: rebuilt,
url: URL.createObjectURL(rebuilt),
name: rebuilt.name,
size: rebuilt.size,
captionTop: entry.captionTop ?? '',
captionBottom: entry.captionBottom ?? '',
place: entry.place,
takenAt: entry.takenAt,
cameraLine: entry.cameraLine,
crop: entry.crop ?? DEFAULT_CROP,
orientation: entry.orientation ?? DEFAULT_ORIENTATION,
enriching: false,
} satisfies Photo
}),
)
return { photos, settings: parsed.settings ?? {} }
}
16 changes: 10 additions & 6 deletions apps/web/src/routes/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createFileRoute } from '@tanstack/react-router'
import { A4Preview } from '@/components/a4-preview'
import { PhotoDropzone } from '@/components/photo-dropzone'
import { PhotoGrid } from '@/components/photo-grid'
import { ProjectControls } from '@/components/project-controls'
import { usePhotoStore } from '@/stores/photo-store'

export const Route = createFileRoute('/')({
Expand All @@ -14,12 +15,15 @@ function Home() {

return (
<main className="mx-auto flex min-h-svh w-full max-w-4xl flex-col gap-6 p-4 sm:gap-8 sm:p-8">
<header className="flex flex-col gap-1">
<h1 className="text-2xl font-semibold tracking-tight">Polaroid</h1>
<p className="text-muted-foreground text-sm">
Add your photos to start building polaroid-style A4 sheets. Everything
stays on your device.
</p>
<header className="flex items-start justify-between gap-3">
<div className="flex flex-col gap-1">
<h1 className="text-2xl font-semibold tracking-tight">Polaroid</h1>
<p className="text-muted-foreground text-sm">
Add your photos to start building polaroid-style print sheets.
Everything stays on your device.
</p>
</div>
<ProjectControls />
</header>

<PhotoDropzone compact={hasPhotos} />
Expand Down
7 changes: 7 additions & 0 deletions apps/web/src/stores/photo-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ interface PhotoState {
/** Re-derives auto date captions when the date format changes. */
applyDateFormat: (format: DateFormat) => void
remove: (id: string) => void
/** Replaces the whole set (e.g. opening a project file), revoking old URLs. */
replaceAll: (photos: Photo[]) => void
clear: () => void
}

Expand Down Expand Up @@ -172,6 +174,11 @@ export const usePhotoStore = create<PhotoState>((set) => {
if (target) URL.revokeObjectURL(target.url)
return { photos: state.photos.filter((photo) => photo.id !== id) }
}),
replaceAll: (photos) =>
set((state) => {
state.photos.forEach((photo) => URL.revokeObjectURL(photo.url))
return { photos }
}),
clear: () =>
set((state) => {
state.photos.forEach((photo) => URL.revokeObjectURL(photo.url))
Expand Down
8 changes: 8 additions & 0 deletions apps/web/src/stores/settings-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ export interface SettingsSnapshot {
showCaptions: boolean
}

/** Extracts the persistable settings (no action functions) from store state. */
export function settingsSnapshot(state: SettingsState): SettingsSnapshot {
return PERSISTED_SETTINGS_KEYS.reduce(
(snapshot, key) => ({ ...snapshot, [key]: state[key] }),
{} as SettingsSnapshot,
)
}

export const PERSISTED_SETTINGS_KEYS: (keyof SettingsSnapshot)[] = [
'framePadding',
'captionFontId',
Expand Down
Loading