chore: extract root element insertion

This commit is contained in:
EnixCoda 2022-06-04 21:11:47 +08:00
parent 9553e1c0bb
commit caaff93ad7
2 changed files with 15 additions and 6 deletions

View file

@ -2,7 +2,7 @@ import { Gitako } from 'components/Gitako'
import { platform } from 'platforms'
import * as React from 'react'
import { createRoot } from 'react-dom/client'
import { rootElementID } from 'utils/DOMHelper'
import { insertMountPoint } from 'utils/DOMHelper'
import './content.scss'
if (platform.resolvePartialMetaData()) {
@ -15,10 +15,7 @@ if (platform.resolvePartialMetaData()) {
async function init() {
await injectStyles(browser.runtime.getURL('content.css'))
const sideBarElement = document.createElement('div')
sideBarElement.setAttribute('id', rootElementID)
document.body.appendChild(sideBarElement)
createRoot(sideBarElement).render(<Gitako />)
createRoot(insertMountPoint()).render(<Gitako />)
}
// injects a copy of stylesheets so that other extensions(e.g. dark reader) could read

View file

@ -48,7 +48,7 @@ export function $<T2>(
selector: string,
existCallback: undefined | null,
otherwise: () => T2,
): HTMLElement | T2 | null
): HTMLElement | T2
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function $(selector: string, existCallback?: any, otherwise?: any) {
const element = document.querySelector(selector)
@ -58,6 +58,18 @@ export function $(selector: string, existCallback?: any, otherwise?: any) {
return otherwise ? otherwise() : null
}
/**
* add the root element into DOM
*/
export function insertMountPoint() {
return $(formatID(rootElementID), undefined, () => {
const rootElement = document.createElement('div')
rootElement.setAttribute('id', rootElementID)
document.body.appendChild(rootElement)
return rootElement
})
}
/**
* add the logo element into DOM
*/