aboutsummaryrefslogtreecommitdiff
path: root/src/routes/+layout.svelte
blob: 5ba94ec7c0f12fbf6d86fae2e1d02307809706eb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
<script lang="ts">
  import Spacer from '$lib/Layout/Spacer.svelte';
  import type { SubsPleaseEpisode } from '$lib/Media/Anime/Airing/Subtitled/subsPlease';
  import { env } from '$env/dynamic/public';
  import { userIdentity as getUserIdentity } from '$lib/Data/AniList/identity';
  import { onDestroy, onMount } from 'svelte';
  import userIdentity from '$stores/identity';
  import settings from '$stores/settings';
  import { browser } from '$app/environment';
  import HeadTitle from '$lib/Home/HeadTitle.svelte';
  import '../app.css';
  import { readable, type Readable } from 'svelte/store';
  import { navigating } from '$app/stores';
  import NotificationsProvider from '$lib/Notification/NotificationsProvider.svelte';
  import Root from '$lib/Home/Root.svelte';
  import root from '$lib/Utility/root';
  import { addMessages, init, locale as i18nLocale, locales } from 'svelte-i18n';
  import english from '$lib/Locale/english';
  import japanese from '$lib/Locale/japanese';
  import type { LocaleDictionary } from '$lib/Locale/layout';
  import locale from '$stores/locale';
  import Skeleton from '$lib/Loading/Skeleton.svelte';
  import subsPlease from '$stores/subsPlease';
  import Dropdown from '$lib/Layout/Dropdown.svelte';
  import { injectSpeedInsights } from '@vercel/speed-insights/sveltekit';
  import subtitles from '$lib/Data/Static/subtitles.json';
  import settingsSyncPulled from '$stores/settingsSyncPulled';
  import settingsSyncTimes from '$stores/settingsSyncTimes';
  import Announcement from '$lib/Announcement.svelte';
  import Message from '$lib/Loading/Message.svelte';
  import { requestNotifications } from '$lib/Utility/notifications';
  import { database as userDatabase } from '$lib/Database/IDB/user';
  import CommandPalette from '$lib/CommandPalette/CommandPalette.svelte';
  import { defaultActions } from '$lib/CommandPalette/actions';
  import { toolsAsCommandPaletteActions } from '$lib/Tools/tools';
  import localforage from 'localforage';

  injectSpeedInsights();

  export let data;

  let isHeaderVisible = true;
  let previousScrollPosition = 0;
  let notificationInterval: NodeJS.Timeout | undefined = undefined;

  addMessages('en', english as unknown as LocaleDictionary);
  addMessages('ja', japanese as unknown as LocaleDictionary);
  init({ fallbackLocale: 'en', initialLocale: $settings.displayLanguage });

  $: i18nLocale.set($settings.displayLanguage);

  const navigationOrder = ['/', '/completed', '/schedule', '/updates', '/tools', '/settings'];
  const previousPage: Readable<string | null> = readable(null, (set) => {
    const unsubscribe = navigating.subscribe(($navigating) => {
      if ($navigating && $navigating.from) set($navigating.from.url.pathname as unknown as null);
    });

    return () => unsubscribe();
  });

  $: way = data.url.includes('/user')
    ? 200
    : $previousPage && $previousPage.includes('/user')
      ? -200
      : navigationOrder.indexOf(data.url) > navigationOrder.indexOf($previousPage ?? '/')
        ? 200
        : -200;

  const handleScroll = () => {
    const currentScrollPosition = window.scrollY;

    isHeaderVisible =
      currentScrollPosition <= 100 || currentScrollPosition < previousScrollPosition;
    previousScrollPosition = currentScrollPosition;
  };

  onMount(async () => {
    if (browser) {
      if (await localforage.getItem('redirect')) {
        window.location.href = (await localforage.getItem('redirect')) ?? '/';

        await localforage.removeItem('redirect');
      }

      window.addEventListener('scroll', handleScroll);

      if ((await localforage.getItem('commit')) !== data.commit) {
        await localforage.removeItem('identity');
        await localforage.removeItem('anime');
        await localforage.removeItem('manga');
        await localforage.removeItem('anime');
        await localforage.removeItem('manga');
        await localforage.removeItem('lastPruneTimes');
        await localforage.setItem('commit', data.commit);
      }
    }

    settings.get();

    if (data.user !== undefined && $userIdentity.id === -2)
      getUserIdentity(data.user).then((h) => userIdentity.set(h));

    if ($settings.settingsSync && $userIdentity.id !== -2)
      fetch(root(`/api/configuration?id=${$userIdentity.id}`)).then((response) => {
        if (response.ok)
          response.json().then((data) => {
            if (data && data.configuration) {
              console.log('Pulled remote configuration');
              settings.set(data.configuration);
              settingsSyncPulled.set(true);
              settingsSyncTimes.set({
                lastPull: new Date(),
                lastPush: new Date(data.updated_at + 'Z')
              });
            }
          });
      });

    await userDatabase.users.where('id').below(0).delete();

    if (!(await userDatabase.users.get($userIdentity.id)) && $userIdentity.id > 0)
      await userDatabase.users.put({
        id: $userIdentity.id,
        user: data.user,
        lastNotificationID: null
      });

    if ($settings.displayAniListNotifications && data.user !== undefined)
      if ('Notification' in window && navigator.serviceWorker) requestNotifications();
  });

  onDestroy(() => {
    if (browser) window.removeEventListener('scroll', handleScroll);

    if (notificationInterval) clearInterval(notificationInterval);
  });

  $: {
    if ((data.url === '/' || data.url === '/completed' || data.url === '/schedule') && !$subsPlease)
      fetch(root(`/api/subsplease?tz=${Intl.DateTimeFormat().resolvedOptions().timeZone}`))
        .then((r) => r.json())
        .then((r) => {
          for (const day in subtitles) {
            if (!r.schedule[day]) r.schedule[day] = [];

            (subtitles[day as keyof typeof subtitles] as SubsPleaseEpisode[]).forEach((episode) => {
              r.schedule[day].push({
                title: episode.title,
                page: episode.page || '',
                image_url: episode.image_url || '',
                time: episode.time
              });
            });
          }

          subsPlease.set(r);
        });
  }
