暂存添加编辑器和modal

This commit is contained in:
熊潇 2024-09-21 04:42:48 +08:00
commit ac8d69f06f
47 changed files with 5426 additions and 0 deletions

9
.gitignore vendored Normal file
View File

@ -0,0 +1,9 @@
node_modules
.pnpm-debug.log
.vscode
dist
build
.env
.DS_Store

1
.npmrc Normal file
View File

@ -0,0 +1 @@
@abearxiong:registry=https://npm.pkg.github.com

12
package.json Normal file
View File

@ -0,0 +1,12 @@
{
"name": "theme",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}

View File

@ -0,0 +1,29 @@
{
"name": "@kevisual/codemirror",
"version": "0.0.1",
"description": "",
"main": "dist/editor.js",
"scripts": {
"build": "rimraf -rf dist && rollup -c"
},
"keywords": [
"kevisual"
],
"files": [
"dist",
"src"
],
"author": "abearxiong",
"license": "ISC",
"dependencies": {},
"devDependencies": {
"codemirror": "^6.0.1",
"@codemirror/lang-javascript": "^6.2.2",
"@codemirror/lang-json": "^6.0.1",
"@rollup/plugin-node-resolve": "^15.2.3",
"@rollup/plugin-typescript": "^11.1.6",
"rollup": "^4.22.2",
"tslib": "^2.7.0",
"typescript": "^5.6.2"
}
}

View File

@ -0,0 +1,6 @@
# kevisual codemirror
```ts
const editor = createEditorInstance(ref.current!, { typescript: false });
editor.dom.style.height = '100%';
```

View File

@ -0,0 +1,22 @@
import { nodeResolve } from '@rollup/plugin-node-resolve';
import typescript from '@rollup/plugin-typescript';
const entrys = ['editor', 'editor.json'];
const configs = entrys.map((entry) => ({
input: `./src/${entry}.ts`, // 修改输入文件为 TypeScript 文件
output: {
file: `./dist/${entry}.js`,
},
plugins: [
nodeResolve(),
typescript({
tsconfig: './tsconfig.json',
compilerOptions: {
declaration: true, // 生成声明文件
declarationDir: './dist', // 声明文件输出目录
},
}), // 添加 TypeScript 插件
],
}));
export default configs;

View File

@ -0,0 +1,37 @@
import { EditorView, basicSetup } from 'codemirror';
import { json } from '@codemirror/lang-json';
let editor: EditorView = null;
/**
*
* @param el
* @returns
*/
const createEditorInstance = (el?: HTMLDivElement) => {
if (editor && el) {
editor.dom.appendChild(el);
return editor;
} else if (editor) {
return editor;
}
editor = new EditorView({
extensions: [basicSetup, json()],
parent: el || document.body,
});
return editor;
};
/**
*
* @param el
* @returns
*/
export const createEditor = (el: HTMLDivElement) => {
return new EditorView({
extensions: [basicSetup, json()],
parent: el || document.body,
});
};
export { editor, createEditorInstance };

View File

@ -0,0 +1,42 @@
import { EditorView, basicSetup } from 'codemirror';
import { javascript } from '@codemirror/lang-javascript';
let editor: EditorView = null;
type CreateOpts = {
jsx?: boolean;
typescript?: boolean;
};
/**
*
* @param el
* @returns
*/
const createEditorInstance = (el?: HTMLDivElement, opts?: CreateOpts) => {
if (editor && el) {
editor.dom.appendChild(el);
return editor;
} else if (editor) {
return editor;
}
const { jsx, typescript } = opts || {};
editor = new EditorView({
extensions: [basicSetup, javascript({ jsx, typescript })],
parent: el || document.body,
});
return editor;
};
/**
*
* @param el
* @returns
*/
export const createEditor = (el: HTMLDivElement, opts?: CreateOpts) => {
return new EditorView({
extensions: [basicSetup, javascript({ jsx: opts?.jsx, typescript: opts?.typescript })],
parent: el || document.body,
});
};
export { editor, createEditorInstance };

View File

