54 lines
2.0 KiB
TypeScript
54 lines
2.0 KiB
TypeScript
type CapacitorFilesystemModule = typeof import('@capacitor/filesystem');
|
|
type CapacitorCoreModule = typeof import('@capacitor/core');
|
|
|
|
/**
|
|
* Minimal Capacitor Filesystem surface the attachment store depends on, plus the
|
|
* `Directory` enum and `convertFileSrc` helper. Loaded lazily so the desktop and
|
|
* browser builds never statically import `@capacitor/*` (see LESSONS:
|
|
* "Lazy-load Capacitor modules on Electron/desktop").
|
|
*/
|
|
export interface CapacitorAttachmentFilesystem {
|
|
filesystem: CapacitorFilesystemModule['Filesystem'];
|
|
directory: CapacitorFilesystemModule['Directory'][keyof CapacitorFilesystemModule['Directory']];
|
|
/** User-visible directory (`Documents`) used when exporting attachments out of app storage. */
|
|
exportDirectory: CapacitorFilesystemModule['Directory'][keyof CapacitorFilesystemModule['Directory']];
|
|
convertFileSrc: (url: string) => string;
|
|
}
|
|
|
|
let cachedFilesystem: Promise<CapacitorAttachmentFilesystem | null> | null = null;
|
|
|
|
/**
|
|
* Resolve the Capacitor Filesystem plugin (scoped to the app `Data` directory)
|
|
* on native shells. Returns `null` on web/Electron or when the plugin is
|
|
* unavailable.
|
|
*/
|
|
export function loadCapacitorAttachmentFilesystem(): Promise<CapacitorAttachmentFilesystem | null> {
|
|
cachedFilesystem ??= resolveCapacitorAttachmentFilesystem();
|
|
|
|
return cachedFilesystem;
|
|
}
|
|
|
|
async function resolveCapacitorAttachmentFilesystem(): Promise<CapacitorAttachmentFilesystem | null> {
|
|
if (typeof window === 'undefined') {
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
const filesystemModule: CapacitorFilesystemModule = await import('@capacitor/filesystem');
|
|
const coreModule: CapacitorCoreModule = await import('@capacitor/core');
|
|
|
|
if (!coreModule.Capacitor.isNativePlatform()) {
|
|
return null;
|
|
}
|
|
|
|
return {
|
|
filesystem: filesystemModule.Filesystem,
|
|
directory: filesystemModule.Directory.Data,
|
|
exportDirectory: filesystemModule.Directory.Documents,
|
|
convertFileSrc: (url: string) => coreModule.Capacitor.convertFileSrc(url)
|
|
};
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|