React Playground temp

This commit is contained in:
2024-01-05 18:28:48 +08:00
parent 6c8c6088d1
commit 82b5e75046
23 changed files with 701 additions and 0 deletions

View File

@@ -0,0 +1,73 @@
import React from 'react'
import { IPlayground } from '@/components/ReactPlayground/shared.ts'
import { PlaygroundContext } from '@/components/ReactPlayground/Provider.tsx'
import { ENTRY_FILE_NAME, initFiles, MAIN_FILE_NAME } from '@/components/files.ts'
import {
getCustomActiveFile,
getMergedCustomFiles,
getPlaygroundTheme
} from '@/components/ReactPlayground/Utils.ts'
const defaultCodeSandboxOptions = {
theme: 'dark',
editorHeight: '100vh',
showUrlHash: true
}
const Playground: React.FC<IPlayground> = (props) => {
const {
width = '100vw',
height = '100vh',
theme,
files: propsFiles,
importMap,
showCompileOutput = true,
showHeader = true,
showFileSelector = true,
fileSelectorReadOnly = false,
border = false,
defaultSizes,
onFilesChange,
autorun = true
} = props
const { filesHash, changeTheme, files, setFiles, setSelectedFileName } =
useContext(PlaygroundContext)
const options = Object.assign(defaultCodeSandboxOptions, props.options || {})
useEffect(() => {
if (propsFiles && !propsFiles?.[MAIN_FILE_NAME]) {
throw new Error(
`Missing required property : '${MAIN_FILE_NAME}' is a mandatory property for 'files'`
)
} else if (propsFiles) {
const newFiles = getMergedCustomFiles(propsFiles, importMap)
if (newFiles) {
setFiles(newFiles)
}
const selectedFileName = getCustomActiveFile(propsFiles)
if (selectedFileName) {
setSelectedFileName(selectedFileName)
}
}
}, [propsFiles])
useEffect(() => {
setTimeout(() => {
if (!theme) {
changeTheme(getPlaygroundTheme())
} else {
changeTheme(theme)
}
}, 15)
}, [theme])
useEffect(() => {
if (!propsFiles) {
setFiles(initFiles)
}
}, [])
return files[ENTRY_FILE_NAME] ? <></> : undefined
}
export default Playground

View File

@@ -0,0 +1,95 @@
import React from 'react'
import { IFiles, IPlaygroundContext, ITheme } from '@/components/ReactPlayground/shared.ts'
import { MAIN_FILE_NAME } from '@/components/files.ts'
import {
fileNameToLanguage,
setPlaygroundTheme,
strToBase64
} from '@/components/ReactPlayground/Utils.ts'
const initialContext: Partial<IPlaygroundContext> = {
selectedFileName: MAIN_FILE_NAME
}
export const PlaygroundContext = createContext<IPlaygroundContext>(
initialContext as IPlaygroundContext
)
interface ProviderProps extends React.PropsWithChildren {
saveOnUrl?: boolean
}
const Provider: React.FC<ProviderProps> = ({ children, saveOnUrl }) => {
const [files, setFiles] = useState<IFiles>({})
const [theme, setTheme] = useState(initialContext.theme!)
const [selectedFileName, setSelectedFileName] = useState(initialContext.selectedFileName!)
const [filesHash, setFilesHash] = useState('')
const addFile = (name: string) => {
files[name] = {
name,
language: fileNameToLanguage(name),
value: ''
}
setFiles({ ...files })
}
const removeFile = (name: string) => {
delete files[name]
setFiles({ ...files })
}
const changeFileName = (oldFileName: string, newFileName: string) => {
if (!files[oldFileName] || !newFileName) {
return
}
const { [oldFileName]: value, ...other } = files
const newFile: IFiles = {
[newFileName]: {
...value,
language: fileNameToLanguage(newFileName),
name: newFileName
}
}
setFiles({
...other,
...newFile
})
}
const changeTheme = (theme: ITheme) => {
setPlaygroundTheme(theme)
setTheme(theme)
}
useEffect(() => {
const hash = strToBase64(JSON.stringify(files))
if (saveOnUrl) {
window.location.hash = hash
}
setFilesHash(hash)
}, [files])
return (
<PlaygroundContext.Provider
value={{
theme,
filesHash,
files,
selectedFileName,
setTheme,
changeTheme,
setSelectedFileName,
setFiles,
addFile,
removeFile,
changeFileName
}}
>
{children}
</PlaygroundContext.Provider>
)
}
export default Provider

View File

