Skip to content

Commit

Permalink
rewrite the logics for loading online and offline Twords (#285)
Browse files Browse the repository at this point in the history
  • Loading branch information
sijumoncy authored Jan 4, 2024
1 parent dee45f0 commit d29c0e6
Showing 1 changed file with 71 additions and 55 deletions.
126 changes: 71 additions & 55 deletions renderer/src/components/EditorPage/Reference/TW/TwNavigation.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,34 +17,30 @@ export default function TwNavigation({ languageId, referenceResources, setRefere
const [openSnackBar, setOpenSnackBar] = useState(false);
const [snackText, setSnackText] = useState('');
const [error, setError] = useState('');
const [onlineMeta, setOnlineMeta] = useState();

// const baseUrl = 'https://git.door43.org/api/v1/repos';
const owner = referenceResources?.owner;

useEffect(() => {
if (referenceResources && referenceResources?.offlineResource?.offline) {
// offline
// console.log('offline : ', { referenceResources });
const taArrayOffline = [];
const { offlineResource } = referenceResources;
localForage.getItem('userProfile').then(async (user) => {
logger.debug('TwNavigation.js', 'reading offline helps ', offlineResource.data?.projectDir);
const fs = window.require('fs');
const path = require('path');
const newpath = localStorage.getItem('userPath');
const currentUser = user?.username;
const folder = path.join(newpath, packageInfo.name, 'users', `${currentUser}`, 'resources');
const projectName = `${offlineResource?.data?.value?.meta?.name}_${offlineResource?.data?.value?.meta?.owner}_${offlineResource?.data?.value?.meta?.release?.tag_name}`;
// set Options

const optionsDir = path.join(folder, projectName, 'bible');
const tempOptions = [];

if (fs.existsSync(optionsDir)) {
fs.readdir(optionsDir, async (err, optionsNames) => {
if (err) {
// console.log(`Unable to scan directory: ${ err}`);
logger.debug('TwNavigation.js', `Unable to scan directory: ${ err}`);
}
// console.log({ optionsNames });
let optionsCount = 0;
await optionsNames.forEach(async (folderName) => {
if (fs.lstatSync(path.join(optionsDir, folderName)).isDirectory()) {
Expand All @@ -53,43 +49,22 @@ export default function TwNavigation({ languageId, referenceResources, setRefere
}
});
if (tempOptions.length === optionsCount) {
setoptions(tempOptions);
setoptions(tempOptions);
setselectedOption(tempOptions[0]);
}
// fetch contents of selected folder
if (selectedOption && selectedOption?.length > 0 && fs.existsSync(path.join(optionsDir, selectedOption))) {
fs.readdir(path.join(optionsDir, selectedOption), async (err, folderContents) => {
let contentsCount = 0;
folderContents.forEach((content) => {
if (fs.lstatSync(path.join(optionsDir, selectedOption, content)).isFile()) {
contentsCount += 1;
taArrayOffline.push(
{
folder: path.join(selectedOption, content),
title: content.replace('.md', ''),
subTitle: '',
},
);
}
});
if (taArrayOffline.length === contentsCount) {
setTwList(taArrayOffline);
}
});
}
});
});
}
});
} else {
// online
// get options
// fetch(`https://git.door43.org/api/catalog/v5/search?subject=Translation%20Words&lang=${languageId}&owner=${owner}`)
fetch(`${environment.GITEA_API_ENDPOINT}/catalog/search?metadataType=rc&subject=Translation%20Words&lang=${languageId}&owner=${owner}`)
.then((res) => res.json())
.then((meta) => {
// console.log('meta : ', { meta });
fetch(meta?.data[0]?.contents_url)
.then((response) => response.json())
.then((contents) => {
setOnlineMeta(meta);
const bibleDirUlr = contents.filter((content) => content?.name === 'bible' && content?.type === 'dir');
// console.log({ bibleDirUlr });
if (bibleDirUlr?.length > 0) {
Expand All @@ -107,45 +82,86 @@ export default function TwNavigation({ languageId, referenceResources, setRefere
});
if (folderCount === tempOptions?.length) {
setoptions(tempOptions);
setselectedOption(tempOptions[0]);
}
}
});
}
});
});
}
}, [owner, languageId]);

Check warning on line 93 in renderer/src/components/EditorPage/Reference/TW/TwNavigation.js

View workflow job for this annotation

GitHub Actions / Lint Run

React Hook useEffect has a missing dependency: 'referenceResources'. Either include it or remove the dependency array

Check warning on line 93 in renderer/src/components/EditorPage/Reference/TW/TwNavigation.js

View workflow job for this annotation

GitHub Actions / Lint Run

React Hook useEffect has a missing dependency: 'referenceResources'. Either include it or remove the dependency array

