impr: restructure src/lib

This commit is contained in:
Xylight committed 2025-09-24 17:12:19 -07:00
1 parent d85b889409
commit 75f907743e
376 files changed
+1000 -1033

No files matched your search

@@ -0,0 +1,55 @@
<script lang="ts">
import { Button } from 'mono-svelte'
import { ArrowUturnDown, Icon, QuestionMarkCircle } from 'svelte-hero-icons'
import type { HTMLButtonAttributes } from 'svelte/elements'
import Avatar from '../../Avatar.svelte'
import type { Action } from './actions.svelte'
import type { Snippet } from 'svelte'
interface Props {
action: Action
class?: string
children?: Snippet
onclick?: HTMLButtonAttributes['onclick']
}
let { action, children, ...rest }: Props = $props()
</script>
<Button
href={action.href}
alignment="left"
color="none"
size="custom"
class="block w-full"
data-sveltekit-preload-code="viewport"
data-sveltekit-preload-data="tap"
{...rest}
>
{#if typeof action.icon === 'string'}
<Avatar url={action.icon} width={20} />
{:else}
<Icon
src={action.icon ?? QuestionMarkCircle}
solid
size="20"
class="text-slate-600 dark:text-zinc-400"
/>
{/if}
{@render children?.()}
<div class="inline-flex flex-col">
<span>{action.name}</span>
{#if action.detail}
<span class="font-normal text-xs">{action.detail}</span>
{/if}
</div>
<div class="flex-1"></div>
{#if action.shortcut}
<div class="flex items-center gap-0.5 text-xs font-medium">
⌘ {action.shortcut}
</div>
{/if}
{#if action.subActions}
<Icon src={ArrowUturnDown} size="16" micro class="" />
{/if}
</Button>
+300
View File
@@ -0,0 +1,300 @@
<script lang="ts">
import { browser } from '$app/environment'
import { goto } from '$app/navigation'
import { page } from '$app/state'
import { profile } from '$lib/app/auth.svelte'
import { t } from '$lib/app/i18n'
import { resumables } from '$lib/lemmy/item'
import { theme } from '$lib/app/theme/theme.svelte'
import { fuzzySearch } from '$lib/util.svelte'
import { TextInput } from 'mono-svelte'
import { createEventDispatcher, onMount } from 'svelte'
import { Home, Icon, MagnifyingGlass } from 'svelte-hero-icons'
import EndPlaceholder from '../../EndPlaceholder.svelte'
import CommonList from '../../layout/CommonList.svelte'
import { getGroups, type Action, type Group } from './actions.svelte'
import CommandItem from './CommandItem.svelte'
interface Props {
open?: boolean
groups?: Group[]
}
let { open = $bindable(false), groups = $bindable([]) }: Props = $props()
$effect(() => {
groups = getGroups(
$resumables,
profile.current,
profile.meta.profiles,
theme.data,
page.data.contextual?.actions,
)
})
let search = $state('')
let container: HTMLElement | undefined = $state()
const dispatch = createEventDispatcher()
let selectedIndex = $state(0)
let filteredGroups: Group[] = $state([])
let breadcrumbs: Action[] = $state([])
let input = $state<HTMLInputElement>()
const debounce = (fn: Function, ms = 300) => {
let timeoutId: ReturnType<typeof setTimeout>
return function (this: any, ...args: any[]) {
clearTimeout(timeoutId)
timeoutId = setTimeout(() => fn.apply(this, args), ms)
}
}
function searchGroup(term: string) {
if (term == '/kill @') {
goto('/you_died')
}
if (term.length < 1) {
if (breadcrumbs.length <= 0) {
filteredGroups = groups.map((group) => ({
...group,
actions: flattenActions(group.actions, false),
}))
}
} else {
filteredGroups = groups
.map((group) => {
const scoredActions = flattenActions(group.actions)
.map((action) => ({
...action,
score: Math.max(
fuzzySearch(action.name, term),
fuzzySearch(group.name, term),
action.detail ? fuzzySearch(action.detail, term) : -1,
),
}))
.filter((action) => action.score > 0)
.sort((a, b) => b.score - a.score)
return {
...group,
actions: scoredActions,
score: Math.max(
fuzzySearch(group.name, term),
...scoredActions.map((a) => a.score),
),
}
})
.filter((group) => group.actions.length > 0)
.sort((a, b) => b.score - a.score)
}
}
const debouncedSearch = debounce((term: string) => searchGroup(term), 50)
function updateFilteredGroups() {
if (breadcrumbs.length === 0) {
filteredGroups = groups
} else {
const lastAction = breadcrumbs[breadcrumbs.length - 1]
filteredGroups = [
{
name: lastAction.name,
actions: lastAction.subActions || [],
},
]
}
selectedIndex = 0
search = ''
}
function goBack() {
breadcrumbs.pop()
updateFilteredGroups()
}
function flattenActions(
actions: Action[],
subaction: boolean = true,
): Action[] {
return actions.flatMap((action) => [
action,
...(action.subActions && subaction
? flattenActions(action.subActions)
: []),
])
}
function togglePalette() {
open = !open
if (open) {
search = ''
selectedIndex = 0
filteredGroups = groups
breadcrumbs = []
}
}
function handleKeydown(event: KeyboardEvent) {
if (event.ctrlKey) {
const actions = groups
.flatMap((g) => g.actions)
.filter((a) => a.shortcut != undefined)
actions.forEach((a) => {
if (event.key === a.shortcut) {
event.preventDefault()
if (a.href) goto(a.href)
if (a.handle) a.handle()
}
})
}
if (!open) return
switch (event.key) {
case 'ArrowDown':
event.preventDefault()
selectedIndex = (selectedIndex + 1) % flattenedActions.length
focusItem(selectedIndex)
break
case 'ArrowUp':
event.preventDefault()
selectedIndex =
(selectedIndex - 1 + flattenedActions.length) %
flattenedActions.length
focusItem(selectedIndex)
break
case 'Enter':
searchGroup(search)
handleSelect(flattenedActions[selectedIndex])
break
case 'Escape':
event.preventDefault()
if (breadcrumbs.length > 0) {
breadcrumbs.pop()
updateFilteredGroups()
} else {
togglePalette()
}
break
}
if (selectedIndex >= flattenedActions.length) selectedIndex = 0
}
function focusItem(index: number) {
if (!browser) return
const listItems = container?.querySelectorAll('li')
if (!listItems) return
listItems[index % listItems.length].focus()
listItems[index % listItems.length].scrollIntoView({
behavior: 'smooth',
block: 'center',
})
}
async function handleSelect(action: Action) {
if (!action) return
if (action.subActions && action.subActions.length > 0) {
breadcrumbs = [...breadcrumbs, action]
updateFilteredGroups()
} else {
if (action.href) goto(action.href)
if (action.handle) action.handle()
togglePalette()
dispatch('select', action)
}
}
$effect(() => {
if (open) search = ''
})
$effect(() => {
debouncedSearch(search)
})
onMount(() => {
if (input) input.focus()
})
let flattenedActions = $derived(
filteredGroups.flatMap((group) => group.actions),
)
</script>
<svelte:window onkeydown={handleKeydown} />
<TextInput
bind:value={search}
class="sticky rounded-none! border-t-0 border-x-0 focus-within:border-inherit! focus-within:ring-0!"
size="lg"
placeholder={$t('nav.commands.prompt')}
bind:element={input}
/>
<div class="h-128 overflow-auto border-slate-200 dark:border-zinc-800 p-5">
{#if breadcrumbs.length > 0}
<div class="flex items-center gap-2 my-1">
<button
class="text-[13px] font-medium text-slate-600 dark:text-zinc-400"
onclick={goBack}
>
<Icon src={Home} size="16" mini />
</button>
{#each breadcrumbs as crumb}
<span class="text-base text-slate-400 dark:text-zinc-600">/</span>
<span class="text-[13px] font-medium">
{crumb.name}
</span>
{/each}
</div>
{/if}
<div class="space-y-1" bind:this={container}>
{#each filteredGroups as group, groupIndex}
<div class="space-y-1">
<EndPlaceholder margin="md" size="sm">{group.name}</EndPlaceholder>
<CommonList size="xs" class="p-0! sm:p-0! lg:p-0!">
{#each group.actions as action, actionIndex}
{@const globalIndex =
filteredGroups
.slice(0, groupIndex)
.reduce((sum, g) => sum + g.actions.length, 0) + actionIndex}
<li
class={[
'custom-size',
globalIndex == selectedIndex &&
'brightness-95 dark:brightness-125',
]}
>
<CommandItem
{action}
onclick={(e) => {
if (action.href) {
togglePalette()
return
}
e.stopPropagation()
handleSelect(action)
}}
/>
</li>
{/each}
</CommonList>
</div>
{/each}
{#if search != ''}
<CommandItem
action={{
name: search,
href: `/search?q=${encodeURIComponent(search)}`,
icon: MagnifyingGlass,
}}
>
<span class="font-normal text-slate-600 dark:text-zinc-400">
{$t('nav.commands.search', { default: '' })}
</span>
</CommandItem>
{/if}
</div>
</div>
@@ -0,0 +1,36 @@
<script lang="ts">
import { t } from '$lib/app/i18n'
import { Modal, TextLoader } from 'mono-svelte'
interface Props {
open?: boolean
}
let { open = $bindable(false) }: Props = $props()
function handleKeydown(event: KeyboardEvent) {
if (
(event.ctrlKey && event.key === 'p') ||
(event.key == '/' && document.activeElement == document.body)
) {
event.preventDefault()
open = !open
}
}
</script>
<svelte:window onkeydown={handleKeydown} />
{#if open}
<Modal bind:open title={null} class="p-0! gap-0!">
{#await import('./Commands.svelte')}
<div class="h-128 flex flex-col gap-2 items-center justify-center">
<TextLoader>
{$t('nav.commands.downloading')}
</TextLoader>
</div>
{:then { default: Commands }}
<Commands bind:open />
{/await}
</Modal>
{/if}
@@ -0,0 +1,414 @@
import { goto } from '$app/navigation'
import { page } from '$app/state'
import {
profile as currentProfile,
type ProfileInfo,
} from '$lib/app/auth.svelte'
import { amModOfAny, isAdmin } from '$comp/lemmy/moderation/moderation'
import { t } from '$lib/app/i18n/translations'
import { type ResumableItem } from '$lib/lemmy/item'
import { settings } from '$lib/settings.svelte'
import { theme, type ThemeData } from '$lib/app/theme/theme.svelte'
import { fullCommunityName } from '$lib/util.svelte'
import {
ArrowRightOnRectangle,
ArrowTrendingDown,
ArrowTrendingUp,
Bookmark,
ChartBar,
ChatBubbleLeftRight,
ChatBubbleOvalLeftEllipsis,
Clock,
Cog6Tooth,
ComputerDesktop,
Fire,
GlobeAlt,
GlobeAmericas,
Home,
Identification,
Inbox,
MapPin,
Moon,
Newspaper,
PaintBrush,
PencilSquare,
Plus,
Scale,
ServerStack,
ShieldCheck,
Star,
Sun,
Swatch,
Trophy,
UserCircle,
UserGroup,
ViewColumns,
type IconSource,
} from 'svelte-hero-icons'
import { SvelteURL } from 'svelte/reactivity'
export interface Group {
name: string
actions: Action[]
}
export interface Action {
name: string
desc?: string
handle?: () => void
href?: string
shortcut?: string
icon: string | IconSource
subActions?: Action[]
detail?: string
}
export function getGroups(
resumables: ResumableItem[],
profile: ProfileInfo,
profiles: ProfileInfo[],
td: ThemeData,
contextual?: Action[],
) {
return [
{
name: t.get('nav.commands.recents'),
actions: resumables.map((r) => ({
name: r.name,
icon: r.avatar ?? PencilSquare,
href: r.url,
})),
},
{
name: t.get('nav.commands.contextual'),
actions: contextual ?? [],
},
{
name: t.get('nav.commands.main'),
actions: [
{ href: '/', name: t.get('nav.home'), icon: Home, shortcut: 'h' },
{
href: '/communities',
name: t.get('nav.communities'),
icon: GlobeAlt,
},
...(amModOfAny(profile.user)
? [
{
href: '/moderation',
name: t.get('nav.moderation'),
icon: ShieldCheck,
},
]
: []),
...(profile.user && isAdmin(profile.user)
? [
{
href: '/admin',
name: t.get('nav.admin'),
icon: ServerStack,
},
]
: []),
],
},
{
name: t.get('nav.commands.feeds'),
actions: [
{
name: t.get('filter.location.label'),
icon: GlobeAmericas,
subActions: [
{
name: t.get('filter.location.all'),
icon: GlobeAmericas,
href: '/?type=All',
},
{
name: t.get('filter.location.local'),
icon: MapPin,
href: '/?type=Local',
},
{
name: t.get('filter.location.subscribed'),
icon: Newspaper,
href: '/?type=Subscribed',
},
],
},
{
name: t.get('filter.sort.label'),
icon: ChartBar,
subActions: [
{
name: t.get('filter.sort.top.label'),
icon: Trophy,
subActions: [
{
name: t.get('filter.sort.top.time.all'),
icon: ChartBar,
href: '/?sort=TopAll',
},
{
name: t.get('filter.sort.top.time.9months'),
icon: ChartBar,
href: '/?sort=TopNineMonths',
},
{
name: t.get('filter.sort.top.time.6months'),
icon: ChartBar,
href: '/?sort=TopSixMonths',
},
{
name: t.get('filter.sort.top.time.3months'),
icon: ChartBar,
href: '/?sort=TopThreeMonths',
},
{
name: t.get('filter.sort.top.time.month'),
icon: ChartBar,
href: '/?sort=TopMonth',
},
{
name: t.get('filter.sort.top.time.week'),
icon: ChartBar,
href: '/?sort=TopWeek',
},
{
name: t.get('filter.sort.top.time.day'),
icon: ChartBar,
href: '/?sort=TopDay',
},
{
name: t.get('filter.sort.top.time.6hours'),
icon: ChartBar,
href: '/?sort=TopSixHour',
},
{
name: t.get('filter.sort.top.time.hour'),
icon: ChartBar,
href: '/?sort=TopHour',
},
],
},
{
name: t.get('filter.sort.active'),
icon: ArrowTrendingUp,
href: '/?sort=Active',
},
{
name: t.get('filter.sort.hot'),
icon: Fire,
href: '/?sort=Hot',
},
{
name: t.get('filter.sort.scaled'),
icon: Scale,
href: '/?sort=Scaled',
},
{
name: t.get('filter.sort.new'),
icon: Star,
href: '/?sort=New',
},
{
name: t.get('filter.sort.old'),
icon: Clock,
href: '/?sort=Old',
},
{
name: t.get('filter.sort.controversial'),
icon: ArrowTrendingDown,
href: '/?sort=Controversial',
},
{
name: t.get('filter.sort.mostcomments'),
icon: ChatBubbleOvalLeftEllipsis,
href: '/?sort=MostComments',
},
{
name: t.get('filter.sort.newcomments'),
icon: ChatBubbleLeftRight,
href: '/?sort=NewComments',
},
],
},
],
},
{
name: t.get('profile.profile'),
actions: profile.jwt
? [
{
href: '/profile/user',
name: t.get('profile.profile'),
icon: UserCircle,
},
{
href: '/inbox',
name: t.get('profile.inbox'),
icon: Inbox,
shortcut: 'i',
},
{
href: '/saved',
name: t.get('profile.saved'),
icon: Bookmark,
},
{
href: '/accounts',
name: t.get('account.accounts'),
icon: UserGroup,
},
{
href: '/login',
name: t.get('account.login'),
icon: ArrowRightOnRectangle,
},
{
href: '/signup',
name: t.get('account.signup'),
icon: Identification,
},
{
href: '/login/guest',
name: t.get('account.addGuest'),
icon: Plus,
},
{
href: '/accounts',
name: t.get('account.accounts'),
icon: UserGroup,
},
]
: [
{
href: '/login',
name: t.get('account.login'),
icon: ArrowRightOnRectangle,
},
{
href: '/signup',
name: t.get('account.signup'),
icon: Identification,
},
{
href: '/login/guest',
name: t.get('account.addGuest'),
icon: Plus,
},
{
href: '/accounts',
name: t.get('account.accounts'),
icon: UserGroup,
},
],
},
{
name: t.get('account.accounts'),
actions: profiles.map((p) => ({
name: p.username ?? t.get('account.guest'),
icon: p.avatar ?? UserCircle,
detail: p.instance,
handle: async () => {
if (profile.id != p.id) {
currentProfile.meta.profile = p.id
}
await goto(page.url, {
invalidateAll: true,
})
},
})),
},
{
name: t.get('nav.menu.app'),
actions: [
{
href: '/settings',
name: t.get('nav.menu.settings'),
icon: Cog6Tooth,
},
{
name: t.get('nav.commands.setView'),
icon: ViewColumns,
subActions: [
{
name: t.get('nav.commands.setViewTo', {
default: t.get('filter.view.compact'),
}),
icon: ViewColumns,
handle: () => (settings.view = 'compact'),
},
{
name: t.get('nav.commands.setViewTo', {
default: t.get('filter.view.cozy'),
}),
icon: ViewColumns,
handle: () => (settings.view = 'cozy'),
},
],
},
{
name: t.get('nav.commands.setColor'),
icon: PaintBrush,
subActions: [
{
name: t.get('nav.commands.setColorTo', {
default: t.get('nav.menu.colorscheme.system'),
}),
handle: () => (theme.colorScheme = 'system'),
icon: ComputerDesktop,
},
{
name: t.get('nav.commands.setColorTo', {
default: t.get('nav.menu.colorscheme.light'),
}),
handle: () => (theme.colorScheme = 'light'),
icon: Sun,
},
{
name: t.get('nav.commands.setColorTo', {
default: t.get('nav.menu.colorscheme.dark'),
}),
handle: () => (theme.colorScheme = 'dark'),
icon: Moon,
},
],
},
{
name: t.get('nav.commands.setTheme'),
icon: Swatch,
subActions: td.themes.map((th) => ({
name: t.get('nav.commands.setThemeTo', { default: th.name }),
icon: Swatch,
handle: () => (theme.data.currentTheme = th.id),
})),
},
],
},
{
name: t.get('nav.commands.content'),
actions: [
{
href: '/create/post',
name: t.get('form.post.create'),
icon: PencilSquare,
},
],
},
{
name: t.get('profile.subscribed'),
actions:
profile.user?.follows.map((f) => ({
icon: f.community.icon,
name: f.community.title,
href: `/c/${fullCommunityName(
f.community.name,
f.community.actor_id,
)}`,
detail: new SvelteURL(f.community.actor_id).hostname,
})) ?? [],
},
]
}