@@ -0,0 +1,113 @@
import { ICustomFiles, IFiles, IImportMap, ITheme } from '@/components/ReactPlayground/shared.ts'
import { strFromU8, strToU8, unzlibSync, zlibSync } from 'fflate'
import { IMPORT_MAP_FILE_NAME, reactTemplateFiles } from '@/components/files.ts'
export const strToBase64 = (str: string) => {
const buffer = strToU8(str)
const zipped = zlibSync(buffer, { level: 9 })
const binary = strFromU8(zipped, true)
return btoa(binary)
}
export const base64ToStr = (base64: string) => {
const binary = atob(base64)
// zlib header (x78), level 9 (xDA)
if (binary.startsWith('\x78\xDA')) {
const buffer = strToU8(binary, true)
const unzipped = unzlibSync(buffer)
return strFromU8(unzipped)
}
return ''
}
export const fileNameToLanguage = (name: string) => {
const suffix = name.split('.').pop() || ''
if (['js', 'jsx'].includes(suffix)) return 'javascript'
if (['ts', 'tsx'].includes(suffix)) return 'typescript'
if (['json'].includes(suffix)) return 'json'
if (['css'].includes(suffix)) return 'css'
return 'javascript'
}
const STORAGE_DARK_THEME = 'react-playground-prefer-dark'
export const setPlaygroundTheme = (theme: ITheme) => {
localStorage.setItem(STORAGE_DARK_THEME, String(theme === 'dark'))
document
.querySelectorAll('div[data-id="react-playground"]')
?.forEach((item) => item.setAttribute('class', theme))
}
export const getPlaygroundTheme = () => {
const isDarkTheme = JSON.parse(localStorage.getItem(STORAGE_DARK_THEME) || 'false')
return isDarkTheme ? 'dark' : 'light'
}
const transformCustomFiles = (files: ICustomFiles) => {
const newFiles: IFiles = {}
Object.keys(files).forEach((key) => {
const tempFile = files[key]
if (typeof tempFile === 'string') {
newFiles[key] = {
name: key,
language: fileNameToLanguage(key),
value: tempFile
}
} else {
newFiles[key] = {
name: key,
language: fileNameToLanguage(key),
value: tempFile.code,
hidden: tempFile.hidden,
active: tempFile.active
}
}
})
return newFiles
}
export const getMergedCustomFiles = (files?: ICustomFiles, importMap?: IImportMap) => {
if (!files) return null
if (importMap) {
return {
...reactTemplateFiles,
...transformCustomFiles(files),
[IMPORT_MAP_FILE_NAME]: {
name: IMPORT_MAP_FILE_NAME,
language: 'json',
value: JSON.stringify(importMap, null, 2)
}
}
} else {
return {
...reactTemplateFiles,
...transformCustomFiles(files)
}
}
}
export const getCustomActiveFile = (files?: ICustomFiles) => {
if (!files) return null
return Object.keys(files).find((key) => {
const tempFile = files[key]
if (typeof tempFile !== 'string' && tempFile.active) {
return key
}
return null
})
}
export const getFilesFromUrl = () => {
let files: IFiles | undefined
try {
if (typeof window !== 'undefined') {
const hash = window.location.hash
if (hash) files = JSON.parse(base64ToStr(hash?.split('#')[1]))
}
} catch (error) {
console.error(error)
}
return files
}

View File

@@ -0,0 +1,16 @@
import React from 'react'
import Provider from '@/components/ReactPlayground/Provider.tsx'
import { IPlayground } from '@/components/ReactPlayground/shared.ts'
import Playground from '@/components/ReactPlayground/Playground.tsx'
const ReactPlayground: React.FC<IPlayground> = (props) => {
return (
<>
<Provider saveOnUrl={props.saveOnUrl}>
<Playground {...props} />
</Provider>
</>
)
}
export default ReactPlayground

View File