@ -0,0 +1,23 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"lib": [
"DOM",
"ESNext"
],
"moduleResolution": "Node",
"declaration": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": [
"src"
],
"exclude": [
"node_modules",
"dist"
]
}

24
packages/theme-preview/.gitignore vendored Normal file
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,32 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import react from 'eslint-plugin-react'
export default tseslint.config(
{ ignores: ['dist'] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
'@typescript-eslint/no-explicit-any': 'off',
...react.configs.recommended.rules,
...react.configs['jsx-runtime'].rules,
},
},
)

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>开发flow的功能记录</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

@ -0,0 +1,53 @@
{
"name": "theme-preview",
"version": "1.0.0",
"description": "",
"main": "index.js",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@abearxiong/ui": "0.0.1-alpha.0",
"@kevisual/codemirror": "workspace:^",
"@kevisual/ui": "workspace:^",
"antd": "^5.20.6",
"clsx": "^2.1.1",
"immer": "^10.1.1",
"lodash-es": "^4.17.21",
"nanoid": "^5.0.7",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router": "^6.26.2",
"react-router-dom": "^6.26.2",
"react-toastify": "^10.0.5",
"zustand": "^4.5.5"
},
"devDependencies": {
"@eslint/js": "^9.10.0",
"@tailwindcss/aspect-ratio": "^0.4.2",
"@tailwindcss/typography": "^0.5.15",
"@types/node": "^22.5.5",
"@types/react": "^18.3.8",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.1",
"autoprefixer": "^10.4.20",
"eslint": "^9.10.0",
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
"eslint-plugin-react-refresh": "^0.4.12",
"globals": "^15.9.0",
"tailwind-merge": "^2.5.2",
"tailwindcss": "^3.4.12",
"tailwindcss-animate": "^1.0.7",
"typescript": "^5.6.2",
"typescript-eslint": "^8.6.0",
"vite": "^5.4.6"
}
}

View File

@ -0,0 +1 @@
# 工作区其他库的测试和预览

View File

@ -0,0 +1,29 @@
import { BrowserRouter as Router, Route, Routes, Navigate } from 'react-router-dom';
import { ConfigProvider } from 'antd';
import { ToastContainer } from 'react-toastify';
import { App as FlowApps } from './pages/model';
import { App as CodeMirrorApp } from './pages/codemirror';
export const App = () => {
return (
<div className='w-full h-full'>
<ConfigProvider
theme={{
token: {},
}}>
<Router>
<Routes>
<Route path='/' element={<Navigate to='/model/' />} />
<Route path='/model/*' element={<FlowApps />} />
<Route path='/codemirror/*' element={<CodeMirrorApp />} />
<Route path='/404' element={<div>404</div>} />
<Route path='*' element={<div>404</div>} />
</Routes>
</Router>
</ConfigProvider>
<div id='for-modal'></div>
<div id='ui-model-list'></div>
<ToastContainer />
</div>
);
};

View File

@ -0,0 +1,15 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
h1 {
@apply text-2xl font-bold;
}
h2 {
@apply text-xl font-bold;
}
h3 {
@apply text-lg font-bold;
}
}

View File

@ -0,0 +1,12 @@
html,
body {
width: 100%;
height: 100%;
font-size: 16px;
font-family: 'Montserrat', sans-serif;
}
#root {
width: 100%;
height: 100%;
}

View File

@ -0,0 +1,7 @@
import { createRoot } from 'react-dom/client';
import { App } from './App.tsx';
// import './tailwind.css';
import './globals.css';
import './index.css';
createRoot(document.getElementById('root')!).render(<App />);

View File

@ -0,0 +1,25 @@
import { createEditorInstance } from '@kevisual/codemirror/dist/editor.json';
import { useEffect, useRef } from 'react';
export const App = () => {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
init();
}, []);
const init = () => {
const editor = createEditorInstance(ref.current!);
editor.dom.style.height = '100%';
};
return (
<div className='h-full w-full bg-gray-400'>
<div className='p-2 bg-white mb-4'>CodeMirror</div>
<div
className='rounded-md border shadow-md p-4 bg-white mx-8'
style={{
height: 'calc(100vh - 100px)',
overflow: 'auto',
}}>
<div ref={ref} className='h-full w-full'></div>
</div>
</div>
);
};

