From b3fdc428249cd80e5973a374397dc592ded8a2bb Mon Sep 17 00:00:00 2001 From: robin Date: Fri, 15 Nov 2024 15:39:26 +0800 Subject: [PATCH] refactor(hooks): Simplify request handling and improve get function for embeds --- embed-basic/hooks.tsx | 38 ++++++++++++++++++++------------------ embed-basic/types.ts | 7 +------ 2 files changed, 21 insertions(+), 24 deletions(-) diff --git a/embed-basic/hooks.tsx b/embed-basic/hooks.tsx index c5e48c159..951f0620d 100644 --- a/embed-basic/hooks.tsx +++ b/embed-basic/hooks.tsx @@ -17,13 +17,7 @@ * under the License. */ -import { - useEffect, - useState, - ReactElement, - isValidElement, - FC, -} from 'react'; +import { useEffect, useState, ReactElement, isValidElement } from 'react'; import { createRoot } from 'react-dom/client'; import { GithubGistEmbed, @@ -36,16 +30,25 @@ import { DropboxEmbed, TwitterEmbed, } from './components'; -import { pluginHookProps, Request } from './types'; +import { Request } from './types'; interface Config { platform: string; enable: boolean; } -const useRenderEmbed : FC = (element, request: Request = { - get: fetch, -})=> { +const get = async (url: string) => { + const response = await fetch(url); + const { data } = await response.json(); + return data; +}; + +const useRenderEmbed = ( + element, + request: Request = { + get, + }, +) => { const [configs, setConfigs] = useState(null); const embeds = [ @@ -234,13 +237,12 @@ const useRenderEmbed : FC = (element, request: Request = { styleElement = document.createElement('style'); styleElement.id = 'embed-style'; if (hasDefaultStyle) { - styleElement.textContent = ` + styleElement.textContent = ` .embed-light:hover { --bs-bg-opacity: 1; background-color: rgba(var(--bs-light-rgb), var(--bs-bg-opacity)) !important; } - ` - // style 插入 header + `; const head = document.querySelector('head') as HTMLElement; head.appendChild(styleElement); } @@ -248,9 +250,9 @@ const useRenderEmbed : FC = (element, request: Request = { }; const getConfig = () => { - request.get('/answer/api/v1/embed/config') - .then((response) => response.json()) - .then((result) => setConfigs(result.data)); + request + .get('/answer/api/v1/embed/config') + .then((result) => setConfigs(result)); }; useEffect(() => { getConfig(); @@ -261,7 +263,7 @@ const useRenderEmbed : FC = (element, request: Request = { if (styleEle) { head.removeChild(styleEle); } - } + }; }, []); useEffect(() => { diff --git a/embed-basic/types.ts b/embed-basic/types.ts index 6a034fcbf..afbc83154 100644 --- a/embed-basic/types.ts +++ b/embed-basic/types.ts @@ -16,11 +16,6 @@ * specific language governing permissions and limitations * under the License. */ - -import { RefObject } from 'react'; - -export type pluginHookProps = HTMLElement | RefObject | null; - export interface Request { - get: (url: string) => Promise; + get: (url: string) => Promise; }