@@ -0,0 +1,78 @@
import React from 'react'
import { editor } from 'monaco-editor'
export interface IFile {
name: string
value: string
language: string
active?: boolean
hidden?: boolean
}
export interface IFiles {
[key: string]: IFile
}
export type ITheme = 'light' | 'dark'
export type IImportMap = { imports: Record<string, string> }
export interface ICustomFiles {
[key: string]:
| string
| {
code: string
active?: boolean
hidden?: boolean
}
}
export type IEditorOptions = editor.IStandaloneEditorConstructionOptions & any
export interface IEditorContainer {
showFileSelector?: boolean
fileSelectorReadOnly?: boolean
options?: IEditorOptions
}
export interface IOutput {
showCompileOutput?: boolean
}
export interface ISplitPane {
children?: React.ReactNode[]
defaultSizes?: number[]
}
export type IPlayground = {
width?: string | number
height?: string | number
theme?: ITheme
importMap?: IImportMap
files?: ICustomFiles
options?: {
lineNumbers?: boolean
fontSize?: number
tabSize?: number
}
showHeader?: boolean
border?: boolean
onFilesChange?: (url: string) => void
saveOnUrl?: boolean
autorun?: boolean
// recompileDelay
} & Omit<IEditorContainer, 'options'> &
IOutput &
ISplitPane
export interface IPlaygroundContext {
files: IFiles
filesHash: string
theme: ITheme
selectedFileName: string
setSelectedFileName: (fileName: string) => void
setTheme: (theme: ITheme) => void
setFiles: (files: IFiles) => void
addFile: (fileName: string) => void
removeFile: (fileName: string) => void
changeFileName: (oldFieldName: string, newFieldName: string) => void
changeTheme: (theme: ITheme) => void
}

View File

@@ -0,0 +1,18 @@
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

@@ -0,0 +1,24 @@
# 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

@@ -0,0 +1,28 @@
# 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

@@ -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,13 @@
<!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

@@ -0,0 +1,28 @@
{
"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

@@ -0,0 +1 @@
<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>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -0,0 +1,65 @@
:root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
line-height: 1.5;
color: rgb(255 255 255 / 87%);
text-rendering: optimizelegibility;
text-size-adjust: 100%;
background-color: #242424;
color-scheme: light dark;
font-synthesis: none;
}
#root {
max-width: 1280px;
padding: 2rem;
margin: 0 auto;
text-align: center;
}
body {
display: flex;
min-width: 320px;
min-height: 100vh;
margin: 0;
place-items: center;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
button {
padding: 0.6em 1.2em;
font-family: inherit;
font-size: 1em;
font-weight: 500;
cursor: pointer;
background-color: #1a1a1a;
border: 1px solid transparent;
border-radius: 8px;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #fff;
}
button {
background-color: #f9f9f9;
}
}

View File

@@ -0,0 +1,17 @@
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

@@ -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,25 @@
{
"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

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

View File

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

46
src/components/files.ts Normal file
View File

@@ -0,0 +1,46 @@
import importMap from './template/import-map.json?raw'
import AppCss from './template/src/App.css?raw'
import App from './template/src/App.tsx?raw'
import main from './template/src/main.tsx?raw'
import { IFiles } from '@/components/ReactPlayground/shared.ts'
import { fileNameToLanguage } from '@/components/ReactPlayground/Utils.ts'
export const MAIN_FILE_NAME = 'App.tsx'
export const IMPORT_MAP_FILE_NAME = 'import-map.json'
export const ENTRY_FILE_NAME = 'main.tsx'
export const initFiles: IFiles = getFilesFromUrl() || {
[ENTRY_FILE_NAME]: {
name: ENTRY_FILE_NAME,
language: fileNameToLanguage(ENTRY_FILE_NAME),
value: main
},
[MAIN_FILE_NAME]: {
name: MAIN_FILE_NAME,
language: fileNameToLanguage(MAIN_FILE_NAME),
value: App
},
'App.css': {
name: 'App.css',
language: 'css',
value: AppCss
},
[IMPORT_MAP_FILE_NAME]: {
name: IMPORT_MAP_FILE_NAME,
language: fileNameToLanguage(IMPORT_MAP_FILE_NAME),
value: importMap
}
}
export const reactTemplateFiles = {
[ENTRY_FILE_NAME]: {
name: ENTRY_FILE_NAME,
language: fileNameToLanguage(ENTRY_FILE_NAME),
value: main
},
[IMPORT_MAP_FILE_NAME]: {
name: IMPORT_MAP_FILE_NAME,
language: fileNameToLanguage(IMPORT_MAP_FILE_NAME),
value: importMap
}
}

View File

@@ -0,0 +1,7 @@
import React from 'react'
const OnlineEditor: React.FC = () => {
return <></>
}
export default OnlineEditor

View File

@@ -62,6 +62,13 @@ const root: RouteJsonObject[] = [
auth: true,
permission: true
},
{
path: 'online-editor',
absolutePath: '/online-editor',
id: 'online-editor',
component: React.lazy(() => import('@/pages/OnlineEditor')),
name: '在线编辑器'
},
{
path: '',
absolutePath: '/',