View File

@ -0,0 +1,29 @@
import { createEditorInstance } from '@kevisual/codemirror';
import { useEffect, useRef } from 'react';
type AppProps = {
typescript?: boolean;
};
export const App = ({ typescript }: AppProps) => {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
init();
}, []);
const init = () => {
const editor = createEditorInstance(ref.current!, { typescript });
editor.dom.style.height = '100%';
};
return (
<div className='h-full w-full bg-gray-400'>
<div className='p-2 bg-white mb-4'>CodeMirror</div>
<div
className='rounded-md border shadow-md p-4 bg-white mx-8'
style={{
height: 'calc(100vh - 100px)',
overflow: 'auto',
}}>
<div ref={ref} className='h-full w-full'></div>
</div>
</div>
);
};

View File

@ -0,0 +1,15 @@
import { Routes, Route, Navigate } from 'react-router-dom';
import { App as TsApp } from './Ts';
import { App as JsonApp } from './Json';
export const App = () => {
return (
<Routes>
<Route path='/' element={<Navigate to='/codemirror/ts' />} />
<Route path='/ts' element={<TsApp typescript={true} />} />
<Route path='/js' element={<TsApp />} />
<Route path='/json' element={<JsonApp />} />
</Routes>
);
};

View File

@ -0,0 +1,73 @@
import { modalStore, Modal, DialogModal } from '@kevisual/ui';
import { calc } from 'antd/es/theme/internal';
import { useEffect, useRef } from 'react';
import '@kevisual/ui/src/index.css';
export const App = () => {
const showModel = () => {
//
};
return (
<div className='flex flex-col w-full h-full bg-gray-400'>
<div className='p-2 bg-white rounded-md border-b rounded-s rounded-e'>Model</div>
<div
className='mt-2 mx-4 bg-white p-2 rounded-md border shadow-sm flex flex-wrap gap-2'
style={{
height: 'calc(100vh - 100px)',
overflow: 'auto',
}}>
<ModelOne />
<ModelTwo />
</div>
</div>
);
};
const ModelOne = () => {
const ref = useRef<HTMLDivElement>(null);
const showModel = () => {
const model = Modal.render(ref.current!, {});
};
return (
<div>
<div className='w-100 h-100 p-4 rounded-md shadow-md bg-slate-200'>
model one
<div className='cursor-pointer p-2 border' onClick={showModel}>
show
</div>
<div ref={ref}> Model的渲染内容</div>
</div>
</div>
);
};
const ModelTwo = () => {
const ref = useRef<HTMLDivElement>(null);
const showModel = () => {
const model = DialogModal.render(ref.current!, {
dialogTitle: 'Dialog Modal',
width: '400px',
dialogTitleCloseIcon: true,
contentStyle: {
// maxHeight: '100px',
// overflow: 'auto',
}
});
};
return (
<div>
<div className='w-100 h-100 p-4 rounded-md shadow-md bg-slate-200'>
model two
<div className='cursor-pointer p-2 border' onClick={showModel}>
show
</div>
<div ref={ref}>
Modal Dialog
<div></div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
</div>
</div>
);
};

View File

@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

View File

@ -0,0 +1,6 @@
/// <reference types="vite/client" />
type SimpleObject = {
[key: string | number]: any;
};
declare let DEV_SERVER: boolean;

View File

@ -0,0 +1,36 @@
console.log('tailwind.config.js');
/** @type {import('tailwindcss').Config} */
export default {
darkMode: ['class'],
content: [
'./src/**/*.{ts,tsx}',
'./node_modules/@abearxiong/flows/components/**/*.{ts,tsx}', //
'./node_modules/@abearxiong/flows/hooks/**/*.{ts,tsx}', //
'./node_modules/@abearxiong/flows/src/**/*.{ts,tsx}' //
],
plugins: [require('@tailwindcss/aspect-ratio'), require('@tailwindcss/typography')],
theme: {
extend: {},
screen: {
sm: '640px',
// => @media (min-width: 640px) { ... }
md: '768px',
// => @media (min-width: 768px) { ... }
lg: '1024px',
// => @media (min-width: 1024px) { ... }
xl: '1280px',
// => @media (min-width: 1280px) { ... }
'2xl': '1536px',
// => @media (min-width: 1536px) { ... }
'3xl': '1920px',
// => @media (min-width: 1920) { ... }
'4xl': '2560px'
// => @media (min-width: 2560) { ... }
}
},
plugins: [require('tailwindcss-animate')]
};

