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
+169 -349

No files matched your search

@@ -6,14 +6,14 @@
message: string
}
export let errors = writable<PageScopedError[]>([])
let errors = $state<PageScopedError[]>([])
export function pushError(args: { scope: string; message: string }) {
errors.update((e) => [...e, args])
errors.push(args)
}
export function clearErrorScope(scope: string | null | undefined) {
errors.update((errors) => errors.filter((error) => error.scope != scope))
errors = errors.filter((error) => error.scope != scope)
}
</script>
@@ -35,7 +35,7 @@
let { scope = undefined, class: clazz = '' }: Props = $props()
let scopedErrors = $derived(
$errors.filter((e) => e.scope == scope || e.scope == 'global'),
errors.filter((e) => e.scope == scope || e.scope == 'global'),
)
</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">
import { run } from 'svelte/legacy'
import { expoOut } from 'svelte/easing'
import { tweened } from 'svelte/motion'
import { Tween } from 'svelte/motion'
interface Props {
progress?: number
@@ -10,14 +8,14 @@
let { progress = 0 }: Props = $props()
let tween = tweened(progress, { easing: expoOut })
let tween = new Tween(progress, { easing: expoOut })
run(() => {
$effect(() => {
tween.set(progress)
})
</script>
<div
class="bg-primary-900 dark:bg-primary-100 h-1 rounded-full"
style="width: {$tween * 100}%;"
style="width: {tween.current * 100}%;"
></div>
+2 -2
View File
@@ -87,7 +87,7 @@
<script lang="ts">
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 type { ClassValue } from 'svelte/elements'
@@ -127,7 +127,7 @@
<div
{...rest}
class="shell bg-slate-50 dark:bg-zinc-950 {clazz}"
style={$themeVars}
style={theme.vars}
>
{@render children?.()}
<div
@@ -10,14 +10,12 @@
import { Button, Menu, MenuButton, MenuDivider, Spinner } from 'mono-svelte'
import {
GlobeAlt,
Home,
Icon,
MagnifyingGlass,
Newspaper,
PencilSquare,
Plus,
ServerStack,
XMark,
} from 'svelte-hero-icons'
import Profile from './Profile.svelte'
import NavButton from './NavButton.svelte'
+9 -5
View File
@@ -33,7 +33,7 @@
UserCircle,
UserGroup,
} from 'svelte-hero-icons'
import { colorScheme } from '$lib/ui/colors'
import { theme } from '$lib/ui/colors.svelte'
import { settings } from '$lib/settings.svelte'
import { site } from '$lib/lemmy.svelte'
import SiteCard from '$lib/components/lemmy/SiteCard.svelte'
@@ -149,11 +149,11 @@
<MenuButton class="!py-0">
{#snippet prefix()}
<Icon
src={$colorScheme == 'system'
src={theme.colorScheme == 'system'
? ComputerDesktop
: $colorScheme == 'light'
: theme.colorScheme == 'light'
? Sun
: $colorScheme == 'dark'
: theme.colorScheme == 'dark'
? Moon
: Moon}
micro
@@ -164,7 +164,11 @@
<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<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}>
{$t('nav.menu.colorscheme.system')}
</Option>
@@ -11,7 +11,7 @@
import { afterNavigate, goto } from '$app/navigation'
import { profile, profileData } from '$lib/auth.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'
interface Props {
@@ -26,7 +26,7 @@
$resumables,
profile.data,
profileData.profiles,
$themeData,
theme.data,
page.data.contextual?.actions,
)
})
@@ -8,7 +8,7 @@ import {
import { resumables, type ResumableItem } from '$lib/lemmy/item'
import { settings } from '$lib/settings.svelte'
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 {
ArrowRightOnRectangle,
@@ -357,21 +357,21 @@ export function getGroups(
name: t.get('nav.commands.setColorTo', {
default: t.get('nav.menu.colorscheme.system'),
}),
handle: () => colorScheme.set('system'),
handle: () => (theme.colorScheme = 'system'),
icon: ComputerDesktop,
},
{
name: t.get('nav.commands.setColorTo', {
default: t.get('nav.menu.colorscheme.light'),
}),
handle: () => colorScheme.set('light'),
handle: () => (theme.colorScheme = 'light'),
icon: Sun,
},
{
name: t.get('nav.commands.setColorTo', {
default: t.get('nav.menu.colorscheme.dark'),
}),
handle: () => colorScheme.set('dark'),
handle: () => (theme.colorScheme = 'dark'),
icon: Moon,
},
],
@@ -382,11 +382,7 @@ export function getGroups(
subActions: td.themes.map((th) => ({
name: t.get('nav.commands.setThemeTo', { default: th.name }),
icon: Swatch,
handle: () =>
themeData.update((td) => ({
...td,
currentTheme: th.id,
})),
handle: () => (theme.data.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 {
Comment,
CommentReplyView,
+2 -7
View File
@@ -104,17 +104,12 @@ function resumableStore(limit: number = 10) {
export let resumables = resumableStore()
export function addFavorite(item: Community, add: boolean = true) {
const pd = get(profileData)
const p = pd.profiles.find((p) => p.id == profile.data?.id)
if (!p) return
let favs = p.favorites ?? []
let favs = profile.data.favorites ?? []
if (favs.map((fav) => fav.id).includes(item.id)) if (add) return
if (!add) {
favs.splice(favs.map((c) => c.id).indexOf(item.id), 1)
} else {
favs.unshift(item)
}
p.favorites = favs
profileData.update(() => pd)
profile.data.favorites = favs
}
+6 -10
View File
@@ -22,23 +22,19 @@ export const addSubscription = (
community: Community,
subscribe: boolean = true,
) => {
const p = profile
if (!p.user) return
const index = p.user.follows.map((f) => f.community.id).indexOf(community.id)
const index = profile.data.user?.follows
.map((f) => f.community.id)
.indexOf(community.id)
if (subscribe && index == -1) {
p.user.follows.push({
profile.data.user?.follows.push({
// @ts-ignore
follower: p.user.follows[0]?.follower,
community: community,
})
} 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) =>
@@ -56,4 +52,4 @@ export const addAdmin = async (handle: string, added: boolean, jwt: string) =>
})
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,
get,
writable,
type Stores,
type Updater,
type Unsubscriber,
type Writable,
type Readable,
} from 'svelte/store'
@@ -79,55 +77,89 @@ export function rgbToHex(rgbString: string): string {
return `#${toHex(r)}${toHex(g)}${toHex(b)}`
}
function themeStore(
data: Writable<ThemeData>,
fn: (
values: ThemeData,
set: (value: Theme) => void,
update: (fn: Updater<Theme>) => void,
) => any,
) {
const derive: Readable<Theme> = derived(data, fn)
const { subscribe } = derive
$effect.root(() => {
$effect(() => {
if (browser) {
const filteredThemes = theme.data.themes.filter((t) => t.id > 0)
localStorage.setItem(
'theme.data',
JSON.stringify({
...theme.data,
themes: filteredThemes,
}),
)
}
})
})
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)
}
}
#data = $state<ThemeData>(
loadTheme() ?? {
scheme: 'system',
themes: presets,
currentTheme: 0,
},
)
#current = $derived(
this.#data.themes.find((i) => i.id == this.#data.currentTheme) ??
getDefaultTheme(),
)
#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
}
get colorScheme() {
return this.#colorScheme
}
set colorScheme(value) {
this.#colorScheme = value
}
get vars() {
return this.#vars
}
get data() {
return this.#data
}
set data(value) {
this.#data = value
}
}
export let themeData = writable<ThemeData>(
loadTheme() ?? {
scheme: 'system',
themes: presets,
currentTheme: 0,
},
)
themeData.subscribe((themeData) => {
if (browser) {
const filteredThemes = themeData.themes.filter((t) => t.id > 0)
localStorage.setItem(
'themeData',
JSON.stringify({
...themeData,
themes: filteredThemes,
}),
)
}
})
export let theme = themeStore(
themeData,
(data) =>
data.themes.find((t) => t.id == data.currentTheme) ?? getDefaultTheme(),
)
export let theme = new ThemeState()
export function calculateVars(theme: Theme) {
let cssVariables = ''
@@ -141,59 +173,18 @@ export function calculateVars(theme: Theme) {
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 => {
if (typeof window != 'undefined') {
return get(colorScheme) == 'system'
if (browser) {
return theme.colorScheme == 'system'
? window.matchMedia('(prefers-color-scheme: dark)').matches
: get(colorScheme) == 'dark'
: theme.colorScheme == 'dark'
}
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() {
if (!browser) return
const localTheme = localStorage.getItem('themeData')
const localTheme = localStorage.getItem('theme.data')
if (localTheme) {
const data = JSON.parse(localTheme)
@@ -204,27 +195,3 @@ function loadTheme() {
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 type { Theme, ThemeColors } from './colors'
import type { Theme, ThemeColors } from './colors.svelte'
export function getDefaultColors(): ThemeColors {
return env.PUBLIC_THEME