fix: guard linux appimage media previews

This commit is contained in:
lucaronin
2026-05-15 01:22:56 +02:00
parent 384c752c33
commit 9b6a43cec7
13 changed files with 241 additions and 16 deletions

View File

@@ -189,7 +189,7 @@ Git-facing renderer code must pass an explicit repository path instead of assumi
| `text` | UTF-8 editable formats such as `.yml`, `.json`, `.ts`, `.py`, `.sh` | Opens through the raw editor without Markdown note semantics |
| `binary` | Images, audio, video, PDFs, archives, other non-text files | Stays a normal vault file; previewable media and PDFs open in `FilePreview`, unsupported or broken binaries show an explicit fallback |
Asset previewability is inferred in the renderer from the filename extension (`src/utils/filePreview.ts`) rather than stored as a new persisted kind. Supported images render through `<img>`, supported audio/video render through native HTML media controls, and supported PDFs render through the webview's PDF object renderer, all backed by Tauri asset URLs. Runtime asset access is accumulated only for vault roots Tolaria has loaded in the current app session, because Tauri directory forbids cannot be safely reversed after a vault switch. The "open in default app" action re-enters the active-vault command boundary through `open_vault_file_external` before delegating to the native opener. This keeps the filesystem as source of truth and avoids converting assets into proprietary objects.
Asset previewability is inferred in the renderer from the filename extension (`src/utils/filePreview.ts`) rather than stored as a new persisted kind. Supported images render through `<img>`, supported audio/video render through native HTML media controls, and supported PDFs render through the webview's PDF object renderer, all backed by Tauri asset URLs. On Linux AppImage builds, `should_use_external_media_preview` can disable in-webview audio/video rendering so the same file blocks show filename/external-open fallback controls instead of triggering unstable WebKitGTK media playback. Runtime asset access is accumulated only for vault roots Tolaria has loaded in the current app session, because Tauri directory forbids cannot be safely reversed after a vault switch. The "open in default app" action re-enters the active-vault command boundary through `open_vault_file_external` before delegating to the native opener. This keeps the filesystem as source of truth and avoids converting assets into proprietary objects.
### Note Content Freshness

View File