View File

@ -0,0 +1,24 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noImplicitAny": false,
"strict": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}

View File

@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@ -0,0 +1,22 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}

View File

@ -0,0 +1,34 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from 'tailwindcss'
import autoprefixer from 'autoprefixer'
import path from 'path'
import nesting from 'tailwindcss/nesting'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
css: {
postcss: {
plugins: [nesting, tailwindcss, autoprefixer]
}
},
resolve: {
alias: {
'@': path.resolve(__dirname, './src')
}
},
define: {
DEV_SERVER: JSON.stringify(process.env.NODE_ENV === 'development')
},
server: {
port: 7101,
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '/api')
}
}
}
})

34
packages/ui/package.json Normal file
View File

@ -0,0 +1,34 @@
{
"name": "@kevisual/ui",
"version": "1.0.0",
"description": "",
"main": "dist/index.js",
"scripts": {
"build": "tsc"
},
"files": [
"dist",
"src",
"components"
],
"keywords": [],
"author": "abearxiong",
"devDependencies": {
"@emotion/serialize": "^1.3.1",
"@types/react": "^18.3.8",
"immer": "^10.1.1",
"nanoid": "^5.0.7",
"rollup": "^4.22.2",
"typescript": "^5.6.2",
"zustand": "5.0.0-rc.2"
},
"dependencies": {
"dayjs": "^1.11.13",
"lodash-es": "^4.17.21",
"style-to-object": "^1.0.8"
},
"publishConfig": {
"registry": "https://registry.npmjs.org/",
"access": "public"
}
}

View File

