Optimize code. Update templates.

This commit is contained in:
2024-01-14 11:14:14 +08:00
parent b0be3bc4a7
commit bcf29f74ef
27 changed files with 125 additions and 247 deletions

View File

@@ -50,6 +50,8 @@ export const useEditor = () => {
onWatch(typeHelper)
typeHelper.acquireType(`import React from 'react'`)
editor.onDidChangeModelContent(() => {
typeHelper.acquireType(editor.getValue())
})

View File

@@ -2,13 +2,13 @@ import { editor, Selection } from 'monaco-editor'
import MonacoEditor, { Monaco } from '@monaco-editor/react'
import '@/components/Playground/CodeEditor/Editor/editor.scss'
import '@/components/Playground/CodeEditor/Editor/loader'
import { IEditorOptions, IFiles, ITheme, ITsConfig } from '@/components/Playground/shared'
import { IEditorOptions, IFiles, ITheme, ITsconfig } from '@/components/Playground/shared'
import { fileNameToLanguage, tsconfigJsonDiagnosticsOptions } from '@/components/Playground/files'
import { useEditor, useTypesProgress } from '@/components/Playground/CodeEditor/Editor/hooks'
import { MonacoEditorConfig } from '@/components/Playground/CodeEditor/Editor/monacoConfig'
interface EditorProps {
tsConfig?: ITsConfig
tsconfig?: ITsconfig
files?: IFiles
selectedFileName?: string
readonly?: boolean
@@ -19,7 +19,7 @@ interface EditorProps {
}
const Editor = ({
tsConfig,
tsconfig,
files = {},
selectedFileName = '',
readonly,
@@ -43,9 +43,9 @@ const Editor = ({
const handleOnEditorWillMount = (monaco: Monaco) => {
monaco.languages.json.jsonDefaults.setDiagnosticsOptions(tsconfigJsonDiagnosticsOptions)
tsConfig &&
tsconfig &&
monaco.languages.typescript.typescriptDefaults.setCompilerOptions(
tsConfig.compilerOptions
tsconfig.compilerOptions
)
files &&
@@ -93,11 +93,11 @@ const Editor = ({
}, [file.name])
useEffect(() => {
tsConfig &&
tsconfig &&
monacoRef.current?.languages.typescript.typescriptDefaults.setCompilerOptions(
tsConfig.compilerOptions
tsconfig.compilerOptions
)
}, [tsConfig])
}, [tsconfig])
return (
<>

View File

@@ -88,7 +88,7 @@ const FileSelector = ({
onChange?.(IMPORT_MAP_FILE_NAME)
}
const editTsConfig = () => {
const editTsconfig = () => {
if (hasEditing) {
return
}
@@ -200,7 +200,7 @@ const FileSelector = ({
<Item
value={'tsconfig.json'}
active={selectedFileName === TS_CONFIG_FILE_NAME}
onClick={editTsConfig}
onClick={editTsconfig}
readonly
/>
)}

View File

@@ -1,7 +1,7 @@
import _ from 'lodash'
import '@/components/Playground/CodeEditor/code-editor.scss'
import FlexBox from '@/components/common/FlexBox'
import { IEditorOptions, IFiles, ITheme, ITsConfig } from '@/components/Playground/shared'
import { IEditorOptions, IFiles, ITheme, ITsconfig } from '@/components/Playground/shared'
import {
fileNameToLanguage,
getFileNameList,
@@ -13,7 +13,7 @@ import Editor from '@/components/Playground/CodeEditor/Editor'
interface CodeEditorProps {
theme?: ITheme
tsConfig?: ITsConfig
tsconfig?: ITsconfig
files: IFiles
readonly?: boolean
readonlyFiles?: string[]
@@ -30,7 +30,7 @@ interface CodeEditorProps {
const CodeEditor = ({
theme,
tsConfig,
tsconfig,
files,
readonly,
readonlyFiles,
@@ -133,7 +133,7 @@ const CodeEditor = ({
onError={handleOnError}
/>
<Editor
tsConfig={tsConfig}
tsconfig={tsconfig}
theme={theme}
selectedFileName={
onSelectedFileChange ? propsSelectedFileName : selectedFileName

View File

@@ -1,16 +1,13 @@
import { strFromU8, strToU8, unzlibSync, zlibSync } from 'fflate'
import { IFile, IFiles, IImportMap, ILanguage, ITsConfig } from '@/components/Playground/shared'
import AppCss from '@/components/Playground/template/src/App.css?raw'
import App from '@/components/Playground/template/src/App.tsx?raw'
import main from '@/components/Playground/template/src/main.tsx?raw'
import tsconfigSchema from '@/components/Playground/tsconfig-schema.json'
import importMapSchema from '@/components/Playground/import-map-schema.json'
import { languages } from 'monaco-editor'
import DiagnosticsOptions = languages.json.DiagnosticsOptions
import ScriptTarget = languages.typescript.ScriptTarget
import ModuleKind = languages.typescript.ModuleKind
import ModuleResolutionKind = languages.typescript.ModuleResolutionKind
import JsxEmit = languages.typescript.JsxEmit
import { IFile, IFiles, IImportMap, ILanguage, ITsconfig } from '@/components/Playground/shared'
import initTsconfigFile from '@/components/Playground/templates/init/tsconfig.json'
import initImportMapFile from '@/components/Playground/templates/init/import-map.json'
import main from '@/components/Playground/templates/init/main.tsx?raw'
import App from '@/components/Playground/templates/init/App.tsx?raw'
import tsconfigSchema from '@/components/Playground/tsconfig-schema.json'
import importMapSchema from '@/components/Playground/import-map-schema.json'
export const TS_CONFIG_FILE_NAME = 'tsconfig.json'
export const MAIN_FILE_NAME = 'App.tsx'
@@ -138,39 +135,9 @@ export const initFiles: IFiles = getFilesFromUrl() || {
name: MAIN_FILE_NAME,
language: fileNameToLanguage(MAIN_FILE_NAME),
value: App
},
'App.css': {
name: 'App.css',
language: 'css',
value: AppCss
}
}
export const initImportMap: IImportMap = {
imports: {
react: 'https://esm.sh/react@18.2.0',
'react-dom/client': 'https://esm.sh/react-dom@18.2.0'
}
}
export const initImportMap: IImportMap = initImportMapFile
export const initTsConfig: ITsConfig = {
compilerOptions: {
target: ScriptTarget.ES2020,
useDefineForClassFields: true,
module: ModuleKind.ESNext,
skipLibCheck: true,
moduleResolution: ModuleResolutionKind.NodeJs,
allowImportingTsExtensions: true,
resolveJsonModule: true,
isolatedModules: true,
noEmit: true,
jsx: JsxEmit.ReactJSX,
strict: true,
noUnusedLocals: true,
noUnusedParameters: true,
noFallthroughCasesInSwitch: true,
composite: true,
types: ['node'],
allowSyntheticDefaultImports: true
}
}
export const initTsconfig: ITsconfig = initTsconfigFile

View File

@@ -1,6 +1,6 @@
import '@/components/Playground/playground.scss'
import { useUpdatedEffect } from '@/util/hooks'
import { IFiles, IImportMap, ITsConfig } from '@/components/Playground/shared'
import { IFiles, IImportMap, ITsconfig } from '@/components/Playground/shared'
import {
IMPORT_MAP_FILE_NAME,
MAIN_FILE_NAME,
@@ -13,16 +13,16 @@ import Output from '@/components/Playground/Output'
interface PlaygroundProps {
initFiles: IFiles
initImportMapRaw: string
initTsConfigRaw: string
initTsconfigRaw: string
}
const Playground = ({ initFiles, initImportMapRaw, initTsConfigRaw }: PlaygroundProps) => {
const Playground = ({ initFiles, initImportMapRaw, initTsconfigRaw }: PlaygroundProps) => {
const [files, setFiles] = useState(initFiles)
const [selectedFileName, setSelectedFileName] = useState(MAIN_FILE_NAME)
const [importMapRaw, setImportMapRaw] = useState<string>(initImportMapRaw)
const [importMap, setImportMap] = useState<IImportMap>()
const [tsConfigRaw, setTsConfigRaw] = useState<string>(initTsConfigRaw)
const [tsConfig, setTsConfig] = useState<ITsConfig>()
const [tsconfigRaw, setTsconfigRaw] = useState<string>(initTsconfigRaw)
const [tsconfig, setTsconfig] = useState<ITsconfig>()
if (!importMap) {
try {
@@ -31,11 +31,11 @@ const Playground = ({ initFiles, initImportMapRaw, initTsConfigRaw }: Playground
setImportMap({ imports: {} })
}
}
if (!tsConfig) {
if (!tsconfig) {
try {
setTsConfig(JSON.parse(tsConfigRaw) as ITsConfig)
setTsconfig(JSON.parse(tsconfigRaw) as ITsconfig)
} catch (e) {
setTsConfig({ compilerOptions: {} })
setTsconfig({ compilerOptions: {} })
}
}
@@ -45,7 +45,7 @@ const Playground = ({ initFiles, initImportMapRaw, initTsConfigRaw }: Playground
return
}
if (fileName === TS_CONFIG_FILE_NAME) {
setTsConfigRaw(content)
setTsconfigRaw(content)
return
}
@@ -64,16 +64,16 @@ const Playground = ({ initFiles, initImportMapRaw, initTsConfigRaw }: Playground
useUpdatedEffect(() => {
try {
setTsConfig(JSON.parse(tsConfigRaw) as ITsConfig)
setTsconfig(JSON.parse(tsconfigRaw) as ITsconfig)
} catch (e) {
/* empty */
}
}, [tsConfigRaw])
}, [tsconfigRaw])
return (
<FlexBox data-component={'playground'} direction={'horizontal'}>
<CodeEditor
tsConfig={tsConfig}
tsconfig={tsconfig}
files={{
...files,
'import-map.json': {
@@ -84,7 +84,7 @@ const Playground = ({ initFiles, initImportMapRaw, initTsConfigRaw }: Playground
'tsconfig.json': {
name: TS_CONFIG_FILE_NAME,
language: 'json',
value: tsConfigRaw
value: tsconfigRaw
}
}}
selectedFileName={selectedFileName}

View File

@@ -18,7 +18,7 @@ export interface IImportMap {
imports: Record<string, string>
}
export interface ITsConfig {
export interface ITsconfig {
compilerOptions: CompilerOptions
}

View File

@@ -1,18 +0,0 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: '@typescript-eslint/parser',
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}

View File

@@ -1,24 +0,0 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@@ -1,28 +0,0 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type aware lint rules:
- Configure the top-level `parserOptions` property like this:
```js
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
project: ['./tsconfig.json', './tsconfig.node.json'],
tsconfigRootDir: __dirname,
},
```
- Replace `plugin:@typescript-eslint/recommended` to `plugin:@typescript-eslint/recommended-type-checked` or `plugin:@typescript-eslint/strict-type-checked`
- Optionally add `plugin:@typescript-eslint/stylistic-type-checked`
- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and add `plugin:react/recommended` & `plugin:react/jsx-runtime` to the `extends` list
gitignore

View File

@@ -1,13 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

@@ -1,28 +0,0 @@
{
"name": "react-playground",
"author": "fewismuch",
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/react": "^18.2.15",
"@types/react-dom": "^18.2.7",
"@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0",
"@vitejs/plugin-react-swc": "^3.3.2",
"eslint": "^8.45.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.3",
"typescript": "^5.0.2",
"vite": "^4.4.5"
}
}

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -1,17 +0,0 @@
import { useState } from 'react'
import './App.css'
function App() {
const [count, setCount] = useState(0)
return (
<>
<h1>Hello World</h1>
<div className='card'>
<button onClick={() => setCount((count) => count + 1)}>count is {count}</button>
</div>
</>
)
}
export default App

View File

@@ -1,25 +0,0 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}

View File

@@ -1,10 +0,0 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts"]
}

View File

@@ -1,7 +0,0 @@
import react from '@vitejs/plugin-react-swc'
import { defineConfig } from 'vite'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()]
})

View File

@@ -0,0 +1,17 @@
import { useState } from 'react'
import './App.css'
const App = () => {
const [count, setCount] = useState(0)
return (
<>
<h1>Hello World</h1>
<div className="card">
<button onClick={() => setCount((count) => count + 1)}>count is {count}</button>
</div>
</>
)
}
export default App

View File

@@ -3,4 +3,4 @@
"react": "https://esm.sh/react@18.2.0",
"react-dom/client": "https://esm.sh/react-dom@18.2.0"
}
}
}

View File

@@ -4,7 +4,7 @@ import ReactDOM from 'react-dom/client'
import App from './App'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>
<React.StrictMode>
<App />
</React.StrictMode>
)

View File

@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": 7,
"useDefineForClassFields": true,
"module": 99,
"skipLibCheck": true,
"moduleResolution": 2,
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": 4,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"composite": true,
"types": ["node"],
"allowSyntheticDefaultImports": true
}
}

View File

@@ -0,0 +1,5 @@
const App = () => {
return <></>
}
export default App

View File

@@ -0,0 +1,6 @@
{
"imports": {
"react": "https://esm.sh/react@18.2.0",
"react-dom/client": "https://esm.sh/react-dom@18.2.0"
}
}

View File

@@ -0,0 +1,10 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>
)

View File

@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": 7,
"useDefineForClassFields": true,
"module": 99,
"skipLibCheck": true,
"moduleResolution": 2,
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": 4,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"composite": true,
"types": ["node"],
"allowSyntheticDefaultImports": true
}
}