* Add drafts functionality to composer

- Add local storage layer for drafts (filesystem on native, IndexedDB on web)
- Add "Drafts" button to composer top bar showing badge with draft count
- Modify discard prompt to offer "Save Draft" option
- Add `restore_from_draft` action to composer reducer
- Support saving/restoring: text, facets, images, labels, threadgate, quote/link embeds
- Add placeholder hooks for future server API integration
- Add unit tests for draft serialization

Note: Video/GIF restoration marked as TODO for future implementation

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix drafts button: always visible, adjacent to post button

- Make drafts button always visible (not just when drafts exist)
- Move button to be adjacent to the publish button
- If composer is empty: opens drafts list directly
- If composer has content: shows prompt to save/discard before viewing drafts
- Add badge showing draft count when drafts exist

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Update drafts button: text-only, ghost/primary style

- Show "Drafts" or "Drafts (N)" as text, no icon
- Use ghost variant with primary color
- Match Cancel button styling

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Remove draft count from button, just show "Drafts"

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Increase drafts button horizontal padding and gap

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Use InnerFlatList and Dialog.Header for drafts dialog

- Switch from ScrollableInner to InnerFlatList
- Add Dialog.Header with back button in left slot
- Use sticky header

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Track draft ID in composer state machine

Adds draftId to ComposerState so that editing an existing draft and
saving it again updates the draft rather than creating a new one.

- Add draftId?: string to ComposerState type
- Set draftId when restoring from draft via restore_from_draft action
- Pass existingDraftId to save functions from composerState.draftId
- Add PageX icon for empty drafts state

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add clear action to discard composer content

When pressing the Drafts button with content in the composer, the user
can choose to discard. This now properly clears the composer by
dispatching a 'clear' action that resets to an empty state.

- Add 'clear' action type to ComposerAction
- Implement clear case in composerReducer (resets to single empty post)
- Add handleClearComposer callback in Composer.tsx
- Pass onDiscard prop through ComposerTopBar to DraftsButton
- Call onDiscard before opening drafts dialog on discard

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Track dirty state to skip discard prompt for unchanged drafts

When a draft is loaded and the user hasn't made any changes, closing
the composer should not show the discard prompt since nothing would
be lost.

- Add isDirty field to ComposerState
- Set isDirty: true on all content-modifying actions
- Set isDirty: false on restore_from_draft, clear, and initial state
- Update onPressCancel to only show prompt if no draft or isDirty

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Redesign drafts list to show full thread preview

- Display all posts in a draft thread, not just the first
- First post uses larger avatar (42px), subsequent posts nested with
  smaller avatar (32px) and thread connector line
- Show author avatar, display name, handle, and relative timestamp
- Add overflow menu button (placeholder) on first post
- Display full text instead of truncated preview
- Add media preview component for images, GIFs, and videos
- Card layout with rounded corners and proper spacing
- Add gap separators between draft cards in list

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix draft item styling based on feedback

- Add border and shadow to draft cards
- Remove trash button, move delete to overflow menu prompt
- Remove size differences for thread posts (same avatar/text size)
- Add spacing between header and first draft item
- Change prompt wording to "Discard draft"

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Use real image embed components for draft preview

Replace custom image preview with AutoSizedImage for single images
and ImageLayoutGrid for multiple images. This gives drafts the same
polished image display as regular posts.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Improve drafts dialog platform handling

- Render header outside FlatList on native, inside on web
- Use web() helper for conditional web-only props
- Replace ItemSeparatorComponent with mt_lg margin on items
- Add minHeight on web for better dialog sizing
- Simplify header structure

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Mark composer as clean after saving draft

Add mark_saved action that resets isDirty to false and updates the
draftId. This is dispatched after successfully saving a draft, allowing
the user to close the composer without a discard prompt since their
changes have been saved.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Apply dirty tracking to Drafts button prompt

Only show the save/discard prompt when pressing the Drafts button if
the composer has unsaved changes (isDirty). If the content is unchanged
from a loaded draft or was just saved, go directly to the drafts list.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix re-saving drafts with existing media

When re-saving a draft, the code was trying to copy media files that
were already in drafts storage to new locations, causing copy errors.

Changes:
- Add extractLocalIdFromPath() to detect if a path is already in drafts
- Track loadedMediaMap in ComposerState for identifying reusable media
- Only delete old media that wasn't reused during re-save
- Pass loadedMediaMap when saving to enable media reuse detection
- Disable pointer events on draft media preview

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* add vertical option to prompt, change copy

* fix import

* fix import

* Migrate drafts from local storage to server API

Replace local-only draft storage with the new `app.bsky.draft.*` server API:
- getDrafts, createDraft, updateDraft, deleteDraft endpoints

Key changes:
- Add api.ts with type converters (ComposerState <-> server Draft)
- Update hooks.ts to use server API instead of local storage
- Simplify storage.ts/storage.web.ts for local media caching only
- Media stored locally via localRef pattern (filepath in server draft)
- GIFs stored as external embeds with Tenor URL + dimensions
- Hide drafts button when replying (reply drafts not supported)
- Show "different device" note when media is missing locally

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* attempt to fix blob mangement

* Migrate storage.ts from expo-file-system/legacy to expo-file-system

Use the new object-based expo-file-system API (SDK 54+) with Directory
and File classes instead of the legacy function-based API. The new API
provides synchronous operations for file/directory existence checks,
creation, copying, deletion, and listing.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: add drafts-specific logger

Add a Drafts context to the logger system for better log categorization
and debugging of draft-related operations.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: use drafts-specific logger in hooks and storage