@ -0,0 +1,175 @@
import { Modal, ModalOpts, KV } from './modal';
import { SelectEl, querySelector, elAddCS, ElStyle, elAddCS2 } from '../../utils/query-el';
import { ObjCss } from '../../utils/css';
export class BlankModal extends Modal {
constructor(opts: ModalOpts) {
super(opts);
}
}
type DialogModalOpts = {
dialogTitle?: string;
dialogTitleClassName?: string;
dialogTitleStyle?: ElStyle;
dialogTitleEl?: HTMLElement;
dialogTitleCloseIcon?: boolean;
dialogContentClassName?: string;
dialogContentStyle?: ElStyle;
dialogFooterClassName?: string;
dialogFooterStyle?: ElStyle;
} & ModalOpts<KV, DialogDefaultStyle>;
type DialogDefaultStyle = {
defaultDialogTitleStyle?: ObjCss;
defaultDialogContentStyle?: ObjCss;
defaultDialogFooterStyle?: ObjCss;
};
export class DialogModal extends Modal<DialogModalOpts, DialogDefaultStyle> {
dialogTitle?: string;
dialogTitleClassName?: string;
dialogTitleStyle?: ElStyle;
dialogTitleEl?: HTMLElement;
dialogTitleCloseIcon?: boolean;
dialogContentClassName?: string;
dialogContentStyle?: ElStyle;
dialogFooterShow?: boolean;
dialogFooterClassName?: string;
dialogFooterStyle?: ElStyle;
constructor(opts: ModalOpts<DialogModalOpts, DialogDefaultStyle>) {
super(opts);
this.dialogTitle = opts.dialogTitle;
this.dialogTitleClassName = opts.dialogTitleClassName;
this.dialogTitleStyle = opts.dialogTitleStyle;
this.dialogTitleEl = opts.dialogTitleEl;
this.dialogTitleCloseIcon = opts.dialogTitleCloseIcon;
this.dialogContentClassName = opts.dialogContentClassName;
this.dialogContentStyle = opts.dialogContentStyle;
this.dialogFooterClassName = opts.dialogFooterClassName;
this.dialogFooterStyle = opts.dialogFooterStyle;
this.dialogFooterShow = opts.dialogFooterShow ?? false;
this.setDefaultStyle('defaultContentStyle', {
position: 'absolute',
padding: '0px',
left: '50%',
top: '20%',
width: '600px',
background: '#fff',
borderRadius: '5px',
boxShadow: '0 0 10px rgba(0,0,0,.1)',
transform: 'translate(-50%, -50%)',
maxHeight: '80vh',
overflow: 'auto',
...opts?.defaultStyle?.defaultContentStyle,
});
this.setDefaultStyle('defaultDialogTitleStyle', {
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
position: 'sticky',
padding: '10px 20px',
top: '0',
background: '#fff',
marginTop: '-10px',
borderBottom: '1px solid #f0f0f0',
marginBottom: '5px',
...opts?.defaultStyle?.defaultDialogTitleStyle,
});
this.setDefaultStyle('defaultDialogContentStyle', {
padding: '20px',
...opts?.defaultStyle?.defaultDialogContentStyle,
});
this.setDefaultStyle('defaultDialogFooterStyle', {
display: 'flex',
justifyItems: 'end',
borderTop: '1px solid #f0f0f0',
padding: '10px 20px',
...opts?.defaultStyle?.defaultDialogFooterStyle,
});
}
static render(el: string | HTMLDivElement, id: string, opts?: DialogModalOpts): any;
static render(el: string | HTMLDivElement, opts?: DialogModalOpts): any;
static render(...args: any[]) {
const [el, id, opts] = args;
super.render(el, id, opts);
}
appendRoot(documentFragment: DocumentFragment): void {
const cacheFragment = document.createDocumentFragment();
// 拿出来
cacheFragment.appendChild(this.Element);
const DialogBox = documentFragment.querySelector('.ui-modal-content');
DialogBox.classList.add('ui-modal-dialog');
// 创建title
const title = document.createElement('div');
title.classList.add('ui-modal-dialog-title');
elAddCS2(title, this.dialogTitleClassName, this.dialogTitleStyle, this.defaultStyle.defaultDialogTitleStyle);
if (this.dialogTitleEl) {
title.appendChild(this.dialogTitleEl);
} else {
title.innerText = this.dialogTitle;
}
if (this.dialogTitleCloseIcon) {
const closeIcon = document.createElement('span');
closeIcon.className = 'ui-modal-dialog-close';
closeIcon.innerHTML = '&times;';
closeIcon.style.cssText = `
cursor: pointer;
font-size: 24px;
margin: -5px 10px 0 0;
`;
closeIcon.onclick = (e) => {
this.setOpen(false);
};
title.appendChild(closeIcon);
}
DialogBox.appendChild(title);
// 创建content
const content = document.createElement('div');
content.className = 'ui-modal-dialog-content';
elAddCS2(content, this.dialogContentClassName, this.dialogContentStyle, this.defaultStyle.defaultDialogContentStyle);
content.appendChild(cacheFragment);
if (this.dialogFooterShow) {
const footer = document.createElement('div');
footer.className = 'ui-modal-dialog-footer';
elAddCS2(footer, this.dialogFooterClassName, this.dialogFooterStyle, this.defaultStyle.defaultDialogFooterStyle);
DialogBox.appendChild(footer);
}
DialogBox.appendChild(content);
super.appendRoot(documentFragment);
}
renderEl(el: HTMLDivElement): this {
return super.renderEl(el);
}
renderFooter(el?: SelectEl): void {
const _el = querySelector(el);
if (!_el) return;
const footer = this.Element.querySelector('.ui-modal-dialog-footer');
if (!footer) return;
footer.innerHTML = '';
footer.appendChild(_el);
}
renerContent(el?: SelectEl): void {
const _el = querySelector(el);
if (!_el) return;
const content = this.Element.querySelector('.ui-modal-dialog-content');
if (!content) return;
content.innerHTML = '';
content.appendChild(_el);
}
}

View File

