Merge pull request #373 from Xyphyn/new-theme-handler

feat: remake theme handling
This commit is contained in:
Xylight authored and GitHub committed 2024-07-25 12:32:25 -07:00
commit e40d3c5b4a
13 files changed
+684 -281

No files matched your search

@@ -1,5 +1,4 @@
<script lang="ts">
import { Color } from '$lib/ui/colors'
import {
ArrowDownCircle,
ArrowUp,
+33 -16
View File
@@ -4,7 +4,7 @@
top: boolean | null
noGap: boolean | null
},
screenWidth: number,
screenWidth: number
): {
noGap: boolean
top: boolean
@@ -35,7 +35,7 @@
export const calculatePadding = (
panel: boolean,
top: boolean,
content: boolean,
content: boolean
): {
top: number
class: string
@@ -62,13 +62,13 @@
})
export let contentPadding: Readable<ReturnType<typeof calculatePadding>> =
derived(dockProps, ($dockProps, set) =>
set(calculatePadding($dockProps.noGap, $dockProps.top, true)),
set(calculatePadding($dockProps.noGap, $dockProps.top, true))
)
</script>
<script lang="ts">
import { userSettings } from '$lib/settings.js'
import { colors, colorsToVars } from '$lib/ui/colors'
import { themeVars } from '$lib/ui/colors'
import { routes } from '$lib/util.js'
import { derived, writable, type Readable, type Writable } from 'svelte/store'
@@ -84,8 +84,8 @@
<div
{...$$restProps}
class="shell {$$props.class}"
style={colorsToVars($colors)}
class="shell bg-slate-50 dark:bg-zinc-950 {$$props.class}"
style={$themeVars}
>
<slot />
<div
@@ -109,10 +109,10 @@
: 'border rounded-full'}
dark:bg-transparent transition-colors duration-500
pointer-events-auto {topPanel
? 'bg-slate-50 dark:bg-zinc-950 border-slate-100 dark:border-zinc-900'
: `border-slate-200 dark:border-zinc-800 shadow-2xl backdrop-blur-xl
dark:backdrop-brightness-[25%] bg-[#ffffff]/75`}"
pointer-events-auto backdrop-blur-xl {topPanel
? 'bg-slate-50/50 dark:bg-zinc-950/90 border-slate-100 dark:border-zinc-900'
: `border-slate-200 dark:border-zinc-800 shadow-2xl
bg-white/50 dark:bg-zinc-925/70`}"
{title}
style="transition: border-radius 250ms;"
/>
@@ -124,7 +124,7 @@
>
<slot
name="sidebar"
class="hidden md:flex sticky top-0 left-0 max-w-full h-max bg-slate-50 dark:bg-zinc-950
class="hidden md:flex sticky top-0 left-0 h-max bg-slate-50 dark:bg-zinc-950
z-40
{sidePadding.class}"
style="grid-area: sidebar; width: 100% !important;"
@@ -132,7 +132,7 @@
<slot
name="main"
class="w-full bg-slate-25 dark:bg-zinc-925 justify-self-center shadow-sm z-0
{$contentPadding.class}"
{$contentPadding.class} main"
style="grid-area: main"
/>
<slot
@@ -163,6 +163,11 @@
grid-template-areas: 'main';
justify-items: start;
}
.content > * {
width: 100%; /* Full width for immediate children */
max-width: 100rem; /* Limit width */
padding: 0 1rem; /* Add some padding on smaller screens */
}
@media (min-width: 768px) {
.content {
@@ -174,13 +179,25 @@
@media (min-width: 1280px) {
.content {
grid-template-columns: 20% 1fr 20%;
grid-template-columns: 20% 60% 20%;
justify-items: end center start;
grid-template-areas: 'sidebar main suffix';
}
}
.limit-width {
max-width: 100rem;
.content:is(.limit-width) {
grid-template-columns: 1fr 2fr 1fr;
}
:global(.content:is(.limit-width) > *:first-child) {
max-width: 20rem;
justify-self: end;
width: 100%;
}
:global(.content:is(.limit-width) > *:last-child) {
max-width: 20rem;
justify-self: start;
width: 100%;
}
}
</style>
+5 -5
View File
@@ -31,7 +31,7 @@
UserCircle,
UserGroup,
} from 'svelte-hero-icons'
import { legacyTheme } from '$lib/ui/colors'
import { colorScheme } from '$lib/ui/colors'
import { userSettings } from '$lib/settings'
import { site } from '$lib/lemmy'
import SiteCard from '$lib/components/lemmy/SiteCard.svelte'
@@ -127,11 +127,11 @@
</MenuButton>
<MenuButton class="!py-0">
<Icon
src={$legacyTheme == 'system'
src={$colorScheme == 'system'
? ComputerDesktop
: $legacyTheme == 'light'
: $colorScheme == 'light'
? Sun
: $legacyTheme == 'dark'
: $colorScheme == 'dark'
? Moon
: Moon}
mini
@@ -142,7 +142,7 @@
<!-- svelte-ignore a11y-click-events-have-key-events -->
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div class="contents" on:click|stopPropagation={() => {}}>
<Select bind:value={$legacyTheme} class="ml-auto my-auto w-24" size="sm">
<Select bind:value={$colorScheme} class="ml-auto my-auto w-24" size="sm">
<option value="system">{$t('nav.menu.colorscheme.system')}</option>
<option value="light">{$t('nav.menu.colorscheme.light')}</option>
<option value="dark">{$t('nav.menu.colorscheme.dark')}</option>
@@ -8,7 +8,7 @@ import {
import { resumables, type ResumableItem } from '$lib/lemmy/item'
import { userSettings } from '$lib/settings'
import { t } from '$lib/translations'
import { legacyTheme } from '$lib/ui/colors'
import { colorScheme } from '$lib/ui/colors'
import { fullCommunityName } from '$lib/util'
import {
ArrowRightOnRectangle,
@@ -354,21 +354,21 @@ export function getGroups(
name: t.get('nav.commands.setColorTo', {
default: t.get('nav.menu.colorscheme.system'),
}),
handle: () => legacyTheme.set('system'),
handle: () => colorScheme.set('system'),
icon: ComputerDesktop,
},
{
name: t.get('nav.commands.setColorTo', {
default: t.get('nav.menu.colorscheme.light'),
}),
handle: () => legacyTheme.set('light'),
handle: () => colorScheme.set('light'),
icon: Sun,
},
{
name: t.get('nav.commands.setColorTo', {
default: t.get('nav.menu.colorscheme.dark'),
}),
handle: () => legacyTheme.set('dark'),
handle: () => colorScheme.set('dark'),
icon: Moon,
},
],
+12
View File
@@ -359,6 +359,18 @@
"resetWarning": {
"title": "Reset Theme",
"description": "This will reset all of your colors to the default. It is recommended to export your theme before this."
},
"preset": {
"title": "Can't be modified",
"description": "This is a default theme, and can't be modified.",
"delete": {
"title": "Delete Theme",
"confirm": "Confirm"
},
"default": "Default",
"classic": "Classic",
"imported": "Your Theme",
"new": "New Theme"
}
},
"community": {
+181 -150
View File
@@ -1,184 +1,178 @@
/**
* This enum represents a UI color as tailwind classes.
*/
export enum Color {
'accent' = 'border border-black dark:border-white bg-black text-white\
dark:bg-white dark:text-black hover:text-inherit hover:bg-transparent hover:dark:bg-transparent active:bg-black/10 active:dark:bg-white/10',
'ghost' = 'bg-black/5 dark:bg-white/5 hover:bg-black/10 hover:dark:bg-white/10 text-black dark:text-white border border-transparent',
'secondary' = 'hover:bg-black/10 hover:dark:bg-white/10 text-black dark:text-white fill-black dark:fill-white',
'danger' = 'border border-red-500 bg-red-500 text-white hover:text-red-500 hover:bg-transparent',
'dangerSecondary' = 'hover:bg-red-500 text-red-500 hover:text-white',
'border' = 'border border-slate-200 dark:border-zinc-700 bg-slate-100 dark:bg-zinc-800 hover:bg-slate-200 hover:dark:bg-zinc-700',
'borderDark' = 'border border-slate-200 dark:border-zinc-800 bg-slate-100 dark:bg-zinc-900 hover:bg-slate-200 hover:dark:bg-zinc-800',
}
import { get, writable } from 'svelte/store'
import {
derived,
get,
writable,
type Stores,
type Updater,
type Unsubscriber,
type Writable,
type Readable,
} from 'svelte/store'
import { env } from '$env/dynamic/public'
import { getDefaultTheme, presets } from './presets'
import { browser } from '$app/environment'
import { t } from '$lib/translations'
interface ColorData {
theme: number
themes: Colors[]
type ColorScheme = 'system' | 'light' | 'dark'
export interface ThemeData {
scheme: ColorScheme
themes: Theme[]
currentTheme: number
}
interface Theme {
colors: Colors
name: string
export interface Theme {
id: number
colors: ThemeColors
name: string
}
export interface Colors {
slate: {
25?: string
50?: string
100?: string
200?: string
400?: string
500?: string
600?: string
700?: string
800?: string
900?: string
925?: string
950?: string
}
zinc: {
100?: string
200?: string
300?: string
400?: string
500?: string
600?: string
700?: string
800?: string
900?: string
925?: string
950?: string
}
primary: {
100?: string
900?: string
}
other: {
black?: string
white?: string
export interface ThemeColors {
[scheme: string]: {
[key: string]: string
}
}
export const defaultColors = {
slate: {
25: `var(--c-s-25,#fcfdfe)`,
50: `var(--c-s-50,#f8fafc)`,
100: `var(--c-s-100,#f1f5f9)`,
200: `var(--c-s-200,#e2e8f0)`,
300: `var(--c-s-300,#cbd5e1)`,
400: `var(--c-s-400,#94a3b8)`,
500: `var(--c-s-500,#64748b)`,
600: `var(--c-s-600,#475569)`,
700: `var(--c-s-700,#334155)`,
800: `var(--c-s-800,#1e293b)`,
900: `var(--c-s-900,#0f172a`,
950: `var(--c-s-950,#020617)`,
},
zinc: {
50: `var(--c-z-50,#fafafa)`,
100: `var(--c-z-100,#f4f4f5)`,
200: `var(--c-z-200,#e4e4e7)`,
300: `var(--c-z-300,#d4d4d8)`,
400: `var(--c-z-400,#a1a1aa)`,
500: `var(--c-z-500,#71717a)`,
600: `var(--c-z-600,#52525b)`,
700: 'var(--c-z-700,#34343b)',
800: 'var(--c-z-800,#1f1f24)',
900: 'var(--c-z-900,#121215)',
925: 'var(--c-z-925,#0c0c0e)',
950: `var(--c-z-950,#09090b)`,
},
primary: {
100: 'var(--c-p-100,#f1f5f9)',
900: 'var(--c-p-900,#0f172a)',
},
other: {
black: `#000`,
white: `var(--c-o-white,#fff)`,
},
export function hexToRgb(value: string) {
// Regular expression to match valid hex color codes
const hexRegex = /^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/
if (!hexRegex.test(value)) {
return value // Not a valid hex color
}
// Remove # if present
let hex = value.replace('#', '')
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
if (hex.length === 3) {
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]
}
// Convert to RGB values
const r = parseInt(hex.substring(0, 2), 16)
const g = parseInt(hex.substring(2, 4), 16)
const b = parseInt(hex.substring(4, 6), 16)
return `${r} ${g} ${b}`
}
export let colors = writable<Colors>({
slate: {},
zinc: {},
primary: {},
other: {},
})
export function rgbToHex(rgbString: string): string {
const rgb = rgbString.split(' ')
export function colorsToVars(colors: Colors): string {
let vars: string[] = []
for (let category in colors) {
for (let shade in colors[category as keyof Colors]) {
if (category)
// @ts-ignore
vars.push(
`--c-${category.slice(0, 1)}-${shade}:${colors[category][shade]}`
)
if (rgb.length !== 3) {
return rgbString
}
const [r, g, b] = rgb.map((val) => {
const num = parseInt(val, 10)
if (isNaN(num) || num < 0 || num > 255) {
return 0
}
}
return vars.join(';')
}
export const colorToVar = (
category: keyof Colors,
shade: keyof (keyof Colors)
): string => `--c-${category.slice(0, 2)}-${shade.toString()}`
function loadColors() {
const loaded = localStorage.getItem('colors')
if (loaded) {
colors.set(JSON.parse(loaded))
}
colors.subscribe((v) => {
localStorage.setItem('colors', JSON.stringify(v))
return num
})
// Convert to hex and pad with zeros if necessary
const toHex = (n: number) => n.toString(16).padStart(2, '0')
// Return the hex color code
return `#${toHex(r)}${toHex(g)}${toHex(b)}`
}
if (browser) {
loadColors()
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
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 configuredLegacyTheme = env.PUBLIC_LEGACYTHEME ?? 'system'
export const legacyTheme = writable<'system' | 'light' | 'dark'>(
configuredLegacyTheme as 'system' | 'light' | 'dark'
export let themeData = writable<ThemeData>(
loadTheme() ?? {
scheme: 'system',
themes: presets,
currentTheme: 0,
}
)
export const toggleLegacyTheme = () => {
legacyTheme.update((legacyTheme) => {
if (legacyTheme == 'light') {
return 'dark'
} else if (legacyTheme == 'dark') {
return 'system'
} else {
return 'light'
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 function calculateVars(theme: Theme) {
let cssVariables = ''
for (const [scheme, colors] of Object.entries(theme.colors)) {
for (const [key, value] of Object.entries(colors)) {
cssVariables += `--c-${scheme[0]}-${key}:${hexToRgb(value)}; `
}
}
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 inDarkLegacyTheme = (): boolean => {
export const inDarkColorScheme = (): boolean => {
if (typeof window != 'undefined') {
return get(legacyTheme) == 'system'
return get(colorScheme) == 'system'
? window.matchMedia('(prefers-color-scheme: dark)').matches
: get(legacyTheme) == 'dark'
: get(colorScheme) == 'dark'
}
return false
}
if (typeof localStorage != 'undefined') {
const localLegacyTheme: 'system' | 'light' | 'dark' =
(localStorage.getItem('legacyTheme') as 'system' | 'light' | 'dark') ||
configuredLegacyTheme
function loadColorScheme() {
const localColorScheme: ColorScheme =
(localStorage.getItem('colorScheme') as ColorScheme) ||
configuredColorScheme
legacyTheme.update((legacyTheme) => localLegacyTheme)
colorScheme.update((colorScheme) => localColorScheme)
legacyTheme.subscribe((legacyTheme) => {
colorScheme.subscribe((colorScheme) => {
if (typeof document != 'undefined') {
const prefersDark = window.matchMedia(
'(prefers-color-scheme: dark)'
@@ -186,13 +180,50 @@ if (typeof localStorage != 'undefined') {
const html = document.querySelector('html')
if (legacyTheme == 'system') {
if (colorScheme == 'system') {
html?.classList.toggle('dark', prefersDark)
} else {
html?.classList.toggle('dark', legacyTheme === 'dark')
html?.classList.toggle('dark', colorScheme === 'dark')
}
localStorage.setItem('legacyTheme', legacyTheme)
localStorage.setItem('colorScheme', colorScheme)
}
})
}
function loadTheme() {
if (!browser) return
const localTheme = localStorage.getItem('themeData')
if (localTheme) {
const data = JSON.parse(localTheme)
if (!data) return
data.themes = [...presets, ...data.themes]
return data
}
return
}
if (browser) {
try {
loadColorScheme()
} catch (e) {}
try {
const oldColors = localStorage.getItem('colors')
if (oldColors) {
themeData.update((td) => ({
...td,
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) {}
}
+168
View File
@@ -0,0 +1,168 @@
import { env } from '$env/dynamic/public'
import type { Theme, ThemeColors } from './colors'
export function getDefaultColors(): ThemeColors {
return env.PUBLIC_THEME
? JSON.parse(env.PUBLIC_THEME)
: {
slate: {
25: '252 253 254',
50: '248 250 252',
100: '241 245 249',
200: '226 232 240',
300: '203 213 225',
400: '148 163 184',
500: '100 116 139',
600: '71 85 105',
700: '51 65 85',
800: '30 41 59',
900: '15 23 42',
950: '2 6 23',
},
zinc: {
50: '250 253 255',
100: '243 244 246',
300: '209 213 219',
400: '156 163 175',
500: '107 114 128',
600: '75 85 99',
700: '55 65 81',
800: '22 31 45',
900: '12 18 32',
925: '8 12 25',
950: '3 7 18',
},
primary: {
100: '241 245 249',
900: '15 23 42',
},
other: {
black: `0 0 0`,
white: `255 255 255`,
},
}
}
export function getDefaultTheme(): Theme {
return {
id: 0,
colors: getDefaultColors(),
name: 'Default',
}
}
export const presets: Theme[] = [
getDefaultTheme(),
{
colors: {
slate: {
25: '252 253 254',
50: '248 250 252',
100: '241 245 249',
200: '226 232 240',
300: '203 213 225',
400: '148 163 184',
500: '100 116 139',
600: '71 85 105',
700: '51 65 85',
800: '30 41 59',
900: '15 23 42',
950: '2 6 23',
},
zinc: {
50: '250 250 250',
100: '244 244 245',
200: '228 228 231',
300: '212 212 216',
400: '161 161 170',
500: '113 113 122',
600: '82 82 91',
700: '52 52 59',
800: '31 31 36',
900: '18 18 21',
925: '12 12 14',
950: '9 9 11',
},
primary: {
100: '241 245 249',
900: '15 23 42',
},
other: {
black: '0 0 0',
white: '255 255 255',
},
},
id: -1,
name: 'Classic',
},
{
colors: {
slate: {
25: '252 253 254',
50: '248 250 252',
100: '241 245 249',
200: '226 232 240',
300: '203 213 225',
400: '148 163 184',
500: '100 116 139',
600: '71 85 105',
700: '51 65 85',
800: '30 41 59',
900: '15 23 42',
950: '2 6 23',
},
zinc: {
50: `249 250 251`,
100: `243 244 246`,
200: `229 231 235`,
300: `209 213 219`,
400: `156 163 175`,
500: `107 114 128`,
600: `75 85 99`,
700: '30 30 30',
800: '22 22 22',
900: '10 10 10',
925: '0 0 0',
950: `0 0 0`,
},
primary: {
100: '241 245 249',
900: '15 23 42',
},
other: {
black: `0 0 0`,
white: `255 255 255`,
},
},
id: -2,
name: 'AMOLED',
},
{
colors: {
zinc: {
50: '205 214 244',
100: '186 194 222',
200: '166 173 200',
300: '147 153 178',
400: '127 132 156',
500: '108 112 134',
600: '88 91 112',
700: '69 71 90',
800: '49 50 68',
900: '30 30 46',
925: '24 24 37',
950: '17 17 27',
},
primary: {
100: '166 227 161',
900: '114 135 253',
},
other: {
white: '255 255 255',
},
slate: {},
},
id: -3,
name: 'Catppuccin',
},
]