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,29 +32,39 @@ function css(strings: TemplateStringsArray, ...values: unknown[]) {
return newStyleSheet(String.raw(strings, ...values)) return newStyleSheet(String.raw(strings, ...values))
} }
function pushSheet(sheet: CSSStyleSheet): () => void {
document.adoptedStyleSheets.push(sheet)
return () => {
const idx = document.adoptedStyleSheets.indexOf(sheet)
if (idx !== -1) {
document.adoptedStyleSheets.splice(idx, 1)
}
}
}
function useStyle(callback: () => CSSStyleSheet | false | undefined | null | "", dependencies: unknown[]) { function useStyle(callback: () => CSSStyleSheet | false | undefined | null | "", dependencies: unknown[]) {
useInsertionEffect(() => { useInsertionEffect(() => {
const sheet = callback() const sheet = callback()
if (!sheet) { if (!sheet) {
return return
} }
document.adoptedStyleSheets.push(sheet) return pushSheet(sheet)
return () => {
const idx = document.adoptedStyleSheets.indexOf(sheet)
if (idx !== -1) {
document.adoptedStyleSheets.splice(idx, 1)
}
}
}, dependencies) }, dependencies)
} }
function useAsyncStyle(callback: () => string | false | undefined | null, dependencies: unknown[]) { function useAsyncStyle(callback: () => string | false | undefined | null, dependencies: unknown[], id?: string) {
useInsertionEffect(() => { useInsertionEffect(() => {
const sheet = callback() const sheet = callback()
if (!sheet) { if (!sheet) {
return return
} }
if (!sheet.includes("@import")) {
return pushSheet(newStyleSheet(sheet))
}
const styleTags = document.createElement("style") const styleTags = document.createElement("style")
if (id) {
styleTags.id = id
}
styleTags.textContent = sheet styleTags.textContent = sheet
document.head.appendChild(styleTags) document.head.appendChild(styleTags)
return () => { return () => {
@ -116,8 +126,8 @@ const StylePreferences = ({ client, activeRoom }: StylePreferencesProps) => {
} }
` : ` ` : `
@import url("_gomuks/codeblock/${preferences.code_block_theme}.css"); @import url("_gomuks/codeblock/${preferences.code_block_theme}.css");
`, [preferences.code_block_theme]) `, [preferences.code_block_theme], "gomuks-pref-code-block-theme")
useStyle(() => preferences.custom_css && newStyleSheet(preferences.custom_css), [preferences.custom_css]) useAsyncStyle(() => preferences.custom_css, [preferences.custom_css], "gomuks-pref-custom-css")
return null return null
} }