@ -0,0 +1,39 @@
import { modalStore } from './store';
// modal 事件实现
const ModalEvent = {
//
};
const onClick = (e: MouseEvent) => {
const target = e.target as HTMLElement;
if (!target) {
console.log('target is null');
return;
}
if (target.classList.contains('ui-modal-mask')) {
const modalState = modalStore.getState();
const modal = modalState.modals.find((modal) => modal.id === target.dataset.id);
if (modal && modal.open) {
modal.onMaskClose(e);
}
e.preventDefault();
return;
}
// const parentModalRoot = target.closest('.ui-modal-root');
// if (!parentModalRoot) {
// return;
// }
};
export const InitModalEvent = (el: HTMLDivElement) => {
const id = el.id;
if (ModalEvent[id] && el === ModalEvent[id]) {
return;
}
// Remove previous event listener to prevent memory leak
if (ModalEvent[id]) {
ModalEvent[id].removeEventListener('click', onClick);
}
ModalEvent[id] = null;
el.addEventListener('click', onClick);
ModalEvent[id] = el;
};

View File

@ -0,0 +1,29 @@
#ui-modal-list {
position: relative;
}
.ui-modal-wrapper {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 200;
display: none;
}
.ui-modal-open {
display: block;
}
.ui-modal-mask {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
z-index: 201;
}
.ui-modal-content {
position: fixed;
z-index: 202;
}

View File

@ -0,0 +1,5 @@
export * from './modal';
export * from './store';
export * from './blank-modal';

View File

