* Adds a CSS variable to the document root and updates it based on a callback. * Should be used inside of the setup lifecycle * @param name - Name of the CSS variable (e.g., --my-variable) * @param callback - Callback that returns the value of the CSS variable * @param defaultValue - Def
(
ctx: ChibiCtx,
input: void,
name: string,
callback: ChibiJson<string>,
defaultValue: string = '',
)
| 368 | * ) |
| 369 | */ |
| 370 | addCssVariable( |
| 371 | ctx: ChibiCtx, |
| 372 | input: void, |
| 373 | name: string, |
| 374 | callback: ChibiJson<string>, |
| 375 | defaultValue: string = '', |
| 376 | ) { |
| 377 | const storageKey = `mal-sync-css-var${name}`; |
| 378 | |
| 379 | // eslint-disable-next-line @typescript-eslint/no-floating-promises |
| 380 | asyncFunctions.domReady(ctx, undefined).then(() => { |
| 381 | const savedValue = localStore.getItem(storageKey); |
| 382 | if (savedValue || defaultValue) { |
| 383 | styleSet(savedValue || defaultValue); |
| 384 | } |
| 385 | |
| 386 | ctx.event.on('overview.uiSelector', runCallback); |
| 387 | ctx.event.on('sync.uiSelector', runCallback); |
| 388 | }); |
| 389 | |
| 390 | function styleSet(value: string) { |
| 391 | domFunctions.setStyle(ctx, document.documentElement, name, value, true); |
| 392 | } |
| 393 | async function runCallback() { |
| 394 | let result; |
| 395 | if (ctx.isAsync()) { |
| 396 | result = await ctx.runAsync(callback); |
| 397 | } else { |
| 398 | result = ctx.run(callback); |
| 399 | } |
| 400 | |
| 401 | if (result && result instanceof ChibiReturn) { |
| 402 | result = result.getValue(); |
| 403 | } |
| 404 | |
| 405 | if (result && result !== localStore.getItem(storageKey)) { |
| 406 | styleSet(result); |
| 407 | localStore.setItem(storageKey, result); |
| 408 | } |
| 409 | } |
| 410 | }, |
| 411 | }; |