Skip to content

Commit

Permalink
Add global set to replace ref hook
Browse files Browse the repository at this point in the history
  • Loading branch information
slytter committed Apr 17, 2023
1 parent fa7ff40 commit 9b333fb
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
4 changes: 3 additions & 1 deletion src/interfaces.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,9 @@ export interface Story {
duration?: number;
styles?: object;
content?: Renderer;
originalContent?: Renderer;
originalContent?: Renderer
// Whether to preload the resource or not, defaults to true for images and false for videos
preloadResource?: boolean;
}

export interface Header {
Expand Down
15 changes: 11 additions & 4 deletions src/util/usePreLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,28 +20,35 @@ const cacheContent = async (contents: Story[]) => {
img.src = content.url;
img.onload = resolve;
img.onerror = reject;

})
})

await Promise.all(promises);
}

// Keeps track of urls that have been loaded
const urlsLoaded = new Set<string>();

// Pushes urls to urlsLoaded
const markUrlsLoaded = (contents: Story[]) => {
contents.forEach((content) => {
urlsLoaded.add(content.url)
})
}

// Preloads images and videos from given Story[] using a cursor and preloadCount
// Preload count is the number of images/videos to preload after the cursor
// Cursor is the current index to start preloading from
export const usePreLoader = (contents: Story[], cursor: number, preloadCount: number) => {
const urlsLoaded = useRef([] as string[]).current;

// Pushes urls to urlsLoaded
const markUrlsLoaded = (contents: Story[]) => urlsLoaded.push(...contents.map((content) => content.url))

useEffect(() => {
const start = cursor + 1;
const end = cursor + preloadCount + 1;

const toPreload = contents.slice(start, end)
.filter((content) => !urlsLoaded.includes(content.url)); // Only preload urls that haven't been loaded yet
.filter((content) => !urlsLoaded.has(content.url)); // Only preload urls that haven't been loaded yet

markUrlsLoaded(toPreload)

Expand Down

0 comments on commit 9b333fb

Please sign in to comment.