@ -0,0 +1,235 @@
import { querySelector, elAddCS, ElStyle, elAddCS2 } from '../../utils/query-el';
import { generateId } from '../../utils/nanoid';
import { modalStore } from './store';
import { InitModalEvent } from './event';
import { ObjCss } from '../../utils/css';
export type KV = {
[key: string]: any;
};
export type ModalOpts<
T = {
[key: string]: any;
},
U = {
[key: string]: any;
},
> = {
root?: HTMLDivElement | string;
id?: string;
mask?: boolean;
maskClassName?: string;
maskStyle?: ElStyle;
maskClose?: boolean;
contentClassName?: string;
contentStyle?: ElStyle;
destroyOnClose?: boolean;
onClose?: () => void;
defaultStyle?: DefaultStyle<U>;
} & T;
export type DefaultStyle<T> = {
defaultContentStyle?: ObjCss;
defaultMaskStyle?: ObjCss;
} & T;
export class Modal<T = any, U = KV> {
root: HTMLDivElement;
id: string;
modalElement?: HTMLDivElement;
Element?: HTMLDivElement;
mask?: boolean;
maskClassName?: string;
maskStyle?: ElStyle;
// 点击mask是否关闭
maskClose?: boolean;
contentClassName?: string;
contentStyle?: ElStyle;
destroyOnClose?: boolean;
open?: boolean;
isUse = true;
// 通知关闭
onClose?: (e: any) => void;
cacheFragment?: DocumentFragment;
defaultStyle?: DefaultStyle<U>;
constructor(opts: ModalOpts<T, U>) {
this.root = this.initRoot(opts.root);
InitModalEvent(this.root);
this.id = opts.id || generateId();
this.mask = opts.mask ?? true;
this.maskClassName = opts.maskClassName;
this.maskStyle = opts.maskStyle;
this.maskClose = opts.maskClose ?? true;
this.contentClassName = opts.contentClassName;
this.contentStyle = opts.contentStyle;
this.destroyOnClose = opts.destroyOnClose ?? false;
this.cacheFragment = new DocumentFragment();
this.defaultStyle = opts.defaultStyle || ({} as DefaultStyle<U>);
this.onClose = opts.onClose;
}
initRoot(root: ModalOpts['root']) {
let _root = querySelector(root);
if (!_root) {
// 查询ui-modal元素,不存在则创建一个ui-modal元素并添加到body上
const queryRoot = document.querySelector('#ui-modal-list') as HTMLDivElement;
if (queryRoot) {
_root = queryRoot;
_root.classList.add('ui-modal-root');
return _root;
}
_root = document.createElement('div');
_root.id = 'ui-modal-list';
_root.classList.add('ui-modal-root');
document.body.appendChild(_root);
return _root;
}
_root.classList.add('ui-custom-modal', 'ui-modal-root');
if (!_root.id) {
_root.id = 'ui-modal' + generateId();
}
return _root;
}
static render(el: string | HTMLDivElement, id: string, opts?: ModalOpts): any;
static render(el: string | HTMLDivElement, opts?: ModalOpts): any;
static render(...args: any[]) {
let [el, id, opts] = args;
const _el = querySelector(el);
if (!_el) {
console.warn('el is not exist', el);
return;
}
let _id: string = '';
if (typeof id === 'string' && id) {
// 如果id是字符串
_id = id;
} else if (typeof id === 'object') {
// 如果id是对象
_id = id.id;
opts = id;
id = id.id;
}
let _modal: Modal | undefined;
const modalState = modalStore.getState();
if (_id) {
// 如果存在id,则判断是否已经存在该id的modal
_modal = modalStore.getState().getModal(_id);
}
if (!_modal) {
// 不存在modal,则创建一个modal
// console.log('create modal', id, opts);
const newModal = new this({ id, ...opts });
_modal = newModal;
modalStore.setState({
modals: [...modalState.modals, newModal],
});
}
_modal.renderEl(_el);
}
createMask() {
const mask = document.createElement('div');
mask.classList.add('ui-modal-mask');
mask.dataset.id = this.id;
elAddCS2(mask, this.maskClassName, this.maskStyle, this.defaultStyle?.defaultMaskStyle);
return mask;
}
renderEl(el: HTMLDivElement) {
const defaultContentStyle = this.defaultStyle?.defaultContentStyle || {
position: 'absolute',
padding: '20px',
left: '50%',
top: '20%',
width: '600px',
background: '#fff',
borderRadius: '5px',
boxShadow: '0 0 10px rgba(0,0,0,.1)',
transform: 'translate(-50%, -50%)',
maxHeight: '80vh',
overflow: 'auto',
};
const fragment = document.createDocumentFragment();
const _modalEl = document.createElement('div');
_modalEl.classList.add('ui-modal-wrapper');
_modalEl.id = this.id;
_modalEl.dataset.mid = this.id;
if (this.mask) {
const mask = this.createMask();
_modalEl.appendChild(mask);
}
const modalContent = document.createElement('div');
modalContent.classList.add('ui-modal-content');
elAddCS2(modalContent, this.contentClassName, this.contentStyle, defaultContentStyle);
modalContent.appendChild(el);
_modalEl.appendChild(modalContent);
fragment.appendChild(_modalEl);
this.modalElement = _modalEl;
this.Element = el;
this.appendRoot(fragment);
return this;
}
appendRoot(document: DocumentFragment) {
this.root.appendChild(document);
this.setOpen(true);
}
setOpen(open: boolean) {
this.open = open;
if (this.destroyOnClose && open === false) {
this.unMount();
}
if (open) {
this.modalElement.classList.add('ui-modal-open');
this.root.appendChild(this.modalElement);
} else {
// this.modalElement.classList.remove('ui-modal-open');
this.cacheFragment.appendChild(this.modalElement);
}
}
unMount() {
// 返回渲染的的Element, 然后删除modalElement
const fragment = document.createDocumentFragment();
fragment.appendChild(this.Element);
this.modalElement?.remove();
const modalState = modalStore.getState();
modalStore.setState({
modals: modalState.modals.filter((modal) => modal.id !== this.id),
});
this.isUse = false;
return fragment;
}
/**
*
* @param force
* @param opts
* @returns
*/
reRender(force?: boolean, opts?: ModalOpts) {
if (force) {
this.modalElement?.remove?.();
this.modalElement = undefined;
if (!this.Element) return;
this.renderEl(this.Element);
}
}
async onMaskClose(e?: any) {
if (this.maskClose) {
this.setOpen(false);
this.onClose?.(e);
}
}
setDefaultStyle(key: keyof DefaultStyle<U>, style: ObjCss) {
this.defaultStyle[key] = style as any;
}
}
// modal.render('#abc'||document.querySelector('#abc'));
// modal.unmount();