@@ -222,7 +222,7 @@ flowchart TD
- **Sidebar** (220-400px, resizable): Top-level filters (All Notes, Changes, Pulse), saved Views, collapsible type-based section groups, and a dedicated folder tree. The folder tree starts with a vault-root row labeled from the opened vault path, shows root-level files when selected, and nests user-created folders plus default vault folders such as `attachments/` and `views/` underneath it; only the dedicated `type/` directory stays hidden because note types already have their own sidebar section. Saved Views persist a top-level YAML `order` field in each view file and use the same ordered-list mental model as Types for single-vault lists: pointer users can drag the existing view row, double-click to rename it, or right-click for edit/rename/appearance/delete actions, while keyboard users can use the row context key for the same menu and command-palette move actions for ordering. In multiple-vault mode, saved View rows are keyed by source vault plus filename so duplicate filenames do not collide, and edits/deletes route to the owning vault. The folder tree supports inline folder creation and rename, exposes a right-click menu for rename/delete plus filesystem reveal/copy-path actions on mutable folders, and auto-expands ancestor folders when the current selection or rename target is nested. Type sections and folder rows also act as note drop targets: dropping a note on a type updates its `type:` frontmatter, while dropping it on a folder runs the same crash-safe move path as the command palette flow. Each type can have a custom icon, color, sort, and visibility set via its `type: Type` document; new type documents created by Tolaria are written at the vault root.
- **Note List / Pulse View** (220-500px, resizable): When a section group, filter, or saved view is selected, shows filtered notes with snippets, modified dates, status indicators, and per-context note-list controls. When `selection.kind === 'entity'`, the same pane enters **Neighborhood** mode: the source note is pinned at the top as a normal active row, outgoing relationship groups render first, inverse/backlink groups follow, empty groups stay visible with `0`, and duplicates across groups are allowed when multiple relationships are true. Plain click / `Enter` open the focused note without replacing the current Neighborhood, while Cmd/Ctrl-click and Cmd/Ctrl-`Enter` pivot the pane into the clicked note's Neighborhood. Inbox organization auto-advance is coordinated by `useInboxOrganizeAdvance`, which only opens the next visible Inbox note when the organized note is still the active requested tab after the write finishes. Folder-backed lists also show non-Markdown files: previewable media and PDF binaries get file indicators and open in the editor pane, while unsupported binaries remain muted instead of auto-launching an external app. Saved views reuse the same sort and visible-column controls as the built-in lists, and those changes persist back into the view `.yml` definition (`sort`, `listPropertiesDisplay`). When Pulse filter is active, shows `PulseView` — a chronological git activity feed grouped by day.
- **Editor** (flex, fills remaining space): Single note open at a time (no tabs — see ADR-0003). Breadcrumb bar with filename controls, read-only legacy display-title context when a no-H1 note's title differs from its filename, word count, rich-editor width toggle, and the secondary-overflow Table of Contents action, BlockNote rich text editor with wikilink support, Markdown-compatible inline/display math rendering, first-class Mermaid diagram blocks, markdown-safe formatting controls, and schema-backed fenced code block highlighting via `@blocknote/code-block`. Can toggle to diff view (modified files), raw CodeMirror view, or a wide rich-editor reading surface with preserved side margins; raw CodeMirror remains full-width and unaffected by note width mode. Inline rich-editor images open in a localized shadcn lightbox on double-click while normal single-click BlockNote selection remains untouched, and tiny tracking-style images are ignored. Binary image, audio, video, and PDF files render through `FilePreview` as ordinary vault files using Tauri asset URLs; editor-embedded audio and video use the same scoped asset sources through the CSP `media-src` allow-list. External-open actions call `open_vault_file_external` so the target is validated against the active vault before the native default app opens it. Unsupported/broken binaries show explicit fallback states and keyboard focus returns to the note list on `Escape`. Decomposed into `Editor` (orchestrator), `EditorContent`, `FilePreview`, `EditorRightPanel`, `TableOfContentsPanel`, `SingleEditorView`, with hooks `useDiffMode`, `useEditorFocus`, and `useEditorSave`, plus the `useRawMode`/`RawEditorView` pair for markdown source editing. Rich BlockNote input and raw CodeMirror input both route typed `->`, `<-`, and `<->` through the shared `src/utils/arrowLigatures.ts` resolver so arrow ligatures stay consistent across mode switches while escaped ASCII sequences remain literal. Navigation history (Cmd+[/]) replaces tabs.
- **Editor** (flex, fills remaining space): Single note open at a time (no tabs — see ADR-0003). Breadcrumb bar with filename controls, read-only legacy display-title context when a no-H1 note's title differs from its filename, word count, rich-editor width toggle, and the secondary-overflow Table of Contents action, BlockNote rich text editor with wikilink support, Markdown-compatible inline/display math rendering, first-class Mermaid diagram blocks, markdown-safe formatting controls, and schema-backed fenced code block highlighting via `@blocknote/code-block`. Can toggle to diff view (modified files), raw CodeMirror view, or a wide rich-editor reading surface with preserved side margins; raw CodeMirror remains full-width and unaffected by note width mode. Inline rich-editor images open in a localized shadcn lightbox on double-click while normal single-click BlockNote selection remains untouched, and tiny tracking-style images are ignored. Binary image, audio, video, and PDF files render through `FilePreview` as ordinary vault files using Tauri asset URLs; editor-embedded audio and video use the same scoped asset sources through the CSP `media-src` allow-list. Linux AppImage builds ask the native runtime whether audio/video should fall back to external-open controls before mounting webview media elements. External-open actions call `open_vault_file_external` so the target is validated against the active vault before the native default app opens it. Unsupported/broken binaries show explicit fallback states and keyboard focus returns to the note list on `Escape`. Decomposed into `Editor` (orchestrator), `EditorContent`, `FilePreview`, `EditorRightPanel`, `TableOfContentsPanel`, `SingleEditorView`, with hooks `useDiffMode`, `useEditorFocus`, and `useEditorSave`, plus the `useRawMode`/`RawEditorView` pair for markdown source editing. Rich BlockNote input and raw CodeMirror input both route typed `->`, `<-`, and `<->` through the shared `src/utils/arrowLigatures.ts` resolver so arrow ligatures stay consistent across mode switches while escaped ASCII sequences remain literal. Navigation history (Cmd+[/]) replaces tabs.
- **Right side panels** (200-500px or hidden): Properties, Table of Contents, and AI Agent are mutually exclusive panels mounted by `EditorRightPanel` and coordinated by `useRightPanelExclusion`. Properties shows frontmatter, relationships, instances, backlinks, and git history; Table of Contents is lazy-mounted only while open, derives a title-rooted H1/H2/H3 hierarchy through a debounced Web Worker per ADR-0109, and reuses folder-tree indentation/guide geometry with heading icons while resolving live BlockNote block IDs at click time for navigation; AI Agent keeps the selected CLI/API target controller mounted for tool execution and chat state. The breadcrumb bar toggles Table of Contents, AI, and Properties actions, and opening one replaces the others. Per-note `icon` is a suggested Properties field and the command palette's "Set Note Icon" action opens that field directly. When viewing a Type note, Properties shows an **Instances** section listing all notes of that type (sorted by modified_at desc, capped at 50).
Panels are separated by `ResizeHandle` components that support drag-to-resize. `useLayoutPanels` clamps the sidebar, note-list, and inspector widths before applying them, keeps the side panes from flex-shrinking below their protected widths, and persists the last chosen widths in installation-local localStorage under `tolaria:layout-panels`.

