Update get-file-from-path to work with folders; fix file-list component.

This commit is contained in:
Franco Montenegro 2022-08-17 12:33:59 -03:00
parent fa5c1a1cf3
commit 25a71be143
3 changed files with 30 additions and 14 deletions

View file

@ -305,23 +305,40 @@ app.on('before-quit', () => {
// Example:
// const result = await ipcMain.invoke('get-file-from-path', 'path/to/file');
// const file = new File([result.buffer], result.name);
// NOTE: if path points to a folder, an empty
// file will be given.
ipcMain.handle('get-file-from-path', (event, path) => {
return new Promise((resolve, reject) => {
// Encoding null ensures data results in a Buffer.
fs.readFile(path, { encoding: null }, (err, data) => {
if (err) {
reject(err);
fs.stat(path, (error, stats) => {
if (error) {
reject(error);
return;
}
// Separate folders considering "\" and "/"
// as separators (cross platform)
const folders = path.split(/[\\/]/);
const fileName = folders[folders.length - 1];
resolve({
name: fileName,
mime: mime.getType(fileName) || undefined,
path: path,
buffer: data,
const name = folders[folders.length - 1];
if (stats.isDirectory()) {
resolve({
name,
mime: undefined,
path,
buffer: new ArrayBuffer(0),
});
return;
}
// Encoding null ensures data results in a Buffer.
fs.readFile(path, { encoding: null }, (err, data) => {
if (err) {
reject(err);
return;
}
resolve({
name,
mime: mime.getType(name) || undefined,
path,
buffer: data,
});
});
});
});

View file

@ -31,11 +31,11 @@ function FileList(props: Props) {
};
React.useEffect(() => {
if (radio.stops.length) {
if (radio.items.length) {
if (!radio.currentId) {
radio.first();
} else {
const first = radio.stops[0].ref.current;
const first = radio.items[0].ref.current;
// First auto-selection
if (first && first.id === radio.currentId && !radio.state) {
const file = getFile(first.value);
@ -46,7 +46,7 @@ function FileList(props: Props) {
if (radio.state) {
// Find selected element
const stop = radio.stops.find((item) => item.id === radio.currentId);
const stop = radio.items.find((item) => item.id === radio.currentId);
const element = stop && stop.ref.current;
// Only update state if new item is selected
if (element && element.value !== radio.state) {

View file

@ -77,7 +77,6 @@ class FileSelector extends React.PureComponent<Props> {
if (path) {
return ipcRenderer.invoke('get-file-from-path', path);
}
return undefined;
})
.then((result) => {
if (!result) {