1
0
Fork 0
forked from Mirrors/gomuks

web/preferences: allow imports in custom CSS

This commit is contained in:
Tulir Asokan 2024-12-18 22:07:36 +02:00
parent ac9e6f356d
commit e95f669ec5

View file

@ -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
}