Switch from the generic logger to the new drafts-specific logger
for better log categorization.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: ensure media cache is populated before checking exists

On iOS (and web), the media cache wasn't populated before the drafts
query ran, causing drafts with local media to incorrectly show as
"missing media" on app restart. The issue would resolve itself after
closing and reopening the composer because by then the cache was ready.

This fix adds ensureMediaCachePopulated() and awaits it in useDrafts
before checking which media exists locally.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: complete Gif object reconstruction for draft rehydration

Fix "Cannot read property 'url' of undefined" error when rehydrating
drafts with GIFs. The Gif object was missing required properties like
url, content_description, and media_formats.preview that are needed
by useResolveGifQuery and other components.

Also preserve alt text through serialization by storing it in URL
query params alongside dimensions.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: load draft preview images and get dimensions

Fix draft preview images not showing on web and add proper aspect
ratio support:

1. Try to load all images regardless of the exists cache flag, which
   may be stale due to async cache population timing
2. Use Image.loadAsync() from expo-image to get image dimensions
3. Pass dimensions to viewImages for proper aspect ratio in previews

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: update save prompt copy when editing existing draft

When editing an existing draft (vs creating a new one), use "Save
changes" instead of "Save draft" in the save/discard prompts. This
provides clearer context to the user about what action they're taking.

Add isEditingDraft prop to DraftsButton and ComposerTopBar, and
update both prompts (in DraftsButton and Composer) with conditional
copy based on whether we're editing an existing draft.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* style: add bottom padding to drafts list

Add pb_xl padding to the drafts list content container for better
visual spacing at the bottom of the list.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: use typed error check for draft limit

Replace manual error object inspection with the proper
AppBskyDraftCreateDraft.DraftLimitReachedError type check for
cleaner and more reliable error handling.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* make storage functions async to match web

* log unknown errors

* delete left-over file

* move state to colo with composer

* fix: handle invalid GIF dimensions gracefully

Fix NaN aspectRatio when rehydrating GIFs from drafts by:

1. Adding validation in parseTenorGif to reject invalid dimensions
   (NaN, zero, or negative values)
2. Adding defensive checks in GifEmbed to fallback to 1:1 aspect
   ratio if dimensions are invalid
3. Adding defensive checks in composer ExternalEmbedGif to fallback
   to 16:9 if gif.media_formats.gif.dims is missing or invalid

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: prevent double query string in GIF draft hydration

When loading a GIF from a draft, the URL was being corrupted with
double query strings like:
`?ww=498&hh=498?hh=498&ww=498`

This happened because:
1. serializeGif() adds ?ww=X&hh=Y&alt=Z to the Tenor URL
2. parseGifFromUrl() returned the full URL including our params
3. resolveGif() in resolve.ts then appends MORE params via string
   concatenation, creating a second ?

Fix: Strip our custom params (ww, hh, alt) from the URL in
parseGifFromUrl() before returning it, so the reconstructed GIF
has a clean base URL.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix draft button behaviour when publishing, tweak buttons

* ensure media unavaiable message is contrasty enough

* infinite query, rename file to queries

* simplify threadgate/postgate handling

* refactor: pass full draft data instead of re-fetching

The useLoadDraft and useDeleteDraftMutation hooks were fetching drafts
via getDrafts() to look up a draft by ID. This was problematic because
getDrafts is paginated, so drafts not on the first page wouldn't be
found.

Changes:
- Add full Draft object to DraftSummary type
- useLoadDraft now takes Draft directly (only loads local media)
- useDeleteDraftMutation now takes {draftId, draft} to avoid re-fetch
- Update DraftItem and DraftsListDialog to pass full draft data

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix type errors

* docs: add notes on platform files and paginated APIs

- Platform-specific files (.web.ts, .native.ts) are resolved by the
  bundler automatically - just import normally, don't use require()
- Paginated APIs should use useInfiniteQuery, not useQuery

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* More CLAUDE.md updates

* Delete PLAN.md

* Use minimal media mode for draft display - REVERT IF NEEDED

* Enable pagination

* Add comment about headers

* remove extraneous comments

* Prevent runaway pagination

* fix detection rebase change

* use border_transparent

* Replace idb with idb-keyval for draft media storage

Simplifies web IndexedDB storage by using idb-keyval instead of the
full idb library. This reduces bundle size and aligns with the pattern
used in src/storage/archive/db/index.web.ts.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix native draft media filename encoding

The previous approach replaced both / and : with _, but the reverse
transformation couldn't distinguish between them. This caused cache
misses for paths containing both characters.

Use encodeURIComponent/decodeURIComponent for a proper reversible
encoding.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* convert useLoadDraft() hook to regular async function

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* update atproto api

* clean up orphaned media

* restore videos

* save/restore captions

* restore postgates

* Copy updates from Darrin

* Ope fix missed vertical props

* get image aspect ratio when restoring

* get videos working on native

* get video restoration working on native

* sanitize handles properly in draftitem

* fix yarn.lock

