mirror of
https://github.com/EnixCoda/Gitako.git
synced 2026-03-11 08:54:44 +00:00
refactor: make$
This commit is contained in:
parent
ba06289ed3
commit
a9979620f4
2 changed files with 26 additions and 21 deletions
|
|
@ -43,8 +43,8 @@ const selectors = {
|
|||
},
|
||||
}
|
||||
|
||||
const getDOMJSON = (selector: string) =>
|
||||
$(selector, e => {
|
||||
const getDOMJSON = (selector: string, _$ = $) =>
|
||||
_$(selector, e => {
|
||||
try {
|
||||
return JSON.parse(e.textContent || '')
|
||||
} catch (error) {
|
||||
|
|
|
|||
|
|
@ -1,20 +1,25 @@
|
|||
export function $<E extends HTMLElement>(selector: string): E | null
|
||||
export function $<R1>(selector: string, existCallback: (element: HTMLElement) => R1): R1 | null
|
||||
export function $<R1, R2>(
|
||||
selector: string,
|
||||
existCallback: (element: HTMLElement) => R1,
|
||||
otherwise: () => R2,
|
||||
): R1 | R2
|
||||
export function $<E extends HTMLElement, R2>(
|
||||
selector: string,
|
||||
existCallback: undefined | null,
|
||||
otherwise: () => R2,
|
||||
): E | R2
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export function $(selector: string, existCallback?: any, otherwise?: any) {
|
||||
const element = document.querySelector(selector)
|
||||
if (element) {
|
||||
return existCallback ? existCallback(element) : element
|
||||
}
|
||||
return otherwise ? otherwise() : null
|
||||
export interface $ {
|
||||
<E extends HTMLElement>(selector: string): E | null
|
||||
<R1>(selector: string, existCallback: (element: HTMLElement) => R1): R1 | null
|
||||
<R1, R2>(selector: string, existCallback: (element: HTMLElement) => R1, otherwise: () => R2):
|
||||
| R1
|
||||
| R2
|
||||
<E extends HTMLElement, R2>(
|
||||
selector: string,
|
||||
existCallback: undefined | null,
|
||||
otherwise: () => R2,
|
||||
): E | R2
|
||||
}
|
||||
|
||||
export const make$ =
|
||||
(root?: Document | HTMLElement): $ =>
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(selector: string, existCallback?: any, otherwise?: any) => {
|
||||
const element = (root ?? document).querySelector(selector)
|
||||
if (element) {
|
||||
return existCallback ? existCallback(element) : element
|
||||
}
|
||||
return otherwise ? otherwise() : null
|
||||
}
|
||||
|
||||
export const $: $ = make$()
|
||||
|
|
|
|||
Loading…
Reference in a new issue