const fetchData = async () => {
await fetch(`${environment.GITEA_API_ENDPOINT}/repos/${owner}/${languageId}_tw/contents/bible/${selectedOption}?ref=${meta?.data[0]?.release?.tag_name}`)
.then((response) => response.json())
.then((twData) => {
twData && twData?.forEach((data) => {
data.folder = data?.path.replace('bible/', '');
data.title = data?.name.replace('.md', '');
data.subTitle = '';
useEffect(() => {
if (referenceResources && referenceResources?.offlineResource?.offline) {
const taArrayOffline = [];
const { offlineResource } = referenceResources;
localForage.getItem('userProfile').then(async (user) => {
const fs = window.require('fs');
const path = require('path');
const newpath = localStorage.getItem('userPath');
const currentUser = user?.username;
const folder = path.join(newpath, packageInfo.name, 'users', `${currentUser}`, 'resources');
const projectName = `${offlineResource?.data?.value?.meta?.name}_${offlineResource?.data?.value?.meta?.owner}_${offlineResource?.data?.value?.meta?.release?.tag_name}`;
// set Options
const optionsDir = path.join(folder, projectName, 'bible');
if (selectedOption && selectedOption?.length > 0 && fs.existsSync(path.join(optionsDir, selectedOption))) {
fs.readdir(path.join(optionsDir, selectedOption), async (err, folderContents) => {
let contentsCount = 0;
folderContents.forEach((content) => {
if (fs.lstatSync(path.join(optionsDir, selectedOption, content)).isFile()) {
contentsCount += 1;
taArrayOffline.push(
{
folder: path.join(selectedOption, content),
title: content.replace('.md', ''),
subTitle: '',
},
);
}
});
setTwList(twData);
}).catch((err) => {
logger.debug('TwNavigation.js', 'reading offline helps ', err);
setOpenSnackBar(true);
setError('failure');
setSnackText('Can not load content');
if (taArrayOffline.length === contentsCount) {
setTwList(taArrayOffline);
setSelected(taArrayOffline[0]);
}
});
};
}
});
} else {
// online data fetch
const fetchData = async () => {
await fetch(`${environment.GITEA_API_ENDPOINT}/repos/${owner}/${languageId}_tw/contents/bible/${selectedOption}?ref=${onlineMeta?.data[0]?.release?.tag_name}`)
.then((response) => response.json())
.then((twData) => {
twData && twData?.forEach((data) => {
data.folder = data?.path.replace('bible/', '');
data.title = data?.name.replace('.md', '');
data.subTitle = '';
});
setTwList(twData);
setSelected(twData[0]);
}).catch((err) => {
logger.debug('TwNavigation.js', 'reading offline helps ', err);
setOpenSnackBar(true);
setError('failure');
setSnackText('Can not load content');
});
};

const getData = async () => {
await fetchData();
};
// console.log({ selectedOption });
selectedOption && getData();
});
const getData = async () => {
await fetchData();
};

selectedOption && getData();
}
}, [languageId, referenceResources, owner, selectedOption]);
}, [options, selectedOption]);

Check warning on line 157 in renderer/src/components/EditorPage/Reference/TW/TwNavigation.js

View workflow job for this annotation

GitHub Actions / Lint Run

React Hook useEffect has missing dependencies: 'languageId', 'onlineMeta?.data', 'owner', and 'referenceResources'. Either include them or remove the dependency array

Check warning on line 157 in renderer/src/components/EditorPage/Reference/TW/TwNavigation.js

View workflow job for this annotation

GitHub Actions / Lint Run

React Hook useEffect has missing dependencies: 'languageId', 'onlineMeta?.data', 'owner', and 'referenceResources'. Either include them or remove the dependency array

useEffect(() => {
selected && setReferenceResources((current) => ({
...current,
offlineResource: { ...current.offlineResource, twSelected: selected },
}));
}, [selected, selectedOption, setReferenceResources]);
}, [selected]);

Check warning on line 164 in renderer/src/components/EditorPage/Reference/TW/TwNavigation.js

View workflow job for this annotation

GitHub Actions / Lint Run

React Hook useEffect has a missing dependency: 'setReferenceResources'. Either include it or remove the dependency array. If 'setReferenceResources' changes too often, find the parent component that defines it and wrap that definition in useCallback

Check warning on line 164 in renderer/src/components/EditorPage/Reference/TW/TwNavigation.js

View workflow job for this annotation

GitHub Actions / Lint Run

React Hook useEffect has a missing dependency: 'setReferenceResources'. Either include it or remove the dependency array. If 'setReferenceResources' changes too often, find the parent component that defines it and wrap that definition in useCallback

return (
<>
Expand Down

0 comments on commit d29c0e6

Please sign in to comment.