Skip to content

Commit

Permalink
refactor(hooks): Simplify request handling and improve get function f…
Browse files Browse the repository at this point in the history
…or embeds
  • Loading branch information
robinv8 committed Nov 15, 2024
1 parent beaac22 commit b3fdc42
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 24 deletions.
38 changes: 20 additions & 18 deletions embed-basic/hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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<pluginHookProps> = (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<Config[] | null>(null);

const embeds = [
Expand Down Expand Up @@ -234,23 +237,22 @@ const useRenderEmbed : FC<pluginHookProps> = (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);
}
}
};

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();
Expand All @@ -261,7 +263,7 @@ const useRenderEmbed : FC<pluginHookProps> = (element, request: Request = {
if (styleEle) {
head.removeChild(styleEle);
}
}
};
}, []);

useEffect(() => {
Expand Down
7 changes: 1 addition & 6 deletions embed-basic/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,6 @@
* specific language governing permissions and limitations
* under the License.
*/

import { RefObject } from 'react';

export type pluginHookProps = HTMLElement | RefObject<HTMLElement> | null;

export interface Request {
get: (url: string) => Promise<Response>;
get: (url: string) => Promise<any>;
}

0 comments on commit b3fdc42

Please sign in to comment.