fix: And refactor onboarding integration components

This commit is contained in:
Aleksi Lassila
2024-06-18 00:58:03 +03:00
parent 1c2fbf74eb
commit 355c93e9e8
10 changed files with 372 additions and 599 deletions

View File

@@ -5,50 +5,51 @@
import { user } from '../../stores/user.store';
import { derived, get } from 'svelte/store';
const dispatch = createEventDispatcher<{
change: { baseUrl: string; apiKey: string; stale: boolean };
}>();
export let baseUrl = get(user)?.settings.sonarr.baseUrl || '';
export let apiKey = get(user)?.settings.sonarr.apiKey || '';
let baseUrl = get(user)?.settings.sonarr.baseUrl || '';
let apiKey = get(user)?.settings.sonarr.apiKey || '';
const originalBaseUrl = derived(user, (u) => u?.settings.sonarr.baseUrl || '');
const originalApiKey = derived(user, (u) => u?.settings.sonarr.apiKey || '');
let timeout: ReturnType<typeof setTimeout>;
let stale = false;
let error = '';
let timeout: ReturnType<typeof setTimeout>;
let healthCheck: Promise<boolean> | undefined;
$: {
if ($originalBaseUrl !== baseUrl && $originalApiKey !== apiKey) handleChange();
else dispatch('change', { baseUrl, apiKey, stale: false });
$originalBaseUrl;
$originalApiKey;
stale = getIsStale();
}
handleChange();
function handleChange() {
console.log('handleChange', $originalBaseUrl, baseUrl, $originalApiKey, apiKey);
function getIsStale() {
return (
(!!healthCheck || (!baseUrl && !apiKey)) &&
($originalBaseUrl !== baseUrl || $originalApiKey !== apiKey)
);
}
function handleChange() {
clearTimeout(timeout);
stale = false;
error = '';
healthCheck = undefined;
if (baseUrl === '' || apiKey === '') {
stale = getIsStale();
return;
}
const baseUrlCopy = baseUrl;
const apiKeyCopy = apiKey;
const stale = baseUrlCopy !== $originalBaseUrl || apiKeyCopy !== $originalApiKey;
dispatch('change', {
baseUrl: '',
apiKey: '',
stale: baseUrl === '' && apiKey === '' && stale
});
if (baseUrlCopy === '' || apiKeyCopy === '') return;
timeout = setTimeout(async () => {
const p = sonarrApi.getHealth(baseUrlCopy, apiKeyCopy);
healthCheck = p.then((res) => res.status === 200);
const res = await p;
if (baseUrlCopy !== baseUrl || apiKeyCopy !== apiKey) return;
if (res.status !== 200) {
error =
res.status === 404
@@ -57,12 +58,29 @@
? 'Invalid api key'
: 'Could not connect';
return; // TODO add notification
stale = false; // TODO add notification
} else {
dispatch('change', { baseUrl: baseUrlCopy, apiKey: apiKeyCopy, stale });
stale = getIsStale();
}
}, 1000);
}
async function handleSave() {
return user.updateUser((prev) => ({
...prev,
settings: {
...prev.settings,
sonarr: {
...prev.settings.sonarr,
baseUrl,
apiKey
}
}
}));
}
$: empty = !baseUrl && !apiKey;
$: unchanged = baseUrl === $originalBaseUrl && apiKey === $originalApiKey;
</script>
<div class="space-y-4 mb-4">
@@ -75,3 +93,5 @@
{#if error}
<div class="text-red-500 mb-4">{error}</div>
{/if}
<slot {handleSave} {stale} {empty} {unchanged} />