cleanup: switch to $state for themes

This commit is contained in:
James Xylight committed 2025-02-10 17:34:40 -08:00
1 parent a5ba6d66f6
commit 80df5c5409
19 files changed
+161 -341

No files matched your search

@@ -6,14 +6,14 @@
message: string message: string
} }
export let errors = writable<PageScopedError[]>([]) let errors = $state<PageScopedError[]>([])
export function pushError(args: { scope: string; message: string }) { export function pushError(args: { scope: string; message: string }) {
errors.update((e) => [...e, args]) errors.push(args)
} }
export function clearErrorScope(scope: string | null | undefined) { export function clearErrorScope(scope: string | null | undefined) {
errors.update((errors) => errors.filter((error) => error.scope != scope)) errors = errors.filter((error) => error.scope != scope)
} }
</script> </script>
@@ -35,7 +35,7 @@
let { scope = undefined, class: clazz = '' }: Props = $props() let { scope = undefined, class: clazz = '' }: Props = $props()
let scopedErrors = $derived( let scopedErrors = $derived(
$errors.filter((e) => e.scope == scope || e.scope == 'global'), errors.filter((e) => e.scope == scope || e.scope == 'global'),
) )
</script> </script>
-44
View File
@@ -1,44 +0,0 @@
<script lang="ts">
import { createBubbler } from 'svelte/legacy'
const bubble = createBubbler()
interface Props {
value: number
min?: number
max?: number
step?: number
}
let { value = $bindable(), min = 0, max = 100, step = 1 }: Props = $props()
</script>
<input
type="range"
bind:value
{min}
{max}
{step}
onchange={bubble('change')}
onclick={bubble('click')}
onkeydown={bubble('keydown')}
onkeypress={bubble('keypress')}
class="w-full appearance-none h-2 cursor-pointer bg-slate-100 dark:bg-zinc-800
rounded-full range"
/>
<style lang="postcss">
.range::-moz-range-thumb {
border-radius: 50%;
width: 12px;
height: 12px;
@apply border-4 bg-white dark:bg-zinc-900 border-primary-900 dark:border-primary-100;
transition: all 0.25s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.range:hover::-moz-range-thumb {
transform: scale(125%);
}
.range:active::-moz-range-thumb {
transform: scale(90%);
}
</style>
+4 -6
View File
@@ -1,8 +1,6 @@
<script lang="ts"> <script lang="ts">
import { run } from 'svelte/legacy'
import { expoOut } from 'svelte/easing' import { expoOut } from 'svelte/easing'
import { tweened } from 'svelte/motion' import { Tween } from 'svelte/motion'
interface Props { interface Props {
progress?: number progress?: number
@@ -10,14 +8,14 @@
let { progress = 0 }: Props = $props() let { progress = 0 }: Props = $props()
let tween = tweened(progress, { easing: expoOut }) let tween = new Tween(progress, { easing: expoOut })
run(() => { $effect(() => {
tween.set(progress) tween.set(progress)
}) })
</script> </script>
<div <div
class="bg-primary-900 dark:bg-primary-100 h-1 rounded-full" class="bg-primary-900 dark:bg-primary-100 h-1 rounded-full"
style="width: {$tween * 100}%;" style="width: {tween.current * 100}%;"
></div> ></div>
+2 -2
View File
@@ -87,7 +87,7 @@
<script lang="ts"> <script lang="ts">
import { settings } from '$lib/settings.svelte.js' import { settings } from '$lib/settings.svelte.js'
import { themeVars } from '$lib/ui/colors' import { theme } from '$lib/ui/colors.svelte'
import { writable, type Readable, type Writable } from 'svelte/store' import { writable, type Readable, type Writable } from 'svelte/store'
import type { ClassValue } from 'svelte/elements' import type { ClassValue } from 'svelte/elements'
@@ -127,7 +127,7 @@
<div <div
{...rest} {...rest}
class="shell bg-slate-50 dark:bg-zinc-950 {clazz}" class="shell bg-slate-50 dark:bg-zinc-950 {clazz}"
style={$themeVars} style={theme.vars}
> >
{@render children?.()} {@render children?.()}
<div <div
@@ -10,14 +10,12 @@
import { Button, Menu, MenuButton, MenuDivider, Spinner } from 'mono-svelte' import { Button, Menu, MenuButton, MenuDivider, Spinner } from 'mono-svelte'
import { import {
GlobeAlt, GlobeAlt,
Home,
Icon, Icon,
MagnifyingGlass, MagnifyingGlass,
Newspaper, Newspaper,
PencilSquare, PencilSquare,
Plus, Plus,
ServerStack, ServerStack,
XMark,
} from 'svelte-hero-icons' } from 'svelte-hero-icons'
import Profile from './Profile.svelte' import Profile from './Profile.svelte'
import NavButton from './NavButton.svelte' import NavButton from './NavButton.svelte'
+9 -5
View File
@@ -33,7 +33,7 @@
UserCircle, UserCircle,
UserGroup, UserGroup,
} from 'svelte-hero-icons' } from 'svelte-hero-icons'
import { colorScheme } from '$lib/ui/colors' import { theme } from '$lib/ui/colors.svelte'
import { settings } from '$lib/settings.svelte' import { settings } from '$lib/settings.svelte'
import { site } from '$lib/lemmy.svelte' import { site } from '$lib/lemmy.svelte'
import SiteCard from '$lib/components/lemmy/SiteCard.svelte' import SiteCard from '$lib/components/lemmy/SiteCard.svelte'
@@ -149,11 +149,11 @@
<MenuButton class="!py-0"> <MenuButton class="!py-0">
{#snippet prefix()} {#snippet prefix()}
<Icon <Icon
src={$colorScheme == 'system' src={theme.colorScheme == 'system'
? ComputerDesktop ? ComputerDesktop
: $colorScheme == 'light' : theme.colorScheme == 'light'
? Sun ? Sun
: $colorScheme == 'dark' : theme.colorScheme == 'dark'
? Moon ? Moon
: Moon} : Moon}
micro micro
@@ -164,7 +164,11 @@
<!-- svelte-ignore a11y_click_events_have_key_events --> <!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions --> <!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="contents" onclick={stopPropagation(() => {})}> <div class="contents" onclick={stopPropagation(() => {})}>
<Select bind:value={$colorScheme} class="ml-auto my-auto w-24" size="sm"> <Select
bind:value={theme.colorScheme}
class="ml-auto my-auto w-24"
size="sm"
>
<Option value="system" icon={ComputerDesktop}> <Option value="system" icon={ComputerDesktop}>
{$t('nav.menu.colorscheme.system')} {$t('nav.menu.colorscheme.system')}
</Option> </Option>
@@ -11,7 +11,7 @@
import { afterNavigate, goto } from '$app/navigation' import { afterNavigate, goto } from '$app/navigation'
import { profile, profileData } from '$lib/auth.svelte' import { profile, profileData } from '$lib/auth.svelte'
import { getGroups, type Action, type Group } from './actions.svelte' import { getGroups, type Action, type Group } from './actions.svelte'
import { themeData } from '$lib/ui/colors' import { theme } from '$lib/ui/colors.svelte'
import { page } from '$app/state' import { page } from '$app/state'
interface Props { interface Props {
@@ -26,7 +26,7 @@
$resumables, $resumables,
profile.data, profile.data,
profileData.profiles, profileData.profiles,
$themeData, theme.data,
page.data.contextual?.actions, page.data.contextual?.actions,
) )
}) })
@@ -8,7 +8,7 @@ import {
import { resumables, type ResumableItem } from '$lib/lemmy/item' import { resumables, type ResumableItem } from '$lib/lemmy/item'
import { settings } from '$lib/settings.svelte' import { settings } from '$lib/settings.svelte'
import { t } from '$lib/translations' import { t } from '$lib/translations'
import { colorScheme, theme, themeData, type ThemeData } from '$lib/ui/colors' import { theme, type ThemeData } from '$lib/ui/colors.svelte'
import { fullCommunityName } from '$lib/util.svelte' import { fullCommunityName } from '$lib/util.svelte'
import { import {
ArrowRightOnRectangle, ArrowRightOnRectangle,
@@ -357,21 +357,21 @@ export function getGroups(
name: t.get('nav.commands.setColorTo', { name: t.get('nav.commands.setColorTo', {
default: t.get('nav.menu.colorscheme.system'), default: t.get('nav.menu.colorscheme.system'),
}), }),
handle: () => colorScheme.set('system'), handle: () => (theme.colorScheme = 'system'),
icon: ComputerDesktop, icon: ComputerDesktop,
}, },
{ {
name: t.get('nav.commands.setColorTo', { name: t.get('nav.commands.setColorTo', {
default: t.get('nav.menu.colorscheme.light'), default: t.get('nav.menu.colorscheme.light'),
}), }),
handle: () => colorScheme.set('light'), handle: () => (theme.colorScheme = 'light'),
icon: Sun, icon: Sun,
}, },
{ {
name: t.get('nav.commands.setColorTo', { name: t.get('nav.commands.setColorTo', {
default: t.get('nav.menu.colorscheme.dark'), default: t.get('nav.menu.colorscheme.dark'),
}), }),
handle: () => colorScheme.set('dark'), handle: () => (theme.colorScheme = 'dark'),
icon: Moon, icon: Moon,
}, },
], ],
@@ -382,11 +382,7 @@ export function getGroups(
subActions: td.themes.map((th) => ({ subActions: td.themes.map((th) => ({
name: t.get('nav.commands.setThemeTo', { default: th.name }), name: t.get('nav.commands.setThemeTo', { default: th.name }),
icon: Swatch, icon: Swatch,
handle: () => handle: () => (theme.data.currentTheme = th.id),
themeData.update((td) => ({
...td,
currentTheme: th.id,
})),
})), })),
}, },
], ],
-91
View File
@@ -1,91 +0,0 @@
enum SwipeDirection {
Up = 'up',
Down = 'down',
Left = 'left',
Right = 'right',
None = 'none',
}
export function swipeGesture(
node: HTMLElement,
swipe: (dir: SwipeDirection) => any,
) {
let touchstartX = 0
let touchstartY = 0
let touchendX = 0
let touchendY = 0
node?.addEventListener(
'touchstart',
function (event) {
// @ts-ignore
touchstartX = event?.screenX
// @ts-ignore
touchstartY = event?.screenY
},
false,
)
node?.addEventListener(
'mousedown',
function (event) {
// @ts-ignore
touchstartX = event?.screenX
// @ts-ignore
touchstartY = event?.screenY
},
false,
)
node?.addEventListener(
'mouseup',
function (event) {
// @ts-ignore
touchendX = event.screenX
// @ts-ignore
touchendY = event.screenY
return swipe(swipeDir(touchstartX, touchstartY, touchendX, touchendY))
},
false,
)
node?.addEventListener(
'touchend',
function (event) {
// @ts-ignore
touchendX = event.screenX
// @ts-ignore
touchendY = event.screenY
return swipe(swipeDir(touchstartX, touchstartY, touchendX, touchendY))
},
false,
)
}
function swipeDir(
touchStartX: number,
touchStartY: number,
touchEndX: number,
touchEndY: number,
): SwipeDirection {
const deltaX = touchEndX - touchStartX
const deltaY = touchEndY - touchStartY
// Define a threshold for the minimum swipe distance
const minSwipeDistance = 10 // Adjust this value as needed
// Check the absolute difference between deltaX and deltaY
if (Math.abs(deltaX) >= Math.abs(deltaY)) {
// Horizontal swipe
if (Math.abs(deltaX) >= minSwipeDistance) {
return deltaX > 0 ? SwipeDirection.Right : SwipeDirection.Left
}
} else {
// Vertical swipe
if (Math.abs(deltaY) >= minSwipeDistance) {
return deltaY > 0 ? SwipeDirection.Down : SwipeDirection.Up
}
}
return SwipeDirection.None
}
-3
View File
@@ -1,6 +1,3 @@
import { publishedToDate } from '$lib/components/util/date.js'
import { getClient } from '$lib/lemmy.svelte.js'
import type { Result } from '$lib/lemmy/item.js'
import type { import type {
Comment, Comment,
CommentReplyView, CommentReplyView,
+2 -7
View File
@@ -104,17 +104,12 @@ function resumableStore(limit: number = 10) {
export let resumables = resumableStore() export let resumables = resumableStore()
export function addFavorite(item: Community, add: boolean = true) { export function addFavorite(item: Community, add: boolean = true) {
const pd = get(profileData) let favs = profile.data.favorites ?? []
const p = pd.profiles.find((p) => p.id == profile.data?.id)
if (!p) return
let favs = p.favorites ?? []
if (favs.map((fav) => fav.id).includes(item.id)) if (add) return if (favs.map((fav) => fav.id).includes(item.id)) if (add) return
if (!add) { if (!add) {
favs.splice(favs.map((c) => c.id).indexOf(item.id), 1) favs.splice(favs.map((c) => c.id).indexOf(item.id), 1)
} else { } else {
favs.unshift(item) favs.unshift(item)
} }
p.favorites = favs profile.data.favorites = favs
profileData.update(() => pd)
} }
+6 -10
View File
@@ -22,23 +22,19 @@ export const addSubscription = (
community: Community, community: Community,
subscribe: boolean = true, subscribe: boolean = true,
) => { ) => {
const p = profile const index = profile.data.user?.follows
.map((f) => f.community.id)
if (!p.user) return .indexOf(community.id)
const index = p.user.follows.map((f) => f.community.id).indexOf(community.id)
if (subscribe && index == -1) { if (subscribe && index == -1) {
p.user.follows.push({ profile.data.user?.follows.push({
// @ts-ignore // @ts-ignore
follower: p.user.follows[0]?.follower, follower: p.user.follows[0]?.follower,
community: community, community: community,
}) })
} else { } else {
p.user.follows.splice(index, 1) profile.data.user?.follows.splice(index ?? 0, 1)
} }
profile.data.set(p)
} }
export const addAdmin = async (handle: string, added: boolean, jwt: string) => export const addAdmin = async (handle: string, added: boolean, jwt: string) =>
@@ -56,4 +52,4 @@ export const addAdmin = async (handle: string, added: boolean, jwt: string) =>
}) })
export const hasFavorite = (profile: Profile, id: number): boolean => export const hasFavorite = (profile: Profile, id: number): boolean =>
profile.data?.favorites?.map((i) => i.id).includes(id) ?? false profile.favorites?.map((i) => i.id).includes(id) ?? false
View File
Whitespace-only changes.
@@ -2,9 +2,7 @@ import {
derived, derived,
get, get,
writable, writable,
type Stores,
type Updater, type Updater,
type Unsubscriber,
type Writable, type Writable,
type Readable, type Readable,
} from 'svelte/store' } from 'svelte/store'
@@ -79,55 +77,89 @@ export function rgbToHex(rgbString: string): string {
return `#${toHex(r)}${toHex(g)}${toHex(b)}` return `#${toHex(r)}${toHex(g)}${toHex(b)}`
} }
function themeStore( $effect.root(() => {
data: Writable<ThemeData>, $effect(() => {
fn: ( if (browser) {
values: ThemeData, const filteredThemes = theme.data.themes.filter((t) => t.id > 0)
set: (value: Theme) => void, localStorage.setItem(
update: (fn: Updater<Theme>) => void, 'theme.data',
) => any, JSON.stringify({
) { ...theme.data,
const derive: Readable<Theme> = derived(data, fn) themes: filteredThemes,
const { subscribe } = derive }),
)
return { }
subscribe,
set: (value: Theme) => {
data.update((data) => {
let index = data.themes.findIndex((t) => t.id == value.id)
data.themes[index] = value
return data
}) })
}, })
const configuredColorScheme = env.PUBLIC_COLORSCHEME ?? 'system'
class ThemeState {
constructor() {
const localColorScheme: ColorScheme =
(localStorage.getItem('colorScheme') as ColorScheme) ||
configuredColorScheme
this.#colorScheme = localColorScheme
if (browser) {
const prefersDark = window.matchMedia(
'(prefers-color-scheme: dark)',
).matches
const html = document.querySelector('html')
if (this.#colorScheme == 'system')
html?.classList.toggle('dark', prefersDark)
else html?.classList.toggle('dark', this.#colorScheme === 'dark')
localStorage.setItem('colorScheme', this.#colorScheme)
} }
} }
export let themeData = writable<ThemeData>( #data = $state<ThemeData>(
loadTheme() ?? { loadTheme() ?? {
scheme: 'system', scheme: 'system',
themes: presets, themes: presets,
currentTheme: 0, currentTheme: 0,
}, },
) )
#current = $derived(
themeData.subscribe((themeData) => { this.#data.themes.find((i) => i.id == this.#data.currentTheme) ??
if (browser) { getDefaultTheme(),
const filteredThemes = themeData.themes.filter((t) => t.id > 0)
localStorage.setItem(
'themeData',
JSON.stringify({
...themeData,
themes: filteredThemes,
}),
) )
#colorScheme = $state<ColorScheme>(configuredColorScheme as ColorScheme)
#vars = $derived(calculateVars(this.#current))
get current() {
return this.#current
}
set current(value) {
if (!value) return
const index = this.#data.themes.findIndex((i) => i.id == value?.id)
this.#data.themes[index] = value
} }
})
export let theme = themeStore( get colorScheme() {
themeData, return this.#colorScheme
(data) => }
data.themes.find((t) => t.id == data.currentTheme) ?? getDefaultTheme(), set colorScheme(value) {
) this.#colorScheme = value
}
get vars() {
return this.#vars
}
get data() {
return this.#data
}
set data(value) {
this.#data = value
}
}
export let theme = new ThemeState()
export function calculateVars(theme: Theme) { export function calculateVars(theme: Theme) {
let cssVariables = '' let cssVariables = ''
@@ -141,59 +173,18 @@ export function calculateVars(theme: Theme) {
return cssVariables.trim() return cssVariables.trim()
} }
export const themeVars = derived(theme, (t) => calculateVars(t as Theme))
const configuredColorScheme = env.PUBLIC_COLORSCHEME ?? 'system'
export const colorScheme = writable<ColorScheme>(
configuredColorScheme as ColorScheme,
)
export const toggleColorScheme = () => {
colorScheme.update((colorScheme) => {
if (colorScheme == 'light') return 'dark'
else if (colorScheme == 'dark') return 'system'
else return 'light'
})
}
export const inDarkColorScheme = (): boolean => { export const inDarkColorScheme = (): boolean => {
if (typeof window != 'undefined') { if (browser) {
return get(colorScheme) == 'system' return theme.colorScheme == 'system'
? window.matchMedia('(prefers-color-scheme: dark)').matches ? window.matchMedia('(prefers-color-scheme: dark)').matches
: get(colorScheme) == 'dark' : theme.colorScheme == 'dark'
} }
return false return false
} }
function loadColorScheme() {
const localColorScheme: ColorScheme =
(localStorage.getItem('colorScheme') as ColorScheme) ||
configuredColorScheme
colorScheme.update((colorScheme) => localColorScheme)
colorScheme.subscribe((colorScheme) => {
if (typeof document != 'undefined') {
const prefersDark = window.matchMedia(
'(prefers-color-scheme: dark)',
).matches
const html = document.querySelector('html')
if (colorScheme == 'system') {
html?.classList.toggle('dark', prefersDark)
} else {
html?.classList.toggle('dark', colorScheme === 'dark')
}
localStorage.setItem('colorScheme', colorScheme)
}
})
}
function loadTheme() { function loadTheme() {
if (!browser) return if (!browser) return
const localTheme = localStorage.getItem('themeData') const localTheme = localStorage.getItem('theme.data')
if (localTheme) { if (localTheme) {
const data = JSON.parse(localTheme) const data = JSON.parse(localTheme)
@@ -204,27 +195,3 @@ function loadTheme() {
return return
} }
if (browser) {
try {
loadColorScheme()
} catch (e) {}
try {
const oldColors = localStorage.getItem('colors')
if (oldColors) {
themeData.update((td) => ({
...td,
currentTheme: Math.max(...td.themes.map((t) => t.id)) + 1,
themes: [
...td.themes,
{
id: Math.max(...td.themes.map((t) => t.id)) + 1,
colors: JSON.parse(oldColors),
name: t.get('routes.theme.preset.imported') || 'Your Theme',
},
],
}))
localStorage.removeItem('colors')
}
} catch (e) {}
}
+1 -1
View File
@@ -1,5 +1,5 @@
import { env } from '$env/dynamic/public' import { env } from '$env/dynamic/public'
import type { Theme, ThemeColors } from './colors' import type { Theme, ThemeColors } from './colors.svelte'
export function getDefaultColors(): ThemeColors { export function getDefaultColors(): ThemeColors {
return env.PUBLIC_THEME return env.PUBLIC_THEME
+8 -13
View File
@@ -6,13 +6,7 @@
import 'nprogress/nprogress.css' import 'nprogress/nprogress.css'
import Moderation from '$lib/components/lemmy/moderation/Moderation.svelte' import Moderation from '$lib/components/lemmy/moderation/Moderation.svelte'
import Sidebar from '$lib/components/ui/sidebar/Sidebar.svelte' import Sidebar from '$lib/components/ui/sidebar/Sidebar.svelte'
import { import { inDarkColorScheme, rgbToHex, theme } from '$lib/ui/colors.svelte.js'
colorScheme,
inDarkColorScheme,
rgbToHex,
theme,
themeVars,
} from '$lib/ui/colors.js'
import { settings } from '$lib/settings.svelte.js' import { settings } from '$lib/settings.svelte.js'
import { import {
Button, Button,
@@ -55,9 +49,6 @@
) )
} }
document.body.querySelector('.loader')?.classList.add('hidden') document.body.querySelector('.loader')?.classList.add('hidden')
themeVars.subscribe((vars) => {
document.body.setAttribute('style', vars)
})
} }
}) })
@@ -82,6 +73,10 @@
) )
} }
}) })
$effect(() => {
document.body.setAttribute('style', theme.vars)
})
} }
$effect(() => { $effect(() => {
@@ -96,9 +91,9 @@
<meta <meta
name="theme-color" name="theme-color"
content={rgbToHex( content={rgbToHex(
$colorScheme && inDarkColorScheme() theme.colorScheme && inDarkColorScheme()
? ($theme.colors.zinc?.[925] ?? getDefaultColors().zinc[925]) ? (theme.current.colors.zinc?.[925] ?? getDefaultColors().zinc[925])
: ($theme.colors.slate?.[25] ?? getDefaultColors().slate[25]), : (theme.current.colors.slate?.[25] ?? getDefaultColors().slate[25]),
)} )}
/> />
{#if LINKED_INSTANCE_URL} {#if LINKED_INSTANCE_URL}
+28 -23
View File
@@ -21,7 +21,7 @@
import ColorSwatch from './ColorSwatch.svelte' import ColorSwatch from './ColorSwatch.svelte'
import { t } from '$lib/translations' import { t } from '$lib/translations'
import Header from '$lib/components/ui/layout/pages/Header.svelte' import Header from '$lib/components/ui/layout/pages/Header.svelte'
import { calculateVars, hexToRgb, theme, themeData } from '$lib/ui/colors' import { theme as themeData } from '$lib/ui/colors.svelte'
import { getDefaultColors } from '$lib/ui/presets' import { getDefaultColors } from '$lib/ui/presets'
import ThemePreset from './ThemePreset.svelte' import ThemePreset from './ThemePreset.svelte'
@@ -39,7 +39,7 @@
if (importText == '') { if (importText == '') {
throw new Error('Import is empty') throw new Error('Import is empty')
} }
$theme.colors = JSON.parse(importText) themeData.current.colors = JSON.parse(importText)
toast({ content: $t('message.success'), type: 'success' }) toast({ content: $t('message.success'), type: 'success' })
importing = false importing = false
} catch (err) { } catch (err) {
@@ -70,20 +70,20 @@
class="grid grid-cols-1 @md:grid-cols-2 @xl:grid-cols-3 @3xl:grid-cols-4 class="grid grid-cols-1 @md:grid-cols-2 @xl:grid-cols-3 @3xl:grid-cols-4
gap-2" gap-2"
> >
{#each $themeData.themes as theme, index} {#each themeData.data.themes as theme, index}
<ThemePreset bind:theme={$themeData.themes[index]} /> <ThemePreset bind:theme={themeData.data.themes[index]} />
{/each} {/each}
<button <button
onclick={() => { onclick={() => {
const newTheme = { const newTheme = {
id: Math.max(...$themeData.themes.map((t) => t.id)) + 1, id: Math.max(...themeData.data.themes.map((t) => t.id)) + 1,
colors: getDefaultColors(), colors: getDefaultColors(),
name: $t('routes.theme.preset.new'), name: $t('routes.theme.preset.new'),
} }
$themeData.themes = [...$themeData.themes, newTheme] themeData.data.themes = [...themeData.data.themes, newTheme]
$themeData.currentTheme = newTheme.id themeData.data.currentTheme = newTheme.id
}} }}
> >
<Material <Material
@@ -105,14 +105,14 @@
importing = !importing importing = !importing
}} }}
size="lg" size="lg"
disabled={$theme.id <= 0} disabled={themeData.current.id <= 0}
> >
<Icon src={ArrowUpTray} size="16" mini /> <Icon src={ArrowUpTray} size="16" mini />
{$t('routes.theme.import')} {$t('routes.theme.import')}
</Button> </Button>
<Button <Button
onclick={() => { onclick={() => {
navigator.clipboard.writeText(JSON.stringify($theme.colors)) navigator.clipboard.writeText(JSON.stringify(themeData.current.colors))
toast({ content: 'Copied theme to clipboard.' }) toast({ content: 'Copied theme to clipboard.' })
}} }}
size="lg" size="lg"
@@ -121,7 +121,7 @@
{$t('routes.theme.export')} {$t('routes.theme.export')}
</Button> </Button>
<Button <Button
disabled={$theme.id <= 0} disabled={themeData.current.id <= 0}
onclick={() => { onclick={() => {
modal({ modal({
actions: [ actions: [
@@ -131,7 +131,12 @@
}), }),
action({ action({
action: () => { action: () => {
$theme.colors = { other: {}, primary: {}, zinc: {}, slate: {} } themeData.current.colors = {
other: {},
primary: {},
zinc: {},
slate: {},
}
}, },
content: $t('routes.theme.reset'), content: $t('routes.theme.reset'),
close: true, close: true,
@@ -148,15 +153,15 @@
{$t('routes.theme.reset')} {$t('routes.theme.reset')}
</Button> </Button>
</div> </div>
{#if $theme.id <= 0} {#if themeData.current.id <= 0}
<Note> <Note>
{$t('routes.theme.preset.description')} {$t('routes.theme.preset.description')}
</Note> </Note>
{/if} {/if}
<div <div
class="relative" class="relative"
class:opacity-50={$theme.id <= 0} class:opacity-50={themeData.current.id <= 0}
class:pointer-events-none={$theme.id <= 0} class:pointer-events-none={themeData.current.id <= 0}
> >
<Material <Material
color="transparent" color="transparent"
@@ -164,13 +169,13 @@
> >
<h1 class="text-2xl font-bold col-span-2">{$t('routes.theme.accent')}</h1> <h1 class="text-2xl font-bold col-span-2">{$t('routes.theme.accent')}</h1>
<ColorSwatch <ColorSwatch
value={$theme.colors.primary?.[900]} value={themeData.current.colors.primary?.[900]}
onchange={(e) => { onchange={(e) => {
$theme.colors.primary[900] = e themeData.current.colors.primary[900] = e
}} }}
oncontextmenu={(e) => { oncontextmenu={(e) => {
e.preventDefault() e.preventDefault()
$theme.colors.primary[900] = themeData.current.colors.primary[900] =
// @ts-ignore // @ts-ignore
defaultColors.primary[900] defaultColors.primary[900]
@@ -179,13 +184,13 @@
class="!w-12 !h-12 col-span-1" class="!w-12 !h-12 col-span-1"
/> />
<ColorSwatch <ColorSwatch
value={$theme.colors.primary?.[100]} value={themeData.current.colors.primary?.[100]}
onchange={(e) => { onchange={(e) => {
$theme.colors.primary[100] = e themeData.current.colors.primary[100] = e
}} }}
oncontextmenu={(e) => { oncontextmenu={(e) => {
e.preventDefault() e.preventDefault()
$theme.colors.primary[100] = themeData.current.colors.primary[100] =
// @ts-ignore // @ts-ignore
defaultColors.primary[100] defaultColors.primary[100]
@@ -209,13 +214,13 @@
<div class="flex flex-col gap-0.5 w-10 group"> <div class="flex flex-col gap-0.5 w-10 group">
<!--@ts-ignore--> <!--@ts-ignore-->
<ColorSwatch <ColorSwatch
bind:value={$theme.colors[category][shade]} bind:value={themeData.current.colors[category][shade]}
onchange={(e) => { onchange={(e) => {
$theme.colors[category][shade] = e themeData.current.colors[category][shade] = e
}} }}
oncontextmenu={(e) => { oncontextmenu={(e) => {
e.preventDefault() e.preventDefault()
$theme.colors[category][shade] = themeData.current.colors[category][shade] =
// @ts-ignore // @ts-ignore
defaultColors[category][shade] defaultColors[category][shade]
+1 -4
View File
@@ -1,8 +1,5 @@
<script lang="ts"> <script lang="ts">
import { createBubbler } from 'svelte/legacy' import { hexToRgb } from '$lib/ui/colors.svelte'
import { hexToRgb } from '$lib/ui/colors'
import { createEventDispatcher } from 'svelte'
interface Props { interface Props {
value: string value: string
+15 -8
View File
@@ -2,7 +2,11 @@
import { preventDefault } from 'svelte/legacy' import { preventDefault } from 'svelte/legacy'
import { t } from '$lib/translations' import { t } from '$lib/translations'
import { calculateVars, themeData, type Theme } from '$lib/ui/colors' import {
calculateVars,
theme as themeData,
type Theme,
} from '$lib/ui/colors.svelte'
import { action, Button, Material, modal, TextInput } from 'mono-svelte' import { action, Button, Material, modal, TextInput } from 'mono-svelte'
import { CheckCircle, Icon, Trash } from 'svelte-hero-icons' import { CheckCircle, Icon, Trash } from 'svelte-hero-icons'
@@ -15,10 +19,10 @@
let editingName = $state(false) let editingName = $state(false)
</script> </script>
<button class="h-full" onclick={() => ($themeData.currentTheme = theme.id)}> <button class="h-full" onclick={() => (themeData.data.currentTheme = theme.id)}>
<Material <Material
padding="none" padding="none"
class="{theme.id == $themeData.currentTheme class="{theme.id == themeData.data.currentTheme
? 'ring-2 ring-inset ring-primary-900 dark:ring-primary-100' ? 'ring-2 ring-inset ring-primary-900 dark:ring-primary-100'
: ''} flex relative cursor-pointer h-full flex-col text-left p-0.5" : ''} flex relative cursor-pointer h-full flex-col text-left p-0.5"
rounding="xl" rounding="xl"
@@ -38,7 +42,7 @@
class="w-3 h-3 bg-primary-900 dark:bg-primary-100 rounded-full ml-auto" class="w-3 h-3 bg-primary-900 dark:bg-primary-100 rounded-full ml-auto"
></div> ></div>
</div> </div>
{#if theme.id == $themeData.currentTheme} {#if theme.id == themeData.data.currentTheme}
<Icon <Icon
src={CheckCircle} src={CheckCircle}
size="20" size="20"
@@ -79,13 +83,16 @@
content: $t('routes.theme.preset.delete.confirm'), content: $t('routes.theme.preset.delete.confirm'),
type: 'danger', type: 'danger',
action: () => { action: () => {
const index = $themeData.themes const index = themeData.data.themes
.map((t) => t.id) .map((t) => t.id)
.indexOf(theme.id) .indexOf(theme.id)
$themeData.themes = $themeData.themes.toSpliced(index, 1) themeData.data.themes = themeData.data.themes.toSpliced(
if (theme.id == $themeData.currentTheme) { index,
$themeData.currentTheme = 0 1,
)
if (theme.id == themeData.data.currentTheme) {
themeData.data.currentTheme = 0
} }
}, },
}), }),