View File

@@ -5,6 +5,7 @@ mod git;
pub mod git_clone;
mod git_connect;
mod memory;
mod runtime;
mod system;
mod vault;
mod version;
@@ -17,6 +18,7 @@ pub use folders::*;
pub use git::*;
pub use git_connect::*;
pub use memory::*;
pub use runtime::*;
pub use system::*;
pub use vault::*;
pub use version::*;

View File

@@ -0,0 +1,29 @@
fn should_use_external_media_preview_for_appimage(is_linux_appimage: bool) -> bool {
is_linux_appimage
}
#[cfg(all(desktop, target_os = "linux"))]
fn linux_appimage_running() -> bool {
crate::linux_appimage::is_running()
}
#[cfg(not(all(desktop, target_os = "linux")))]
fn linux_appimage_running() -> bool {
false
}
#[tauri::command]
pub fn should_use_external_media_preview() -> bool {
should_use_external_media_preview_for_appimage(linux_appimage_running())
}
#[cfg(test)]
mod tests {
use super::should_use_external_media_preview_for_appimage;
#[test]
fn external_media_preview_is_limited_to_linux_appimage() {
assert!(should_use_external_media_preview_for_appimage(true));
assert!(!should_use_external_media_preview_for_appimage(false));
}
}

View File

@@ -517,6 +517,7 @@ macro_rules! app_invoke_handler {
commands::get_process_memory_snapshot,
commands::repair_vault,
commands::reinit_telemetry,
commands::should_use_external_media_preview,
commands::list_views,
commands::save_view_cmd,
commands::delete_view_cmd,

View File

@@ -365,24 +365,23 @@ vi.mock('./hooks/useUpdater', async () => {
// Mock BlockNote components (they need DOM APIs not available in jsdom)
vi.mock('@blocknote/core', () => ({
audioParse: vi.fn(() => undefined), createAudioBlockConfig: vi.fn(() => ({})),
BlockNoteSchema: { create: () => ({ extend: () => ({}) }) },
createCodeBlockSpec: vi.fn(() => ({})),
createExtension: (factory: unknown) => () => factory,
defaultInlineContentSpecs: {},
filterSuggestionItems: vi.fn(() => []),
createVideoBlockConfig: vi.fn(() => ({})), defaultInlineContentSpecs: {},
filterSuggestionItems: vi.fn(() => []), videoParse: vi.fn(() => undefined),
}))
vi.mock('@blocknote/code-block', () => ({
codeBlockOptions: {},
}))
vi.mock('@blocknote/code-block', () => ({ codeBlockOptions: {} }))
vi.mock('@blocknote/core/extensions', () => ({
filterSuggestionItems: vi.fn(() => []),
}))
vi.mock('@blocknote/core/extensions', () => ({ filterSuggestionItems: vi.fn(() => []) }))
vi.mock('@blocknote/react', () => ({
AudioBlock: () => null, AudioToExternalHTML: () => null,
createReactBlockSpec: () => () => ({}),
createReactInlineContentSpec: () => ({ render: () => null }),
VideoBlock: () => null, VideoToExternalHTML: () => null,
BlockNoteViewRaw: ({ children, editable }: { children?: ReactNode; editable?: boolean }) => (
<div data-testid="blocknote-view" data-editable={editable !== false ? 'true' : 'false'}>
<div contentEditable={editable !== false} suppressContentEditableWarning data-testid="mock-editor">

View File

@@ -49,11 +49,15 @@ const blockNoteViewState = vi.hoisted(() => ({
// Mock BlockNote components
vi.mock('@blocknote/core', () => ({
audioParse: vi.fn(() => undefined),
BlockNoteSchema: { create: () => ({ extend: () => ({}) }) },
createAudioBlockConfig: vi.fn(() => ({})),
createCodeBlockSpec: vi.fn(() => ({})),
createExtension: (factory: unknown) => () => factory,
createVideoBlockConfig: vi.fn(() => ({})),
defaultInlineContentSpecs: {},
filterSuggestionItems: vi.fn(() => []),
videoParse: vi.fn(() => undefined),
}))
vi.mock('@blocknote/code-block', () => ({
@@ -71,8 +75,12 @@ const capturedGetItemsByTrigger: Record<string, (query: string) => Promise<any[]
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock
let capturedGetItems: ((query: string) => Promise<any[]>) | null = null
vi.mock('@blocknote/react', () => ({
AudioBlock: () => null,
AudioToExternalHTML: () => null,
createReactBlockSpec: () => () => ({}),
createReactInlineContentSpec: () => ({ render: () => null }),
VideoBlock: () => null,
VideoToExternalHTML: () => null,
useCreateBlockNote: (options: unknown) => {
blockNoteCreation.options.push(options)
return mockEditor

View File

@@ -3,7 +3,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { FilePreview } from './FilePreview'
import type { VaultEntry } from '../types'
const { trackEventMock } = vi.hoisted(() => ({
const { externalMediaPreviewMock, trackEventMock } = vi.hoisted(() => ({
externalMediaPreviewMock: vi.fn(() => false),
trackEventMock: vi.fn(),
}))
@@ -15,6 +16,10 @@ vi.mock('../lib/telemetry', () => ({
trackEvent: trackEventMock,
}))
vi.mock('../utils/mediaPreviewRuntime', () => ({
useExternalMediaPreview: externalMediaPreviewMock,
}))
const imageEntry: VaultEntry = {
path: '/vault/Attachments/photo.png',
filename: 'photo.png',
@@ -69,6 +74,7 @@ const videoEntry: VaultEntry = {
describe('FilePreview', () => {
beforeEach(() => {
externalMediaPreviewMock.mockReturnValue(false)
trackEventMock.mockClear()
})
@@ -138,6 +144,19 @@ describe('FilePreview', () => {
expect(trackEventMock).toHaveBeenCalledWith('file_preview_opened', { preview_kind: 'video' })
})
it('uses the external-open fallback for media when native playback is unsafe', () => {
const onOpenExternalFile = vi.fn()
externalMediaPreviewMock.mockReturnValue(true)
render(<FilePreview entry={videoEntry} onOpenExternalFile={onOpenExternalFile} />)
expect(screen.queryByTestId('video-file-preview')).not.toBeInTheDocument()
expect(screen.getByTestId('file-preview-fallback')).toHaveTextContent('Preview unavailable')
fireEvent.click(screen.getByRole('button', { name: 'Open in default app' }))
expect(onOpenExternalFile).toHaveBeenCalledWith('/vault/Attachments/demo.mp4')
})
it('provides a graceful fallback when a PDF preview cannot render', () => {
render(<FilePreview entry={pdfEntry} />)

View File

@@ -4,6 +4,7 @@ import { ArrowSquareOut, ClipboardText, FileDashed, FilePdf, FolderOpen, ImageSq
import type { VaultEntry } from '../types'
import { trackFilePreviewAction, trackFilePreviewFailed, trackFilePreviewOpened } from '../lib/productAnalytics'
import { filePreviewKind, previewFileTypeLabel, type FilePreviewKind } from '../utils/filePreview'
import { useExternalMediaPreview } from '../utils/mediaPreviewRuntime'
import { focusNoteListContainer } from '../utils/neighborhoodHistory'
import { openLocalFile } from '../utils/url'
import { Button } from './ui/button'
@@ -357,8 +358,17 @@ function useFilePreviewActions({
return { handleOpenExternal, handleRevealFile, handleCopyFilePath }
}
function previewKindForBody(previewKind: FilePreviewKind | null, mediaFailed: boolean): FilePreviewKind | null {
return mediaFailed ? null : previewKind
function isMediaPreviewKind(previewKind: FilePreviewKind | null): boolean {
return previewKind === 'audio' || previewKind === 'video'
}
function previewKindForBody(
previewKind: FilePreviewKind | null,
mediaFailed: boolean,
externalMediaPreview: boolean,
): FilePreviewKind | null {
if (mediaFailed || (externalMediaPreview && isMediaPreviewKind(previewKind))) return null
return previewKind
}
export function FilePreview({
@@ -370,6 +380,7 @@ export function FilePreview({
const previewKind = filePreviewKind(entry)
const assetSrc = useMemo(() => (previewKind ? convertFileSrc(entry.path) : null), [entry.path, previewKind])
const fileTypeLabel = previewFileTypeLabel(entry)
const externalMediaPreview = useExternalMediaPreview()
const failures = useFilePreviewFailureState(entry.path)
const actions = useFilePreviewActions({
entryPath: entry.path,
@@ -409,7 +420,7 @@ export function FilePreview({
<div className="min-h-0 flex-1 overflow-auto bg-background">
<FilePreviewBody
entry={entry}
previewKind={previewKindForBody(previewKind, failures.mediaFailed)}
previewKind={previewKindForBody(previewKind, failures.mediaFailed, externalMediaPreview)}
assetSrc={assetSrc}
imageFailed={failures.imageFailed}
onImageError={failures.handleImageError}

View File

@@ -0,0 +1,32 @@
import { describe, expect, it } from 'vitest'
import {
mediaBlockPropsForPreviewRuntime,
schema,
} from './editorSchema'
describe('editor schema media blocks', () => {
it('keeps embedded audio and video blocks available in the editor schema', () => {
expect(schema.blockSpecs.audio.config.type).toBe('audio')
expect(schema.blockSpecs.video.config.type).toBe('video')
})
it('turns embedded media previews into file-name fallbacks for unsafe runtimes', () => {
const props = {
block: {
id: 'media-block',
props: {
name: 'demo.mp4',
showPreview: true,
url: 'asset://localhost/demo.mp4',
},
},
}
const fallbackProps = mediaBlockPropsForPreviewRuntime(props, true)
expect(fallbackProps).not.toBe(props)
expect(fallbackProps.block.props.showPreview).toBe(false)
expect(props.block.props.showPreview).toBe(true)
expect(mediaBlockPropsForPreviewRuntime(props, false)).toBe(props)
})
})

View File

@@ -1,11 +1,22 @@
/* eslint-disable react-refresh/only-export-components -- module-level schema, not a component file */
import {
audioParse,
createCodeBlockSpec,
BlockNoteSchema,
createAudioBlockConfig,
createVideoBlockConfig,
defaultInlineContentSpecs,
videoParse,
} from '@blocknote/core'
import { createReactBlockSpec, createReactInlineContentSpec } from '@blocknote/react'
import { lazy, Suspense } from 'react'
import {
AudioBlock,
AudioToExternalHTML,
createReactBlockSpec,
createReactInlineContentSpec,
VideoBlock,
VideoToExternalHTML,
} from '@blocknote/react'
import { lazy, Suspense, type ComponentProps } from 'react'
import { resolveWikilinkColor as resolveColor } from '../utils/wikilinkColors'
import { resolveEntry } from '../utils/wikilink'
import { MATH_BLOCK_TYPE, MATH_INLINE_TYPE, renderMathToHtml } from '../utils/mathMarkdown'
@@ -17,10 +28,20 @@ import { NoteTitleIcon } from './NoteTitleIcon'
import { MermaidDiagram } from './MermaidDiagram'
import { SafeHtmlSpan } from './SafeMarkup'
import { updateTldrawBlockPropsSafely } from './tldrawBlockProps'
import { useExternalMediaPreview } from '../utils/mediaPreviewRuntime'
const TldrawWhiteboard = lazy(() => import('./TldrawWhiteboard').then(module => ({
default: module.TldrawWhiteboard,
})))
type AudioBlockProps = ComponentProps<typeof AudioBlock>
type VideoBlockProps = ComponentProps<typeof VideoBlock>
type MediaBlockPreviewProps = {
block: {
props: {
showPreview: boolean
}
}
}
// Module-level cache so the WikiLink renderer (defined outside React) can access entries
export const _wikilinkEntriesRef: { current: VaultEntry[] } = { current: [] }
@@ -165,6 +186,54 @@ const MermaidBlock = createReactBlockSpec(
},
)
export function mediaBlockPropsForPreviewRuntime<T extends MediaBlockPreviewProps>(
props: T,
externalMediaPreview: boolean,
): T {
if (!externalMediaPreview) return props
return {
...props,
block: {
...props.block,
props: {
...props.block.props,
showPreview: false,
},
},
}
}
export function TolariaAudioBlock(props: AudioBlockProps) {
const externalMediaPreview = useExternalMediaPreview()
return <AudioBlock {...mediaBlockPropsForPreviewRuntime(props, externalMediaPreview)} />
}
export function TolariaVideoBlock(props: VideoBlockProps) {
const externalMediaPreview = useExternalMediaPreview()
return <VideoBlock {...mediaBlockPropsForPreviewRuntime(props, externalMediaPreview)} />
}
const AudioBlockSpec = createReactBlockSpec(
createAudioBlockConfig,
(config) => ({
render: TolariaAudioBlock,
parse: audioParse(config),
toExternalHTML: AudioToExternalHTML,
runsBefore: ['file'],
}),
)
const VideoBlockSpec = createReactBlockSpec(
createVideoBlockConfig,
(config) => ({
render: TolariaVideoBlock,
parse: videoParse(config),
toExternalHTML: VideoToExternalHTML,
runsBefore: ['file'],
}),
)
const TldrawBlock = createReactBlockSpec(
{
type: TLDRAW_BLOCK_TYPE,
@@ -214,9 +283,11 @@ const TldrawBlock = createReactBlockSpec(
)
const codeBlock = createCodeBlockSpec(createTolariaCodeBlockOptions())
const audioBlock = AudioBlockSpec()
const mathBlock = MathBlock()
const mermaidBlock = MermaidBlock()
const tldrawBlock = TldrawBlock()
const videoBlock = VideoBlockSpec()
export const schema = BlockNoteSchema.create({
inlineContentSpecs: {
@@ -226,9 +297,11 @@ export const schema = BlockNoteSchema.create({
},
}).extend({
blockSpecs: {
audio: audioBlock,
mathBlock,
mermaidBlock,
tldrawBlock,
codeBlock,
video: videoBlock,
},
})

View File

@@ -421,6 +421,7 @@ export const mockHandlers: Record<string, (args: any) => any> = {
return `[main abc1234] ${args.message}\n ${count} files changed`
},
get_build_number: () => 'bDEV',
should_use_external_media_preview: () => false,
get_last_commit_info: (): LastCommitInfo => ({ shortHash: 'a1b2c3d', commitUrl: 'https://github.com/lucaong/laputa-vault/commit/a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0' }),
is_git_repo: () => true,
init_git_repo: () => null,

View File

@@ -0,0 +1,50 @@
import { useEffect, useState } from 'react'
import { invoke } from '@tauri-apps/api/core'
import { isTauri } from '../mock-tauri'
import { isLinux } from './platform'
let cachedExternalMediaPreview: boolean | null = null
let pendingExternalMediaPreview: Promise<boolean> | null = null
function initialExternalMediaPreview(): boolean {
return isTauri() && isLinux()
}
async function loadExternalMediaPreview(): Promise<boolean> {
if (!isTauri()) return false
if (cachedExternalMediaPreview !== null) return cachedExternalMediaPreview
if (pendingExternalMediaPreview) return pendingExternalMediaPreview
pendingExternalMediaPreview = invoke<boolean>('should_use_external_media_preview')
.catch((error: unknown) => {
console.warn('[media] Failed to resolve media preview runtime:', error)
return false
})
.then((value) => {
cachedExternalMediaPreview = value
pendingExternalMediaPreview = null
return value
})
return pendingExternalMediaPreview
}
export function useExternalMediaPreview(): boolean {
const [externalMediaPreview, setExternalMediaPreview] = useState(
cachedExternalMediaPreview ?? initialExternalMediaPreview(),
)
useEffect(() => {
let cancelled = false
void loadExternalMediaPreview().then((value) => {
if (!cancelled) setExternalMediaPreview(value)
})
return () => {
cancelled = true
}
}, [])
return externalMediaPreview
}