Design system.
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 

81 рядки
2.1 KiB

  1. import * as React from 'react';
  2. import {addDataUrl, FileWithDataUrl} from 'packages/web-kitchensink-reactnext/src/utils/blob';
  3. export interface UseFileUrlOptions {
  4. file?: Partial<File>;
  5. }
  6. export const useFileUrl = (options: UseFileUrlOptions) => {
  7. const { file } = options;
  8. const [fileWithUrl, setFileWithUrl] = React.useState<Partial<FileWithDataUrl> | undefined>(file);
  9. const [loading, setLoading] = React.useState(false);
  10. React.useEffect(() => {
  11. if (!file) {
  12. if (fileWithUrl) {
  13. setFileWithUrl(undefined);
  14. }
  15. setLoading(false);
  16. return;
  17. }
  18. setFileWithUrl(undefined);
  19. setLoading(true);
  20. addDataUrl(file)
  21. .then((fileWithUrl) => {
  22. setFileWithUrl(fileWithUrl);
  23. setLoading(false);
  24. })
  25. .catch(() => {
  26. setLoading(false);
  27. });
  28. }, [file]);
  29. return React.useMemo(() => ({
  30. fileWithUrl,
  31. loading,
  32. }), [fileWithUrl, loading]);
  33. };
  34. export interface UseFileMetadataOptions<T extends Partial<File> = Partial<File>, U extends Partial<File> = Partial<File>> {
  35. file?: U;
  36. augmentFunction: (file: U) => Promise<T>;
  37. }
  38. export const useFileMetadata = <T extends Partial<FileWithDataUrl>>(options: UseFileMetadataOptions<T>) => {
  39. const { file, augmentFunction } = options;
  40. const [fileWithMetadata, setFileWithMetadata] = React.useState<T | undefined>(file as T | undefined);
  41. const [loading, setLoading] = React.useState(false);
  42. const [error, setError] = React.useState<Error>();
  43. React.useEffect(() => {
  44. if (!file) {
  45. if (fileWithMetadata) {
  46. setFileWithMetadata(undefined);
  47. }
  48. setLoading(false);
  49. return;
  50. }
  51. setFileWithMetadata(undefined);
  52. setLoading(true);
  53. setError(undefined);
  54. augmentFunction(file)
  55. .then((theAugmentedFile) => {
  56. setFileWithMetadata(theAugmentedFile);
  57. setLoading(false);
  58. })
  59. .catch((error) => {
  60. setFileWithMetadata(file as T);
  61. setError(error);
  62. setLoading(false);
  63. });
  64. }, [file, augmentFunction]);
  65. return React.useMemo(() => ({
  66. fileWithMetadata,
  67. error,
  68. loading,
  69. }), [fileWithMetadata, loading, error]);
  70. };