View File

@ -0,0 +1,16 @@
import { createStore } from '../../utils';
import { Modal } from './modal';
type ModeStore = {
modals: Modal[];
getModal: (id: string) => Modal | undefined;
};
export const modalStore = createStore<ModeStore>((set, get) => {
return {
modals: [],
getModal: (id: string) => {
return get().modals.find((model) => model.id === id) as Modal;
},
};
});

View File

@ -0,0 +1 @@
@import 'components/model/index.css';

3
packages/ui/src/index.ts Normal file
View File

@ -0,0 +1,3 @@
import { Modal, modalStore, BlankModal, DialogModal } from './components/modal';
export { Modal, modalStore, BlankModal, DialogModal };

View File

@ -0,0 +1,19 @@
import { serializeStyles } from '@emotion/serialize';
export const getCssText = (obj?: ObjCss) => {
if (!obj) return '';
const serialized = serializeStyles([obj]);
return serialized.styles;
};
export const getCssTextObjs = (objs?: ObjCss[]) => {
if (!objs) return '';
const serialized = serializeStyles(objs);
return serialized.styles;
};
export type ObjCss = { [key: string]: number | string } & React.CSSProperties;
export const obj2css = (el?: HTMLDivElement, obj?: ObjCss) => {
if (!el) return;
if (!obj) return;
const serialized = serializeStyles([obj as unknown as Record<string, string>]);
el.style.cssText = serialized.styles;
};

View File

@ -0,0 +1,2 @@
export * from './query-el';
export * from './store';

View File

@ -0,0 +1,8 @@
import { customAlphabet } from 'nanoid';
// 全小写的字母和数字
const alphabetLetter = 'abcdefghijklmnopqrstuvwxyz';
const alphabet = '0123456789abcdefghijklmnopqrstuvwxyz';
export const generateId6 = customAlphabet(alphabet, 6);
export const generateId = (size = 6) => {
return 'b-' + generateId6(size);
};

View File

@ -0,0 +1,54 @@
import { obj2css, ObjCss } from './css';
import parse from 'style-to-object';
export type SelectEl = string | HTMLDivElement;
export const querySelector = (el?: string | HTMLDivElement): HTMLDivElement | null => {
if (!el) {
return null;
}
if (typeof el === 'string') {
return document.querySelector(el) as HTMLDivElement;
}
return el;
};
export type ElStyle = ObjCss | string;
/**
* el add class and style
* @param el
* @param className
* @param style
* @returns
*/
export const elAddCS = (el: HTMLDivElement, className?: string, style?: ElStyle) => {
if (!el) return;
if (className) {
el.classList.add(className);
}
if (style && typeof style === 'string') {
el.style.cssText = style;
} else if (style) {
obj2css(el, style as ObjCss);
}
};
/**
* style的同时保留默认的的style
* @param el
* @param className
* @param style
* @param defaultStyle
* @returns
*/
export const elAddCS2 = (el: HTMLDivElement, className?: string, style?: ElStyle, defaultStyle?: ObjCss) => {
if (!el) return;
if (className) {
el.classList.add(className);
}
let _style: ObjCss = { ...defaultStyle };
if (style && typeof style === 'string') {
_style = { ...defaultStyle, ...parse(style) };
} else if (style && typeof style === 'object') {
_style = { ...defaultStyle, ...style };
}
obj2css(el, _style);
};

View File

@ -0,0 +1,3 @@
import { createStore } from 'zustand/vanilla';
export { createStore };

23
packages/ui/tsconfig.json Normal file
View File

@ -0,0 +1,23 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"lib": [
"DOM",
"ESNext"
],
"moduleResolution": "Node",
"declaration": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": [
"src"
],
"exclude": [
"node_modules",
"dist"
]
}

4132
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

2
pnpm-workspace.yaml Normal file
View File

@ -0,0 +1,2 @@
packages:
- 'packages/*'

5
readme.md Normal file
View File

@ -0,0 +1,5 @@
# theme for kevisual
vanilla
theme and ui tools, some library for envision-cli