Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(runtime): update & allow access to updateStyle() #1770

Merged
merged 1 commit into from Oct 18, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 20 additions & 3 deletions packages/runtime/src/index.ts
@@ -1,4 +1,4 @@
import type { UnoGenerator, UserConfig, UserConfigDefaults } from '@unocss/core'
import type { GenerateResult, UnoGenerator, UserConfig, UserConfigDefaults } from '@unocss/core'
import { createGenerator } from '@unocss/core'
import { autoPrefixer, decodeHtml } from './utils'

Expand Down Expand Up @@ -69,6 +69,13 @@ export interface RuntimeContext {
*/
toggleObserver: (state?: boolean) => void

/**
* Manually run the update cycle.
*
* @returns {GenerateResult & { styleElement: HTMLStyleElement}}
*/
update: () => Promise<GenerateResult & { styleElement: HTMLStyleElement }>

/**
* The UnoCSS version.
*
Expand Down Expand Up @@ -137,14 +144,23 @@ export default function init(inlineConfig: RuntimeOptions = {}) {
})
}

async function updateStyle() {
const result = await uno.generate(tokens)
function getStyleElement() {
if (!styleElement) {
styleElement = document.createElement('style')
document.documentElement.prepend(styleElement)
}
return styleElement
}

async function updateStyle() {
const result = await uno.generate(tokens)
const styleElement = getStyleElement()
styleElement.innerHTML = result.css
tokens = result.matched
return {
...result,
styleElement,
}
}

async function extract(str: string) {
Expand Down Expand Up @@ -247,6 +263,7 @@ export default function init(inlineConfig: RuntimeOptions = {}) {
if (!observing && !paused)
ready()
},
update: updateStyle,
}

if (runtime?.ready?.(unoCssRuntime) !== false) {
Expand Down