Compare commits
3 Commits
main
...
feat/share
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4490b0341d | ||
|
|
1ceff81885 | ||
|
|
36c80ac60c |
@ -46,6 +46,14 @@ The Cloudflare custom domain is source-controlled in `wrangler.jsonc`. Do not
|
||||
attach this Worker to the apex domain, and do not add marketing-site source,
|
||||
styles, assets, or production-only configuration to this repository.
|
||||
|
||||
The Worker also runs the share API (`scripts/share-api.ts`) for short
|
||||
project share links. It stores opaque share payloads in the `SHARE_KV` KV
|
||||
namespace referenced in `wrangler.jsonc`; the API token therefore needs
|
||||
Workers KV Storage edit permission (included in the standard Edit Cloudflare
|
||||
Workers token template). The editor falls back to self-contained share links
|
||||
when the API is unavailable, so a deployment without the KV binding degrades
|
||||
gracefully.
|
||||
|
||||
Keep `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID` available only to the
|
||||
`bun run deploy-only` command. The GitHub Actions workflow follows the same
|
||||
boundary: it builds without Cloudflare credentials and supplies them only to
|
||||
|
||||
@ -91,6 +91,42 @@ Persistence is browser-local:
|
||||
|
||||
Avoid putting credentials or provider responses into persisted project data.
|
||||
|
||||
### Share links
|
||||
|
||||
`src/app/share-link.ts` implements project sharing. The share payload is the
|
||||
whole project as deflate-raw-compressed JSON with every image inlined as a
|
||||
data URL (images are additionally capped at export resolution and re-encoded
|
||||
as WebP when that is smaller). Two link forms exist:
|
||||
|
||||
- `/s/<id>` (preferred): the payload is uploaded to the share API and only a
|
||||
short id travels in the link. `scripts/share-api.ts` is mounted into the
|
||||
`shotluma-app` Worker entry (`scripts/shotluma-worker.ts`) that also serves
|
||||
the editor assets (`assets.run_worker_first` routes `/api/share*` and
|
||||
`/s/*` through the script) and stores payloads opaquely in the `SHARE_KV`
|
||||
KV namespace with a 90-day TTL and a 10 MB cap. The id lives in the URL path because link-preview crawlers
|
||||
never send fragments: `GET /s/<id>` serves the editor's index.html with
|
||||
per-share Open Graph tags injected (project name plus a 1200 × 630 unfurl
|
||||
image that `src/app/share-preview.ts` renders client-side from the live
|
||||
artboards and uploads best-effort at share time). The app consumes the path
|
||||
on boot and rewrites the URL back to `/`. The equivalent `#s=<id>` fragment
|
||||
form is also consumed on boot as a compatibility format — it just cannot
|
||||
carry per-share OG tags because crawlers never send fragments. During local
|
||||
dev the Vite server proxies `/api/share` to the deployed Worker.
|
||||
- `#share=<base64url payload>` (fallback): when the share API is unreachable
|
||||
the link carries the payload itself, so sharing degrades gracefully instead
|
||||
of failing; such links can get very long and the dialog says so.
|
||||
|
||||
Opening either link imports the payload as a new, independent local project —
|
||||
inlined images become locally stored Blobs — so the recipient can edit or
|
||||
delete their copy without ever affecting the sender's project. This is the
|
||||
only place project data can leave the browser, and only when the user
|
||||
explicitly creates a share link. A share payload is untrusted input: decoding
|
||||
re-sanitizes AI screen markup and rich text, drops malformed slides, elements,
|
||||
and uploads, rejects unsafe image source schemes, and caps the decompressed
|
||||
size so a handcrafted link cannot act as a decompression bomb. The import path
|
||||
consumes the fragment exactly once and is cached module-wide because React
|
||||
StrictMode double-invokes the hydration effect in development.
|
||||
|
||||
Developer AI run logging is enabled only when `SHOTLUMA_AI_LOGGING=true`. The browser sends a versioned, bounded record to the local Vite middleware, which validates it and writes one JSON file per run to the git-ignored `ai-logs/` directory in the repository. Records include normalized total and per-step token usage, per-step tool and preview counts, visible text and reasoning output, tool activity, and coarse request sizes. Shotluma does not add input prompt text, screenshot payloads or names, credentials, or raw provider metadata to the records.
|
||||
|
||||
## Export
|
||||
|
||||
234
scripts/share-api.ts
Normal file
234
scripts/share-api.ts
Normal file
@ -0,0 +1,234 @@
|
||||
/**
|
||||
* Share API for short project links, mounted into the `shotluma-app` Worker
|
||||
* entry (`scripts/shotluma-worker.ts`); `run_worker_first` routes only
|
||||
* `/api/share*` and `/s/*` through the Worker script for it.
|
||||
*
|
||||
* The API stores opaque, client-compressed share payloads in KV and hands
|
||||
* back a short id. It never inspects project content — decoding, validation,
|
||||
* and sanitization all stay in the browser (`src/app/share-link.ts`), and the
|
||||
* editor falls back to self-contained `#share=` links when this API is
|
||||
* unreachable. Alongside the payload the client may upload a rendered
|
||||
* Open Graph preview and the project name; `/s/<id>` serves the editor's
|
||||
* index.html with per-share OG tags injected so pasted links unfurl with the
|
||||
* project's own artwork.
|
||||
*/
|
||||
|
||||
type ShareKv = {
|
||||
get(key: string, type: 'arrayBuffer'): Promise<ArrayBuffer | null>
|
||||
get(key: string, type: 'text'): Promise<string | null>
|
||||
put(key: string, value: ArrayBuffer | string, options?: { expirationTtl?: number }): Promise<void>
|
||||
}
|
||||
|
||||
type RateLimiter = {
|
||||
limit(options: { key: string }): Promise<{ success: boolean }>
|
||||
}
|
||||
|
||||
export type ShareApiEnv = {
|
||||
SHARE_KV: ShareKv
|
||||
ASSETS: { fetch(request: Request): Promise<Response> }
|
||||
/** Optional Workers rate-limiting binding; writes are allowed when absent. */
|
||||
SHARE_RATE?: RateLimiter
|
||||
}
|
||||
|
||||
/** Must stay at or below the client cap so accepted uploads always fit KV. */
|
||||
const MAX_PAYLOAD_BYTES = 10 * 1024 * 1024
|
||||
const MAX_PREVIEW_BYTES = 2 * 1024 * 1024
|
||||
const MAX_TITLE_LENGTH = 120
|
||||
const SHARE_TTL_SECONDS = 60 * 60 * 24 * 90
|
||||
const SHARE_ID_PATTERN = /^[A-Za-z0-9_-]{6,32}$/
|
||||
const SHARE_API_PATH = '/api/share'
|
||||
const SHARE_PAGE_PREFIX = '/s/'
|
||||
|
||||
const previewKey = (id: string) => `preview:${id}`
|
||||
const metaKey = (id: string) => `meta:${id}`
|
||||
|
||||
const jsonResponse = (value: unknown, status = 200): Response =>
|
||||
new Response(JSON.stringify(value), {
|
||||
status,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})
|
||||
|
||||
const methodNotAllowed = (allow: string): Response =>
|
||||
new Response('Method not allowed', { status: 405, headers: { allow } })
|
||||
|
||||
const invalidShareId = (): Response => jsonResponse({ error: 'The share id is invalid.' }, 400)
|
||||
|
||||
const createShareId = (): string => {
|
||||
// 9 random bytes → 12 base64url characters, no padding.
|
||||
const bytes = new Uint8Array(9)
|
||||
crypto.getRandomValues(bytes)
|
||||
let binary = ''
|
||||
for (const byte of bytes) binary += String.fromCharCode(byte)
|
||||
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_')
|
||||
}
|
||||
|
||||
const escapeHtml = (value: string): string =>
|
||||
value
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll('\'', ''')
|
||||
|
||||
/** Rejects oversized uploads before buffering the body. */
|
||||
const declaredLengthExceeds = (request: Request, maxBytes: number): boolean => {
|
||||
const declared = Number(request.headers.get('content-length') ?? '0')
|
||||
return Number.isFinite(declared) && declared > maxBytes
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort write throttle per client IP. The binding is optional so a
|
||||
* deployment without it stays functional.
|
||||
*/
|
||||
const writeAllowed = async (request: Request, env: ShareApiEnv): Promise<boolean> => {
|
||||
if (!env.SHARE_RATE) return true
|
||||
const key = request.headers.get('cf-connecting-ip') ?? 'unknown'
|
||||
try {
|
||||
return (await env.SHARE_RATE.limit({ key })).success
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
const rateLimited = (): Response =>
|
||||
jsonResponse({ error: 'Too many shares — try again in a minute.' }, 429)
|
||||
|
||||
const storeShare = async (request: Request, env: ShareApiEnv): Promise<Response> => {
|
||||
if (declaredLengthExceeds(request, MAX_PAYLOAD_BYTES)) {
|
||||
return jsonResponse({ error: 'The share payload is too large.' }, 413)
|
||||
}
|
||||
if (!await writeAllowed(request, env)) return rateLimited()
|
||||
const payload = await request.arrayBuffer()
|
||||
if (payload.byteLength === 0) return jsonResponse({ error: 'The share payload is empty.' }, 400)
|
||||
if (payload.byteLength > MAX_PAYLOAD_BYTES) {
|
||||
return jsonResponse({ error: 'The share payload is too large.' }, 413)
|
||||
}
|
||||
const id = createShareId()
|
||||
await env.SHARE_KV.put(id, payload, { expirationTtl: SHARE_TTL_SECONDS })
|
||||
return jsonResponse({ id })
|
||||
}
|
||||
|
||||
const storeSharePreview = async (id: string, request: Request, env: ShareApiEnv): Promise<Response> => {
|
||||
if (declaredLengthExceeds(request, MAX_PREVIEW_BYTES)) {
|
||||
return jsonResponse({ error: 'The share preview is too large.' }, 413)
|
||||
}
|
||||
if (!await writeAllowed(request, env)) return rateLimited()
|
||||
const existing = await env.SHARE_KV.get(id, 'arrayBuffer')
|
||||
if (!existing) return jsonResponse({ error: 'This share link has expired or does not exist.' }, 404)
|
||||
|
||||
const title = (new URL(request.url).searchParams.get('title') ?? '').trim().slice(0, MAX_TITLE_LENGTH)
|
||||
const preview = await request.arrayBuffer()
|
||||
if (preview.byteLength > MAX_PREVIEW_BYTES) {
|
||||
return jsonResponse({ error: 'The share preview is too large.' }, 413)
|
||||
}
|
||||
if (preview.byteLength > 0) {
|
||||
await env.SHARE_KV.put(previewKey(id), preview, { expirationTtl: SHARE_TTL_SECONDS })
|
||||
}
|
||||
await env.SHARE_KV.put(metaKey(id), JSON.stringify({ title }), { expirationTtl: SHARE_TTL_SECONDS })
|
||||
return jsonResponse({ ok: true })
|
||||
}
|
||||
|
||||
const readShare = async (id: string, env: ShareApiEnv): Promise<Response> => {
|
||||
const payload = await env.SHARE_KV.get(id, 'arrayBuffer')
|
||||
if (!payload) return jsonResponse({ error: 'This share link has expired or does not exist.' }, 404)
|
||||
return new Response(payload, {
|
||||
headers: {
|
||||
'content-type': 'application/octet-stream',
|
||||
'cache-control': 'public, max-age=3600',
|
||||
'x-content-type-options': 'nosniff',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const readSharePreview = async (id: string, env: ShareApiEnv): Promise<Response> => {
|
||||
const preview = await env.SHARE_KV.get(previewKey(id), 'arrayBuffer')
|
||||
if (!preview) return new Response('Not found', { status: 404 })
|
||||
return new Response(preview, {
|
||||
headers: {
|
||||
'content-type': 'image/jpeg',
|
||||
'cache-control': 'public, max-age=3600',
|
||||
'x-content-type-options': 'nosniff',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const readShareTitle = async (id: string, env: ShareApiEnv): Promise<string> => {
|
||||
try {
|
||||
const meta = await env.SHARE_KV.get(metaKey(id), 'text')
|
||||
if (!meta) return ''
|
||||
const parsed = JSON.parse(meta) as { title?: unknown }
|
||||
return typeof parsed.title === 'string' ? parsed.title : ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
// index.html ships static og:/twitter: tags for the editor itself. Crawlers
|
||||
// often honor the first tag they see, so the defaults must be removed before
|
||||
// the per-share tags are injected.
|
||||
const stripDefaultSocialTags = (html: string): string =>
|
||||
html.replace(/[ \t]*<meta (?:property="og:|name="twitter:)[^>]*>\n?/g, '')
|
||||
|
||||
/** Serves the editor with per-share OG tags so pasted links unfurl nicely. */
|
||||
const sharePage = async (id: string, url: URL, env: ShareApiEnv): Promise<Response> => {
|
||||
const assetResponse = await env.ASSETS.fetch(new Request(new URL('/', url).toString()))
|
||||
if (!assetResponse.ok) return assetResponse
|
||||
const html = stripDefaultSocialTags(await assetResponse.text())
|
||||
const title = await readShareTitle(id, env)
|
||||
const pageTitle = escapeHtml(title === '' ? 'Shared Shotluma project' : `${title} — Shotluma`)
|
||||
const tags = [
|
||||
'<meta property="og:site_name" content="Shotluma">',
|
||||
`<meta property="og:title" content="${pageTitle}">`,
|
||||
'<meta property="og:description" content="App Store screens shared with Shotluma. Open the link to get your own editable copy.">',
|
||||
'<meta property="og:type" content="website">',
|
||||
`<meta property="og:url" content="${url.origin}${SHARE_PAGE_PREFIX}${id}">`,
|
||||
`<meta property="og:image" content="${url.origin}${SHARE_API_PATH}/${id}/preview">`,
|
||||
'<meta property="og:image:width" content="1200">',
|
||||
'<meta property="og:image:height" content="630">',
|
||||
'<meta name="twitter:card" content="summary_large_image">',
|
||||
].join('\n')
|
||||
return new Response(html.replace('</head>', `${tags}\n</head>`), {
|
||||
headers: {
|
||||
'content-type': 'text/html; charset=utf-8',
|
||||
'cache-control': 'public, max-age=300',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const routeShareApi = (segments: string[], request: Request, env: ShareApiEnv): Promise<Response> | Response => {
|
||||
const [id, action] = segments
|
||||
if (!id || !SHARE_ID_PATTERN.test(id)) return invalidShareId()
|
||||
if (action === undefined) {
|
||||
return request.method === 'GET' ? readShare(id, env) : methodNotAllowed('GET')
|
||||
}
|
||||
if (action === 'preview' && segments.length === 2) {
|
||||
if (request.method === 'GET') return readSharePreview(id, env)
|
||||
if (request.method === 'POST') return storeSharePreview(id, request, env)
|
||||
return methodNotAllowed('GET, POST')
|
||||
}
|
||||
return new Response('Not found', { status: 404 })
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a share API or share page request; returns null for every other
|
||||
* request so the Worker entry can continue with its remaining routes.
|
||||
*/
|
||||
export const handleShareRequest = (
|
||||
request: Request,
|
||||
env: ShareApiEnv,
|
||||
): Promise<Response> | Response | null => {
|
||||
const url = new URL(request.url)
|
||||
if (url.pathname === SHARE_API_PATH) {
|
||||
return request.method === 'POST' ? storeShare(request, env) : methodNotAllowed('POST')
|
||||
}
|
||||
if (url.pathname.startsWith(`${SHARE_API_PATH}/`)) {
|
||||
const segments = url.pathname.slice(SHARE_API_PATH.length + 1).split('/')
|
||||
return routeShareApi(segments, request, env)
|
||||
}
|
||||
if (url.pathname.startsWith(SHARE_PAGE_PREFIX)) {
|
||||
const id = url.pathname.slice(SHARE_PAGE_PREFIX.length)
|
||||
if (SHARE_ID_PATTERN.test(id) && request.method === 'GET') return sharePage(id, url, env)
|
||||
// Unknown /s/ paths behave like any other SPA route.
|
||||
}
|
||||
return null
|
||||
}
|
||||
@ -1,20 +1,19 @@
|
||||
import { proxyOpencodeRequest, rewriteOpencodeProxyUrl } from './opencode-proxy'
|
||||
import { handleShareRequest, type ShareApiEnv } from './share-api'
|
||||
|
||||
type AssetFetcher = {
|
||||
fetch: (request: Request) => Promise<Response>
|
||||
}
|
||||
|
||||
export type ShotlumaWorkerEnv = {
|
||||
ASSETS: AssetFetcher
|
||||
}
|
||||
export type ShotlumaWorkerEnv = ShareApiEnv
|
||||
|
||||
/**
|
||||
* Hosted same-origin CORS proxy for OpenCode Zen/Go. Browser keys stay on the
|
||||
* request; the worker only rewrites the URL so app.shotluma.com can call an
|
||||
* API that does not answer OPTIONS preflight.
|
||||
* Single Worker entry for app.shotluma.com. It mounts the share API and
|
||||
* share pages (`scripts/share-api.ts`) and the hosted same-origin CORS proxy
|
||||
* for OpenCode Zen/Go — browser keys stay on the request; the worker only
|
||||
* rewrites the URL so app.shotluma.com can call an API that does not answer
|
||||
* OPTIONS preflight. Everything else is served from static assets.
|
||||
*/
|
||||
export default {
|
||||
async fetch(request: Request, env: ShotlumaWorkerEnv): Promise<Response> {
|
||||
const shareResponse = handleShareRequest(request, env)
|
||||
if (shareResponse) return shareResponse
|
||||
if (rewriteOpencodeProxyUrl(new URL(request.url))) {
|
||||
return proxyOpencodeRequest(request)
|
||||
}
|
||||
|
||||
10
src/App.tsx
10
src/App.tsx
@ -3,6 +3,7 @@ import { useAiWorkflow } from './ai/use-ai-workflow'
|
||||
import { AppHeader } from './app/AppHeader'
|
||||
import { loadInitialState } from './app/project-utils'
|
||||
import { ProjectDeleteDialog } from './app/ProjectDeleteDialog'
|
||||
import { ShareLinkDialog } from './app/ShareLinkDialog'
|
||||
import { useProjectWorkspace } from './app/use-project-workspace'
|
||||
import { useSlideExport } from './app/use-slide-export'
|
||||
import { APP_LOGO_URL } from './brand'
|
||||
@ -32,6 +33,7 @@ export default function App() {
|
||||
const [isSidebarOpen, setIsSidebarOpen] = useState(false)
|
||||
const [zoom, setZoom] = useState(0.9)
|
||||
const [toast, setToast] = useState<string | null>(null)
|
||||
const [shareDialogOpen, setShareDialogOpen] = useState(false)
|
||||
|
||||
const selectedElementId = selectedElementIds.at(-1) ?? null
|
||||
const clearSelection = useCallback(() => setSelectedElementIds([]), [])
|
||||
@ -221,6 +223,7 @@ export default function App() {
|
||||
onOpenProject={project.openProject}
|
||||
onCreateProject={project.createNewProject}
|
||||
onDuplicateProject={project.duplicateCurrentProject}
|
||||
onShareProject={() => setShareDialogOpen(true)}
|
||||
onSaveProject={() => void project.saveCurrentProject(true)}
|
||||
onRequestProjectDeletion={() => project.setDeleteDialogOpen(true)}
|
||||
onUndo={history.undo}
|
||||
@ -313,6 +316,13 @@ export default function App() {
|
||||
<button onClick={() => setToast(null)}><X size={14} /></button>
|
||||
</div>
|
||||
)}
|
||||
<ShareLinkDialog
|
||||
open={shareDialogOpen}
|
||||
projectName={project.projectName}
|
||||
slides={slides}
|
||||
uploads={uploads}
|
||||
onOpenChange={setShareDialogOpen}
|
||||
/>
|
||||
<ProjectDeleteDialog
|
||||
open={project.deleteDialogOpen}
|
||||
deleting={project.deletingProject}
|
||||
|
||||
@ -46,6 +46,7 @@ const headerProps = {
|
||||
onOpenProject: () => undefined,
|
||||
onCreateProject: () => undefined,
|
||||
onDuplicateProject: () => undefined,
|
||||
onShareProject: () => undefined,
|
||||
onSaveProject: () => undefined,
|
||||
onRequestProjectDeletion: () => undefined,
|
||||
onUndo: () => undefined,
|
||||
@ -74,6 +75,18 @@ describe('App header', () => {
|
||||
expect(markup).not.toMatch(/aria-label="New project"[^>]*disabled/)
|
||||
})
|
||||
|
||||
it('offers sharing the project as a link from the project menu', () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<AppHeader
|
||||
{...headerProps}
|
||||
saveStatus="saved"
|
||||
persistenceReady
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(markup).toContain('Share as link')
|
||||
})
|
||||
|
||||
it('disables the new-project button until persistence is ready', () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<AppHeader
|
||||
|
||||
@ -7,6 +7,7 @@ import {
|
||||
Cloud,
|
||||
Copy,
|
||||
Download,
|
||||
Link01,
|
||||
Plus,
|
||||
Redo2,
|
||||
Save,
|
||||
@ -46,6 +47,7 @@ type AppHeaderProps = {
|
||||
onOpenProject: (projectId: string) => void
|
||||
onCreateProject: () => void
|
||||
onDuplicateProject: () => void
|
||||
onShareProject: () => void
|
||||
onSaveProject: () => void
|
||||
onRequestProjectDeletion: () => void
|
||||
onUndo: () => void
|
||||
@ -62,6 +64,7 @@ function ProjectMenu({
|
||||
onOpenProject,
|
||||
onCreateProject,
|
||||
onDuplicateProject,
|
||||
onShareProject,
|
||||
onSaveProject,
|
||||
onRequestProjectDeletion,
|
||||
}: Pick<
|
||||
@ -71,6 +74,7 @@ function ProjectMenu({
|
||||
| 'onOpenProject'
|
||||
| 'onCreateProject'
|
||||
| 'onDuplicateProject'
|
||||
| 'onShareProject'
|
||||
| 'onSaveProject'
|
||||
| 'onRequestProjectDeletion'
|
||||
> & { disabled: boolean }) {
|
||||
@ -115,6 +119,10 @@ function ProjectMenu({
|
||||
<Copy size={15} />
|
||||
<span>Duplicate project</span>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="project-menu-action" disabled={disabled} onClick={onShareProject}>
|
||||
<Link01 size={15} />
|
||||
<span>Share as link</span>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="project-menu-action" disabled={disabled} onClick={onSaveProject}>
|
||||
@ -208,6 +216,7 @@ export function AppHeader({
|
||||
onOpenProject,
|
||||
onCreateProject,
|
||||
onDuplicateProject,
|
||||
onShareProject,
|
||||
onSaveProject,
|
||||
onRequestProjectDeletion,
|
||||
onUndo,
|
||||
@ -256,6 +265,7 @@ export function AppHeader({
|
||||
onOpenProject={onOpenProject}
|
||||
onCreateProject={onCreateProject}
|
||||
onDuplicateProject={onDuplicateProject}
|
||||
onShareProject={onShareProject}
|
||||
onSaveProject={onSaveProject}
|
||||
onRequestProjectDeletion={onRequestProjectDeletion}
|
||||
/>
|
||||
|
||||
156
src/app/ShareLinkDialog.tsx
Normal file
156
src/app/ShareLinkDialog.tsx
Normal file
@ -0,0 +1,156 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Check, Copy, Link01 } from '../components/icons'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogMedia,
|
||||
AlertDialogTitle,
|
||||
} from '../components/ui/alert-dialog'
|
||||
import { Button } from '../components/ui/button'
|
||||
import { createShareLink, SHARE_LINK_LENGTH_WARNING, type ShareLinkResult } from './share-link'
|
||||
import { createSharePreviewImage } from './share-preview'
|
||||
import type { Slide, UploadAsset } from '../types'
|
||||
|
||||
type ShareLinkDialogProps = {
|
||||
open: boolean
|
||||
projectName: string
|
||||
slides: Slide[]
|
||||
uploads: UploadAsset[]
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
// Share links can reach megabytes, so the dialog never renders the full URL —
|
||||
// a short preview stands in and the copy button hands over the real thing.
|
||||
const LINK_PREVIEW_LENGTH = 120
|
||||
|
||||
const formatLinkSize = (length: number) => (length >= 1024 * 1024
|
||||
? `${(length / (1024 * 1024)).toFixed(1)} MB`
|
||||
: `${Math.max(1, Math.round(length / 1024))} KB`)
|
||||
|
||||
type ShareRequestKey = readonly [string, Slide[], UploadAsset[]]
|
||||
|
||||
// Everything shown by the dialog is keyed to the inputs that produced it, so
|
||||
// a change to the project while the dialog is open (for example an AI run
|
||||
// mutating slides) immediately renders as pending instead of surfacing the
|
||||
// previous project's link or error.
|
||||
type ShareState = {
|
||||
key: ShareRequestKey
|
||||
result: ShareLinkResult | null
|
||||
failed: boolean
|
||||
copied: boolean
|
||||
copyFailed: boolean
|
||||
}
|
||||
|
||||
export function ShareLinkDialog({
|
||||
open,
|
||||
projectName,
|
||||
slides,
|
||||
uploads,
|
||||
onOpenChange,
|
||||
}: ShareLinkDialogProps) {
|
||||
const [state, setState] = useState<ShareState | null>(null)
|
||||
const key = useMemo<ShareRequestKey>(
|
||||
() => [projectName, slides, uploads],
|
||||
[projectName, slides, uploads],
|
||||
)
|
||||
const active = state !== null && state.key === key ? state : null
|
||||
const link = active?.result ?? null
|
||||
const failed = active?.failed ?? false
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
let cancelled = false
|
||||
const [name, keyedSlides, keyedUploads] = key
|
||||
createShareLink({ projectName: name, slides: keyedSlides, uploads: keyedUploads }, {
|
||||
createPreview: () => createSharePreviewImage(name, keyedSlides),
|
||||
})
|
||||
.then((result) => {
|
||||
if (!cancelled) setState({ key, result, failed: false, copied: false, copyFailed: false })
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setState({ key, result: null, failed: true, copied: false, copyFailed: false })
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [open, key])
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
if (!nextOpen) setState(null)
|
||||
onOpenChange(nextOpen)
|
||||
}
|
||||
|
||||
const copyLink = async () => {
|
||||
if (!link) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(link.url)
|
||||
setState((current) => current && { ...current, copied: true, copyFailed: false })
|
||||
} catch {
|
||||
setState((current) => current && { ...current, copyFailed: true })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<AlertDialog open={open} onOpenChange={handleOpenChange}>
|
||||
<AlertDialogContent className="share-link-dialog">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogMedia><Link01 size={17} /></AlertDialogMedia>
|
||||
<AlertDialogTitle>Share as link</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
The link carries a full copy of “{projectName}”, images included.
|
||||
Whoever opens it gets their own local copy to edit or delete —
|
||||
without ever touching your project.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<div className="share-link-dialog-body">
|
||||
{failed && <p className="share-link-dialog-error">The share link couldn’t be created.</p>}
|
||||
{!failed && !link && <p className="share-link-dialog-status">Preparing link …</p>}
|
||||
{link && (
|
||||
<>
|
||||
<div className="share-link-dialog-preview" aria-label="Share link preview">
|
||||
{link.url.length > LINK_PREVIEW_LENGTH ? `${link.url.slice(0, LINK_PREVIEW_LENGTH)}…` : link.url}
|
||||
</div>
|
||||
<p className="share-link-dialog-meta">
|
||||
{link.mode === 'short'
|
||||
? 'The shared copy is stored for 90 days; the project itself stays local.'
|
||||
: `${formatLinkSize(link.url.length)} link — the share service couldn’t be reached, so this link carries the full project data.${
|
||||
link.url.length > SHARE_LINK_LENGTH_WARNING
|
||||
? ' Some messengers truncate links this size.'
|
||||
: ''}`}
|
||||
</p>
|
||||
{active?.copyFailed && (
|
||||
<>
|
||||
<p className="share-link-dialog-error">
|
||||
Copying was blocked by the browser — select the link below instead.
|
||||
</p>
|
||||
<input
|
||||
className="share-link-dialog-fallback"
|
||||
value={link.url}
|
||||
readOnly
|
||||
aria-label="Share link"
|
||||
onFocus={(event) => event.currentTarget.select()}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel className="share-link-dialog-close">Close</AlertDialogCancel>
|
||||
<Button
|
||||
type="button"
|
||||
className="share-link-dialog-copy"
|
||||
disabled={!link}
|
||||
onClick={() => void copyLink()}
|
||||
>
|
||||
{active?.copied ? <><Check size={14} /> Copied</> : <><Copy size={14} /> Copy link</>}
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)
|
||||
}
|
||||
286
src/app/share-link.test.ts
Normal file
286
src/app/share-link.test.ts
Normal file
@ -0,0 +1,286 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
consumeShareLinkHash,
|
||||
createShareLink,
|
||||
decodeSharePayload,
|
||||
SHARE_HASH_PREFIX,
|
||||
SHORT_SHARE_HASH_PREFIX,
|
||||
SHORT_SHARE_PATH_PREFIX,
|
||||
type SharedProjectPayload,
|
||||
} from './share-link'
|
||||
import type { Slide, TextElement } from '../types'
|
||||
|
||||
const makeSlide = (overrides: Partial<Slide> = {}): Slide => ({
|
||||
id: 'slide-1',
|
||||
name: 'Hero',
|
||||
background: { type: 'solid', color1: '#111111', color2: '#222222', angle: 45 },
|
||||
elements: [],
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const makeTextElement = (overrides: Partial<TextElement> = {}): TextElement => ({
|
||||
id: 'element-1',
|
||||
type: 'text',
|
||||
x: 10,
|
||||
y: 12,
|
||||
width: 60,
|
||||
rotation: 0,
|
||||
opacity: 1,
|
||||
text: 'Hello',
|
||||
color: '#ffffff',
|
||||
fontFamily: 'Geist',
|
||||
fontSize: 32,
|
||||
fontWeight: 700,
|
||||
align: 'center',
|
||||
lineHeight: 1.2,
|
||||
letterSpacing: 0,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const makeProject = (overrides: Partial<SharedProjectPayload> = {}): SharedProjectPayload => ({
|
||||
projectName: 'Summer Launch',
|
||||
slides: [makeSlide({ elements: [makeTextElement()] })],
|
||||
uploads: [],
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const hashOf = (link: string) => link.slice(link.indexOf('#'))
|
||||
|
||||
/** Builds an inline fallback link (the share API is stubbed offline). */
|
||||
const inlineShareHash = async (project: SharedProjectPayload) =>
|
||||
hashOf((await createShareLink(project)).url)
|
||||
|
||||
const compressJson = async (value: unknown): Promise<Uint8Array<ArrayBuffer>> => {
|
||||
const bytes = new TextEncoder().encode(JSON.stringify(value))
|
||||
const stream = new ReadableStream<BufferSource>({
|
||||
start(controller) {
|
||||
controller.enqueue(bytes)
|
||||
controller.close()
|
||||
},
|
||||
}).pipeThrough(new CompressionStream('deflate-raw'))
|
||||
return new Uint8Array(await new Response(stream).arrayBuffer())
|
||||
}
|
||||
|
||||
// Handcrafts a `#share=` fragment the way an attacker could, bypassing
|
||||
// createShareLink's well-formed input assumptions.
|
||||
const craftShareHash = async (value: unknown) => {
|
||||
const compressed = await compressJson(value)
|
||||
const base64 = btoa(String.fromCharCode(...compressed))
|
||||
return `${SHARE_HASH_PREFIX}${base64.replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '')}`
|
||||
}
|
||||
|
||||
describe('share links', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('fetch', vi.fn(() => Promise.reject(new Error('share API offline'))))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('falls back to a self-contained link when the share API is unreachable', async () => {
|
||||
const project = makeProject({
|
||||
uploads: [{ id: 'upload-1', name: 'shot.png', src: 'data:image/png;base64,aGk=' }],
|
||||
})
|
||||
|
||||
const result = await createShareLink(project)
|
||||
expect(result.mode).toBe('inline')
|
||||
expect(result.url).toContain(SHARE_HASH_PREFIX)
|
||||
|
||||
const decoded = await decodeSharePayload(hashOf(result.url))
|
||||
expect(decoded).toEqual(project)
|
||||
})
|
||||
|
||||
it('creates a short /s/ link and uploads the unfurl preview', async () => {
|
||||
const upload = vi.fn((input: unknown) => Promise.resolve({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(input === '/api/share' ? { id: 'abcDEF123456' } : { ok: true }),
|
||||
}))
|
||||
vi.stubGlobal('fetch', upload)
|
||||
|
||||
const result = await createShareLink(makeProject(), {
|
||||
createPreview: () => Promise.resolve(new Blob(['jpeg'], { type: 'image/jpeg' })),
|
||||
})
|
||||
expect(result.mode).toBe('short')
|
||||
expect(result.url).toBe(`${window.location.origin}${SHORT_SHARE_PATH_PREFIX}abcDEF123456`)
|
||||
expect(upload).toHaveBeenCalledWith('/api/share', expect.objectContaining({ method: 'POST' }))
|
||||
expect(upload).toHaveBeenCalledWith(
|
||||
'/api/share/abcDEF123456/preview?title=Summer%20Launch',
|
||||
expect.objectContaining({ method: 'POST' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('creates the short link even when rendering the preview fails', async () => {
|
||||
const upload = vi.fn((input: unknown) => Promise.resolve({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(input === '/api/share' ? { id: 'abcDEF123456' } : { ok: true }),
|
||||
}))
|
||||
vi.stubGlobal('fetch', upload)
|
||||
|
||||
const result = await createShareLink(makeProject(), {
|
||||
createPreview: () => Promise.reject(new Error('no canvas')),
|
||||
})
|
||||
expect(result.mode).toBe('short')
|
||||
})
|
||||
|
||||
it('falls back to a self-contained link when the API answers with something else', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(() => Promise.resolve({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ unexpected: true }),
|
||||
})))
|
||||
|
||||
const result = await createShareLink(makeProject())
|
||||
expect(result.mode).toBe('inline')
|
||||
})
|
||||
|
||||
it('decodes a short link by downloading the stored payload', async () => {
|
||||
const project = makeProject()
|
||||
const payload = await compressJson({ v: 1, ...project })
|
||||
const download = vi.fn(() => Promise.resolve({
|
||||
ok: true,
|
||||
arrayBuffer: () => Promise.resolve(payload.buffer),
|
||||
}))
|
||||
vi.stubGlobal('fetch', download)
|
||||
|
||||
const decoded = await decodeSharePayload(`${SHORT_SHARE_HASH_PREFIX}abcDEF123456`)
|
||||
expect(decoded).toEqual(project)
|
||||
expect(download).toHaveBeenCalledWith(
|
||||
'/api/share/abcDEF123456',
|
||||
expect.objectContaining({ signal: expect.any(AbortSignal) as unknown }),
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects malformed short ids without calling the API', async () => {
|
||||
const download = vi.fn()
|
||||
vi.stubGlobal('fetch', download)
|
||||
|
||||
expect(await decodeSharePayload(`${SHORT_SHARE_HASH_PREFIX}../evil`)).toBeNull()
|
||||
expect(await decodeSharePayload(`${SHORT_SHARE_HASH_PREFIX}ab`)).toBeNull()
|
||||
expect(download).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns null when the stored payload is missing or expired', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(() => Promise.resolve({ ok: false, status: 404 })))
|
||||
|
||||
expect(await decodeSharePayload(`${SHORT_SHARE_HASH_PREFIX}abcDEF123456`)).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps inline data URL image sources intact for the recipient', async () => {
|
||||
const slide = makeSlide({
|
||||
background: {
|
||||
type: 'image',
|
||||
color1: '#111111',
|
||||
color2: '#222222',
|
||||
angle: 0,
|
||||
image: 'data:image/png;base64,aGk=',
|
||||
},
|
||||
})
|
||||
|
||||
const decoded = await decodeSharePayload(await inlineShareHash(makeProject({ slides: [slide] })))
|
||||
expect(decoded?.slides[0]?.background.image).toBe('data:image/png;base64,aGk=')
|
||||
})
|
||||
|
||||
it('sanitizes AI screen markup carried by a link', async () => {
|
||||
const slide = makeSlide({ html: '<div>Safe</div><script>alert(1)</script>' })
|
||||
|
||||
const decoded = await decodeSharePayload(await inlineShareHash(makeProject({ slides: [slide] })))
|
||||
expect(decoded?.slides[0]?.html).toContain('Safe')
|
||||
expect(decoded?.slides[0]?.html).not.toContain('script')
|
||||
})
|
||||
|
||||
it('sanitizes rich text markup on text elements', async () => {
|
||||
const element = makeTextElement({ html: 'Hi <img src="x" onerror="alert(1)"> there' })
|
||||
|
||||
const decoded = await decodeSharePayload(
|
||||
await inlineShareHash(makeProject({ slides: [makeSlide({ elements: [element] })] })),
|
||||
)
|
||||
const decodedElement = decoded?.slides[0]?.elements[0]
|
||||
expect(decodedElement?.type).toBe('text')
|
||||
expect((decodedElement as TextElement).html).not.toContain('onerror')
|
||||
expect((decodedElement as TextElement).html).not.toContain('img')
|
||||
})
|
||||
|
||||
it('drops unsafe image source schemes from a handcrafted payload', async () => {
|
||||
const slide = makeSlide({
|
||||
elements: [{
|
||||
id: 'element-2',
|
||||
type: 'image',
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 50,
|
||||
rotation: 0,
|
||||
opacity: 1,
|
||||
src: 'javascript:alert(1)',
|
||||
borderRadius: 0,
|
||||
}],
|
||||
})
|
||||
|
||||
const decoded = await decodeSharePayload(await inlineShareHash(makeProject({ slides: [slide] })))
|
||||
const decodedElement = decoded?.slides[0]?.elements[0]
|
||||
expect(decodedElement?.type).toBe('image')
|
||||
expect(decodedElement && 'src' in decodedElement ? decodedElement.src : null).toBe('')
|
||||
})
|
||||
|
||||
it('drops malformed slides, elements, and uploads instead of importing them', async () => {
|
||||
const hash = await craftShareHash({
|
||||
v: 1,
|
||||
projectName: 'Mixed bag',
|
||||
slides: [makeSlide(), { id: 42 }, 'nonsense'],
|
||||
uploads: [{ id: 'upload-1', name: 'ok.png', src: 'data:image/png;base64,aGk=' }, { id: 7 }],
|
||||
})
|
||||
|
||||
const decoded = await decodeSharePayload(hash)
|
||||
expect(decoded?.slides).toHaveLength(1)
|
||||
expect(decoded?.uploads).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('supports projects with zero slides', async () => {
|
||||
const decoded = await decodeSharePayload(await inlineShareHash(makeProject({ slides: [] })))
|
||||
expect(decoded?.slides).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects payloads that are not valid share links', async () => {
|
||||
expect(await decodeSharePayload('#other=abc')).toBeNull()
|
||||
expect(await decodeSharePayload(`${SHARE_HASH_PREFIX}not-real-base64!!!`)).toBeNull()
|
||||
expect(await decodeSharePayload(`${SHARE_HASH_PREFIX}${btoa('plain json')}`)).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects a payload with an unknown format version', async () => {
|
||||
expect(await decodeSharePayload(await craftShareHash({ v: 99, slides: [] }))).toBeNull()
|
||||
})
|
||||
|
||||
it('consumes short and inline share fragments exactly once', () => {
|
||||
window.location.hash = `${SHARE_HASH_PREFIX}payload`
|
||||
expect(consumeShareLinkHash()).toBe(`${SHARE_HASH_PREFIX}payload`)
|
||||
expect(window.location.hash).toBe('')
|
||||
expect(consumeShareLinkHash()).toBeNull()
|
||||
|
||||
window.location.hash = `${SHORT_SHARE_HASH_PREFIX}abcDEF123456`
|
||||
expect(consumeShareLinkHash()).toBe(`${SHORT_SHARE_HASH_PREFIX}abcDEF123456`)
|
||||
expect(window.location.hash).toBe('')
|
||||
})
|
||||
|
||||
it('consumes a /s/<id> share path and rewrites the URL back to the root', () => {
|
||||
history.replaceState(null, '', `${SHORT_SHARE_PATH_PREFIX}abcDEF123456`)
|
||||
|
||||
expect(consumeShareLinkHash()).toBe(`${SHORT_SHARE_HASH_PREFIX}abcDEF123456`)
|
||||
expect(window.location.pathname).toBe('/')
|
||||
expect(consumeShareLinkHash()).toBeNull()
|
||||
})
|
||||
|
||||
it('leaves /s/ paths that are not share ids alone', () => {
|
||||
history.replaceState(null, '', `${SHORT_SHARE_PATH_PREFIX}ab`)
|
||||
|
||||
expect(consumeShareLinkHash()).toBeNull()
|
||||
expect(window.location.pathname).toBe(`${SHORT_SHARE_PATH_PREFIX}ab`)
|
||||
history.replaceState(null, '', '/')
|
||||
})
|
||||
|
||||
it('ignores unrelated fragments', () => {
|
||||
window.location.hash = '#section'
|
||||
|
||||
expect(consumeShareLinkHash()).toBeNull()
|
||||
expect(window.location.hash).toBe('#section')
|
||||
window.location.hash = ''
|
||||
})
|
||||
})
|
||||
336
src/app/share-link.ts
Normal file
336
src/app/share-link.ts
Normal file
@ -0,0 +1,336 @@
|
||||
import { collectAssetSources, mapAssetSources } from '../asset-sources'
|
||||
import { hydrateProjectAssets } from '../asset-store'
|
||||
import { sanitizeScreenHtml } from '../html-slide/sanitize'
|
||||
import { fileToDataUrl, sanitizeRichText } from '../utils'
|
||||
import type { Background, CanvasElement, Slide, UploadAsset } from '../types'
|
||||
|
||||
/**
|
||||
* Project share links. The share payload is the project as deflate-raw
|
||||
* compressed JSON — screens, uploads, and every image inlined as a data URL —
|
||||
* so a link always transfers a complete, independent copy. Two link forms
|
||||
* exist:
|
||||
*
|
||||
* - `/s/<id>` (preferred): the payload is stored by the share API
|
||||
* (`scripts/share-api.ts`, Cloudflare KV, 90-day retention) and the link
|
||||
* stays short. The id lives in the path — not the fragment — so the Worker
|
||||
* can serve per-share Open Graph tags to link-preview crawlers; the app
|
||||
* itself consumes the id on boot and rewrites the URL back to `/`. A
|
||||
* rendered preview image and the project name are uploaded best-effort for
|
||||
* that unfurl. `#s=<id>` stays readable for compatibility.
|
||||
* - `#share=<base64url payload>` (fallback): when the share API is
|
||||
* unreachable, the link carries the payload itself and can get very long,
|
||||
* but sharing keeps working without any server.
|
||||
*
|
||||
* Opening either link imports an independent copy into the recipient's local
|
||||
* workspace; their edits and deletions stay on their device and never affect
|
||||
* the sender's project.
|
||||
*
|
||||
* A share payload is untrusted input: a link can be handcrafted, so decoding
|
||||
* re-sanitizes AI screen markup and rich text and drops unsafe image sources
|
||||
* before anything reaches the editor.
|
||||
*/
|
||||
|
||||
export type SharedProjectPayload = {
|
||||
projectName: string
|
||||
slides: Slide[]
|
||||
uploads: UploadAsset[]
|
||||
}
|
||||
|
||||
export const SHARE_HASH_PREFIX = '#share='
|
||||
export const SHORT_SHARE_HASH_PREFIX = '#s='
|
||||
export const SHORT_SHARE_PATH_PREFIX = '/s/'
|
||||
|
||||
const SHARE_API_PATH = '/api/share'
|
||||
const SHARE_ID_PATTERN = /^[A-Za-z0-9_-]{6,32}$/
|
||||
const SHARE_FORMAT_VERSION = 1
|
||||
|
||||
// A stalled share API request must degrade to the inline fallback (or a
|
||||
// failed import) instead of leaving the dialog on "Preparing link …" forever.
|
||||
const SHARE_API_TIMEOUT_MS = 15_000
|
||||
|
||||
// Ceiling for the decompressed payload so a handcrafted link cannot act as a
|
||||
// decompression bomb against the importing tab.
|
||||
const MAX_DECODED_BYTES = 64 * 1024 * 1024
|
||||
|
||||
/** Links longer than this are likely to be truncated by messengers. */
|
||||
export const SHARE_LINK_LENGTH_WARNING = 30_000
|
||||
|
||||
const bytesToBase64Url = (bytes: Uint8Array): string => {
|
||||
let binary = ''
|
||||
const chunkSize = 0x8000
|
||||
for (let index = 0; index < bytes.length; index += chunkSize) {
|
||||
binary += String.fromCharCode(...bytes.subarray(index, index + chunkSize))
|
||||
}
|
||||
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '')
|
||||
}
|
||||
|
||||
const base64UrlToBytes = (encoded: string): Uint8Array<ArrayBuffer> => {
|
||||
const binary = atob(encoded.replaceAll('-', '+').replaceAll('_', '/'))
|
||||
const bytes = new Uint8Array(binary.length)
|
||||
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index)
|
||||
return bytes
|
||||
}
|
||||
|
||||
// jsdom's Blob lacks stream(), so the pipelines start from a plain
|
||||
// ReadableStream over the raw bytes instead. BufferSource chunks match the
|
||||
// writable side of Compression/DecompressionStream.
|
||||
const bytesToStream = (bytes: Uint8Array<ArrayBuffer>): ReadableStream<BufferSource> =>
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(bytes)
|
||||
controller.close()
|
||||
},
|
||||
})
|
||||
|
||||
const compressText = async (text: string): Promise<Uint8Array<ArrayBuffer>> => {
|
||||
const stream = bytesToStream(new TextEncoder().encode(text)).pipeThrough(new CompressionStream('deflate-raw'))
|
||||
return new Uint8Array(await new Response(stream).arrayBuffer())
|
||||
}
|
||||
|
||||
const decompressBytes = async (bytes: Uint8Array<ArrayBuffer>): Promise<string> => {
|
||||
const stream = bytesToStream(bytes).pipeThrough(new DecompressionStream('deflate-raw'))
|
||||
const reader = stream.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let decodedBytes = 0
|
||||
let text = ''
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) return text + decoder.decode()
|
||||
decodedBytes += value.byteLength
|
||||
if (decodedBytes > MAX_DECODED_BYTES) {
|
||||
void reader.cancel()
|
||||
throw new Error('The share payload is too large.')
|
||||
}
|
||||
text += decoder.decode(value, { stream: true })
|
||||
}
|
||||
}
|
||||
|
||||
// Images dominate link length, so shared copies are capped at export
|
||||
// resolution and re-encoded as WebP. The smaller encoding wins; failures fall
|
||||
// back to the original bytes.
|
||||
const MAX_SHARED_IMAGE_DIMENSION = 2796
|
||||
const SHARED_IMAGE_WEBP_QUALITY = 0.85
|
||||
|
||||
const reencodeImageBlob = async (blob: Blob): Promise<Blob> => {
|
||||
if (blob.type === 'image/svg+xml') return blob
|
||||
try {
|
||||
const bitmap = await createImageBitmap(blob)
|
||||
const scale = Math.min(1, MAX_SHARED_IMAGE_DIMENSION / Math.max(bitmap.width, bitmap.height))
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = Math.max(1, Math.round(bitmap.width * scale))
|
||||
canvas.height = Math.max(1, Math.round(bitmap.height * scale))
|
||||
const context = canvas.getContext('2d')
|
||||
if (!context) return blob
|
||||
context.drawImage(bitmap, 0, 0, canvas.width, canvas.height)
|
||||
bitmap.close()
|
||||
const encoded = await new Promise<Blob | null>((resolve) => {
|
||||
canvas.toBlob(resolve, 'image/webp', SHARED_IMAGE_WEBP_QUALITY)
|
||||
})
|
||||
return encoded && encoded.size < blob.size ? encoded : blob
|
||||
} catch {
|
||||
return blob
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces session-local object URLs with inlined data URLs so the link is
|
||||
* meaningful on another device. Sources that cannot be read keep their URL and
|
||||
* degrade to a missing image instead of failing the whole share.
|
||||
*/
|
||||
const inlineImageSources = async (project: SharedProjectPayload): Promise<SharedProjectPayload> => {
|
||||
const hydrated = await hydrateProjectAssets(project)
|
||||
const replacements = new Map<string, string>()
|
||||
for (const src of collectAssetSources(hydrated)) {
|
||||
if (!src.startsWith('blob:')) continue
|
||||
try {
|
||||
const blob = await (await fetch(src)).blob()
|
||||
replacements.set(src, await fileToDataUrl(await reencodeImageBlob(blob)))
|
||||
} catch {
|
||||
// Keep the source as-is; see above.
|
||||
}
|
||||
}
|
||||
return mapAssetSources(hydrated, (src) => replacements.get(src) ?? src)
|
||||
}
|
||||
|
||||
export type ShareLinkResult = {
|
||||
url: string
|
||||
/** 'short' when the payload is stored by the share API; 'inline' when the URL carries it. */
|
||||
mode: 'short' | 'inline'
|
||||
}
|
||||
|
||||
const requestShortShareId = async (payload: Uint8Array<ArrayBuffer>): Promise<string | null> => {
|
||||
try {
|
||||
const response = await fetch(SHARE_API_PATH, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/octet-stream' },
|
||||
body: payload,
|
||||
signal: AbortSignal.timeout(SHARE_API_TIMEOUT_MS),
|
||||
})
|
||||
if (!response.ok) return null
|
||||
const result = (await response.json()) as { id?: unknown }
|
||||
return typeof result.id === 'string' && SHARE_ID_PATTERN.test(result.id) ? result.id : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploads the unfurl artwork and title for a stored share. Best-effort: the
|
||||
* link works without it, it just unfurls generically.
|
||||
*/
|
||||
const uploadSharePreview = async (id: string, title: string, preview: Blob | null): Promise<void> => {
|
||||
try {
|
||||
await fetch(`${SHARE_API_PATH}/${id}/preview?title=${encodeURIComponent(title)}`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'image/jpeg' },
|
||||
body: preview ?? new Blob([]),
|
||||
signal: AbortSignal.timeout(SHARE_API_TIMEOUT_MS),
|
||||
})
|
||||
} catch {
|
||||
// See above.
|
||||
}
|
||||
}
|
||||
|
||||
export type ShareLinkOptions = {
|
||||
/** Renders the Open Graph preview image; only invoked for short links. */
|
||||
createPreview?: () => Promise<Blob | null>
|
||||
}
|
||||
|
||||
export const createShareLink = async (
|
||||
project: SharedProjectPayload,
|
||||
options: ShareLinkOptions = {},
|
||||
): Promise<ShareLinkResult> => {
|
||||
const inlined = await inlineImageSources(project)
|
||||
const json = JSON.stringify({
|
||||
v: SHARE_FORMAT_VERSION,
|
||||
projectName: inlined.projectName,
|
||||
slides: inlined.slides,
|
||||
uploads: inlined.uploads,
|
||||
})
|
||||
const compressed = await compressText(json)
|
||||
const { origin, pathname } = window.location
|
||||
|
||||
const id = await requestShortShareId(compressed)
|
||||
if (id) {
|
||||
const preview = options.createPreview ? await options.createPreview().catch(() => null) : null
|
||||
await uploadSharePreview(id, project.projectName, preview)
|
||||
return { url: `${origin}${SHORT_SHARE_PATH_PREFIX}${id}`, mode: 'short' }
|
||||
}
|
||||
return { url: `${origin}${pathname}${SHARE_HASH_PREFIX}${bytesToBase64Url(compressed)}`, mode: 'inline' }
|
||||
}
|
||||
|
||||
// Sources render through <img> and CSS backgrounds only, but a handcrafted
|
||||
// payload gets no chance to smuggle in exotic schemes regardless.
|
||||
const isSafeImageSource = (src: string): boolean =>
|
||||
src.startsWith('data:image/')
|
||||
|| src.startsWith('https://')
|
||||
|| src.startsWith('http://')
|
||||
|| src.startsWith('blob-asset:')
|
||||
|| !src.includes(':')
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === 'object' && value !== null
|
||||
|
||||
const normalizeSharedElement = (value: unknown): CanvasElement | null => {
|
||||
if (!isRecord(value) || typeof value['id'] !== 'string' || typeof value['type'] !== 'string') return null
|
||||
const element = value as unknown as CanvasElement
|
||||
if (element.type === 'text' && typeof element.html === 'string') {
|
||||
return { ...element, html: sanitizeRichText(element.html) }
|
||||
}
|
||||
return element
|
||||
}
|
||||
|
||||
const normalizeSharedSlide = (value: unknown): Slide | null => {
|
||||
if (!isRecord(value)) return null
|
||||
if (typeof value['id'] !== 'string' || typeof value['name'] !== 'string') return null
|
||||
if (!isRecord(value['background']) || !Array.isArray(value['elements'])) return null
|
||||
|
||||
const slide: Slide = {
|
||||
id: value['id'],
|
||||
name: value['name'],
|
||||
background: value['background'] as unknown as Background,
|
||||
elements: value['elements']
|
||||
.map(normalizeSharedElement)
|
||||
.filter((element): element is CanvasElement => element !== null),
|
||||
}
|
||||
if (typeof value['html'] === 'string') slide.html = sanitizeScreenHtml(value['html']).html
|
||||
return slide
|
||||
}
|
||||
|
||||
const normalizeSharedUpload = (value: unknown): UploadAsset | null => {
|
||||
if (!isRecord(value)) return null
|
||||
if (typeof value['id'] !== 'string' || typeof value['name'] !== 'string' || typeof value['src'] !== 'string') return null
|
||||
return { id: value['id'], name: value['name'], src: value['src'] }
|
||||
}
|
||||
|
||||
const normalizeSharedProject = (value: unknown): SharedProjectPayload | null => {
|
||||
if (!isRecord(value) || value['v'] !== SHARE_FORMAT_VERSION) return null
|
||||
if (!Array.isArray(value['slides'])) return null
|
||||
|
||||
const project: SharedProjectPayload = {
|
||||
projectName: typeof value['projectName'] === 'string' && value['projectName'].trim() !== ''
|
||||
? value['projectName']
|
||||
: 'Shared project',
|
||||
slides: value['slides']
|
||||
.map(normalizeSharedSlide)
|
||||
.filter((slide): slide is Slide => slide !== null),
|
||||
uploads: (Array.isArray(value['uploads']) ? value['uploads'] : [])
|
||||
.map(normalizeSharedUpload)
|
||||
.filter((upload): upload is UploadAsset => upload !== null),
|
||||
}
|
||||
return mapAssetSources(project, (src) => (isSafeImageSource(src) ? src : ''))
|
||||
}
|
||||
|
||||
const fetchStoredPayloadBytes = async (id: string): Promise<Uint8Array<ArrayBuffer> | null> => {
|
||||
if (!SHARE_ID_PATTERN.test(id)) return null
|
||||
const response = await fetch(`${SHARE_API_PATH}/${id}`, {
|
||||
signal: AbortSignal.timeout(SHARE_API_TIMEOUT_MS),
|
||||
})
|
||||
if (!response.ok) return null
|
||||
return new Uint8Array(await response.arrayBuffer())
|
||||
}
|
||||
|
||||
const sharePayloadBytes = async (hash: string): Promise<Uint8Array<ArrayBuffer> | null> => {
|
||||
if (hash.startsWith(SHORT_SHARE_HASH_PREFIX)) {
|
||||
return fetchStoredPayloadBytes(hash.slice(SHORT_SHARE_HASH_PREFIX.length))
|
||||
}
|
||||
if (hash.startsWith(SHARE_HASH_PREFIX)) {
|
||||
return base64UrlToBytes(hash.slice(SHARE_HASH_PREFIX.length))
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Decodes and validates a `#s=` or `#share=` fragment; null when it cannot be trusted. */
|
||||
export const decodeSharePayload = async (hash: string): Promise<SharedProjectPayload | null> => {
|
||||
try {
|
||||
const bytes = await sharePayloadBytes(hash)
|
||||
if (!bytes) return null
|
||||
const parsed: unknown = JSON.parse(await decompressBytes(bytes))
|
||||
return normalizeSharedProject(parsed)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const isShareHash = (hash: string) =>
|
||||
hash.startsWith(SHARE_HASH_PREFIX) || hash.startsWith(SHORT_SHARE_HASH_PREFIX)
|
||||
|
||||
/**
|
||||
* Reads and clears a pending share fragment or `/s/<id>` path so a reload
|
||||
* does not re-import the project. Returns a hash for {@link decodeSharePayload}.
|
||||
*/
|
||||
export const consumeShareLinkHash = (): string | null => {
|
||||
const { hash, pathname, search } = window.location
|
||||
if (isShareHash(hash)) {
|
||||
history.replaceState(null, '', `${pathname}${search}`)
|
||||
return hash
|
||||
}
|
||||
if (pathname.startsWith(SHORT_SHARE_PATH_PREFIX)) {
|
||||
const id = pathname.slice(SHORT_SHARE_PATH_PREFIX.length)
|
||||
if (SHARE_ID_PATTERN.test(id)) {
|
||||
history.replaceState(null, '', `/${search}`)
|
||||
return `${SHORT_SHARE_HASH_PREFIX}${id}`
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
225
src/app/share-preview.ts
Normal file
225
src/app/share-preview.ts
Normal file
@ -0,0 +1,225 @@
|
||||
import { toCanvas } from 'html-to-image'
|
||||
import { EXPORT_ARTBOARD_WIDTH, EXPORT_FORMATS } from './export-formats'
|
||||
import type { Slide } from '../types'
|
||||
|
||||
/**
|
||||
* Renders the Open Graph preview image for a share link: up to three screens
|
||||
* captured from the live artboard DOM, composed on a gradient drawn from the
|
||||
* first screen's background colors, with the project name set in the UI face.
|
||||
* The share flow treats the preview as best-effort — any failure returns null
|
||||
* and the link still works, it just unfurls without an image.
|
||||
*/
|
||||
|
||||
export const SHARE_PREVIEW_WIDTH = 1200
|
||||
export const SHARE_PREVIEW_HEIGHT = 630
|
||||
|
||||
const MAX_PREVIEW_SCREENS = 3
|
||||
const PREVIEW_JPEG_QUALITY = 0.9
|
||||
|
||||
const ARTBOARD_ASPECT = EXPORT_FORMATS[0].width / EXPORT_FORMATS[0].height
|
||||
|
||||
const captureSlideCanvas = async (slide: Slide, screenHeight: number): Promise<HTMLCanvasElement | null> => {
|
||||
const node = document.getElementById(`artboard-${slide.id}`)
|
||||
if (!node) return null
|
||||
try {
|
||||
return await toCanvas(node, {
|
||||
pixelRatio: 1,
|
||||
width: EXPORT_ARTBOARD_WIDTH,
|
||||
height: EXPORT_ARTBOARD_WIDTH / ARTBOARD_ASPECT,
|
||||
canvasWidth: Math.round(screenHeight * ARTBOARD_ASPECT),
|
||||
canvasHeight: screenHeight,
|
||||
backgroundColor: slide.background.color1,
|
||||
filter: (candidate: HTMLElement) =>
|
||||
!(candidate instanceof HTMLElement && candidate.dataset['aiOverlay']),
|
||||
})
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const parseHexColor = (value: string): { r: number; g: number; b: number } | null => {
|
||||
const match = /^#([0-9a-f]{6})$/i.exec(value.trim())
|
||||
if (!match?.[1]) return null
|
||||
const hex = Number.parseInt(match[1], 16)
|
||||
return { r: (hex >> 16) & 255, g: (hex >> 8) & 255, b: hex & 255 }
|
||||
}
|
||||
|
||||
const isLightColor = (value: string): boolean => {
|
||||
const rgb = parseHexColor(value)
|
||||
if (!rgb) return false
|
||||
return (0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b) / 255 > 0.62
|
||||
}
|
||||
|
||||
type ScreenPlacement = { x: number; y: number; rotation: number; height: number; z: number }
|
||||
|
||||
// Indexed by slide order: the first screen takes the hero spot in front.
|
||||
const screenPlacements = (count: number): ScreenPlacement[] => {
|
||||
if (count >= 3) {
|
||||
return [
|
||||
{ x: 860, y: 310, rotation: 0.02, height: 500, z: 2 },
|
||||
{ x: 690, y: 345, rotation: -0.1, height: 470, z: 0 },
|
||||
{ x: 1030, y: 360, rotation: 0.12, height: 470, z: 1 },
|
||||
]
|
||||
}
|
||||
if (count === 2) {
|
||||
return [
|
||||
{ x: 750, y: 340, rotation: -0.07, height: 490, z: 1 },
|
||||
{ x: 985, y: 320, rotation: 0.06, height: 490, z: 0 },
|
||||
]
|
||||
}
|
||||
return [{ x: 880, y: 330, rotation: 0.03, height: 540, z: 0 }]
|
||||
}
|
||||
|
||||
const drawScreen = (
|
||||
context: CanvasRenderingContext2D,
|
||||
screen: HTMLCanvasElement,
|
||||
placement: ScreenPlacement,
|
||||
) => {
|
||||
const height = placement.height
|
||||
const width = Math.round(height * ARTBOARD_ASPECT)
|
||||
context.save()
|
||||
context.translate(placement.x, placement.y)
|
||||
context.rotate(placement.rotation)
|
||||
const frame = new Path2D()
|
||||
frame.roundRect(-width / 2, -height / 2, width, height, 18)
|
||||
context.shadowColor = 'rgba(10, 12, 24, 0.45)'
|
||||
context.shadowBlur = 42
|
||||
context.shadowOffsetY = 22
|
||||
context.fillStyle = '#ffffff'
|
||||
context.fill(frame)
|
||||
context.shadowColor = 'transparent'
|
||||
context.shadowBlur = 0
|
||||
context.shadowOffsetY = 0
|
||||
context.clip(frame)
|
||||
context.drawImage(screen, -width / 2, -height / 2, width, height)
|
||||
context.restore()
|
||||
}
|
||||
|
||||
const ellipsize = (context: CanvasRenderingContext2D, text: string, maxWidth: number): string => {
|
||||
if (context.measureText(text).width <= maxWidth) return text
|
||||
let trimmed = text.replace(/…$/, '')
|
||||
while (trimmed.length > 1 && context.measureText(`${trimmed}…`).width > maxWidth) {
|
||||
trimmed = trimmed.slice(0, -1)
|
||||
}
|
||||
return `${trimmed}…`
|
||||
}
|
||||
|
||||
const wrapProjectName = (
|
||||
context: CanvasRenderingContext2D,
|
||||
name: string,
|
||||
maxWidth: number,
|
||||
): string[] => {
|
||||
const words = name.trim().split(/\s+/)
|
||||
const lines: string[] = []
|
||||
let current = ''
|
||||
for (const word of words) {
|
||||
const candidate = current === '' ? word : `${current} ${word}`
|
||||
if (current !== '' && context.measureText(candidate).width > maxWidth) {
|
||||
lines.push(current)
|
||||
current = word
|
||||
} else {
|
||||
current = candidate
|
||||
}
|
||||
}
|
||||
if (current !== '') lines.push(current)
|
||||
|
||||
// At most two lines fit the layout; a dropped remainder gets an ellipsis so
|
||||
// truncation is visible.
|
||||
const shown = lines.slice(0, 2)
|
||||
const overflowed = lines.length > shown.length
|
||||
return shown.map((line, index) => {
|
||||
const marked = overflowed && index === shown.length - 1 ? `${line}…` : line
|
||||
return ellipsize(context, marked, maxWidth)
|
||||
})
|
||||
}
|
||||
|
||||
const drawBackdrop = (context: CanvasRenderingContext2D, slide: Slide | undefined) => {
|
||||
const color1 = slide?.background.color1 ?? '#101014'
|
||||
const color2 = slide?.background.color2 ?? '#1c1c26'
|
||||
const gradient = context.createLinearGradient(0, 0, SHARE_PREVIEW_WIDTH, SHARE_PREVIEW_HEIGHT)
|
||||
gradient.addColorStop(0, parseHexColor(color1) ? color1 : '#101014')
|
||||
gradient.addColorStop(1, parseHexColor(color2) ? color2 : '#1c1c26')
|
||||
context.fillStyle = gradient
|
||||
context.fillRect(0, 0, SHARE_PREVIEW_WIDTH, SHARE_PREVIEW_HEIGHT)
|
||||
|
||||
// A quiet vignette keeps white artboards from bleeding into the canvas edge
|
||||
// and gives the name block contrast on light gradients.
|
||||
const vignette = context.createLinearGradient(0, 0, SHARE_PREVIEW_WIDTH * 0.7, 0)
|
||||
vignette.addColorStop(0, 'rgba(8, 9, 18, 0.34)')
|
||||
vignette.addColorStop(1, 'rgba(8, 9, 18, 0)')
|
||||
context.fillStyle = vignette
|
||||
context.fillRect(0, 0, SHARE_PREVIEW_WIDTH, SHARE_PREVIEW_HEIGHT)
|
||||
return isLightColor(color1)
|
||||
}
|
||||
|
||||
const drawNameBlock = (context: CanvasRenderingContext2D, projectName: string, onLight: boolean) => {
|
||||
const ink = onLight ? '#15161c' : '#ffffff'
|
||||
const muted = onLight ? 'rgba(21, 22, 28, 0.66)' : 'rgba(255, 255, 255, 0.72)'
|
||||
const fontStack = '\'Instrument Sans Variable\', \'Instrument Sans\', system-ui, sans-serif'
|
||||
|
||||
context.textBaseline = 'alphabetic'
|
||||
context.fillStyle = muted
|
||||
context.font = `600 21px ${fontStack}`
|
||||
try {
|
||||
context.letterSpacing = '4px'
|
||||
} catch {
|
||||
// Older engines without canvas letter spacing simply render tighter.
|
||||
}
|
||||
context.fillText('SHOTLUMA', 84, 214)
|
||||
try {
|
||||
context.letterSpacing = '0px'
|
||||
} catch {
|
||||
// See above.
|
||||
}
|
||||
|
||||
context.fillStyle = ink
|
||||
context.font = `640 58px ${fontStack}`
|
||||
const lines = wrapProjectName(context, projectName, 430)
|
||||
lines.forEach((line, index) => {
|
||||
context.fillText(line, 84, 288 + index * 70)
|
||||
})
|
||||
|
||||
context.fillStyle = muted
|
||||
context.font = `500 22px ${fontStack}`
|
||||
context.fillText('Open the link to edit', 84, 320 + lines.length * 70)
|
||||
context.fillText('your own copy.', 84, 352 + lines.length * 70)
|
||||
}
|
||||
|
||||
const canvasToJpeg = (canvas: HTMLCanvasElement): Promise<Blob | null> =>
|
||||
new Promise((resolve) => {
|
||||
canvas.toBlob(resolve, 'image/jpeg', PREVIEW_JPEG_QUALITY)
|
||||
})
|
||||
|
||||
export const createSharePreviewImage = async (
|
||||
projectName: string,
|
||||
slides: Slide[],
|
||||
): Promise<Blob | null> => {
|
||||
try {
|
||||
await document.fonts.ready
|
||||
const shown = slides.slice(0, MAX_PREVIEW_SCREENS)
|
||||
const placements = screenPlacements(shown.length)
|
||||
const screens = await Promise.all(
|
||||
shown.map((slide, index) => captureSlideCanvas(slide, placements[index]?.height ?? 470)),
|
||||
)
|
||||
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = SHARE_PREVIEW_WIDTH
|
||||
canvas.height = SHARE_PREVIEW_HEIGHT
|
||||
const context = canvas.getContext('2d')
|
||||
if (!context) return null
|
||||
|
||||
const onLight = drawBackdrop(context, shown[0])
|
||||
screens
|
||||
.map((screen, index) => ({ screen, placement: placements[index] }))
|
||||
.filter((entry): entry is { screen: HTMLCanvasElement; placement: ScreenPlacement } =>
|
||||
entry.screen !== null && entry.placement !== undefined)
|
||||
.sort((a, b) => a.placement.z - b.placement.z)
|
||||
.forEach(({ screen, placement }) => {
|
||||
drawScreen(context, screen, placement)
|
||||
})
|
||||
drawNameBlock(context, projectName.trim() === '' ? 'Shared project' : projectName, onLight)
|
||||
return await canvasToJpeg(canvas)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,5 @@
|
||||
import { useCallback, useEffect, useRef, useState, type Dispatch, type RefObject, type SetStateAction } from 'react'
|
||||
import { hydrateProjectAssets } from '../asset-store'
|
||||
import { createInitialSlides } from '../data'
|
||||
import {
|
||||
deleteProject,
|
||||
@ -12,6 +13,7 @@ import {
|
||||
} from '../persistence'
|
||||
import { uid } from '../utils'
|
||||
import { DEFAULT_PROJECT_NAME, getUniqueProjectName, upsertProjectSummary } from './project-utils'
|
||||
import { consumeShareLinkHash, decodeSharePayload } from './share-link'
|
||||
import type { Slide, UploadAsset } from '../types'
|
||||
import type { SaveStatus } from './project-types'
|
||||
|
||||
@ -43,6 +45,57 @@ const makeNewProject = (
|
||||
}
|
||||
}
|
||||
|
||||
type SharedImportResult =
|
||||
| { status: 'none' }
|
||||
| { status: 'invalid' }
|
||||
| { status: 'imported'; project: PersistedProject }
|
||||
|
||||
/**
|
||||
* Imports a project carried by a `#share=` link as a new, independent local
|
||||
* copy: inlined images become locally stored blobs on save, so later edits or
|
||||
* deletion only ever touch this browser's copy.
|
||||
*/
|
||||
const importSharedProject = async (existingProjects: ProjectSummary[]): Promise<SharedImportResult> => {
|
||||
const sharedHash = consumeShareLinkHash()
|
||||
if (!sharedHash) return { status: 'none' }
|
||||
sharedImportPending = true
|
||||
try {
|
||||
const shared = await decodeSharePayload(sharedHash)
|
||||
if (!shared) return { status: 'invalid' }
|
||||
const project = await hydrateProjectAssets(makeNewProject(
|
||||
getUniqueProjectName(existingProjects, shared.projectName),
|
||||
shared.slides,
|
||||
shared.uploads,
|
||||
))
|
||||
await saveProject(project)
|
||||
return { status: 'imported', project }
|
||||
} catch {
|
||||
return { status: 'invalid' }
|
||||
}
|
||||
}
|
||||
|
||||
// React StrictMode double-invokes the hydration effect in development. The
|
||||
// first run consumes the one-shot URL fragment and may be cancelled mid-way,
|
||||
// so both runs must share a single import request — otherwise the shared
|
||||
// project is either lost or saved twice.
|
||||
let sharedImportRequest: Promise<SharedImportResult> | null = null
|
||||
let sharedImportPending = false
|
||||
|
||||
const importSharedProjectOnce = (existingProjects: ProjectSummary[]): Promise<SharedImportResult> => {
|
||||
sharedImportRequest ??= importSharedProject(existingProjects)
|
||||
return sharedImportRequest
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the import as fully handled. Later effect runs (dependency identity
|
||||
* changes) then resolve to 'none' instead of re-applying the imported project
|
||||
* or re-showing its toast.
|
||||
*/
|
||||
const settleSharedImport = () => {
|
||||
sharedImportPending = false
|
||||
sharedImportRequest = Promise.resolve({ status: 'none' })
|
||||
}
|
||||
|
||||
export function useProjectWorkspace({
|
||||
initialProjectName,
|
||||
slides,
|
||||
@ -108,24 +161,40 @@ export function useProjectWorkspace({
|
||||
const workspace = await loadProjectWorkspace()
|
||||
if (isCancelled()) return
|
||||
|
||||
const project = workspace.activeProject ?? makeNewProject(
|
||||
const sharedImport = await importSharedProjectOnce(workspace.projects)
|
||||
const imported = sharedImport.status === 'imported' ? sharedImport.project : null
|
||||
const project = imported ?? workspace.activeProject ?? makeNewProject(
|
||||
projectNameRef.current,
|
||||
slidesRef.current,
|
||||
uploadsRef.current,
|
||||
)
|
||||
if (!workspace.activeProject) await saveProject(project)
|
||||
if (!imported && !workspace.activeProject) await saveProject(project)
|
||||
await setActiveProjectId(project.id)
|
||||
if (isCancelled()) return
|
||||
|
||||
replaceProject(project)
|
||||
setProjects(workspace.activeProject
|
||||
? workspace.projects
|
||||
setProjects(imported || workspace.activeProject
|
||||
? upsertProjectSummary(workspace.projects, project)
|
||||
: upsertProjectSummary([], project))
|
||||
if (sharedImport.status === 'imported') {
|
||||
setToast('Shared project imported as your own local copy')
|
||||
} else if (sharedImport.status === 'invalid') {
|
||||
setToast('Couldn’t open the shared project link')
|
||||
}
|
||||
if (sharedImport.status !== 'none') settleSharedImport()
|
||||
removeLegacyProject()
|
||||
skipNextAutoSaveRef.current = true
|
||||
setSaveStatus('saved')
|
||||
} catch {
|
||||
if (!isCancelled()) setSaveStatus('error')
|
||||
if (!isCancelled()) {
|
||||
// The share fragment is already consumed, so a hydration failure
|
||||
// must still tell the user their shared link went nowhere.
|
||||
if (sharedImportPending) {
|
||||
settleSharedImport()
|
||||
setToast('Couldn’t open the shared project link')
|
||||
}
|
||||
setSaveStatus('error')
|
||||
}
|
||||
} finally {
|
||||
if (!isCancelled()) {
|
||||
persistenceReadyRef.current = true
|
||||
@ -138,7 +207,7 @@ export function useProjectWorkspace({
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [replaceProject, slidesRef, uploadsRef])
|
||||
}, [replaceProject, setToast, slidesRef, uploadsRef])
|
||||
|
||||
const saveCurrentProject = useCallback(async (showConfirmation = false) => {
|
||||
if (!persistenceReadyRef.current || projectTransitionRef.current) return false
|
||||
|
||||
@ -29,6 +29,7 @@ import {
|
||||
KimiAiIcon,
|
||||
Layers as Layers3Icon,
|
||||
LayoutTwoColumnIcon,
|
||||
Link01Icon,
|
||||
Lock as LockIcon,
|
||||
LockKeyhole as LockKeyholeIcon,
|
||||
LockOpen as LockOpenIcon,
|
||||
@ -95,6 +96,7 @@ export const Italic = createIcon(ItalicIcon)
|
||||
export const KimiAi = createIcon(KimiAiIcon)
|
||||
export const Layers3 = createIcon(Layers3Icon)
|
||||
export const LayoutTwoColumn = createIcon(LayoutTwoColumnIcon)
|
||||
export const Link01 = createIcon(Link01Icon)
|
||||
export const Lock = createIcon(LockIcon)
|
||||
export const LockKeyhole = createIcon(LockKeyholeIcon)
|
||||
export const LockOpen = createIcon(LockOpenIcon)
|
||||
|
||||
@ -362,6 +362,133 @@ select:focus-visible {
|
||||
box-shadow: 0 0 0 2px color-mix(in oklch, var(--ring) 45%, transparent);
|
||||
}
|
||||
|
||||
.share-link-dialog {
|
||||
width: min(calc(100vw - 32px), 380px);
|
||||
max-width: 380px;
|
||||
gap: 0;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
border-radius: var(--radius-lg);
|
||||
box-shadow: 0 18px 48px oklch(0 0 0 / 18%), 0 2px 8px oklch(0 0 0 / 8%);
|
||||
}
|
||||
.share-link-dialog [data-slot='alert-dialog-header'] {
|
||||
display: grid;
|
||||
grid-template-columns: 34px minmax(0, 1fr);
|
||||
grid-template-rows: auto auto;
|
||||
place-items: start;
|
||||
gap: 3px 12px;
|
||||
padding: 18px 18px 14px;
|
||||
text-align: left;
|
||||
}
|
||||
.share-link-dialog [data-slot='alert-dialog-media'] {
|
||||
grid-row: 1 / span 2;
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
margin: 0;
|
||||
color: var(--foreground);
|
||||
background: var(--muted);
|
||||
border-radius: var(--radius-md);
|
||||
}
|
||||
.share-link-dialog [data-slot='alert-dialog-title'] {
|
||||
grid-column: 2;
|
||||
color: var(--foreground);
|
||||
font-size: 13px;
|
||||
font-weight: 580;
|
||||
line-height: 18px;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
.share-link-dialog [data-slot='alert-dialog-description'] {
|
||||
grid-column: 2;
|
||||
color: var(--muted-foreground);
|
||||
font-size: 11px;
|
||||
font-weight: 400;
|
||||
line-height: 16px;
|
||||
text-wrap: pretty;
|
||||
}
|
||||
.share-link-dialog-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
padding: 0 18px 16px;
|
||||
}
|
||||
.share-link-dialog-preview {
|
||||
max-height: 44px;
|
||||
padding: 8px 10px;
|
||||
overflow: hidden;
|
||||
color: var(--muted-foreground);
|
||||
background: color-mix(in oklch, var(--muted) 70%, transparent);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
font-family: ui-monospace, 'SFMono-Regular', Menlo, monospace;
|
||||
font-size: 10px;
|
||||
line-height: 1.4;
|
||||
word-break: break-all;
|
||||
user-select: none;
|
||||
}
|
||||
.share-link-dialog-status,
|
||||
.share-link-dialog-meta {
|
||||
margin: 0;
|
||||
color: var(--muted-foreground);
|
||||
font-size: 10px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
.share-link-dialog-error {
|
||||
margin: 0;
|
||||
color: var(--destructive);
|
||||
font-size: 10px;
|
||||
font-weight: 540;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.share-link-dialog-fallback {
|
||||
height: 28px;
|
||||
padding: 0 10px;
|
||||
color: var(--foreground);
|
||||
background: var(--background);
|
||||
border: 1px solid var(--input);
|
||||
border-radius: var(--radius-md);
|
||||
font-family: ui-monospace, 'SFMono-Regular', Menlo, monospace;
|
||||
font-size: 10px;
|
||||
}
|
||||
.share-link-dialog [data-slot='alert-dialog-footer'] {
|
||||
margin: 0;
|
||||
padding: 11px 14px 13px;
|
||||
flex-direction: row;
|
||||
justify-content: flex-end;
|
||||
gap: 7px;
|
||||
background: var(--muted);
|
||||
border-top: 1px solid var(--border);
|
||||
border-radius: 0 0 var(--radius-lg) var(--radius-lg);
|
||||
}
|
||||
.share-link-dialog [data-slot='alert-dialog-cancel'],
|
||||
.share-link-dialog .share-link-dialog-copy {
|
||||
min-width: 78px;
|
||||
height: 29px;
|
||||
padding: 0 10px;
|
||||
border-radius: var(--radius-md);
|
||||
font-size: 11px;
|
||||
font-weight: 520;
|
||||
line-height: 1;
|
||||
}
|
||||
.share-link-dialog .share-link-dialog-close {
|
||||
color: var(--foreground);
|
||||
background: var(--background);
|
||||
border-color: var(--input);
|
||||
}
|
||||
.share-link-dialog .share-link-dialog-close:hover { background: var(--accent); }
|
||||
.share-link-dialog .share-link-dialog-copy {
|
||||
color: white;
|
||||
background: var(--foreground);
|
||||
border-color: var(--foreground);
|
||||
}
|
||||
.share-link-dialog .share-link-dialog-copy:hover:not(:disabled) {
|
||||
color: white;
|
||||
background: color-mix(in oklch, var(--foreground) 88%, black);
|
||||
}
|
||||
.share-link-dialog button:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 2px color-mix(in oklch, var(--ring) 45%, transparent);
|
||||
}
|
||||
|
||||
.history-actions button:hover {
|
||||
background: var(--accent);
|
||||
color: var(--accent-foreground);
|
||||
|
||||
@ -29,6 +29,15 @@ export default defineConfig(({ command, mode }) => {
|
||||
requestPath.replace(/^\/api\/opencode\/zen/, '/zen') || '/zen',
|
||||
},
|
||||
}
|
||||
// Local dev has no share Worker, so short share links go through the
|
||||
// deployed one; the client falls back to self-contained links on failure.
|
||||
const devProxy = {
|
||||
...moonshotAndOpencodeProxy,
|
||||
'/api/share': {
|
||||
target: 'https://app.shotluma.com',
|
||||
changeOrigin: true,
|
||||
},
|
||||
}
|
||||
|
||||
return {
|
||||
define: {
|
||||
@ -52,10 +61,10 @@ export default defineConfig(({ command, mode }) => {
|
||||
server: {
|
||||
host: '127.0.0.1',
|
||||
port: Number(process.env['PORT']) || 4173,
|
||||
proxy: moonshotAndOpencodeProxy,
|
||||
proxy: devProxy,
|
||||
},
|
||||
preview: {
|
||||
proxy: moonshotAndOpencodeProxy,
|
||||
proxy: devProxy,
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
@ -21,6 +21,7 @@ export default defineConfig({
|
||||
'src/app/export-image-sizing.ts',
|
||||
'src/asset-sources.ts',
|
||||
'src/app/project-utils.ts',
|
||||
'src/app/share-link.ts',
|
||||
'src/editor/drag-bounds.ts',
|
||||
'src/editor/element-utils.ts',
|
||||
'src/editor/nudge.ts',
|
||||
|
||||
@ -7,7 +7,26 @@
|
||||
"directory": "./dist",
|
||||
"binding": "ASSETS",
|
||||
"not_found_handling": "single-page-application",
|
||||
"run_worker_first": ["/api/opencode/*"]
|
||||
"run_worker_first": ["/api/opencode/*", "/api/share", "/api/share/*", "/s/*"]
|
||||
},
|
||||
"kv_namespaces": [
|
||||
{
|
||||
"binding": "SHARE_KV",
|
||||
"id": "a5c85baed396460b8f79536f88692afc"
|
||||
}
|
||||
],
|
||||
"unsafe": {
|
||||
"bindings": [
|
||||
{
|
||||
"type": "ratelimit",
|
||||
"name": "SHARE_RATE",
|
||||
"namespace_id": "2101",
|
||||
"simple": {
|
||||
"limit": 10,
|
||||
"period": 60
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"routes": [
|
||||
{
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user