@tamagui/next-theme 1.0.1-beta.57 → 1.0.1-beta.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tamagui/next-theme",
3
- "version": "1.0.1-beta.57",
3
+ "version": "1.0.1-beta.61",
4
4
  "sideEffects": false,
5
5
  "source": "src/index.ts",
6
6
  "types": "./types/index.d.ts",
@@ -8,6 +8,7 @@
8
8
  "module": "dist/esm",
9
9
  "module:jsx": "dist/jsx",
10
10
  "files": [
11
+ "src",
11
12
  "types",
12
13
  "dist"
13
14
  ],
@@ -16,13 +17,13 @@
16
17
  "watch": "tamagui-build --watch"
17
18
  },
18
19
  "dependencies": {
19
- "@tamagui/core": "^1.0.1-beta.57"
20
+ "@tamagui/core": "^1.0.1-beta.61"
20
21
  },
21
22
  "peerDependencies": {
22
23
  "react": "*"
23
24
  },
24
25
  "devDependencies": {
25
- "@tamagui/build": "^1.0.1-beta.57",
26
+ "@tamagui/build": "^1.0.1-beta.61",
26
27
  "react": "*"
27
28
  },
28
29
  "publishConfig": {
@@ -0,0 +1,364 @@
1
+ // https://raw.githubusercontent.com/pacocoursey/next-themes/master/index.tsx
2
+ // forked temporarily due to buggy theme change
3
+
4
+ import NextHead from 'next/head'
5
+ import React, {
6
+ createContext,
7
+ memo,
8
+ useCallback,
9
+ useContext,
10
+ useEffect,
11
+ useLayoutEffect,
12
+ useMemo,
13
+ useRef,
14
+ useState,
15
+ } from 'react'
16
+
17
+ const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect
18
+
19
+ export interface UseThemeProps {
20
+ /** List of all available theme names */
21
+ themes: string[]
22
+ /** Forced theme name for the current page */
23
+ forcedTheme?: string
24
+ /** Update the theme */
25
+ setTheme: (theme: string) => void
26
+ toggleTheme: () => void
27
+ /** Active theme name */
28
+ theme?: string
29
+ /** If `enableSystem` is true and the active theme is "system", this returns whether the system preference resolved to "dark" or "light". Otherwise, identical to `theme` */
30
+ resolvedTheme?: string
31
+ /** If enableSystem is true, returns the System theme preference ("dark" or "light"), regardless what the active theme is */
32
+ systemTheme?: 'dark' | 'light'
33
+ }
34
+
35
+ export interface ThemeProviderProps {
36
+ /** List of all available theme names */
37
+ themes?: string[]
38
+ /** Forced theme name for the current page */
39
+ forcedTheme?: string
40
+ /** Whether to switch between dark and light themes based on prefers-color-scheme */
41
+ enableSystem?: boolean
42
+ systemTheme?: string
43
+ /** Disable all CSS transitions when switching themes */
44
+ disableTransitionOnChange?: boolean
45
+ /** Whether to indicate to browsers which color scheme is used (dark or light) for built-in UI like inputs and buttons */
46
+ enableColorScheme?: boolean
47
+ /** Key used to store theme setting in localStorage */
48
+ storageKey?: string
49
+ /** Default theme name (for v0.0.12 and lower the default was light). If `enableSystem` is false, the default theme is light */
50
+ defaultTheme?: string
51
+ /** HTML attribute modified based on the active theme. Accepts `class` and `data-*` (meaning any data attribute, `data-mode`, `data-color`, etc.) */
52
+ attribute?: string | 'class'
53
+ /** Mapping of theme name to HTML attribute value. Object where key is the theme name and value is the attribute value */
54
+ value?: ValueObject
55
+
56
+ onChangeTheme?: (name: string) => void
57
+ }
58
+
59
+ const ThemeContext = createContext<UseThemeProps>({
60
+ toggleTheme: () => {},
61
+ setTheme: (_) => {},
62
+ themes: [],
63
+ })
64
+ export const useTheme = () => useContext(ThemeContext)
65
+
66
+ const colorSchemes = ['light', 'dark']
67
+ const MEDIA = '(prefers-color-scheme: dark)'
68
+
69
+ interface ValueObject {
70
+ [themeName: string]: string
71
+ }
72
+
73
+ export const useRootTheme = () => {
74
+ const isClient = typeof document !== 'undefined'
75
+ // @ts-ignore
76
+ const classes = isClient ? [...document.documentElement.classList] : []
77
+ const isDark = classes.includes('tui_dark')
78
+ return useState(isDark ? 'dark' : 'light')
79
+ }
80
+
81
+ export const NextThemeProvider: React.FC<ThemeProviderProps> = ({
82
+ forcedTheme,
83
+ disableTransitionOnChange = true,
84
+ enableSystem = true,
85
+ enableColorScheme = true,
86
+ storageKey = 'theme',
87
+ themes = ['light', 'dark'],
88
+ defaultTheme = enableSystem ? 'system' : 'light',
89
+ attribute = 'class',
90
+ onChangeTheme,
91
+ value = {
92
+ dark: 'tui_dark',
93
+ light: 'tui_light',
94
+ },
95
+ children,
96
+ }) => {
97
+ const [theme, setThemeState] = useState(() => getTheme(storageKey, defaultTheme))
98
+ const [resolvedTheme, setResolvedTheme] = useState(() => getTheme(storageKey))
99
+ const attrs = !value ? themes : Object.values(value)
100
+
101
+ const handleMediaQuery = useCallback(
102
+ (e?) => {
103
+ const systemTheme = getSystemTheme(e)
104
+ setResolvedTheme(systemTheme)
105
+ if (theme === 'system' && !forcedTheme) handleChangeTheme(systemTheme, false)
106
+ },
107
+ [theme, forcedTheme]
108
+ )
109
+
110
+ // Ref hack to avoid adding handleMediaQuery as a dep
111
+ const mediaListener = useRef(handleMediaQuery)
112
+ mediaListener.current = handleMediaQuery
113
+
114
+ const handleChangeTheme = useCallback((theme, updateStorage = true, updateDOM = true) => {
115
+ let name = value?.[theme] || theme
116
+
117
+ const enable = disableTransitionOnChange && updateDOM ? disableAnimation() : null
118
+
119
+ if (updateStorage) {
120
+ try {
121
+ localStorage.setItem(storageKey, theme)
122
+ } catch (e) {
123
+ // Unsupported
124
+ }
125
+ }
126
+
127
+ if (theme === 'system' && enableSystem) {
128
+ const resolved = getSystemTheme()
129
+ name = value?.[resolved] || resolved
130
+ }
131
+
132
+ onChangeTheme?.(name.replace('tui_', ''))
133
+
134
+ if (updateDOM) {
135
+ const d = document.documentElement
136
+
137
+ if (attribute === 'class') {
138
+ d.classList.remove(...attrs)
139
+ d.classList.add(name)
140
+ } else {
141
+ d.setAttribute(attribute, name)
142
+ }
143
+ enable?.()
144
+ }
145
+ }, [])
146
+
147
+ useIsomorphicLayoutEffect(() => {
148
+ const handler = (...args: any) => mediaListener.current(...args)
149
+ // Always listen to System preference
150
+ const media = window.matchMedia(MEDIA)
151
+ // Intentionally use deprecated listener methods to support iOS & old browsers
152
+ media.addListener(handler)
153
+ handler(media)
154
+ return () => {
155
+ media.removeListener(handler)
156
+ }
157
+ }, [])
158
+
159
+ const setTheme = useCallback(
160
+ (newTheme) => {
161
+ if (forcedTheme) {
162
+ handleChangeTheme(newTheme, true, false)
163
+ } else {
164
+ handleChangeTheme(newTheme)
165
+ }
166
+ setThemeState(newTheme)
167
+ },
168
+ [forcedTheme]
169
+ )
170
+
171
+ // localStorage event handling
172
+ useEffect(() => {
173
+ const handleStorage = (e: StorageEvent) => {
174
+ if (e.key !== storageKey) {
175
+ return
176
+ }
177
+ // If default theme set, use it if localstorage === null (happens on local storage manual deletion)
178
+ const theme = e.newValue || defaultTheme
179
+ setTheme(theme)
180
+ }
181
+ window.addEventListener('storage', handleStorage)
182
+ return () => {
183
+ window.removeEventListener('storage', handleStorage)
184
+ }
185
+ }, [])
186
+
187
+ // color-scheme handling
188
+ useIsomorphicLayoutEffect(() => {
189
+ if (!enableColorScheme) return
190
+
191
+ let colorScheme =
192
+ // If theme is forced to light or dark, use that
193
+ forcedTheme && colorSchemes.includes(forcedTheme)
194
+ ? forcedTheme
195
+ : // If regular theme is light or dark
196
+ theme && colorSchemes.includes(theme)
197
+ ? theme
198
+ : // If theme is system, use the resolved version
199
+ theme === 'system'
200
+ ? resolvedTheme || null
201
+ : null
202
+
203
+ // color-scheme tells browser how to render built-in elements like forms, scrollbars, etc.
204
+ // if color-scheme is null, this will remove the property
205
+ document.documentElement.style.setProperty('color-scheme', colorScheme)
206
+ }, [enableColorScheme, theme, resolvedTheme, forcedTheme])
207
+
208
+ const contextValue = useMemo(() => {
209
+ return {
210
+ theme,
211
+ setTheme,
212
+ toggleTheme() {
213
+ const order =
214
+ resolvedTheme === 'dark' ? ['system', 'light', 'dark'] : ['system', 'dark', 'light']
215
+ const next = order[(order.indexOf(theme) + 1) % order.length]
216
+ setTheme(next)
217
+ },
218
+ forcedTheme,
219
+ resolvedTheme: theme === 'system' ? resolvedTheme : theme,
220
+ themes: enableSystem ? [...themes, 'system'] : themes,
221
+ systemTheme: (enableSystem ? resolvedTheme : undefined) as 'light' | 'dark' | undefined,
222
+ } as const
223
+ }, [theme, forcedTheme, resolvedTheme, enableSystem])
224
+
225
+ return (
226
+ <ThemeContext.Provider value={contextValue}>
227
+ <ThemeScript
228
+ {...{
229
+ forcedTheme,
230
+ storageKey,
231
+ systemTheme: resolvedTheme,
232
+ attribute,
233
+ value,
234
+ enableSystem,
235
+ defaultTheme,
236
+ attrs,
237
+ }}
238
+ />
239
+ {children}
240
+ </ThemeContext.Provider>
241
+ )
242
+ }
243
+
244
+ const ThemeScript = memo(
245
+ ({
246
+ forcedTheme,
247
+ storageKey,
248
+ attribute,
249
+ enableSystem,
250
+ defaultTheme,
251
+ value,
252
+ attrs,
253
+ }: {
254
+ forcedTheme?: string
255
+ storageKey: string
256
+ attribute?: string
257
+ enableSystem?: boolean
258
+ defaultTheme: string
259
+ value?: ValueObject
260
+ attrs: any
261
+ }) => {
262
+ // Code-golfing the amount of characters in the script
263
+ const optimization = (() => {
264
+ if (attribute === 'class') {
265
+ const removeClasses = attrs.map((t: string) => `d.remove('${t}')`).join(';')
266
+ return `var d=document.documentElement.classList;${removeClasses};`
267
+ } else {
268
+ return `var d=document.documentElement;`
269
+ }
270
+ })()
271
+
272
+ const updateDOM = (name: string, literal?: boolean) => {
273
+ name = value?.[name] || name
274
+ const val = literal ? name : `'${name}'`
275
+
276
+ if (attribute === 'class') {
277
+ return `d.add(${val})`
278
+ }
279
+
280
+ return `d.setAttribute('${attribute}', ${val})`
281
+ }
282
+
283
+ const defaultSystem = defaultTheme === 'system'
284
+
285
+ return (
286
+ <NextHead>
287
+ {forcedTheme ? (
288
+ <script
289
+ key="next-themes-script"
290
+ dangerouslySetInnerHTML={{
291
+ // These are minified via Terser and then updated by hand, don't recommend
292
+ // prettier-ignore
293
+ __html: `!function(){${optimization}${updateDOM(forcedTheme)}}()`,
294
+ }}
295
+ />
296
+ ) : enableSystem ? (
297
+ <script
298
+ key="next-themes-script"
299
+ dangerouslySetInnerHTML={{
300
+ // prettier-ignore
301
+ __html: `!function(){try {${optimization}var e=localStorage.getItem('${storageKey}');${!defaultSystem ? updateDOM(defaultTheme) + ';' : ''}if("system"===e||(!e&&${defaultSystem})){var t="${MEDIA}",m=window.matchMedia(t);m.media!==t||m.matches?${updateDOM('dark')}:${updateDOM('light')}}else if(e) ${value ? `var x=${JSON.stringify(value)};` : ''}${updateDOM(value ? 'x[e]' : 'e', true)}}catch(e){}}()`,
302
+ }}
303
+ />
304
+ ) : (
305
+ <script
306
+ key="next-themes-script"
307
+ dangerouslySetInnerHTML={{
308
+ // prettier-ignore
309
+ __html: `!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)};}}catch(t){}}();`,
310
+ }}
311
+ />
312
+ )}
313
+ </NextHead>
314
+ )
315
+ },
316
+ (prevProps, nextProps) => {
317
+ // Only re-render when forcedTheme changes
318
+ // the rest of the props should be completely stable
319
+ if (prevProps.forcedTheme !== nextProps.forcedTheme) return false
320
+ return true
321
+ }
322
+ )
323
+
324
+ // Helpers
325
+ const getTheme = (key: string, fallback?: string) => {
326
+ if (typeof window === 'undefined') return undefined
327
+ let theme
328
+ try {
329
+ theme = localStorage.getItem(key) || undefined
330
+ } catch (e) {
331
+ // Unsupported
332
+ }
333
+ return theme || fallback
334
+ }
335
+
336
+ const disableAnimation = () => {
337
+ const css = document.createElement('style')
338
+ css.appendChild(
339
+ document.createTextNode(
340
+ `*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}`
341
+ )
342
+ )
343
+ document.head.appendChild(css)
344
+
345
+ return () => {
346
+ // Force restyle
347
+ ;(() => window.getComputedStyle(document.body))()
348
+
349
+ // Wait for next tick before removing
350
+ setTimeout(() => {
351
+ document.head.removeChild(css)
352
+ }, 1)
353
+ }
354
+ }
355
+
356
+ const getSystemTheme = (e?: MediaQueryList) => {
357
+ if (!e) {
358
+ e = window.matchMedia(MEDIA)
359
+ }
360
+
361
+ const isDark = e.matches
362
+ const systemTheme = isDark ? 'dark' : 'light'
363
+ return systemTheme
364
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './NextTheme'