forked from Mirrors/gomuks
web/preferences: allow imports in custom CSS
This commit is contained in:
parent
ac9e6f356d
commit
e95f669ec5
1 changed files with 20 additions and 10 deletions
|
@ -32,12 +32,7 @@ function css(strings: TemplateStringsArray, ...values: unknown[]) {
|
|||
return newStyleSheet(String.raw(strings, ...values))
|
||||
}
|
||||
|
||||
function useStyle(callback: () => CSSStyleSheet | false | undefined | null | "", dependencies: unknown[]) {
|
||||
useInsertionEffect(() => {
|
||||
const sheet = callback()
|
||||
if (!sheet) {
|
||||
return
|
||||
}
|
||||
function pushSheet(sheet: CSSStyleSheet): () => void {
|
||||
document.adoptedStyleSheets.push(sheet)
|
||||
return () => {
|
||||
const idx = document.adoptedStyleSheets.indexOf(sheet)
|
||||
|
@ -45,16 +40,31 @@ function useStyle(callback: () => CSSStyleSheet | false | undefined | null | "",
|
|||
document.adoptedStyleSheets.splice(idx, 1)
|
||||
}
|
||||
}
|
||||
}, dependencies)
|
||||
}
|
||||
|
||||
function useAsyncStyle(callback: () => string | false | undefined | null, dependencies: unknown[]) {
|
||||
function useStyle(callback: () => CSSStyleSheet | false | undefined | null | "", dependencies: unknown[]) {
|
||||
useInsertionEffect(() => {
|
||||
const sheet = callback()
|
||||
if (!sheet) {
|
||||
return
|
||||
}
|
||||
return pushSheet(sheet)
|
||||
}, dependencies)
|
||||
}
|
||||
|
||||
function useAsyncStyle(callback: () => string | false | undefined | null, dependencies: unknown[], id?: string) {
|
||||
useInsertionEffect(() => {
|
||||
const sheet = callback()
|
||||
if (!sheet) {
|
||||
return
|
||||
}
|
||||
if (!sheet.includes("@import")) {
|
||||
return pushSheet(newStyleSheet(sheet))
|
||||
}
|
||||
const styleTags = document.createElement("style")
|
||||
if (id) {
|
||||
styleTags.id = id
|
||||
}
|
||||
styleTags.textContent = sheet
|
||||
document.head.appendChild(styleTags)
|
||||
return () => {
|
||||
|
@ -116,8 +126,8 @@ const StylePreferences = ({ client, activeRoom }: StylePreferencesProps) => {
|
|||
}
|
||||
` : `
|
||||
@import url("_gomuks/codeblock/${preferences.code_block_theme}.css");
|
||||
`, [preferences.code_block_theme])
|
||||
useStyle(() => preferences.custom_css && newStyleSheet(preferences.custom_css), [preferences.custom_css])
|
||||
`, [preferences.code_block_theme], "gomuks-pref-code-block-theme")
|
||||
useAsyncStyle(() => preferences.custom_css, [preferences.custom_css], "gomuks-pref-custom-css")
|
||||
return null
|
||||
}
|
||||
|
||||
|
|
Loading…
Add table
Reference in a new issue