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

simplify code in generated <script />. Update index.tsx #175

Closed
wants to merge 6 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 17 additions & 15 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -219,8 +219,8 @@ const ThemeScript = memo(
// MUCH faster to set colorScheme alongside HTML attribute/class
// as it only incurs 1 style recalculation rather than 2
// This can save over 250ms of work for pages with big DOM
if (enableColorScheme && setColorScheme && !literal && colorSchemes.includes(name)) {
text += `d.style.colorScheme = '${name}';`
if (enableColorScheme && setColorScheme) {
text += `d.style.colorScheme = ${val};`
}

if (attribute === 'class') {
Expand All @@ -243,23 +243,25 @@ const ThemeScript = memo(
return `!function(){${optimization}${updateDOM(forcedTheme)}}()`
}

const updateDataAttr = `if(e){${value ? `var x=${JSON.stringify(value)};` : ''}${updateDOM(
value ? `x[e]` : 'e',
true,
false
)}}`
const updateDefaultDataAttr = `else{${updateDOM(defaultTheme, false, false)}}`

if (enableSystem) {
return `!function(){try{${optimization}var e=localStorage.getItem('${storageKey}');if('system'===e||(!e&&${defaultSystem})){var t='${MEDIA}',m=window.matchMedia(t);if(m.media!==t||m.matches){${updateDOM(
'dark'
)}}else{${updateDOM('light')}}}else if(e){${
value ? `var x=${JSON.stringify(value)};` : ''
}${updateDOM(value ? `x[e]` : 'e', true)}}${
!defaultSystem ? `else{` + updateDOM(defaultTheme, false, false) + '}' : ''
return `!function(){try{${optimization}var e=localStorage.getItem('${storageKey}');if(e==='system'${
defaultSystem ? '||!e' : ''
}){var t='${MEDIA}',m=window.matchMedia(t),x=t!==m.media||m.matches?'dark':'light';${updateDOM(
'x',
true
)}}else ${updateDataAttr}${
!defaultSystem ? updateDefaultDataAttr : ''
}${fallbackColorScheme}}catch(e){}}()`
}

return `!function(){try{${optimization}var e=localStorage.getItem('${storageKey}');if(e){${
value ? `var x=${JSON.stringify(value)};` : ''
}${updateDOM(value ? `x[e]` : 'e', true)}}else{${updateDOM(
defaultTheme,
false,
false
)};}${fallbackColorScheme}}catch(t){}}();`
return `!function(){try{${optimization}var e=localStorage.getItem('${storageKey}');${updateDataAttr}${updateDefaultDataAttr}${fallbackColorScheme}}catch(t){}}();`
})()

return <script nonce={nonce} dangerouslySetInnerHTML={{ __html: scriptSrc }} />
Expand Down