Skip to content

Commit

Permalink
Refactor initialization code
Browse files Browse the repository at this point in the history
  • Loading branch information
kyoshino committed Oct 1, 2023
1 parent 4a719ab commit 6fee766
Show file tree
Hide file tree
Showing 17 changed files with 232 additions and 200 deletions.
6 changes: 3 additions & 3 deletions src/app.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
import SveltiaLogo from '$lib/assets/sveltia-logo.svg?raw&inline';
import EntrancePage from '$lib/components/entrance/entrance-page.svelte';
import MainRouter from '$lib/components/global/main-router.svelte';
import { user } from '$lib/services/auth';
import { entriesLoaded } from '$lib/services/contents';
import { dataLoaded } from '$lib/services/contents';
import { initAppLocale } from '$lib/services/i18n';
import { user } from '$lib/services/user';
initAppLocale();
</script>
Expand All @@ -32,7 +32,7 @@

<AppShell>
{#if !$isLoading}
{#if $user && $entriesLoaded}
{#if $user && $dataLoaded}
<MainRouter />
{:else}
<EntrancePage />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@
import UploadAssetsPreview from '$lib/components/assets/shared/upload-assets-preview.svelte';
import { showUploadAssetsDialog, uploadingAssets } from '$lib/services/assets';
import { saveAssets } from '$lib/services/assets/data';
import { user } from '$lib/services/auth';
import { backendName } from '$lib/services/backends';
</script>

<!-- @todo Confirm to replace an old image if a file with the same same exists. -->

<Dialog
open={$showUploadAssetsDialog}
title={$_('upload_files')}
okLabel={$_($user?.backendName === 'local' ? 'save' : 'upload_and_publish')}
okLabel={$_($backendName === 'local' ? 'save' : 'upload_and_publish')}
on:ok={async () => {
await saveAssets($uploadingAssets, { commitType: 'uploadMedia' });
$uploadingAssets = { folder: null, files: [] };
Expand Down
4 changes: 2 additions & 2 deletions src/lib/components/contents/details/toolbar.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
} from '@sveltia/ui';
import equal from 'fast-deep-equal';
import { _ } from 'svelte-i18n';
import { user } from '$lib/services/auth';
import { backendName } from '$lib/services/backends';
import { deleteEntries } from '$lib/services/contents/data';
import {
entryDraft,
Expand Down Expand Up @@ -121,7 +121,7 @@
</MenuButton>
<Button
class="primary"
label={saving ? $_('saving') : $_($user?.backendName === 'local' ? 'save' : 'save_and_publish')}
label={saving ? $_('saving') : $_($backendName === 'local' ? 'save' : 'save_and_publish')}
disabled={!modified || saving}
keyShortcuts="Accel+S"
on:click={async () => {
Expand Down
37 changes: 9 additions & 28 deletions src/lib/components/entrance/entrance-page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -3,36 +3,17 @@
import { marked } from 'marked';
import { onMount } from 'svelte';
import { _ } from 'svelte-i18n';
import { get } from 'svelte/store';
// @ts-ignore
import SveltiaLogo from '$lib/assets/sveltia-logo.svg?raw&inline';
import SignIn from '$lib/components/entrance/sign-in.svelte';
import { user } from '$lib/services/auth';
import { backend } from '$lib/services/backends';
import { fetchSiteConfig, siteConfig } from '$lib/services/config';
import { entriesLoaded } from '$lib/services/contents';
import { dataLoaded } from '$lib/services/contents';
import { prefs } from '$lib/services/prefs';
let loadingError;
import { authError, unauthenticated, user } from '$lib/services/user';
onMount(() => {
fetchSiteConfig();
});
$: {
if ($siteConfig && !$siteConfig.error && $prefs && !$prefs.error && $user) {
(async () => {
try {
await get(backend).fetchFiles();
$entriesLoaded = true;
} catch (ex) {
loadingError = ex.cause || $_('unexpected_error');
// eslint-disable-next-line no-console
console.error(ex);
}
})();
}
}
</script>

<div class="container">
Expand All @@ -44,30 +25,30 @@
class="logo"
/>
<h1>Sveltia CMS</h1>
{#if !$siteConfig}
{#if !$siteConfig || !$prefs}
<h2>{$_('loading_site_config')}</h2>
{:else if $siteConfig.error}
<h2>
{$siteConfig.error}
{$_('config.error.try_again')}
</h2>
{:else if $prefs?.error}
{:else if $prefs.error}
<h2>
{$_(`prefs.error.${$prefs.error}`)}
</h2>
{:else if !$user}
<SignIn />
{:else if loadingError}
{:else if $authError}
<div>
<h2>{$_('loading_site_data_error')}</h2>
<div class="error" role="alert">
{@html DOMPurify.sanitize(/** @type {string } */ (marked.parseInline(loadingError)), {
{@html DOMPurify.sanitize(/** @type {string } */ (marked.parseInline($authError)), {
ALLOWED_TAGS: ['a', 'code'],
ALLOWED_ATTR: ['href'],
})}
</div>
</div>
{:else if !$entriesLoaded}
{:else if !$user || $unauthenticated}
<SignIn />
{:else if !$dataLoaded}
<h2>{$_('loading_site_data')}</h2>
{/if}
</div>
Expand Down
108 changes: 11 additions & 97 deletions src/lib/components/entrance/sign-in.svelte
Original file line number Diff line number Diff line change
@@ -1,98 +1,18 @@
<script>
import { Button, Dialog } from '@sveltia/ui';
import { onMount, tick } from 'svelte';
import { Button } from '@sveltia/ui';
import { onMount } from 'svelte';
import { _ } from 'svelte-i18n';
import { user } from '$lib/services/auth';
import { allBackendServices, backend } from '$lib/services/backends';
import { siteConfig } from '$lib/services/config';
import LocalStorage from '$lib/services/utils/local-storage';
/**
* @type {string}
*/
let backendName = $siteConfig.backend?.name;
let isLocal = false;
let isFileAccessUnsupported = false;
let isLocalStorageDisabled = false;
let showErrorDialog = false;
/**
* @type {string}
*/
let errorReason = undefined;
$: $backend = allBackendServices[backendName];
/**
* Sign in with the given backend.
* @param {string} [savedToken] User’s auth token. Can be empty for the local backend or when a
* token is not saved in the local storage.
*/
const signIn = async (savedToken = '') => {
try {
const _user = await $backend.signIn(savedToken);
$user = _user;
await LocalStorage.set('sveltia-cms.user', _user);
} catch (error) {
showErrorDialog = true;
errorReason = 'unexpected';
// eslint-disable-next-line no-console
console.error(error);
}
};
import { signInAutomatically, signInManually, unauthenticated } from '$lib/services/user';
import { backend, backendName } from '$lib/services/backends';
onMount(() => {
// Local editing needs a secure context, either `http://localhost` or `http://*.localhost`
// https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts
isLocal = !!window.location.hostname.match(/^(?:.+\.)?localhost$/);
// Check if the browser supports the File System Access API
isFileAccessUnsupported = isLocal && !('showDirectoryPicker' in window);
if (isLocal) {
backendName = 'local';
}
// Automatically sign into a Git-based backend if the user info is cached. Check the compatible
// Netlify CMS cache as well.
(async () => {
try {
const { backendName: name, token } =
(await LocalStorage.get('sveltia-cms.user')) ||
(await LocalStorage.get('decap-cms-user')) ||
(await LocalStorage.get('netlify-cms-user')) ||
{};
if (name) {
// Don’t try to sign in automatically if the local backend is being used, because it
// requires user interaction to acquire file/directory handles. Also, ignore the `proxy`
// backend that was set when using the Netlify CMS local proxy server.
if (['local', 'proxy'].includes(name)) {
return;
}
backendName = name;
await tick();
if ($backend && token) {
await signIn(token);
}
}
} catch {
isLocalStorageDisabled = true;
}
})();
signInAutomatically();
});
</script>

<div class="buttons">
{#if isLocalStorageDisabled}
<div role="alert">
{$_('unsupported.storage')}
</div>
{:else if isLocal}
{#if isFileAccessUnsupported}
{#if $backendName === 'local'}
{#if !('showDirectoryPicker' in window)}
<div role="alert">
{$_(`unsupported.browser`)}
</div>
Expand All @@ -101,31 +21,25 @@
class="primary"
label={$_('work_with_local_repo')}
on:click={async () => {
await signIn();
await signInManually();
}}
/>
{/if}
{:else if $backend}
{:else if $backend || $unauthenticated}
<Button
class="primary"
label={$_('sign_in_with_x', { values: { name: $backend.label } })}
on:click={async () => {
await signIn();
await signInManually();
}}
/>
{:else}
<div role="alert">
{$_('config.error.unsupported_backend', { values: { name: backendName } })}
{$_('config.error.unsupported_backend', { values: { name: $backendName } })}
</div>
{/if}
</div>

<Dialog bind:open={showErrorDialog} showCancel={false}>
<div role="alert">
{$_(`unsupported.${errorReason}`)}
</div>
</Dialog>

<style lang="scss">
.buttons {
display: flex;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
import { _ } from 'svelte-i18n';
import ShortcutsDialog from '$lib/components/keyboard-shortcuts/shortcuts-dialog.svelte';
import PrefsDialog from '$lib/components/prefs/prefs-dialog.svelte';
import { user } from '$lib/services/auth';
import { backend } from '$lib/services/backends';
import { backend, backendName } from '$lib/services/backends';
import { openProductionSite } from '$lib/services/navigation';
import LocalStorage from '$lib/services/utils/local-storage';
import { user } from '$lib/services/user';
let showPrefsDialog = false;
let showShortcutsDialog = false;
$: isLocal = $backendName === 'local';
</script>

<MenuButton class="ghost iconic" popupPosition="bottom-right">
Expand All @@ -27,10 +28,10 @@
/>
<Menu slot="popup">
<MenuItem
label={$user?.backendName === 'local'
label={isLocal
? $_('working_with_local_repo')
: $_('signed_in_as_x', { values: { name: $user?.login } })}
disabled={$user?.backendName === 'local'}
disabled={isLocal}
on:click={() => {
window.open($user?.html_url, '_blank');
}}
Expand All @@ -44,7 +45,7 @@
/>
<MenuItem
label={$_('git_repository')}
disabled={$user?.backendName === 'local'}
disabled={isLocal}
on:click={() => {
window.open($backend.repository.url);
}}
Expand Down Expand Up @@ -92,12 +93,6 @@
<MenuItem
label={$_('sign_out')}
on:click={async () => {
try {
await LocalStorage.delete('sveltia-cms.user');
} catch {
//
}

// Wait a bit before the menu is closed
window.requestAnimationFrame(() => {
$user = null;
Expand Down
Loading

0 comments on commit 6fee766

Please sign in to comment.