live-code-demo/src/pages/editor/index.tsx

144 lines
4.6 KiB
TypeScript

import LiveEditor from "../../components/Live/LiveEditor";
import LiveError from "../../components/Live/LiveError";
import LivePreview from "../../components/Live/LivePreview";
import LiveProvider from "../../components/Live/LiveProvider";
import { ThemeProvider } from "../../components/Theme/ThemePrivider";
import { useState } from "react";
import { functionBlockList } from "../../data/functionBlocks";
import ClickContextProvider from "../../components/Selected/ClickContext";
const editor = (setShowEdit: React.Dispatch<React.SetStateAction<boolean>>) => {
return (
<div className="bg-primary-1 fixed inset-0 flex flex-col items-center bg-gray-900 p-4 overflow-y-auto">
<div className="fixed top-4 right-2">
<button
className="bg-primary-6 text-white py-2 px-4 rounded-lg mr-2"
onClick={() => setShowEdit(false)}
>
</button>
</div>
<div className="flex flex-col items-center w-full space-y-4 mt-12">
{functionBlockList.map((func, index) => {
return (
<div
className="w-full p-4 text-white bg-gray-800 font-mono"
key={index}
>
<LiveEditor
code={func.code}
language={"tsx"}
onChange={(code) => {
functionBlockList[index].code = code
}}
/>
{/* 插入按钮 */}
<button
className="bg-primary-6 text-white py-2 px-4 rounded-lg mt-2"
onClick={() => {
functionBlockList.splice(index + 1, 0, {
code: "const NewComponent = () => {return <>Hello World</>};",
props: {},
cpnName: "NewComponent",
});
setShowEdit(false);
}}
>
</button>
{/* 删除按钮 */}
<button
className="bg-primary-6 text-white py-2 px-4 rounded-lg mt-2 ml-2"
onClick={() => {
functionBlockList.splice(index, 1);
setShowEdit(false);
}}
>
</button>
</div>
);
})}
</div>
</div>
);
};
export const Editor = () => {
const [theme, setTheme] = useState<"system" | "dark" | "light">("system");
const [showEdit, setShowEdit] = useState(false);
return (
<div>
<ThemeProvider activeTheme={theme}>
{showEdit && editor(setShowEdit)}
{!showEdit && (
<>
<div className="fixed top-4 right-4">
<button
className="bg-primary-6 text-white py-2 px-4 rounded-lg mr-2"
onClick={() => setTheme("system")}
>
</button>
<button
className="bg-primary-6 text-white py-2 px-4 rounded-lg mr-2"
onClick={() => setTheme("dark")}
>
</button>
<button
className="bg-primary-6 text-white py-2 px-4 rounded-lg"
onClick={() => setTheme("light")}
>
</button>
<button
className="bg-primary-6 text-white py-2 px-4 rounded-lg ml-2"
onClick={() => setShowEdit(true)}
>
</button>
</div>
</>
)}
{functionBlockList.map((func, index) => {
return (
<LiveProvider
code={func.code}
key={index}
>
<ClickContextProvider
meun={[
{
key: "copy",
text: "复制",
handler: ({ selected }) => {
if (selected) {
navigator.clipboard.writeText(selected.outerHTML);
}
},
},
{
key: "delete",
text: "删除",
handler: ({ selected }) => {
if (selected) {
selected.remove();
}
},
},
]}
>
<LivePreview {...func.props}/>
<LiveError />
</ClickContextProvider>
</LiveProvider>
);
})}
</ThemeProvider>
</div>
);
};