* Swap console logs

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Eric Bailey <git@esb.lol>
This commit is contained in:
Samuel Newman
2026-01-29 00:54:26 +02:00
committed by GitHub
parent a18f1b68e8
commit d13df6c7e6
30 changed files with 2546 additions and 136 deletions
+630
View File
@@ -0,0 +1,630 @@
/**
* Type converters for Draft API - convert between ComposerState and server Draft types.
*/
import {type AppBskyDraftDefs, RichText} from '@atproto/api'
import {nanoid} from 'nanoid/non-secure'
import {getImageDim} from '#/lib/media/manip'
import {mimeToExt} from '#/lib/media/video/util'
import {type ComposerImage} from '#/state/gallery'
import {type Gif} from '#/state/queries/tenor'
import {
type ComposerState,
type EmbedDraft,
type PostDraft,
} from '#/view/com/composer/state/composer'
import {type VideoState} from '#/view/com/composer/state/video'
import {logger} from './logger'
import {type DraftPostDisplay, type DraftSummary} from './schema'
const TENOR_HOSTNAME = 'media.tenor.com'
/**
* Video data from a draft that needs to be restored by re-processing.
* Contains the local file URI, alt text, mime type, and captions to restore.
*/
export type RestoredVideo = {
uri: string
altText: string
mimeType: string
localRefPath: string
captions: Array<{lang: string; content: string}>
}
/**
* Parse mime type from video localRefPath.
* Format: `video:${mimeType}:${nanoid()}` (new) or `video:${nanoid()}` (legacy)
*/
function parseVideoMimeType(localRefPath: string): string {
const parts = localRefPath.split(':')
// New format: video:video/mp4:abc123 -> parts[1] is mime type
// Legacy format: video:abc123 -> no mime type, default to video/mp4
if (parts.length >= 3 && parts[1].includes('/')) {
return parts[1]
}
return 'video/mp4' // Default for legacy drafts
}
/**
* Convert ComposerState to server Draft format for saving.
* Returns both the draft and a map of localRef paths to their source paths.
*/
export async function composerStateToDraft(state: ComposerState): Promise<{
draft: AppBskyDraftDefs.Draft
localRefPaths: Map<string, string>
}> {
const localRefPaths = new Map<string, string>()
const posts: AppBskyDraftDefs.DraftPost[] = await Promise.all(
state.thread.posts.map(post => {
return postDraftToServerPost(post, localRefPaths)
}),
)
// Convert threadgate settings to server format
const threadgateAllow: AppBskyDraftDefs.Draft['threadgateAllow'] = []
for (const setting of state.thread.threadgate) {
if (setting.type === 'mention') {
threadgateAllow.push({
$type: 'app.bsky.feed.threadgate#mentionRule' as const,
})
} else if (setting.type === 'following') {
threadgateAllow.push({
$type: 'app.bsky.feed.threadgate#followingRule' as const,
})
} else if (setting.type === 'followers') {
threadgateAllow.push({
$type: 'app.bsky.feed.threadgate#followerRule' as const,
})
} else if (setting.type === 'list') {
threadgateAllow.push({
$type: 'app.bsky.feed.threadgate#listRule' as const,
list: setting.list,
})
}
}
const draft: AppBskyDraftDefs.Draft = {
$type: 'app.bsky.draft.defs#draft',
posts,
threadgateAllow: threadgateAllow.length > 0 ? threadgateAllow : undefined,
postgateEmbeddingRules:
state.thread.postgate.embeddingRules &&
state.thread.postgate.embeddingRules.length > 0
? state.thread.postgate.embeddingRules
: undefined,
}
return {draft, localRefPaths}
}
/**
* Convert a single PostDraft to server DraftPost format.
*/
async function postDraftToServerPost(
post: PostDraft,
localRefPaths: Map<string, string>,
): Promise<AppBskyDraftDefs.DraftPost> {
const draftPost: AppBskyDraftDefs.DraftPost = {
$type: 'app.bsky.draft.defs#draftPost',
text: post.richtext.text,
}
// Add labels if present
if (post.labels.length > 0) {
draftPost.labels = {
$type: 'com.atproto.label.defs#selfLabels',
values: post.labels.map(label => ({val: label})),
}
}
// Add embeds
if (post.embed.media) {
if (post.embed.media.type === 'images') {
draftPost.embedImages = serializeImages(
post.embed.media.images,
localRefPaths,
)
} else if (post.embed.media.type === 'video') {
const video = await serializeVideo(post.embed.media.video, localRefPaths)
if (video) {
draftPost.embedVideos = [video]
}
} else if (post.embed.media.type === 'gif') {
const external = serializeGif(post.embed.media)
if (external) {
draftPost.embedExternals = [external]
}
}
}
// Add quote record embed
if (post.embed.quote) {
draftPost.embedRecords = [
{
$type: 'app.bsky.draft.defs#draftEmbedRecord',
record: {
uri: post.embed.quote.uri,
cid: '', // We don't have the CID at draft time
},
},
]
}
// Add external link embed (only if no media, otherwise it's ignored)
if (post.embed.link && !post.embed.media) {
draftPost.embedExternals = [
{
$type: 'app.bsky.draft.defs#draftEmbedExternal',
uri: post.embed.link.uri,
},
]
}
return draftPost
}
/**
* Serialize images to server format with localRef paths.
* Reuses existing localRefPath if present (when editing a draft),
* otherwise generates a new one.
*/
function serializeImages(
images: ComposerImage[],
localRefPaths: Map<string, string>,
): AppBskyDraftDefs.DraftEmbedImage[] {
return images.map(image => {
const sourcePath = image.transformed?.path || image.source.path
// Reuse existing localRefPath if present (editing draft), otherwise generate new
const isReusing = !!image.localRefPath
const localRefPath = image.localRefPath || `image:${nanoid()}`
localRefPaths.set(localRefPath, sourcePath)
logger.debug('serializing image', {
localRefPath,
isReusing,
sourcePath,
})
return {
$type: 'app.bsky.draft.defs#draftEmbedImage',
localRef: {
$type: 'app.bsky.draft.defs#draftEmbedLocalRef',
path: localRefPath,
},
alt: image.alt || undefined,
}
})
}
/**
* Serialize video to server format with localRef path.
* The localRef path encodes the mime type: `video:${mimeType}:${nanoid()}`
*/
async function serializeVideo(
videoState: VideoState,
localRefPaths: Map<string, string>,
): Promise<AppBskyDraftDefs.DraftEmbedVideo | undefined> {
// Only save videos that have been compressed (have a video file)
if (!videoState.video) {
return undefined
}
// Encode mime type in the path for restoration
const mimeType = videoState.video.mimeType || 'video/mp4'
const ext = mimeToExt(mimeType)
const localRefPath = `video:${mimeType}:${nanoid()}.${ext}`
localRefPaths.set(localRefPath, videoState.video.uri)
// Read caption file contents as text
const captions: AppBskyDraftDefs.DraftEmbedCaption[] = []
for (const caption of videoState.captions) {
if (caption.lang) {
const content = await caption.file.text()
captions.push({
$type: 'app.bsky.draft.defs#draftEmbedCaption',
lang: caption.lang,
content,
})
}
}
return {
$type: 'app.bsky.draft.defs#draftEmbedVideo',
localRef: {
$type: 'app.bsky.draft.defs#draftEmbedLocalRef',
path: localRefPath,
},
alt: videoState.altText || undefined,
captions: captions.length > 0 ? captions : undefined,
}
}
/**
* Serialize GIF to server format as external embed.
* URL format: https://media.tenor.com/{id}/{filename}.gif?hh=HEIGHT&ww=WIDTH&alt=ALT_TEXT
*/
function serializeGif(gifMedia: {
type: 'gif'
gif: Gif
alt: string
}): AppBskyDraftDefs.DraftEmbedExternal | undefined {
const gif = gifMedia.gif
const gifFormat = gif.media_formats.gif || gif.media_formats.tinygif
if (!gifFormat?.url) {
return undefined
}
// Build URL with dimensions and alt text in query params
const url = new URL(gifFormat.url)
if (gifFormat.dims) {
url.searchParams.set('ww', String(gifFormat.dims[0]))
url.searchParams.set('hh', String(gifFormat.dims[1]))
}
// Store alt text if present
if (gifMedia.alt) {
url.searchParams.set('alt', gifMedia.alt)
}
return {
$type: 'app.bsky.draft.defs#draftEmbedExternal',
uri: url.toString(),
}
}
/**
* Convert server DraftView to DraftSummary for list display.
* Also checks which media files exist locally.
*/
export function draftViewToSummary(
view: AppBskyDraftDefs.DraftView,
localMediaExists: (path: string) => boolean,
): DraftSummary {
const firstPost = view.draft.posts[0]
const previewText = firstPost?.text?.slice(0, 100) || ''
let mediaCount = 0
let hasMedia = false
let hasMissingMedia = false
const posts: DraftPostDisplay[] = view.draft.posts.map((post, index) => {
const images: DraftPostDisplay['images'] = []
const videos: DraftPostDisplay['video'][] = []
let gif: DraftPostDisplay['gif']
// Process images
if (post.embedImages) {
for (const img of post.embedImages) {
mediaCount++
hasMedia = true
const exists = localMediaExists(img.localRef.path)
if (!exists) {
hasMissingMedia = true
}
images.push({
localPath: img.localRef.path,
altText: img.alt || '',
exists,
})
}
}
// Process videos
if (post.embedVideos) {
for (const vid of post.embedVideos) {
mediaCount++
hasMedia = true
const exists = localMediaExists(vid.localRef.path)
if (!exists) {
hasMissingMedia = true
}
videos.push({
localPath: vid.localRef.path,
altText: vid.alt || '',
exists,
})
}
}
// Process externals (check for GIFs)
if (post.embedExternals) {
for (const ext of post.embedExternals) {
const gifData = parseGifFromUrl(ext.uri)
if (gifData) {
mediaCount++
hasMedia = true
gif = gifData
}
}
}
return {
id: `post-${index}`,
text: post.text || '',
images: images.length > 0 ? images : undefined,
video: videos[0], // Only one video per post
gif,
}
})
return {
id: view.id,
draft: view.draft,
previewText,
hasMedia,
hasMissingMedia,
mediaCount,
postCount: view.draft.posts.length,
updatedAt: view.updatedAt,
posts,
}
}
/**
* Parse GIF data from a Tenor URL.
* URL format: https://media.tenor.com/{id}/{filename}.gif?hh=HEIGHT&ww=WIDTH&alt=ALT_TEXT
*/
function parseGifFromUrl(
uri: string,
): {url: string; width: number; height: number; alt: string} | undefined {
try {
const url = new URL(uri)
if (url.hostname !== TENOR_HOSTNAME) {
return undefined
}
const height = parseInt(url.searchParams.get('hh') || '', 10)
const width = parseInt(url.searchParams.get('ww') || '', 10)
const alt = url.searchParams.get('alt') || ''
if (!height || !width) {
return undefined
}
// Strip our custom params to get clean base URL
// This prevents double query strings when resolveGif() adds params again
url.searchParams.delete('ww')
url.searchParams.delete('hh')
url.searchParams.delete('alt')
return {url: url.toString(), width, height, alt}
} catch {
return undefined
}
}
/**
* Convert server Draft back to composer-compatible format for restoration.
* Returns posts and a map of videos that need to be restored by re-processing.
*
* Videos cannot be restored synchronously like images because they need to go through
* the compression and upload pipeline. The caller should handle the restoredVideos
* by initiating video processing for each entry.
*/
export async function draftToComposerPosts(
draft: AppBskyDraftDefs.Draft,
loadedMedia: Map<string, string>,
): Promise<{posts: PostDraft[]; restoredVideos: Map<number, RestoredVideo>}> {
const restoredVideos = new Map<number, RestoredVideo>()
const posts = await Promise.all(
draft.posts.map(async (post, index) => {
const richtext = new RichText({text: post.text || ''})
richtext.detectFacetsWithoutResolution()
const embed: EmbedDraft = {
quote: undefined,
link: undefined,
media: undefined,
}
// Restore images
if (post.embedImages && post.embedImages.length > 0) {
const imagePromises = post.embedImages.map(async img => {
const path = loadedMedia.get(img.localRef.path)
if (!path) {
return null
}
let width = 0
let height = 0
try {
const dims = await getImageDim(path)
width = dims.width
height = dims.height
} catch (e) {
logger.warn('Failed to get image dimensions', {
path,
error: e,
})
}
logger.debug('restoring image with localRefPath', {
localRefPath: img.localRef.path,
loadedPath: path,
width,
height,
})
return {
alt: img.alt || '',
// Preserve the original localRefPath for reuse when saving
localRefPath: img.localRef.path,
source: {
id: nanoid(),
path,
width,
height,
mime: 'image/jpeg',
},
} as ComposerImage
})
const images = (await Promise.all(imagePromises)).filter(
(img): img is ComposerImage => img !== null,
)
if (images.length > 0) {
embed.media = {type: 'images', images}
}
}
// Restore GIF from external embed
if (post.embedExternals) {
for (const ext of post.embedExternals) {
const gifData = parseGifFromUrl(ext.uri)
if (gifData) {
// Reconstruct a Gif object with all required properties
const mediaObject = {
url: gifData.url,
dims: [gifData.width, gifData.height] as [number, number],
duration: 0,
size: 0,
}
embed.media = {
type: 'gif',
gif: {
id: '',
created: 0,
hasaudio: false,
hascaption: false,
flags: '',
tags: [],
title: '',
content_description: gifData.alt || '',
itemurl: '',
url: gifData.url, // Required for useResolveGifQuery
media_formats: {
gif: mediaObject,
tinygif: mediaObject,
preview: mediaObject,
},
} as Gif,
alt: gifData.alt,
}
break
}
}
}
// Collect video for restoration (processed async by caller)
if (post.embedVideos && post.embedVideos.length > 0) {
const vid = post.embedVideos[0]
const videoUri = loadedMedia.get(vid.localRef.path)
if (videoUri) {
const mimeType = parseVideoMimeType(vid.localRef.path)
logger.debug('found video to restore', {
localRefPath: vid.localRef.path,
videoUri,
altText: vid.alt,
mimeType,
captionCount: vid.captions?.length ?? 0,
})
restoredVideos.set(index, {
uri: videoUri,
altText: vid.alt || '',
mimeType,
localRefPath: vid.localRef.path,
captions:
vid.captions?.map(c => ({lang: c.lang, content: c.content})) ??
[],
})
}
}
// Restore quote embed
if (post.embedRecords && post.embedRecords.length > 0) {
const record = post.embedRecords[0]
embed.quote = {type: 'link', uri: record.record.uri}
}
// Restore link embed (only if not a GIF)
if (post.embedExternals && !embed.media) {
for (const ext of post.embedExternals) {
const gifData = parseGifFromUrl(ext.uri)
if (!gifData) {
embed.link = {type: 'link', uri: ext.uri}
break
}
}
}
// Parse labels
const labels: string[] = []
if (post.labels && 'values' in post.labels) {
for (const val of post.labels.values) {
labels.push(val.val)
}
}
return {
id: `draft-post-${index}`,
richtext,
shortenedGraphemeLength: richtext.graphemeLength,
labels,
embed,
} as PostDraft
}),
)
return {posts, restoredVideos}
}
/**
* Convert server threadgate rules back to UI settings.
*/
export function threadgateToUISettings(
threadgateAllow?: AppBskyDraftDefs.Draft['threadgateAllow'],
): Array<{type: string; list?: string}> {
if (!threadgateAllow) {
return []
}
return threadgateAllow
.map(rule => {
if ('$type' in rule) {
if (rule.$type === 'app.bsky.feed.threadgate#mentionRule') {
return {type: 'mention'}
}
if (rule.$type === 'app.bsky.feed.threadgate#followingRule') {
return {type: 'following'}
}
if (rule.$type === 'app.bsky.feed.threadgate#followerRule') {
return {type: 'followers'}
}
if (
rule.$type === 'app.bsky.feed.threadgate#listRule' &&
'list' in rule
) {
return {type: 'list', list: (rule as {list: string}).list}
}
}
return null
})
.filter((s): s is {type: string; list?: string} => s !== null)
}
/**
* Extract all localRef paths from a draft.
* Used to identify which media files belong to a draft for cleanup.
*/
export function extractLocalRefs(draft: AppBskyDraftDefs.Draft): Set<string> {
const refs = new Set<string>()
for (const post of draft.posts) {
if (post.embedImages) {
for (const img of post.embedImages) {
refs.add(img.localRef.path)
}
}
if (post.embedVideos) {
for (const vid of post.embedVideos) {
refs.add(vid.localRef.path)
}
}
}
logger.debug('extracted localRefs from draft', {
count: refs.size,
refs: Array.from(refs),
})
return refs
}
@@ -0,0 +1,3 @@
import {Logger} from '#/logger'
export const logger = Logger.create(Logger.Context.Drafts)
@@ -0,0 +1,271 @@
import {AppBskyDraftCreateDraft, type AppBskyDraftDefs} from '@atproto/api'
import {
useInfiniteQuery,
useMutation,
useQueryClient,
} from '@tanstack/react-query'
import {isNetworkError} from '#/lib/strings/errors'
import {useAgent} from '#/state/session'
import {type ComposerState} from '#/view/com/composer/state/composer'
import {composerStateToDraft, draftViewToSummary} from './api'
import {logger} from './logger'
import * as storage from './storage'
const DRAFTS_QUERY_KEY = ['drafts']
/**
* Hook to list all drafts for the current account
*/
export function useDraftsQuery() {
const agent = useAgent()
return useInfiniteQuery({
queryKey: DRAFTS_QUERY_KEY,
queryFn: async ({pageParam}) => {
// Ensure media cache is populated before checking which media exists
await storage.ensureMediaCachePopulated()
const res = await agent.app.bsky.draft.getDrafts({cursor: pageParam})
return {
cursor: res.data.cursor,
drafts: res.data.drafts.map(view =>
draftViewToSummary(view, path => storage.mediaExists(path)),
),
}
},
initialPageParam: undefined as string | undefined,
getNextPageParam: page => page.cursor || undefined,
})
}
/**
* Load a draft's local media for editing.
* Takes the full Draft object (from DraftSummary) to avoid re-fetching.
*/
export async function loadDraft(draft: AppBskyDraftDefs.Draft): Promise<{
loadedMedia: Map<string, string>
}> {
// Load local media files
const loadedMedia = new Map<string, string>()
for (const post of draft.posts) {
// Load images
if (post.embedImages) {
for (const img of post.embedImages) {
try {
const url = await storage.loadMediaFromLocal(img.localRef.path)
loadedMedia.set(img.localRef.path, url)
} catch (e) {
logger.warn('Failed to load draft image', {
path: img.localRef.path,
error: e,
})
}
}
}
// Load videos
if (post.embedVideos) {
for (const vid of post.embedVideos) {
try {
const url = await storage.loadMediaFromLocal(vid.localRef.path)
loadedMedia.set(vid.localRef.path, url)
} catch (e) {
logger.warn('Failed to load draft video', {
path: vid.localRef.path,
error: e,
})
}
}
}
}
return {loadedMedia}
}
/**
* Hook to save a draft.
*
* IMPORTANT: Network operations happen first in mutationFn.
* Local storage operations (save new media, delete orphaned media) happen in onSuccess.
* This ensures we don't lose data if the network request fails.
*/
export function useSaveDraftMutation() {
const agent = useAgent()
const queryClient = useQueryClient()
return useMutation({
mutationFn: async ({
composerState,
existingDraftId,
}: {
composerState: ComposerState
existingDraftId?: string
}): Promise<{
draftId: string
localRefPaths: Map<string, string>
originalLocalRefs: Set<string> | undefined
}> => {
// Convert composer state to server draft format
const {draft, localRefPaths} = await composerStateToDraft(composerState)
logger.debug('saving draft', {
existingDraftId,
localRefPathCount: localRefPaths.size,
originalLocalRefCount: composerState.originalLocalRefs?.size ?? 0,
})
// 1. NETWORK FIRST - Update/create server draft
let draftId: string
if (existingDraftId) {
// Update existing draft
logger.debug('updating existing draft on server', {
draftId: existingDraftId,
})
await agent.app.bsky.draft.updateDraft({
draft: {
id: existingDraftId,
draft,
},
})
draftId = existingDraftId
} else {
// Create new draft
logger.debug('creating new draft on server')
const res = await agent.app.bsky.draft.createDraft({draft})
draftId = res.data.id
logger.debug('created new draft', {draftId})
}
// Return data needed for onSuccess
return {
draftId,
localRefPaths,
originalLocalRefs: composerState.originalLocalRefs,
}
},
onSuccess: async ({draftId, localRefPaths, originalLocalRefs}) => {
// 2. LOCAL STORAGE ONLY AFTER NETWORK SUCCEEDS
logger.debug('network save succeeded, processing local storage', {
draftId,
})
// Save new/changed media files
for (const [localRefPath, sourcePath] of localRefPaths) {
// Only save if this media doesn't already exist (reusing localRefPath)
if (!storage.mediaExists(localRefPath)) {
logger.debug('saving new media file', {localRefPath})
await storage.saveMediaToLocal(localRefPath, sourcePath)
} else {
logger.debug('skipping existing media file', {localRefPath})
}
}
// Delete orphaned media (old refs not in new)
if (originalLocalRefs) {
const newLocalRefs = new Set(localRefPaths.keys())
for (const oldRef of originalLocalRefs) {
if (!newLocalRefs.has(oldRef)) {
logger.debug('deleting orphaned media file', {
localRefPath: oldRef,
})
await storage.deleteMediaFromLocal(oldRef)
}
}
}
queryClient.invalidateQueries({queryKey: DRAFTS_QUERY_KEY})
},
onError: error => {
// Check for draft limit error
if (error instanceof AppBskyDraftCreateDraft.DraftLimitReachedError) {
logger.error('Draft limit reached', {safeMessage: error.message})
// Error will be handled by caller
} else if (!isNetworkError(error)) {
logger.error('Could not create draft (reason unknown)', {
safeMessage: error.message,
})
}
},
})
}
/**
* Hook to delete a draft.
* Takes the full draft data to avoid re-fetching for media cleanup.
*/
export function useDeleteDraftMutation() {
const agent = useAgent()
const queryClient = useQueryClient()
return useMutation({
mutationFn: async ({
draftId,
}: {
draftId: string
draft: AppBskyDraftDefs.Draft
}) => {
// Delete from server first - if this fails, we keep local media for retry
await agent.app.bsky.draft.deleteDraft({id: draftId})
},
onSuccess: async (_, {draft}) => {
// Only delete local media after server deletion succeeds
for (const post of draft.posts) {
if (post.embedImages) {
for (const img of post.embedImages) {
await storage.deleteMediaFromLocal(img.localRef.path)
}
}
if (post.embedVideos) {
for (const vid of post.embedVideos) {
await storage.deleteMediaFromLocal(vid.localRef.path)
}
}
}
queryClient.invalidateQueries({queryKey: DRAFTS_QUERY_KEY})
},
})
}
/**
* Hook to clean up a draft after it has been published.
* Deletes the draft from server and all associated local media.
* Takes draftId and originalLocalRefs from composer state.
*/
export function useCleanupPublishedDraftMutation() {
const agent = useAgent()
const queryClient = useQueryClient()
return useMutation({
mutationFn: async ({
draftId,
originalLocalRefs,
}: {
draftId: string
originalLocalRefs: Set<string>
}) => {
logger.debug('cleaning up published draft', {
draftId,
mediaFileCount: originalLocalRefs.size,
})
// Delete from server first
await agent.app.bsky.draft.deleteDraft({id: draftId})
logger.debug('deleted draft from server', {draftId})
},
onSuccess: async (_, {originalLocalRefs}) => {
// Delete all local media files for this draft
for (const localRef of originalLocalRefs) {
logger.debug('deleting media file after publish', {
localRefPath: localRef,
})
await storage.deleteMediaFromLocal(localRef)
}
queryClient.invalidateQueries({queryKey: DRAFTS_QUERY_KEY})
logger.debug('cleanup after publish complete')
},
onError: error => {
// Log but don't throw - the post was already published successfully
logger.warn('Failed to clean up published draft', {
safeMessage: error instanceof Error ? error.message : String(error),
})
},
})
}
@@ -0,0 +1,69 @@
/**
* Types for draft display and local media tracking.
* Server draft types come from @atproto/api.
*/
import {type AppBskyDraftDefs} from '@atproto/api'
/**
* Reference to locally cached media file for display
*/
export type LocalMediaDisplay = {
/** Path stored in server draft (used as key for local lookup) */
localPath: string
/** Alt text */
altText: string
/** Whether the local file exists on this device */
exists: boolean
}
/**
* GIF display data (parsed from external embed URL)
*/
export type GifDisplay = {
/** Full URL with dimensions */
url: string
/** Width */
width: number
/** Height */
height: number
/** Alt text */
alt: string
}
/**
* Post content for display in draft list
*/
export type DraftPostDisplay = {
id: string
/** Full text content */
text: string
/** Image references for display */
images?: LocalMediaDisplay[]
/** Video reference */
video?: LocalMediaDisplay
/** GIF data (from URL) */
gif?: GifDisplay
}
/**
* Draft summary for list display
*/
export type DraftSummary = {
id: string
/** The full draft data from the server */
draft: AppBskyDraftDefs.Draft
/** First ~100 chars of first post */
previewText: string
/** Whether the draft has media */
hasMedia: boolean
/** Whether some media is missing (saved on another device) */
hasMissingMedia?: boolean
/** Number of media items */
mediaCount: number
/** Number of posts in thread */
postCount: number
/** ISO timestamp of last update */
updatedAt: string
/** All posts in the draft for full display */
posts: DraftPostDisplay[]
}
@@ -0,0 +1,156 @@
/**
* Native file system storage for draft media.
* Media is stored by localRefPath key (unique identifier stored in server draft).
*/
import {Directory, File, Paths} from 'expo-file-system'
import {logger} from './logger'
const MEDIA_DIR = 'bsky-draft-media'
function getMediaDirectory(): Directory {
return new Directory(Paths.document, MEDIA_DIR)
}
function getMediaFile(localRefPath: string): File {
const safeFilename = encodeURIComponent(localRefPath)
return new File(getMediaDirectory(), safeFilename)
}
let dirCreated = false
/**
* Ensure the media directory exists
*/
function ensureDirectory(): void {
if (dirCreated) return
const dir = getMediaDirectory()
if (!dir.exists) {
dir.create()
}
dirCreated = true
}
/**
* Save a media file to local storage by localRefPath key
*/
export async function saveMediaToLocal(
localRefPath: string,
sourcePath: string,
): Promise<void> {
ensureDirectory()
const destFile = getMediaFile(localRefPath)
// Ensure source path has file:// prefix for expo-file-system
let normalizedSource = sourcePath
if (!sourcePath.startsWith('file://') && sourcePath.startsWith('/')) {
normalizedSource = `file://${sourcePath}`
}
try {
const sourceFile = new File(normalizedSource)
sourceFile.copy(destFile)
// Update cache after successful save
mediaExistsCache.set(localRefPath, true)
} catch (error) {
logger.error('Failed to save media to drafts storage', {
error,
localRefPath,
sourcePath: normalizedSource,
destPath: destFile.uri,
})
throw error
}
}
/**
* Load a media file path from local storage
* @returns The file URI for the saved media
*/
export async function loadMediaFromLocal(
localRefPath: string,
): Promise<string> {
const file = getMediaFile(localRefPath)
if (!file.exists) {
throw new Error(`Media file not found: ${localRefPath}`)
}
return file.uri
}
/**
* Delete a media file from local storage
*/
export async function deleteMediaFromLocal(
localRefPath: string,
): Promise<void> {
const file = getMediaFile(localRefPath)
// Idempotent: only delete if file exists
if (file.exists) {
file.delete()
}
}
/**
* Check if a media file exists in local storage (synchronous check using cache)
* Note: This uses a cached directory listing for performance
*/
const mediaExistsCache = new Map<string, boolean>()
let cachePopulated = false
export function mediaExists(localRefPath: string): boolean {
// For native, we need an async check but the API requires sync
// Use cached result if available, otherwise assume doesn't exist
if (mediaExistsCache.has(localRefPath)) {
return mediaExistsCache.get(localRefPath)!
}
// If cache not populated yet, trigger async population
if (!cachePopulated && !populateCachePromise) {
populateCachePromise = populateCacheInternal()
}
return false // Conservative: assume doesn't exist if not in cache
}
let populateCachePromise: Promise<void> | null = null
function populateCacheInternal(): Promise<void> {
return new Promise(resolve => {
try {
const dir = getMediaDirectory()
if (dir.exists) {
const items = dir.list()
for (const item of items) {
// Reverse the URL encoding to get the original localRefPath
const localRefPath = decodeURIComponent(item.name)
mediaExistsCache.set(localRefPath, true)
}
}
cachePopulated = true
} catch (e) {
logger.warn('Failed to populate media cache', {error: e})
}
resolve()
})
}
/**
* Ensure the media cache is populated. Call this before checking mediaExists.
*/
export async function ensureMediaCachePopulated(): Promise<void> {
if (cachePopulated) return
if (!populateCachePromise) {
populateCachePromise = populateCacheInternal()
}
await populateCachePromise
}
/**
* Clear the media exists cache (call when media is added/deleted)
*/
export function clearMediaCache(): void {
mediaExistsCache.clear()
cachePopulated = false
populateCachePromise = null
}
@@ -0,0 +1,170 @@
/**
* Web IndexedDB storage for draft media.
* Media is stored by localRefPath key (unique identifier stored in server draft).
*/
import {createStore, del, get, keys, set} from 'idb-keyval'
import {logger} from './logger'
const DB_NAME = 'bsky-draft-media'
const STORE_NAME = 'media'
type MediaRecord = {
blob: Blob
createdAt: string
}
const store = createStore(DB_NAME, STORE_NAME)
/**
* Convert a path/URL to a Blob
*/
async function toBlob(sourcePath: string): Promise<Blob> {
// Handle data URIs directly
if (sourcePath.startsWith('data:')) {
const response = await fetch(sourcePath)
return response.blob()
}
// Handle blob URLs
if (sourcePath.startsWith('blob:')) {
try {
const response = await fetch(sourcePath)
return response.blob()
} catch (e) {
logger.error('Failed to fetch blob URL - it may have been revoked', {
error: e,
sourcePath,
})
throw e
}
}
// Handle regular URLs
const response = await fetch(sourcePath)
if (!response.ok) {
throw new Error(`Failed to fetch media: ${response.status}`)
}
return response.blob()
}
/**
* Save a media file to IndexedDB by localRefPath key
*/
export async function saveMediaToLocal(
localRefPath: string,
sourcePath: string,
): Promise<void> {
let blob: Blob
try {
blob = await toBlob(sourcePath)
} catch (error) {
logger.error('Failed to convert source to blob', {
error,
localRefPath,
sourcePath,
})
throw error
}
try {
await set(
localRefPath,
{
blob,
createdAt: new Date().toISOString(),
},
store,
)
// Update cache
mediaExistsCache.set(localRefPath, true)
} catch (error) {
logger.error('Failed to save media to IndexedDB', {error, localRefPath})
throw error
}
}
/**
* Load a media file from IndexedDB
* @returns A blob URL for the saved media
*/
export async function loadMediaFromLocal(
localRefPath: string,
): Promise<string> {
const record = await get<MediaRecord>(localRefPath, store)
if (!record) {
throw new Error(`Media file not found: ${localRefPath}`)
}
return URL.createObjectURL(record.blob)
}
/**
* Delete a media file from IndexedDB
*/
export async function deleteMediaFromLocal(
localRefPath: string,
): Promise<void> {
await del(localRefPath, store)
mediaExistsCache.delete(localRefPath)
}
/**
* Check if a media file exists in IndexedDB (synchronous check using cache)
*/
const mediaExistsCache = new Map<string, boolean>()
let cachePopulated = false
let populateCachePromise: Promise<void> | null = null
export function mediaExists(localRefPath: string): boolean {
if (mediaExistsCache.has(localRefPath)) {
return mediaExistsCache.get(localRefPath)!
}
// If cache not populated yet, trigger async population
if (!cachePopulated && !populateCachePromise) {
populateCachePromise = populateCacheInternal()
}
return false // Conservative: assume doesn't exist if not in cache
}
async function populateCacheInternal(): Promise<void> {
try {
const allKeys = await keys(store)
for (const key of allKeys) {
mediaExistsCache.set(key as string, true)
}
cachePopulated = true
} catch (e) {
logger.warn('Failed to populate media cache', {error: e})
}
}
/**
* Ensure the media cache is populated. Call this before checking mediaExists.
*/
export async function ensureMediaCachePopulated(): Promise<void> {
if (cachePopulated) return
if (!populateCachePromise) {
populateCachePromise = populateCacheInternal()
}
await populateCachePromise
}
/**
* Clear the media exists cache (call when media is added/deleted)
*/
export function clearMediaCache(): void {
mediaExistsCache.clear()
cachePopulated = false
populateCachePromise = null
}
/**
* Revoke a blob URL when done with it (to prevent memory leaks)
*/
export function revokeMediaUrl(url: string): void {
if (url.startsWith('blob:')) {
URL.revokeObjectURL(url)
}
}