Skip to content

Commit

Permalink
merged with dev
Browse files Browse the repository at this point in the history
  • Loading branch information
danielc-n committed Feb 19, 2024
2 parents 5c9eef4 + 34d947a commit 15ba171
Show file tree
Hide file tree
Showing 28 changed files with 428 additions and 202 deletions.
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"eslint.codeAction.disableRuleComment": {},
"eslint.codeAction.showDocumentation": {},
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
"source.fixAll.eslint": "explicit"
},
"eslint.workingDirectories": [],
"editor.tabSize": 2
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"productName": "scribe-scripture-editor",
"description": "A friendly assistant for Bible Translators.",
"author": "Bible Technology <[email protected]>",
"version": "0.5.6",
"version": "0.5.8",
"license": "MIT",
"private": true,
"main": "main/index.js",
Expand Down
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
43 changes: 43 additions & 0 deletions renderer/src/components/EditorPage/Reference/TabSelector.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import React from 'react';
import { Tab } from '@headlessui/react';
import PropTypes from 'prop-types';

function classNames(...classes) {
return classes.filter(Boolean).join(' ');
}

function TabSelector({ currentTab, setCurrentTab, tabData }) {
return (
<div className="w-full px-2 sm:px-0 pb-2">
<Tab.Group manual defaultIndex={2} selectedIndex={currentTab} onChange={setCurrentTab}>
<Tab.List className="flex space-x-1 rounded-xl bg-gray-200 p-1">
{tabData.map((data) => (
<Tab
key={data.id}
className={({ selected }) => classNames(
'w-full rounded-lg py-1 text-sm font-medium leading-5',
'ring-white/60 ring-offset-2 ring-offset-gray-400 focus:outline-none focus:ring-2',
selected
? 'bg-primary/80 text-white shadow'
: 'text-[#4b5563] hover:bg-[#4b5563]/40 hover:text-white',
)}
>
{data.title}
</Tab>
))}
</Tab.List>
</Tab.Group>
</div>
);
}

export default TabSelector;

TabSelector.propTypes = {
currentTab: PropTypes.object,
setCurrentTab: PropTypes.func,
tabData: PropTypes.shape({
id: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
title: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
}),
};
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,17 @@ import {
useContent,
} from 'translation-helps-rcl';
import localForage from 'localforage';
import LoadingScreen from '@/components/Loading/LoadingScreen';
import ReferenceCard from './ReferenceCard';
import * as logger from '../../../logger';
import packageInfo from '../../../../../package.json';
import TabSelector from './TabSelector';

const tnTabHeads = [
{ id: 1, title: 'Book Overview' },
{ id: 2, title: 'Chapter Overview' },
{ id: 3, title: 'Verse Note' },
];

export default function TranslationHelpsCard({
title,
Expand All @@ -30,10 +38,14 @@ export default function TranslationHelpsCard({
const [offlineMarkdown, setOfflineMarkdown] = useState('');
const [resetTrigger, setResetTrigger] = useState(false);

const [currentTnTab, setCurrentTnTab] = useState(2);

const [currentChapterVerse, setCurrentChapterVerse] = useState({ verse, chapter });

// eslint-disable-next-line prefer-const
let { items, markdown, isLoading } = useContent({
verse,
chapter,
verse: currentChapterVerse.verse,
chapter: currentChapterVerse.chapter,
projectId,
branch,
languageId,
Expand All @@ -44,6 +56,16 @@ export default function TranslationHelpsCard({
readyToFetch: true,
});

useEffect(() => {
if (currentTnTab === 1) {
setCurrentChapterVerse({ chapter, verse: 'intro' });
} else if (currentTnTab === 0) {
setCurrentChapterVerse({ verse: 'intro', chapter: 'front' });
} else {
setCurrentChapterVerse({ verse, chapter });
}
}, [currentTnTab, verse, chapter]);

useEffect(() => {
if (offlineResource && offlineResource.offline) {
// read tn tsv contents and pass to items
Expand Down Expand Up @@ -102,7 +124,7 @@ export default function TranslationHelpsCard({
return {
Book, Chapter, Verse, ID, [noteName]: file.split('\t')[indexOfNote],
};
}).filter((data) => data.Chapter === chapter && data.Verse === verse);
}).filter((data) => data.Chapter === currentChapterVerse.chapter && data.Verse === currentChapterVerse.verse);
setOfflineItemsDisable(false);
setOfflineItems(json);
}
Expand Down Expand Up @@ -177,7 +199,7 @@ export default function TranslationHelpsCard({
setOfflineItemsDisable(true);
setOfflineMarkdown(filecontent);
} else {
setOfflineMarkdown('');
setOfflineMarkdown({ error: true, data: 'No Content Avaialble' });
}
}
});
Expand All @@ -191,6 +213,8 @@ export default function TranslationHelpsCard({
const filecontent = fs.readFileSync(path.join(folder, projectName, projectId, filePath), 'utf8');
setOfflineItemsDisable(true);
setOfflineMarkdown(filecontent);
} else {
setOfflineMarkdown({ error: true, data: 'No Content Available' });
}
break;

Expand All @@ -201,6 +225,8 @@ export default function TranslationHelpsCard({
const filecontent = fs.readFileSync(path.join(folder, projectName, 'bible', filePath), 'utf8');
setOfflineItemsDisable(true);
setOfflineMarkdown(filecontent);
} else {
setOfflineMarkdown({ error: true, data: 'No Content Available' });
}
break;

Expand All @@ -220,21 +246,38 @@ export default function TranslationHelpsCard({
items = !offlineItemsDisable && offlineResource?.offline ? offlineItems : items;
markdown = offlineResource?.offline ? offlineMarkdown : markdown;

if (resourceId === 'tn' && items) {
if (items[0]?.Note) {
items[0].Note = (items[0].Note).replace(/(<br>|\\n)/gm, '\n');
}
if (items[0]?.OccurrenceNote) {
items[0].OccurrenceNote = (items[0].OccurrenceNote).replace(/(<br>|\\n)/gm, '\n');
}
}

return (
<ReferenceCard
items={items}
filters={['OccurrenceNote']}
markdown={markdown}
isLoading={isLoading}
languageId={languageId}
title={title}
viewMode={viewMode}
selectedQuote={selectedQuote}
setQuote={setQuote}
font={font}
setResetTrigger={setResetTrigger}
resetTrigger={resetTrigger}
/>
<>
{resourceId === 'tn' && (<TabSelector currentTab={currentTnTab} setCurrentTab={setCurrentTnTab} tabData={tnTabHeads} />)}
{(markdown || items) ? (
<ReferenceCard
resourceId={resourceId}
items={items}
filters={['OccurrenceNote']}
markdown={markdown}
isLoading={isLoading}
languageId={languageId}
title={title}
viewMode={viewMode}
selectedQuote={selectedQuote}
setQuote={setQuote}
font={font}
setResetTrigger={setResetTrigger}
resetTrigger={resetTrigger}
/>
)
: <LoadingScreen />}
</>

);
}

Expand Down
Loading

0 comments on commit 15ba171

Please sign in to comment.