Skip to content

Modern Docker Management, Designed for Everyone

2.3 KB
Raw Blame
<script lang="ts">
	import { createMutation, useQueryClient } from '@tanstack/svelte-query';
	import { toast } from 'svelte-sonner';

	import * as Select from '#lib/components/ui/select/index.js';
	import { m } from '#lib/paraglide/messages.js';
	import { queryKeys } from '#lib/query/query-keys.js';
	import { userService } from '#lib/services/user-service.js';
	import { timeFormatStore } from '#lib/stores/time-format.store.svelte.js';
	import userStore from '#lib/stores/user-store.svelte.js';
	import type { TimeFormat } from '#lib/types/auth.js';
	import { extractApiErrorMessage } from '#lib/utils/api.js';

	let {
		id = 'timeFormatPicker',
		class: className = ''
	}: {
		id?: string;
		class?: string;
	} = $props();

	const queryClient = useQueryClient();
	const options = $derived([
		{ value: 'auto' as const, label: m.auto() },
		{ value: '12h' as const, label: m.time_format_12_hour() },
		{ value: '24h' as const, label: m.time_format_24_hour() }
	]);
	const currentLabel = $derived(options.find((option) => option.value === timeFormatStore.current)?.label ?? m.auto());

	const updateTimeFormatMutation = createMutation(() => ({
		mutationFn: (timeFormat: TimeFormat) => userService.updateMyProfile({ timeFormat }),
		onMutate: (timeFormat) => {
			const previousTimeFormat = timeFormatStore.current;
			timeFormatStore.set(timeFormat);
			return { previousTimeFormat };
		},
		onSuccess: async (updatedUser) => {
			await userStore.setUser(updatedUser);
			await queryClient.invalidateQueries({ queryKey: queryKeys.users.all });
		},
		onError: (error, _timeFormat, context) => {
			timeFormatStore.set(context?.previousTimeFormat ?? 'auto');
			toast.error(m.common_update_failed({ resource: m.time_format() }), { description: extractApiErrorMessage(error) });
		}
	}));
</script>

<div class={className}>
	<Select.Root
		type="single"
		value={timeFormatStore.current}
		onValueChange={(value) => updateTimeFormatMutation.mutate(value as TimeFormat)}
	>
		<Select.Trigger {id} class="h-9 w-32" aria-label={m.time_format_select()}>
			<span class="truncate">{currentLabel}</span>
		</Select.Trigger>
		<Select.Content class="max-w-70 min-w-40">
			{#each options as option (option.value)}
				<Select.Item value={option.value}>{option.label}</Select.Item>
			{/each}
		</Select.Content>
	</Select.Root>
</div>