Skip to content

Commit

Permalink
feat:快捷键ctrl+s时,自动读取prettier文件格式化代码 (#123)
Browse files Browse the repository at this point in the history
* feat:快捷键格式化代码(未完成)

* feat:prettier格式化(未完成)

* feat:快捷键ctrl+s自动格式化完成

* fix:移除无用的代码和优化ts

* fix:优化ts代码

* fix:解决格式问题
  • Loading branch information
kankan-web authored Sep 25, 2024
1 parent 8845cf3 commit 4af7110
Show file tree
Hide file tree
Showing 6 changed files with 297 additions and 18 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"monaco-editor": "^0.50.0",
"next": "14.2.4",
"nextjs-toploader": "^1.6.12",
"prettier": "3.3.2",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-icons": "^5.2.1",
Expand Down Expand Up @@ -82,6 +83,7 @@
"@testing-library/react": "^16.0.0",
"@testing-library/user-event": "^14.5.2",
"@types/node": "^20.14.9",
"@types/prettier": "^3.0.0",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@types/react-window": "^1.8.8",
Expand All @@ -104,7 +106,6 @@
"jsdom": "^24.1.0",
"lint-staged": "^15.2.7",
"postcss": "^8.4.39",
"prettier": "^3.3.2",
"storybook": "^8.1.11",
"tailwindcss": "^3.4.4",
"typescript": "^4.9.5",
Expand Down
33 changes: 22 additions & 11 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

58 changes: 55 additions & 3 deletions src/components/editor/index.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
'use client';

import { useCallback } from 'react';
import { useCallback, useState } from 'react';
import Editor, { Monaco, loader } from '@monaco-editor/react';
import * as monaco from 'monaco-editor';
import { editor } from 'monaco-editor';
import { useDroppable } from '@dnd-kit/core';
import { createHighlighter } from 'shiki';
import { shikiToMonaco } from '@shikijs/monaco';
import parserBabel from 'prettier/plugins/babel';
import parserEstree from 'prettier/plugins/estree';
// import parserTypescript from 'prettier/plugins/typescript';

import {
useEditorStore,
Expand All @@ -20,6 +23,7 @@ import LoadingComponent from '@/components/edit/edit-loading';
import { useWebContainerStore } from '@/store/webContainerStore';
import { useUploadFileDataStore } from '@/store/uploadFileDataStore';
import { cn, writeFile, MONACO_THEME_ARRAY } from '@/utils';
import { getPrettierConfig } from '@/utils/file';

interface CodeEditorProps {
editorId: number;
Expand All @@ -28,15 +32,17 @@ export type EditorWithThemeService = monaco.editor.IStandaloneCodeEditor & { _th

export default function CodeEditor({ editorId }: CodeEditorProps) {
const { webContainerInstance } = useWebContainerStore();
const { updateItem } = useUploadFileDataStore();
const { updateItem, fileData } = useUploadFileDataStore();
const { getEditor, setEditor } = useEditorStore();
const { setMonaco } = useMonacoStore();
const { setModels, models } = useModelsStore();
const { activeMap, setActiveModel } = useActiveModelStore();
const { activeEditorId, setActiveEditor } = useActiveEditorStore();
const thisEditor = getEditor(editorId);
const currentModel = activeMap[editorId];
// console.log(thisEditor);

const [_editor, _setEditor] = useState<monaco.editor.IStandaloneCodeEditor | undefined>();

// used for dnd
// console.log(activeMap, activeEditorId);
// 当前编辑model的path,用于与webContainer文件系统同步
Expand All @@ -55,6 +61,49 @@ export default function CodeEditor({ editorId }: CodeEditorProps) {
border: isOver ? '1px #3b82f6 solid' : undefined,
};

_editor &&
_editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => {
const prettierValue = getPrettierConfig(fileData);
formatWithPrettier(_editor, prettierValue);
});

// 格式化代码
const formatWithPrettier = async (
item: editor.IStandaloneCodeEditor,
prettierConfig: Record<string, any>,
) => {
if (!item) return;

try {
const model = item.getModel();
if (!model) return;

const unformattedCode = model.getValue();
const prettier = await import('prettier/standalone');

// 使用找到的 Prettier 配置
const formattedCode = await prettier.format(unformattedCode, {
parser: 'babel',
plugins: [parserBabel, parserEstree],
...prettierConfig,
});

// 应用格式化后的代码
model.pushEditOperations(
[],
[
{
range: model.getFullModelRange(),
text: formattedCode,
},
],
() => null,
);
} catch (error) {
console.error('格式化代码时出错:', error);
}
};

const handleEditorDidMount = useCallback(
async (editor: monaco.editor.IStandaloneCodeEditor, monaco: Monaco) => {
monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
Expand Down Expand Up @@ -123,6 +172,8 @@ export default function CodeEditor({ editorId }: CodeEditorProps) {
setActiveEditor(editor, editorId);
});

_setEditor(editor);

loader.init().then(/* ... */);
},
[],
Expand All @@ -145,6 +196,7 @@ export default function CodeEditor({ editorId }: CodeEditorProps) {
<div className=" h-[3.5vh] w-full bg-[#202327]/80">
<TabBar editorId={editorId} />
</div>

<Editor
className={'editor'}
theme="dark-plus"
Expand Down
4 changes: 2 additions & 2 deletions src/components/extension/tree-view-api/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -258,8 +258,8 @@ const Folder = forwardRef<HTMLDivElement, FolderProps & React.HTMLAttributes<HTM
>
<div className=" flex items-center justify-start gap-x-1">
{expendedItems?.includes(value)
? (openIcon ?? <FolderOpenIcon className="h-3 w-3" />)
: (closeIcon ?? <FolderIcon className="h-3 w-3" />)}
? openIcon ?? <FolderOpenIcon className="h-3 w-3" />
: closeIcon ?? <FolderIcon className="h-3 w-3" />}
<span>{element}</span>
</div>
<div className=" flex gap-x-1 items-center mr-1">
Expand Down
2 changes: 1 addition & 1 deletion src/store/uploadFileDataStore.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { create } from 'zustand';
import { v4 as uuidv4 } from 'uuid';
import localforage from 'localforage';

interface DirectoryInterface {
export interface DirectoryInterface {
id: string;
filename: string;
path: string;
Expand Down
Loading

0 comments on commit 4af7110

Please sign in to comment.