feat: update useMediaFiles to allow for arbitrary folder

This commit is contained in:
Daniel Lautzenheiser 2023-04-03 13:56:46 -04:00
parent f07b9489f1
commit 4704485009
2 changed files with 35 additions and 5 deletions

View File

@ -743,8 +743,8 @@ export class Backend<BC extends BackendClass = BackendClass> {
return entryValue;
}
getMedia() {
return this.implementation.getMedia();
getMedia(folder?: string | undefined, mediaPath?: string | undefined) {
return this.implementation.getMedia(folder, mediaPath);
}
getMediaFile(path: string) {

View File

@ -1,4 +1,4 @@
import { useMemo } from 'react';
import { useEffect, useMemo, useState } from 'react';
import { dirname } from 'path';
import { selectMediaLibraryFiles } from '@staticcms/core/reducers/selectors/mediaLibrary';
@ -7,10 +7,12 @@ import { useAppSelector } from '@staticcms/core/store/hooks';
import { selectCollection } from '@staticcms/core/reducers/selectors/collections';
import { selectConfig } from '@staticcms/core/reducers/selectors/config';
import { selectMediaFolder } from '../util/media.util';
import { currentBackend } from '@staticcms/core/backend';
import type { MediaField, MediaFile } from '@staticcms/core/interface';
export default function useMediaFiles(field?: MediaField): MediaFile[] {
export default function useMediaFiles(field?: MediaField, currentFolder?: string): MediaFile[] {
const [currentFolderMediaFiles, setCurrentFolderMediaFiles] = useState<MediaFile[] | null>(null);
const mediaLibraryFiles = useAppSelector(selectMediaLibraryFiles);
const entry = useAppSelector(selectEditingDraft);
const config = useAppSelector(selectConfig);
@ -21,7 +23,35 @@ export default function useMediaFiles(field?: MediaField): MediaFile[] {
);
const collection = useAppSelector(collectionSelector);
useEffect(() => {
if (!currentFolder || !config) {
setCurrentFolderMediaFiles(null);
return;
}
let alive = true;
const getMediaFiles = async () => {
const backend = currentBackend(config);
const files = await backend.getMedia(currentFolder);
if (alive) {
setCurrentFolderMediaFiles(files);
}
};
getMediaFiles();
return () => {
alive = false;
};
}, [currentFolder, config]);
return useMemo(() => {
if (currentFolderMediaFiles) {
return currentFolderMediaFiles;
}
if (entry) {
const entryFiles = entry.mediaFiles ?? [];
if (config) {
@ -33,5 +63,5 @@ export default function useMediaFiles(field?: MediaField): MediaFile[] {
}
return mediaLibraryFiles ?? [];
}, [collection, config, entry, field, mediaLibraryFiles]);
}, [collection, config, currentFolderMediaFiles, entry, field, mediaLibraryFiles]);
}