|
| 1 | +import { useEffect, useState } from 'react'; |
| 2 | + |
| 3 | +import { formatByteSize } from '@douglasneuroinformatics/libjs'; |
| 4 | +import { Button, Dialog } from '@douglasneuroinformatics/libui/components'; |
| 5 | + |
| 6 | +import { useAppStore } from '@/store'; |
| 7 | +export type StorageUsageDialogProps = { |
| 8 | + isOpen: boolean; |
| 9 | + setIsOpen: (value: boolean) => void; |
| 10 | +}; |
| 11 | + |
| 12 | +export const StorageUsageDialog = ({ isOpen, setIsOpen }: StorageUsageDialogProps) => { |
| 13 | + const [storageEstimate, setStorageEstimate] = useState<null | StorageEstimate>(null); |
| 14 | + const [updateKey, setUpdateKey] = useState(0); |
| 15 | + const [message, setMessage] = useState<null | string>('Loading...'); |
| 16 | + |
| 17 | + const updateStorage = async () => { |
| 18 | + setMessage('Loading...'); |
| 19 | + const [updated] = await Promise.all([ |
| 20 | + await navigator.storage.estimate(), |
| 21 | + new Promise((resolve) => setTimeout(resolve, 500)) |
| 22 | + ]); |
| 23 | + setStorageEstimate(updated); |
| 24 | + setMessage(null); |
| 25 | + }; |
| 26 | + |
| 27 | + useEffect(() => { |
| 28 | + void updateStorage(); |
| 29 | + }, [isOpen, updateKey]); |
| 30 | + |
| 31 | + return ( |
| 32 | + <Dialog open={isOpen} onOpenChange={setIsOpen}> |
| 33 | + <Dialog.Content> |
| 34 | + <Dialog.Header> |
| 35 | + <Dialog.Title>Storage Usage</Dialog.Title> |
| 36 | + <Dialog.Description> |
| 37 | + Check the details below to see how much storage your browser is using for instruments and how much space is |
| 38 | + still available. |
| 39 | + </Dialog.Description> |
| 40 | + </Dialog.Header> |
| 41 | + <Dialog.Body> |
| 42 | + {message ? ( |
| 43 | + <p>{message}</p> |
| 44 | + ) : ( |
| 45 | + <> |
| 46 | + <p>Usage: {storageEstimate?.usage ? formatByteSize(storageEstimate.usage, true) : 'N/A'}</p> |
| 47 | + <p>Quota: {storageEstimate?.quota ? formatByteSize(storageEstimate.quota, true) : 'N/A'} </p> |
| 48 | + </> |
| 49 | + )} |
| 50 | + </Dialog.Body> |
| 51 | + <Dialog.Footer> |
| 52 | + <Button |
| 53 | + variant="danger" |
| 54 | + onClick={() => { |
| 55 | + useAppStore.persist.clearStorage(); |
| 56 | + setMessage('Deleting...'); |
| 57 | + void new Promise((resolve) => setTimeout(resolve, 2000)).then(() => { |
| 58 | + setUpdateKey(updateKey + 1); |
| 59 | + }); |
| 60 | + }} |
| 61 | + > |
| 62 | + Drop Database (Irreversible) |
| 63 | + </Button> |
| 64 | + <Button type="button" variant="outline" onClick={() => setIsOpen(false)}> |
| 65 | + Close |
| 66 | + </Button> |
| 67 | + </Dialog.Footer> |
| 68 | + </Dialog.Content> |
| 69 | + </Dialog> |
| 70 | + ); |
| 71 | +}; |
0 commit comments