From 1ea82996c85f7644dc4433bddf442ec5347f25f5 Mon Sep 17 00:00:00 2001 From: sijumoncy <72241997+sijumoncy@users.noreply.github.com> Date: Thu, 2 May 2024 14:38:33 +0530 Subject: [PATCH] lint fix --- .../TranslationMergeUI copy.jsx | 468 ------------------ renderer/src/hooks/useGrammartoPerf.js | 3 +- renderer/src/layouts/projects/Layout.js | 2 +- 3 files changed, 3 insertions(+), 470 deletions(-) delete mode 100644 renderer/src/components/TextTranslationMerge/TranslationMergeUI copy.jsx diff --git a/renderer/src/components/TextTranslationMerge/TranslationMergeUI copy.jsx b/renderer/src/components/TextTranslationMerge/TranslationMergeUI copy.jsx deleted file mode 100644 index fcd664a8..00000000 --- a/renderer/src/components/TextTranslationMerge/TranslationMergeUI copy.jsx +++ /dev/null @@ -1,468 +0,0 @@ -/* eslint-disable no-nested-ternary */ -import React, { - useRef, Fragment, useState, useEffect, useContext, useMemo, -} from 'react'; -import { Dialog, Transition } from '@headlessui/react'; -import { AutographaContext } from '@/components/context/AutographaContext'; -import { useTranslation } from 'react-i18next'; -import { XMarkIcon } from '@heroicons/react/24/outline'; -import ConfirmationModal from '@/layouts/editor/ConfirmationModal'; -import { readUsfmFile } from '@/core/projects/userSettings'; -import DiffMatchPatch from 'diff-match-patch'; -import localforage from 'localforage'; -import TranslationMergNavBar from './TranslationMergNavBar'; -import * as logger from '../../logger'; -import useGetCurrentProjectMeta from '../Sync/hooks/useGetCurrentProjectMeta'; -import LoadingScreen from '../Loading/LoadingScreen'; -import ImportUsfmUI from './ImportUsfmUI'; -import UsfmConflictEditor from './UsfmConflictEditor'; -import { processAndIdentiyVerseChangeinUSFMJsons } from './processUsfmObjs'; -import packageInfo from '../../../../package.json'; - -const grammar = require('usfm-grammar'); - -function TranslationMergeUI({ conflictData, setConflictPopup }) { - console.log({ conflictData }); - const [importedUsfmFolderPath, setImportedUsfmFolderPath] = useState([]); - const [usfmJsons, setUsfmJsons] = useState({ - imported: null, - current: null, - }); - const [selectedChapter, setSelectedChapter] = useState(1); - const [selectedBookId, setSelectedBookId] = useState(null); - const [conflictedChapters, setConflictedChapters] = useState([]); - const [resolvedChapters, setResolvedChapters] = useState([]); - const [chapterResolveDone, setChapterResolveDone] = useState(false); - - const [savedConflictsBooks, setSavedConflictsBooks] = useState([]); - const [existImportedBook, setExistImportedBook] = useState({ status: false, bookId: null }); - - const [loading, setLoading] = useState(false); - const [error, setError] = useState(''); - const [finishedConflict, setFinishedConflict] = useState(false); - - const { t } = useTranslation(); - const cancelButtonRef = useRef(null); - const [model, setModel] = React.useState({ - openModel: false, - title: '', - confirmMessage: '', - buttonName: '', - }); - - const { - state: { currentProjectMeta }, - actions: { getProjectMeta }, - } = useGetCurrentProjectMeta(); - - console.log({ - currentProjectMeta, selectedBookId, usfmJsons, - }); - - const modalClose = () => { - setModel({ - openModel: false, - title: '', - confirmMessage: '', - buttonName: '', - }); - }; - - const handleStartOver = () => { - console.log('start over called ----'); - setExistImportedBook({ status: false, bookId: null }); - modalClose(); - }; - - const handleOnAbortMerge = (buttonName) => { - console.log({ buttonName }, model); - if (model.buttonName === t('label-abort')) { - setError(''); - setUsfmJsons({}); - setImportedUsfmFolderPath([]); - setOpenTextTranslationMerge({ open: false, meta: null }); - modalClose(); - } else { - handleStartOver(); - } - }; - - const removeSection = async (abort = false) => { - if (abort === false) { - // pass - } else { - // popup with warning - setModel({ - openModel: true, - title: t('modal-title-abort-conflict-resolution'), - confirmMessage: t('msg-abort-conflict-resolution'), - buttonName: t('label-abort'), - }); - } - }; - - const readMergeDirOrSingleFile = async (readDir = true, fileName = null) => { - const fs = window.require('fs'); - const { id, name } = openTextTranslationMerge.meta; - const _projectName = `${name}_${id[0]}`; - const newpath = localStorage.getItem('userPath'); - const path = require('path'); - - const user = await localforage.getItem('userProfile'); - if (user?.username) { - const USFMMergeDirPath = path.join(newpath, packageInfo.name, 'users', user?.username, '.merge-usfm'); - if (!fs.existsSync(path.join(USFMMergeDirPath, _projectName))) { - return null; - } - if (readDir) { - const files = fs.readdirSync(path.join(USFMMergeDirPath, _projectName)); - console.log({ files }); - return files; - } - // read file - json - let jsonFile = fs.readFileSync(path.join(USFMMergeDirPath, _projectName, fileName)); - jsonFile = JSON.parse(jsonFile); - return jsonFile; - } - console.error('no user : ', { user }); - }; - - useEffect(() => { - if (openTextTranslationMerge?.meta) { - const { id, name } = openTextTranslationMerge.meta; - (async () => { - await getProjectMeta(`${name}_${id[0]}`); - // check for existing merge and display ui based on that - const mergeDirContents = await readMergeDirOrSingleFile(); - setSavedConflictsBooks(mergeDirContents); - })(); - } - }, []); - - const openFileDialogSettingData = async () => { - logger.debug('translationMergeUI.js', 'Inside openFileDialogSettingData'); - const options = { - properties: ['openFile'], - filters: [{ name: 'usfm files', extensions: ['usfm', 'sfm', 'USFM', 'SFM'] }], - }; - const { dialog } = window.require('@electron/remote'); - const chosenFolder = await dialog.showOpenDialog(options); - if ((chosenFolder.filePaths).length > 0) { - logger.debug('translationMergeUI.js', 'Selected the files'); - setImportedUsfmFolderPath(chosenFolder.filePaths); - } else { - logger.debug('translationMergeUI.js', 'Didn\'t select any file'); - } - }; - - const handleImportUsfm = () => { - openFileDialogSettingData(); - }; - - const resumeConflictResolution = async (bookId) => { - // bookid (same as backendfilename) - > mat.json - console.log('book id : ', bookId); - const { usfmJsons } = await readMergeDirOrSingleFile(false, bookId); - setUsfmJsons(usfmJsons); - setExistImportedBook({ status: false, bookId: null }); - - const _conflictedBooks = []; - setSelectedBookId(usfmJsons.mergeJson.book.bookCode.toLowerCase()); - usfmJsons.mergeJson.chapters.forEach((chapter, index) => { - chapter.contents.forEach((content) => { - if (content.verseNumber) { - if (content?.resolved && !content?.resolved?.status) { - !_conflictedBooks.includes(chapter.chapterNumber) && _conflictedBooks.push(chapter.chapterNumber); - } - } - }); - }); - - setConflictedChapters(_conflictedBooks); - setFinishedConflict(false); - console.log({ usfmJsons }); - }; - - async function parseUsfm(usfm) { - const myUsfmParser = new grammar.USFMParser(usfm, grammar.LEVEL.RELAXED); - const isJsonValid = myUsfmParser.validate(); - return { valid: isJsonValid, data: myUsfmParser.toJSON() }; - } - - async function parseJsonToUsfm(json) { - const myUsfmParser = new grammar.JSONParser(json); - const usfm = myUsfmParser.toUSFM(); - return usfm; - } - - const parseFiles = async () => { - // parse imported - const fs = window.require('fs'); - const IncomingUsfm = fs.readFileSync(importedUsfmFolderPath[0], 'utf8'); - if (IncomingUsfm) { - const importedJson = await parseUsfm(IncomingUsfm); - // const normalisedIncomingUSFM = await parseJsonToUsfm(importedJson.data); - if (!importedJson.valid) { - setError('Imported Usfm is invalid'); - } else if (!Object.keys(currentProjectMeta?.type?.flavorType?.currentScope).includes(importedJson?.data?.book?.bookCode) - && !Object.keys(currentProjectMeta?.type?.flavorType?.currentScope).includes(importedJson?.data?.book?.bookCode?.toLowerCase())) { - setError('Imported USFM is not in the scope of Current Project'); - } else { - // Parse current project same book - const importedBookCode = `${importedJson.data.book.bookCode.toLowerCase()}.usfm`; - - setError(''); - setUsfmJsons((prev) => ({ ...prev, imported: importedJson.data })); - setSelectedBookId(importedJson.data.book.bookCode.toLowerCase()); - const currentBookPath = Object.keys(currentProjectMeta?.ingredients).find((code) => code.toLowerCase().endsWith(importedBookCode)); - const { id, name } = openTextTranslationMerge.meta; - const currentBookUsfm = await readUsfmFile(currentBookPath, `${name}_${id[0]}`); - // console.log('FOUND ====> ', { currentBookPath, currentBookUsfm }); - if (currentBookUsfm) { - const currentJson = await parseUsfm(currentBookUsfm); - // const currentNormalisedUsfm = await parseJsonToUsfm(currentJson.data); - - // generate the merge object with current , incoming , merge verses - // const mergeJson = JSON.parse(JSON.stringify(currentJson.data)); - const processOutArr = await processAndIdentiyVerseChangeinUSFMJsons(importedJson.data, currentJson.data).catch((err) => { - console.log('process usfm : ', err); - }); - const mergeJson = processOutArr[0]; - console.log('processOutArr[1] : ', processOutArr[1]); - setConflictedChapters(processOutArr[1]); - - if (savedConflictsBooks.includes(`${importedJson.data.book.bookCode.toLowerCase()}.json`)) { - setExistImportedBook({ status: true, bookId: importedJson.data.book.bookCode.toLowerCase() }); - console.log('existing book'); - setModel({ - openModel: true, - title: t('modal-title-abort-conflict-resolution'), - confirmMessage: t('msg-conflict-resolution-duplicate-book', { bookId: importedJson.data.book.bookCode.toUpperCase() }), - buttonName: t('label-startover'), - }); - } - - currentJson && currentJson?.valid && setUsfmJsons((prev) => ({ ...prev, current: currentJson.data, mergeJson })); - - // compare usfms to check conflcit or not - // const diffOut = await dmp.diff_main(normalisedIncomingUSFM, currentNormalisedUsfm); - // setUsfmJsons((prev) => ({ ...prev, diffOut })); - } - } - } else { - setError('unable to read imported USFM'); - } - setLoading(false); - }; - - useEffect(() => { - // get usfm and parse - if (importedUsfmFolderPath.length === 1 && currentProjectMeta) { - setLoading(true); - parseFiles(); - setFinishedConflict(false); - } - }, [importedUsfmFolderPath, currentProjectMeta]); - - useEffect(() => { - if (conflictedChapters.length === resolvedChapters.length) { - setFinishedConflict(true); - } - }, [conflictedChapters.length, resolvedChapters.length]); - - const resolveAndMarkDoneChapter = () => { - setResolvedChapters((prev) => [...prev, selectedChapter]); - // store the jsons to the backend (/.merge/projectName/BookID.json) - const fs = window.require('fs'); - const { id, name } = openTextTranslationMerge.meta; - const _projectName = `${name}_${id[0]}`; - const newpath = localStorage.getItem('userPath'); - const path = require('path'); - localforage.getItem('userProfile').then((user) => { - const USFMMergeDirPath = path.join(newpath, packageInfo.name, 'users', user?.username, '.merge-usfm'); - if (!fs.existsSync(path.join(USFMMergeDirPath, _projectName))) { - fs.mkdirSync(path.join(USFMMergeDirPath, _projectName), { recursive: true }); - } - console.log('write this book :', `${selectedBookId}.json`); - fs.writeFileSync(path.join(USFMMergeDirPath, _projectName, `${selectedBookId}.json`), JSON.stringify({ usfmJsons })); - }); - }; - - const handleFinishedResolution = async () => { - try { - const path = require('path'); - const fs = window.require('fs'); - - const { id, name } = openTextTranslationMerge.meta; - const _projectName = `${name}_${id[0]}`; - const newpath = localStorage.getItem('userPath'); - - const user = await localforage.getItem('userProfile'); - if (user?.username) { - const USFMMergeDirPath = path.join(newpath, packageInfo.name, 'users', user?.username, '.merge-usfm'); - const currentJsonFile = `${existImportedBook.bookId}.json`; - const OrgProjectFilePath = path.join(newpath, packageInfo.name, 'users', user?.username, 'projects', _projectName, 'ingredients', existImportedBook.bookId.toUpperCase()); - - // convert usfmJson.mergeJson to norml parsedJson and convert to usfm - - const resolvedTempJson = JSON.parse(JSON.stringify(usfmJsons.mergeJson)); - - for (let index = 0; index < resolvedTempJson.chapters.length; index++) { - const chObjContents = usfmJsons.mergeJson.chapters[index].contents; - for (let j = 0; j < chObjContents.length; j++) { - let verseObj = chObjContents[j]; - if (verseObj?.resolved) { - const tempResolvedContent = verseObj.resolved.resolvedContent; - verseObj = { ...tempResolvedContent }; - } - } - } - - const usfm = await parseJsonToUsfm(resolvedTempJson); - fs.writeFileSync(OrgProjectFilePath, usfm, 'utf-8'); - - // delete saved json in merge dir - check if it is the last one then delete folder too - if (!fs.existsSync(path.join(USFMMergeDirPath, _projectName))) { - const files = fs.readdirSync(path.join(USFMMergeDirPath, _projectName)); - if (files?.length > 1) { - // delete single file - await fs.unlinkSync(path.join(USFMMergeDirPath, currentJsonFile)); - } else { - // delete dir - await fs.rmdirSync(USFMMergeDirPath, { recursive: true }, (err) => { - if (err) { - throw new Error(`Error delete .usfm-merge dir : ${err}`); - } - }); - } - } - } - } catch (err) { - console.log('error : finishd move file ---> ', err); - } - }; - - return ( - <> - - removeSection(true)} - > - - -
-
-

{t('label-resolve-conflict')}

-
- {/* close btn section */} - -
- - {/* contents section */} -
-
- - -
-
- - {loading ? () : ( - - (usfmJsons.current && usfmJsons.imported && !existImportedBook.status) ? ( -
- -
- ) - : ( - - ) - - )} - -
-
-

{error}

- {usfmJsons.current && usfmJsons.imported && ( - finishedConflict ? ( - - - ) : ( - - - ) - )} -
-
-
-
-
-
-
- - modalClose()} - confirmMessage={model.confirmMessage} - buttonName={model.buttonName} - closeModal={() => handleOnAbortMerge(model.buttonName)} - /> - - ); -} - -export default TranslationMergeUI; diff --git a/renderer/src/hooks/useGrammartoPerf.js b/renderer/src/hooks/useGrammartoPerf.js index 097acde5..aa7c787f 100644 --- a/renderer/src/hooks/useGrammartoPerf.js +++ b/renderer/src/hooks/useGrammartoPerf.js @@ -41,7 +41,8 @@ export const useGrammartoPerf = (perfArr = [], selectedBook = '', setGeneratedPe console.log({ selectedDocument }); - const { bookCode, h: bookName } = selectedDocument || {}; + // const { bookCode, h: bookName } = selectedDocument || {}; + const { bookCode } = selectedDocument || {}; const ready = (docSetId && bookCode) || false; console.log({ bookCode, ready }); diff --git a/renderer/src/layouts/projects/Layout.js b/renderer/src/layouts/projects/Layout.js index b85d064a..580a3695 100644 --- a/renderer/src/layouts/projects/Layout.js +++ b/renderer/src/layouts/projects/Layout.js @@ -9,11 +9,11 @@ import { } from '@heroicons/react/24/outline'; import { useTranslation } from 'react-i18next'; import { ProjectContext } from '@/components/context/ProjectContext'; +import TranslationMergeUI from '@/components/TextTranslationMerge/TranslationMergeUI.jsx'; import SideBar from './SideBar'; import TopMenuBar from './TopMenuBar'; import ImportProjectPopUp from './ImportProjectPopUp'; import ConflictResolverUI from './Import/ConflictResolverUI'; -import TranslationMergeUI from '@/components/TextTranslationMerge/TranslationMergeUI'; export default function ProjectsLayout(props) { const {