</script>

<HeadTitle />

<CommandPalette items={defaultActions.concat(toolsAsCommandPaletteActions())} />

{#if !$locales.includes('en') || !$locale().navigation}
  <Message />

  {#if data.url === '/settings'}
    <Skeleton grid={true} count={1} height="10vh" />
    <Skeleton grid={true} count={1} height="30vh" />
    <Skeleton grid={true} count={1} height="30vh" />
  {:else}
    <Skeleton grid={true} count={1} height="10vh" />
    <Skeleton grid={true} count={1} height="80vh" />
  {/if}
{:else}
  <Announcement />

  <div class="container">
    <div class="card card-centered header" class:header-hidden={!isHeaderVisible}>
      <div>
        <a href={root('/')} class="header-item">{$locale().navigation.home}</a><a
          href={root('/completed')}
          class="header-item"
        >
          {$locale().navigation.completed}
        </a>
        <Dropdown
          items={[
            { name: $locale().navigation.subtitleSchedule, url: root('/schedule') },
            { name: $locale().navigation.hololive, url: root('/hololive') },
            { name: $locale().tools.tool.characterBirthdays.short, url: root('/birthdays') },
            { name: $locale().navigation.newReleases, url: root('/updates') }
          ]}
          header={false}
        >
          <span slot="title" class="header-item">{$locale().navigation.schedule}</span>
        </Dropdown>
        <a href={root('/tools')} class="header-item">{$locale().navigation.tools}</a>
        <a href={root('/settings')} class="header-item">{$locale().navigation.settings}</a>

        <span class="header-item opaque separator">•</span>

        {#if data.user}
          <Dropdown
            items={[
              { name: $locale().navigation.myProfile, url: root(`/user/${$userIdentity.name}`) },
              {
                name: $locale().navigation.myBadgeWall,
                url: root(`/user/${$userIdentity.name}/badges`)
              },
              {
                name: $locale().navigation.logOut,
                url: '#',
                preventDefault: true,
                onClick: async () => {
                  await localforage.removeItem('identity');
                  await localforage.removeItem('commit');

                  document.cookie = 'user=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';

                  window.location.href = root('/api/authentication/log-out');
                }
              }
            ]}
            header={false}
          >
            <span slot="title" class="header-item">
              {$locale().navigation.profile}
            </span>
          </Dropdown>
        {/if}

        {#if data.user === undefined}
          <a
            class="header-item"
            href={`https://anilist.co/api/v2/oauth/authorize?client_id=${env.PUBLIC_ANILIST_CLIENT_ID}&redirect_uri=${env.PUBLIC_ANILIST_REDIRECT_URI}&response_type=code`}
            on:click={async () => {
              await localforage.setItem(
                'redirect',
                window.location.origin + window.location.pathname + window.location.search
              );
            }}
          >
            {$locale().navigation.logIn}
          </a>
        {:else if data.user}
          <a href={root(`/user/${$userIdentity.name}`)} class="header-item">
            <img class="avatar" src={$userIdentity.avatar} alt="Avatar" />
          </a>
        {/if}
      </div>
    </div>

    <Spacer />

    <NotificationsProvider zIndex={5000}>
      <Root {data} {way}>
        {#if $userIdentity.id !== -1}
          <slot />
        {:else if data.url === '/settings'}
          <Skeleton grid={true} count={1} height="10vh" />
          <Skeleton grid={true} count={1} height="30vh" />
          <Skeleton grid={true} count={1} height="30vh" />
        {:else}
          <Skeleton grid={true} count={1} height="10vh" />
          <Skeleton grid={true} count={1} height="80vh" />
        {/if}
      </Root>
    </NotificationsProvider>
  </div>
{/if}

<style lang="scss">
  .header {
    font-family:
      'DM Sans',
      system-ui,
      -apple-system,
      BlinkMacSystemFont,
      'Segoe UI',
      Roboto,
      Oxygen,
      Ubuntu,
      Cantarell,
      'Open Sans',
      'Helvetica Neue',
      sans-serif;
    font-size: 1.05em;
    font-weight: 600;
    padding: 0.8rem 0.4rem;
    z-index: 4;
    position: sticky;
    top: 1.25rem;
    transition: transform 0.3s ease;
  }

  .header-hidden {
    transform: translateY(-150%);
  }

  :global(html.light-theme) {
    filter: invert(0);
  }

  :global(html.light-theme img) {
    filter: invert(0);
  }

  .container {
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  :global(a) {
    text-decoration: none;
    transition: all 0.15s ease-in-out;
  }

  :global(a:hover) {
    text-decoration: underline;
  }

  .header-item {
    margin: 0 0.5rem;
    color: var(--base06);
    white-space: nowrap;
  }

  .header-item:hover {
    text-decoration: none;
  }

  .header-item:active {
    outline: none;
  }

  .avatar {
    width: 2em;
    display: inline-block;
    vertical-align: middle;
    border-radius: 8px;
    box-shadow:
      0 1.5px 9px var(--base01),
      0 0 0 4px var(--base0E),
      0 4px 30px var(--base01);
  }

  .separator {
    color: var(--base04);
  }
</style>