Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ feat: #13

Merged
merged 1 commit into from
Jan 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions src/components/Editor/Editor.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import React from "react";
import React, { useEffect } from "react";
import MonacoEditor from "@monaco-editor/react";
import "./editor.less";
import noop from "../../utils";
import SSE from "../../server/serverSentEvent";
import { useSSESub } from "../../hooks/useSSESub";

interface EditorProps {
value?: string;
Expand All @@ -25,6 +27,7 @@ export const Editor = ({
onValidate = noop,
innerProps,
}: EditorProps) => {

const editorProps = {
value,
theme,
Expand All @@ -33,5 +36,15 @@ export const Editor = ({
onChange,
onValidate,
};
return <MonacoEditor height={'100%'} {...innerProps} {...editorProps} />;

useEffect(() => {
const sse = new SSE();
return sse.close;
}, []);

useSSESub(()=>{

})

return <MonacoEditor height={"100%"} {...innerProps} {...editorProps} />;
};
4 changes: 2 additions & 2 deletions src/contexts/playgroundContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ export const PlaygroundProvider: React.FC<PlaygroundProviderProps> = (
return (
<Playground.Provider
value={{
value: "test",
test: "test2",
editorValue: "test",
consoleValue: "test2",
}}
>
<div className={`${className}`} style={style}>
Expand Down
10 changes: 5 additions & 5 deletions src/hooks/usePlayground.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,18 @@ export interface UsePlayground {
* @category Hooks
*/
export function usePlayground(): UsePlayground {
const sandpack = React.useContext(PlaygroundReactContext);
const playgroud = React.useContext(PlaygroundReactContext);

if (sandpack === null) {
if (playgroud === null) {
throw new Error(
`[sandpack-react]: "usePlayground" must be wrapped by a "SandpackProvider"`
`[playgroud-react]: "usePlayground" must be wrapped by a "SandpackProvider"`
);
}

const { dispatch, listen, ...rest } = sandpack;
const { dispatch, listen, ...rest } = playgroud;

return {
sandpack: { ...rest },
playgroud: { ...rest },
dispatch,
listen,
};
Expand Down
11 changes: 11 additions & 0 deletions src/hooks/useSSESub.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { useEffect } from "react"
import SSE, { Callback } from "../server/serverSentEvent"

// 添加sse订阅
export const useSSESub = (callback:Callback)=>{
useEffect(()=>{
const sse = new SSE();
sse.subscribe(callback);
return ()=>{sse.unsubscribe(callback)}
},[])
}
8 changes: 8 additions & 0 deletions src/server/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { deleteRequest, getRequest, patchRequest, postRequest } from "../utils/request";

export const getDetails = (id: string) => getRequest(`/v1/playbooks/${id}`);
export const delatePlaygronds = (id: string) =>
deleteRequest(`/v1/playbooks/${id}`);
export const updateDetails = (id: string) =>
patchRequest(`/v1/playbooks/${id}`);
export const createId = () => postRequest(`/v1/playbooks`);
69 changes: 69 additions & 0 deletions src/server/serverSentEvent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// sse.js
export type Callback = (eventData: any) => void;

// 后续添加装饰器

class SSE {
url: URL | undefined;
eventSource: EventSource | null | undefined;
subscribers: Callback[] = [];
static instance: null;
constructor(endpoint: string = "") {
if (SSE.instance) {
return SSE.instance;
}

this.url = new URL(endpoint, window.location.origin);
this.eventSource = null;
}

connect() {
if (!this.url) {
return;
}
this.eventSource = new EventSource(this.url, { withCredentials: true });

this.eventSource.onopen = () => {
console.log("SSE connection opened");
};

this.eventSource.onmessage = (event) => {
const eventData = JSON.parse(event.data);
this.notifySubscribers(eventData);
};

this.eventSource.onerror = (error) => {
console.error("SSE error:", error);
this.eventSource?.close();
};
}

close() {
if (this.eventSource) {
this.eventSource.close();
console.log("SSE connection closed");
}
}

subscribe(callback: Callback) {
this.subscribers = this.subscribers || [];
this.subscribers.push(callback);
}

unsubscribe(callback: Callback) {
if (this.subscribers) {
this.subscribers = this.subscribers.filter(
(subscriber) => subscriber !== callback
);
}
}

notifySubscribers(data: any) {
if (this.subscribers) {
this.subscribers.forEach((callback) => callback(data));
}
}
}
new SSE("/test");

export default SSE;
6 changes: 1 addition & 5 deletions src/types/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
export type PlaygroundContext = SandpackState & {};

export interface SandpackState {
status: string;
}
export type PlaygroundContext = { editorValue?: string; consoleValue?: string };

export interface Style {
className?: string;
Expand Down
41 changes: 41 additions & 0 deletions src/utils/request.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const requestFactory =
(method = "GET") =>
async (interface, data = null) => {
const url = `https://example.com/api${interface}`;
const options = {
method,
headers: {
"Content-Type": "application/json", // 根据需要设置合适的 Content-Type
},
} as RequestInit;

if ((method === "PUT" || method === "DELETE") && data) {
options.body = JSON.stringify(data);
} else if (data) {
// 对于其他 HTTP 方法,你可以根据需要修改请求体的格式
options.body = data;
}

try {
const response = await fetch(url, options);

if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}

// 根据实际需要,这里可以根据响应的 Content-Type 来解析数据
const responseData = await response.json();

return responseData;
} catch (error) {
console.error("Error during fetch:", error.message);
throw error;
}
};

export const getRequest = requestFactory("GET");
export const postRequest = requestFactory("POST");
export const putRequest = requestFactory("PUT");
export const deleteRequest = requestFactory("DELETE");
export const optionsRequest = requestFactory("OPTIONS");
export const patchRequest = requestFactory("PATCH");