| 1 |
import React, { useCallback, useState } from 'react' |
| 2 |
import { createContextHook } from '../../../utils/bootstrap' |
| 3 |
import type { PropsWithChildren } from 'react' |
| 4 |
import type { CloudSnippetSchema } from '../../../types/schema/CloudSnippetSchema' |
| 5 |
|
| 6 |
export interface CloudSnippetDownloadRecord { |
| 7 |
isDownloading: boolean |
| 8 |
localId?: number |
| 9 |
} |
| 10 |
|
| 11 |
interface CloudSnippetDownloadsContext { |
| 12 |
downloadRecords: Partial<Record<CloudSnippetSchema['id'], CloudSnippetDownloadRecord>> |
| 13 |
updateDownloadRecord: ( |
| 14 |
snippetId: CloudSnippetSchema['id'], |
| 15 |
update: Partial<CloudSnippetDownloadRecord> |
| 16 |
) => void |
| 17 |
} |
| 18 |
|
| 19 |
const [Context, useCloudSnippetDownloads] = |
| 20 |
createContextHook<CloudSnippetDownloadsContext>('useCloudSnippetDownloads') |
| 21 |
|
| 22 |
export const WithCloudSnippetDownloadsContext: React.FC<PropsWithChildren> = ({ children }) => { |
| 23 |
const [downloadRecords, setDownloadRecords] = |
| 24 |
useState<CloudSnippetDownloadsContext['downloadRecords']>({}) |
| 25 |
const updateDownloadRecord = useCallback<CloudSnippetDownloadsContext['updateDownloadRecord']>( |
| 26 |
(snippetId, update) => setDownloadRecords(previous => ({ |
| 27 |
...previous, |
| 28 |
[snippetId]: { |
| 29 |
isDownloading: false, |
| 30 |
...previous[snippetId], |
| 31 |
...update |
| 32 |
} |
| 33 |
})), |
| 34 |
[] |
| 35 |
) |
| 36 |
|
| 37 |
return ( |
| 38 |
<Context.Provider value={{ downloadRecords, updateDownloadRecord }}> |
| 39 |
{children} |
| 40 |
</Context.Provider> |
| 41 |
) |
| 42 |
} |
| 43 |
|
| 44 |
export { useCloudSnippetDownloads } |
| 45 |
|