aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Article.svelte
blob: caa28ed4754510bc08004da269a72ba59eb5c053 (plain)
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
<script lang="ts">
  import { ndk } from '$lib/ndk';
  import type { NDKEvent } from '@nostr-dev-kit/ndk';
  import { page } from '$app/stores';
  import { Button, Heading, Sidebar, SidebarGroup, SidebarItem, SidebarWrapper, Skeleton, TextPlaceholder, Tooltip } from 'flowbite-svelte';
  import showdown from 'showdown';
  import { onMount } from 'svelte';
  import { BookOutline } from 'flowbite-svelte-icons';
  import { zettelKinds } from './consts';

  export let index: NDKEvent | null | undefined;

  $: activeHash = $page.url.hash;

  const getEvents = async (index?: NDKEvent | null | undefined): Promise<Set<NDKEvent>> => {
    if (index == null) {
      // TODO: Add error handling.
    }

    const eventIds = index!.getMatchingTags('e').map((value) => value[1]);
    const events = await $ndk.fetchEvents(
      {
        // @ts-ignore
        kinds: zettelKinds,
        ids: eventIds,
      },
      { 
        groupable: false,
        skipVerification: false,
        skipValidation: false
      }
  );

    console.debug(`Fetched ${events.size} events from ${eventIds.length} references.`);
    return events;
  };

  function normalizeHashPath(str: string): string {
    return str
      .toLowerCase()
      .replace(/\s+/g, '-')
      .replace(/[^\w-]/g, '');
  }

  function scrollToElementWithOffset() {
    const hash = window.location.hash;
    if (hash) {
      const targetElement = document.querySelector(hash);
      if (targetElement) {
        const headerOffset = 80;
        const elementPosition = targetElement.getBoundingClientRect().top;
        const offsetPosition = elementPosition + window.scrollY - headerOffset;

        window.scrollTo({
          top: offsetPosition,
          behavior: 'auto',
        });
      }
    }
  }

  let showToc: boolean = true;
  let showTocButton: boolean = false;
  const tocBreakpoint = 1140;

  /**
   * Hides the table of contents sidebar when the window shrinks below a certain size.  This
   * prevents the sidebar from occluding the article content.
   */
  const setTocVisibilityOnResize = () => {
    showToc = window.innerWidth >= tocBreakpoint;
    showTocButton = window.innerWidth < tocBreakpoint;
  };

  /**
   * Hides the table of contents sidebar when the user clicks outside of it.
   */
  const hideTocOnClick = (ev: MouseEvent) => {
    const target = ev.target as HTMLElement;

    if (target.closest('.sidebar-leather') || target.closest('.btn-leather')) {
      return;
    }

    if (showToc) {
      showToc = false;
    }
  };

  onMount(() => {
    // Always check whether the TOC sidebar should be visible.
    setTocVisibilityOnResize();

    window.addEventListener('hashchange', scrollToElementWithOffset);
    // Also handle the case where the user lands on the page with a hash in the URL
    scrollToElementWithOffset();

    window.addEventListener('resize', setTocVisibilityOnResize);
    window.addEventListener('click', hideTocOnClick);

    return () => {
      window.removeEventListener('hashchange', scrollToElementWithOffset);
      window.removeEventListener('resize', setTocVisibilityOnResize);
      window.removeEventListener('click', hideTocOnClick);
    };
  });

  const converter = new showdown.Converter();
</script>

{#await getEvents(index)}
  <Sidebar class='sidebar-leather fixed top-20 left-0 px-4 w-60'>
    <SidebarWrapper>
      <Skeleton/>
    </SidebarWrapper>
  </Sidebar>
  <TextPlaceholder class='max-w-2xl'/>
{:then events}
  {#if showTocButton && !showToc}
    <Button
      class='btn-leather fixed top-20 left-4 h-6 w-6'
      outline={true}
      on:click={ev => {
        showToc = true;
        ev.stopPropagation();
      }}
    >
      <BookOutline />
    </Button>
    <Tooltip>
      Show Table of Contents
    </Tooltip>
  {/if}
  {#if showToc}
    <Sidebar class='sidebar-leather fixed top-20 left-0 px-4 w-60' {activeHash}>
      <SidebarWrapper>
        <SidebarGroup class='sidebar-group-leather overflow-y-scroll'>
          {#each events as event}
            <SidebarItem
              class='sidebar-item-leather'
              label={event.getMatchingTags('title')[0][1]}
              href={`${$page.url.pathname}#${normalizeHashPath(event.getMatchingTags('title')[0][1])}`}
            />
          {/each}
        </SidebarGroup>
      </SidebarWrapper>
    </Sidebar>
  {/if}
  <div class='flex flex-col space-y-4 max-w-2xl'>
    {#each events as event}
      <div class='note-leather flex flex-col space-y-2'>
        <Heading
          tag='h3'
          class='h-leather'
          id={normalizeHashPath(event.getMatchingTags('title')[0][1])}
        >
          {event.getMatchingTags('title')[0][1]}
        </Heading>
        {@html converter.makeHtml(event.content)}
      </div>
    {/each}
  </div>
{/await}

<style>
  :global(.sidebar-group-leather) {
    max-height: calc(100vh - 8rem);
  }
</style>