Skip to content

Commit

Permalink
refactor: drop custom logic in favor of vueuse useDark (#2818)
Browse files Browse the repository at this point in the history
  • Loading branch information
brc-dd committed Aug 19, 2023
1 parent 3c736c1 commit 9499953
Show file tree
Hide file tree
Showing 7 changed files with 49 additions and 87 deletions.
4 changes: 3 additions & 1 deletion docs/reference/site-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,7 @@ When set to `true`, the production app will be built in [MPA Mode](../guide/mpa-

### appearance

- Type: `boolean | 'dark'`
- Type: `boolean | 'dark' | import('@vueuse/core').UseDarkOptions`
- Default: `true`

Whether to enable dark mode (by adding the `.dark` class to the `<html>` element).
Expand All @@ -437,6 +437,8 @@ Whether to enable dark mode (by adding the `.dark` class to the `<html>` element

This option injects an inline script that restores users settings from local storage using the `vitepress-theme-appearance` key. This ensures the `.dark` class is applied before the page is rendered to avoid flickering.

`appearance.initialValue` can only be `'dark' | undefined`. Refs or getters are not supported.

### lastUpdated

- Type: `boolean`
Expand Down
33 changes: 24 additions & 9 deletions src/client/app/data.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
import siteData from '@siteData'
import { useDark } from '@vueuse/core'
import {
type InjectionKey,
type Ref,
computed,
inject,
readonly,
ref,
shallowRef
shallowRef,
type InjectionKey,
type Ref
} from 'vue'
import type { Route } from './router'
import siteData from '@siteData'
import {
type PageData,
type SiteData,
APPEARANCE_KEY,
createTitle,
resolveSiteDataByRoute,
createTitle
type PageData,
type SiteData
} from '../shared'
import type { Route } from './router'

export const dataSymbol: InjectionKey<VitePressData> = Symbol()

Expand Down Expand Up @@ -67,6 +69,19 @@ export function initData(route: Route): VitePressData {
resolveSiteDataByRoute(siteDataRef.value, route.data.relativePath)
)

const isDark = site.value.appearance
? useDark({
storageKey: APPEARANCE_KEY,
initialValue: () =>
typeof site.value.appearance === 'string'
? site.value.appearance
: 'auto',
...(typeof site.value.appearance === 'object'
? site.value.appearance
: {})
})
: ref(false)

return {
site,
theme: computed(() => site.value.themeConfig),
Expand All @@ -82,7 +97,7 @@ export function initData(route: Route): VitePressData {
description: computed(() => {
return route.data.description || site.value.description
}),
isDark: ref(false)
isDark
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/client/theme-default/components/VPSwitch.vue
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
flex-shrink: 0;
border: 1px solid var(--vp-input-border-color);
background-color: var(--vp-input-switch-bg-color);
transition: border-color 0.25s;
transition: border-color 0.25s !important;
}
.VPSwitch:hover {
Expand All @@ -35,7 +35,7 @@
border-radius: 50%;
background-color: var(--vp-c-neutral-inverse);
box-shadow: var(--vp-shadow-1);
transition: transform 0.25s;
transition: transform 0.25s !important;
}
.icon {
Expand All @@ -58,6 +58,6 @@
.dark .icon :deep(svg) {
fill: var(--vp-c-text-1);
transition: opacity 0.25s;
transition: opacity 0.25s !important;
}
</style>
75 changes: 4 additions & 71 deletions src/client/theme-default/components/VPSwitchAppearance.vue
Original file line number Diff line number Diff line change
@@ -1,85 +1,18 @@
<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue'
import { useData } from '../composables/data'
import { inBrowser, APPEARANCE_KEY } from '../../shared'
import VPSwitch from './VPSwitch.vue'
import VPIconSun from './icons/VPIconSun.vue'
import VPIconMoon from './icons/VPIconMoon.vue'
import VPIconSun from './icons/VPIconSun.vue'
const { site, isDark } = useData()
const checked = ref(false)
const toggle = inBrowser ? useAppearance() : () => {}
onMounted(() => {
checked.value = document.documentElement.classList.contains('dark')
})
function useAppearance() {
const query = window.matchMedia('(prefers-color-scheme: dark)')
const classList = document.documentElement.classList
let userPreference = localStorage.getItem(APPEARANCE_KEY)
let isDark =
(site.value.appearance === 'dark' && userPreference == null) ||
(userPreference === 'auto' || userPreference == null
? query.matches
: userPreference === 'dark')
query.onchange = (e) => {
if (userPreference === 'auto') {
setClass((isDark = e.matches))
}
}
function toggle() {
setClass((isDark = !isDark))
userPreference = isDark
? query.matches ? 'auto' : 'dark'
: query.matches ? 'light' : 'auto'
localStorage.setItem(APPEARANCE_KEY, userPreference)
}
function setClass(dark: boolean): void {
const css = document.createElement('style')
css.type = 'text/css'
css.appendChild(
document.createTextNode(
`:not(.VPSwitchAppearance):not(.VPSwitchAppearance *) {
-webkit-transition: none !important;
-moz-transition: none !important;
-o-transition: none !important;
-ms-transition: none !important;
transition: none !important;
}`
)
)
document.head.appendChild(css)
checked.value = dark
classList[dark ? 'add' : 'remove']('dark')
// @ts-expect-error keep unused declaration, used to force the browser to redraw
const _ = window.getComputedStyle(css).opacity
document.head.removeChild(css)
}
return toggle
}
watch(checked, (newIsDark) => {
isDark.value = newIsDark
})
const { isDark } = useData()
</script>

<template>
<VPSwitch
title="toggle dark mode"
class="VPSwitchAppearance"
:aria-checked="checked"
@click="toggle"
:aria-checked="isDark"
@click="isDark = !isDark"
>
<VPIconSun class="sun" />
<VPIconMoon class="moon" />
Expand Down
6 changes: 5 additions & 1 deletion src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,11 @@ function resolveSiteDataHead(userConfig?: UserConfig): HeadConfig[] {
// if appearance mode set to light or dark, default to the defined mode
// in case the user didn't specify a preference - otherwise, default to auto
const fallbackPreference =
userConfig?.appearance !== true ? userConfig?.appearance ?? '' : 'auto'
typeof userConfig?.appearance === 'string'
? userConfig?.appearance
: typeof userConfig?.appearance === 'object'
? userConfig.appearance.initialValue ?? 'auto'
: 'auto'

head.push([
'script',
Expand Down
6 changes: 5 additions & 1 deletion src/node/siteConfig.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Options as VuePluginOptions } from '@vitejs/plugin-vue'
import type { UseDarkOptions } from '@vueuse/core'
import type { SitemapStreamOptions } from 'sitemap'
import type { Logger, UserConfig as ViteConfig } from 'vite'
import type { SitemapItem } from './build/generateSitemap'
Expand Down Expand Up @@ -68,7 +69,10 @@ export interface UserConfig<ThemeConfig = any>

locales?: LocaleConfig<ThemeConfig>

appearance?: boolean | 'dark'
appearance?:
| boolean
| 'dark'
| (Omit<UseDarkOptions, 'initialValue'> & { initialValue?: 'dark' })
lastUpdated?: boolean
contentProps?: Record<string, any>

Expand Down
6 changes: 5 additions & 1 deletion types/shared.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// types shared between server and client
import type { UseDarkOptions } from '@vueuse/core'
import type { SSRContext } from 'vue/server-renderer'
export type { DefaultTheme } from './default-theme.js'

Expand Down Expand Up @@ -55,7 +56,10 @@ export interface SiteData<ThemeConfig = any> {
titleTemplate?: string | boolean
description: string
head: HeadConfig[]
appearance: boolean | 'dark'
appearance:
| boolean
| 'dark'
| (Omit<UseDarkOptions, 'initialValue'> & { initialValue?: 'dark' })
themeConfig: ThemeConfig
scrollOffset:
| number
Expand Down

0 comments on commit 9499953

Please sign in to comment.