Skip to content

Commit

Permalink
feat(Core): inline small OPFS files without using blob:.... URLs.
Browse files Browse the repository at this point in the history
  • Loading branch information
akopachov committed Apr 16, 2024
1 parent 5fdd802 commit 1efc963
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion apps/webextension/src/actions/opfs-src.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { Action } from 'svelte/action';
type HTMLElementWithRef = HTMLElement & ({ src: string | undefined } | { href: string | undefined });

const log = logger.getSubLogger({ prefix: ['OPFS source loader:'] });
const BLOB_STRATEGY_THRESHOLD = 32_768; // 32KiB

export const opfsSrc: Action<HTMLElementWithRef, string | undefined> = function (
node: HTMLElementWithRef,
Expand Down Expand Up @@ -32,7 +33,17 @@ export const opfsSrc: Action<HTMLElementWithRef, string | undefined> = function
if (s.startsWith('opfs://')) {
try {
const file = await Opfs.get(s);
setRef(URL.createObjectURL(file));
if (file.size > BLOB_STRATEGY_THRESHOLD) {
// If file is too big, use blob URL
setRef(URL.createObjectURL(file));
} else {
// Otherwise, load it as data URL
const reader = new FileReader();
reader.onload = () => {
setRef(reader.result as string);
};
reader.readAsDataURL(file);
}
} catch (e) {
log.error('Error loading file from OPFS:', e);
setRef('');
Expand Down

0 comments on commit 1efc963

Please sign in to comment.