feat:保存文件使用ipcRenderer

This commit is contained in:
shixiaohua 2024-02-21 18:04:03 +08:00
parent 4a163039a8
commit 245c4df326
2 changed files with 72 additions and 62 deletions

View File

@ -28,7 +28,7 @@ function App() {
const element = useRoutes(routes) const element = useRoutes(routes)
useIpcRenderer({'redirectUrl':redirectUrl}) useIpcRenderer({'redirectUrl':redirectUrl})
useIpcRenderer({'openDirectory':addNewDir}) useIpcRenderer({'openDirectory':addNewDir})
useIpcRenderer({'pushHotkeys':pushHotkeysAction}) // useIpcRenderer({'pushHotkeys':pushHotkeysAction})
return ( return (
<> <>
{/* 注册路由 */} {/* 注册路由 */}

View File

@ -10,27 +10,30 @@ import ToolbarPlugin from "./plugins/ToolbarPlugin";
import {HeadingNode, QuoteNode} from "@lexical/rich-text"; import {HeadingNode, QuoteNode} from "@lexical/rich-text";
import {TableCellNode, TableNode, TableRowNode} from "@lexical/table"; import {TableCellNode, TableNode, TableRowNode} from "@lexical/table";
import {ListItemNode, ListNode} from "@lexical/list"; import {ListItemNode, ListNode} from "@lexical/list";
import {CodeHighlightNode, CodeNode,$createCodeNode, $isCodeNode} from "@lexical/code"; import {CodeHighlightNode, CodeNode, $createCodeNode, $isCodeNode} from "@lexical/code";
import {AutoLinkNode, LinkNode} from "@lexical/link"; import {AutoLinkNode, LinkNode} from "@lexical/link";
import {MarkdownShortcutPlugin} from "@lexical/react/LexicalMarkdownShortcutPlugin"; import {MarkdownShortcutPlugin} from "@lexical/react/LexicalMarkdownShortcutPlugin";
import {TRANSFORMERS, $convertFromMarkdownString, import {
$convertToMarkdownString,} from "@lexical/markdown"; TRANSFORMERS, $convertFromMarkdownString,
$convertToMarkdownString,
} from "@lexical/markdown";
import "./index.less" import "./index.less"
import {useEffect, useId, useState} from 'react'; import {useEffect, useId, useState} from 'react';
import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext'; import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
import {importFile, overWriteFile, saveFileWithName} from "../../../utils/File" import {importFile, overWriteFile, saveFileWithName} from "../../../utils/File"
import {$getRoot, CLEAR_HISTORY_COMMAND, $createTextNode,} from "lexical"; import {$getRoot, CLEAR_HISTORY_COMMAND, $createTextNode,} from "lexical";
import {store} from "../../../redux/store";
import {SAVE} from "../../../utils/HotkeyConst";
import md5 from "md5" import md5 from "md5"
import {isEmpty} from "../../../utils/ObjectUtils"; import {isEmpty} from "../../../utils/ObjectUtils";
import {useDispatch} from "react-redux"; import {useDispatch, useSelector} from "react-redux";
import {updatedSavedFile} from "../../../redux/tableBarItem_reducer"; import {updatedSavedFile} from "../../../redux/tableBarItem_reducer";
import {ListPlugin} from "@lexical/react/LexicalListPlugin"; import {ListPlugin} from "@lexical/react/LexicalListPlugin";
import {LinkPlugin} from "@lexical/react/LexicalLinkPlugin"; import {LinkPlugin} from "@lexical/react/LexicalLinkPlugin";
import AutoLinkPlugin from "./plugins/AutoLinkPlugin"; import AutoLinkPlugin from "./plugins/AutoLinkPlugin";
import ListMaxIndentLevelPlugin from "./plugins/ListMaxIndentLevelPlugin"; import ListMaxIndentLevelPlugin from "./plugins/ListMaxIndentLevelPlugin";
import CodeHighlightPlugin from "./plugins/CodeHighlightPlugin"; import CodeHighlightPlugin from "./plugins/CodeHighlightPlugin";
const {ipcRenderer} = window.require('electron')
function Placeholder() { function Placeholder() {
return <div className="editor-placeholder">Enter some rich text...</div>; return <div className="editor-placeholder">Enter some rich text...</div>;
} }
@ -71,12 +74,12 @@ function OnChangePlugin({onChange}) {
function ImportFilePlugin(props) { function ImportFilePlugin(props) {
const [editor] = useLexicalComposerContext(); const [editor] = useLexicalComposerContext();
useEffect(() => { useEffect(() => {
if (props.filePath){ if (props.filePath) {
importFile(props.filePath).then(value => { importFile(props.filePath).then(value => {
if (isEmpty(value)){ if (isEmpty(value)) {
return return
} }
if (props.filePath.endsWith(".md")){ if (props.filePath.endsWith(".md")) {
const root = $getRoot(); const root = $getRoot();
const firstChild = root.getFirstChild(); const firstChild = root.getFirstChild();
if ($isCodeNode(firstChild) && firstChild.getLanguage() === 'markdown') { if ($isCodeNode(firstChild) && firstChild.getLanguage() === 'markdown') {
@ -93,7 +96,7 @@ function ImportFilePlugin(props) {
); );
} }
root.selectEnd(); root.selectEnd();
}else { } else {
const editorState = editor.parseEditorState( const editorState = editor.parseEditorState(
JSON.stringify(JSON.parse(value.toString()).editorState) JSON.stringify(JSON.parse(value.toString()).editorState)
); );
@ -113,10 +116,10 @@ function ImportFilePlugin(props) {
// editor.setEditorState(editorState); // editor.setEditorState(editorState);
export default function Hlexical(props) { export default function Hlexical(props) {
console.log("this.props.filePath:", props.filePath) console.log("Hlexical(props):this.props.filePath:", props.filePath)
const [editorState, setEditorState] = useState(""); const [editorState, setEditorState] = useState();
const [lastId ,setLastId]= useState("");
const dispatch = useDispatch(); const dispatch = useDispatch();
function onChange(editorState) { function onChange(editorState) {
// Call toJSON on the EditorState object, which produces a serialization safe string // Call toJSON on the EditorState object, which produces a serialization safe string
const editorStateJSON = editorState.toJSON(); const editorStateJSON = editorState.toJSON();
@ -125,51 +128,59 @@ export default function Hlexical(props) {
setEditorState(JSON.stringify(editorStateJSON)); setEditorState(JSON.stringify(editorStateJSON));
} }
function SaveFilePlugin(props) { let pushHotKey = useSelector(state => state.pushHotkeys.data);
useEffect(()=>{ let activeKey = useSelector(state => state.tableBarItem.activeKey);
let unsubscribe = store.subscribe(() => { const saveFile = (event, args) => {
let filePath =props.filePath; console.log("event,args:", event, args)
console.log("触发保存filePath:",filePath) console.log("触发保存pushHotKey:", pushHotKey)
if (isEmpty(props.editorState)) { if (pushHotKey !== "CTRL+S") {
return return
} }
// let filePath = props.filePath;
if (!filePath){ if (filePath !== activeKey) {
let saveDialogReturnValuePromise = saveFileWithName(); console.log("文件不同", filePath, activeKey)
console.log("saveDialogReturnValuePromise",saveDialogReturnValuePromise) return;
saveDialogReturnValuePromise.then(result=>{ }
if (!result.canceled){ console.log("触发保存filePath:", filePath)
const editorStateSave = {"editorState": JSON.parse(props.editorState)}; if (isEmpty(editorState)) {
let resultSave = JSON.stringify(editorStateSave); return
overWriteFile(result.filePath, resultSave) }
// const editorStateSave = {"editorState": JSON.parse(editorState)};
dispatch(updatedSavedFile({filePath:result.filePath})) let resultSave = JSON.stringify(editorStateSave);
}
})
return
}
const editorStateSave = {"editorState": JSON.parse(props.editorState)}; //
let resultSave = JSON.stringify(editorStateSave); if (!filePath) {
console.log("lastId", lastId) let saveDialogReturnValuePromise = saveFileWithName();
if ((lastId === "" || lastId !== store.getState().pushHotkeys.id) && store.getState().pushHotkeys.data === SAVE) { console.log("saveDialogReturnValuePromise", saveDialogReturnValuePromise)
setLastId(store.getState().pushHotkeys.id); saveDialogReturnValuePromise.then(result => {
importFile(filePath).then(value => { if (!result.canceled) {
let save = (isEmpty(value))||md5(resultSave) !== md5(JSON.stringify(JSON.parse(value.toString())));
if (save) {
console.log("保存重写")
overWriteFile(filePath, resultSave)
}
}).catch(error =>
console.error(error)
)
}
});
console.log("return unsubscribe();")
return ()=>unsubscribe();
},[])
overWriteFile(result.filePath, resultSave)
//
dispatch(updatedSavedFile({filePath: result.filePath}))
}
})
return
}
importFile(filePath).then(value => {
let save = (isEmpty(value)) || md5(resultSave) !== md5(JSON.stringify(JSON.parse(value.toString())));
if (save) {
console.log("保存重写" + filePath)
overWriteFile(filePath, resultSave)
}
}).catch(error =>
console.error(error)
)
} }
useEffect(() => {
ipcRenderer.on("pushHotkeys", saveFile);
return () => {
console.log("销毁取消监听");
ipcRenderer.removeListener("pushHotkeys", saveFile)
};
}
)
return ( return (
<LexicalComposer initialConfig={editorConfig}> <LexicalComposer initialConfig={editorConfig}>
@ -187,16 +198,15 @@ export default function Hlexical(props) {
{/*<TreeViewPlugin/>*/} {/*<TreeViewPlugin/>*/}
<AutoFocusPlugin/> <AutoFocusPlugin/>
<CodeHighlightPlugin /> <CodeHighlightPlugin/>
<ListPlugin /> <ListPlugin/>
<LinkPlugin /> <LinkPlugin/>
<AutoLinkPlugin/> <AutoLinkPlugin/>
<ListMaxIndentLevelPlugin maxDepth={7} /> <ListMaxIndentLevelPlugin maxDepth={7}/>
{/*markdown 快捷键*/} {/*markdown 快捷键*/}
<MarkdownShortcutPlugin transformers={TRANSFORMERS}/> <MarkdownShortcutPlugin transformers={TRANSFORMERS}/>
<OnChangePlugin onChange={onChange}/> <OnChangePlugin onChange={onChange}/>
<ImportFilePlugin filePath={props.filePath}/> <ImportFilePlugin filePath={props.filePath}/>
<SaveFilePlugin filePath={props.filePath} editorState={editorState}/>
{/*文件操作导入文件*/} {/*文件操作导入文件*/}
{/*<ActionPlugin/>*/} {/*<ActionPlugin/>*/}
</div> </div>