aboutsummaryrefslogtreecommitdiffstats
path: root/frontend-vanilla/src/main.ts
blob: c0a4e665edbd1f8b2699759d49075eaccb441ec2 (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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
import './style.css';
import { apiFetch } from './api';
import { store } from './store';
import type { FilterType } from './store';
import { router } from './router';
import type { Feed, Item, Category } from './types';
import { createFeedItem } from './components/FeedItem';

// Extend Window interface for app object (keeping for compatibility if needed, but removing inline dependencies)
declare global {
  interface Window {
    app: any;
  }
}

// Global App State
let activeItemId: number | null = null;

// Cache elements (initialized in renderLayout)
let appEl: HTMLDivElement | null = null;

// Initial Layout (v2-style 2-pane)
export function renderLayout() {
  appEl = document.querySelector<HTMLDivElement>('#app');
  if (!appEl) return;
  appEl.className = `theme-${store.theme} font-${store.fontTheme}`;
  appEl.innerHTML = `
    <div class="layout">
      <aside class="sidebar" id="sidebar">
        <div class="sidebar-header">
          <h2 id="logo-link">Neko v3</h2>
        </div>
        <div class="sidebar-search">
          <input type="search" id="search-input" placeholder="Search..." value="${store.searchQuery}">
        </div>
        <div class="sidebar-scroll">
          <section class="sidebar-section">
            <h3>Filters</h3>
            <ul id="filter-list">
              <li class="filter-item" data-filter="unread"><a href="/v3/?filter=unread" data-nav="filter" data-value="unread">Unread</a></li>
              <li class="filter-item" data-filter="all"><a href="/v3/?filter=all" data-nav="filter" data-value="all">All</a></li>
              <li class="filter-item" data-filter="starred"><a href="/v3/?filter=starred" data-nav="filter" data-value="starred">Starred</a></li>
            </ul>
          </section>
          <section class="sidebar-section">
            <h3>Tags</h3>
            <ul id="tag-list"></ul>
          </section>
          <section class="sidebar-section">
            <h3>Feeds</h3>
            <ul id="feed-list"></ul>
          </section>
        </div>
        <div class="sidebar-footer">
          <a href="/v3/settings" id="settings-link">Settings</a>
          <a href="#" id="logout-button">Logout</a>
        </div>
      </aside>
      <main class="main-content" id="main-content">
        <div id="content-area"></div>
      </main>
    </div>
  `;

  attachLayoutListeners();
}

export function attachLayoutListeners() {
  const searchInput = document.getElementById('search-input') as HTMLInputElement;
  searchInput?.addEventListener('input', (e) => {
    const query = (e.target as HTMLInputElement).value;
    router.updateQuery({ q: query });
  });

  const logoLink = document.getElementById('logo-link');
  logoLink?.addEventListener('click', () => router.navigate('/'));

  const logoutBtn = document.getElementById('logout-button');
  logoutBtn?.addEventListener('click', (e) => {
    e.preventDefault();
    logout();
  });

  const settingsLink = document.getElementById('settings-link');
  settingsLink?.addEventListener('click', (e) => {
    e.preventDefault();
    router.navigate('/settings');
  });

  // Event delegation for filters, tags, and feeds in sidebar
  const sidebar = document.getElementById('sidebar');
  sidebar?.addEventListener('click', (e) => {
    const target = e.target as HTMLElement;
    const link = target.closest('a');
    if (!link) return;

    const navType = link.getAttribute('data-nav');
    const currentQuery = Object.fromEntries(router.getCurrentRoute().query.entries());

    if (navType === 'filter') {
      e.preventDefault();
      const filter = link.getAttribute('data-value') as FilterType;
      router.updateQuery({ filter });
    } else if (navType === 'tag') {
      e.preventDefault();
      const tag = link.getAttribute('data-value')!;
      router.navigate(`/tag/${encodeURIComponent(tag)}`, currentQuery);
    } else if (navType === 'feed') {
      e.preventDefault();
      const feedId = link.getAttribute('data-value')!;
      router.navigate(`/feed/${feedId}`, currentQuery);
    }
  });

  // Event delegation for content area (items)
  const contentArea = document.getElementById('content-area');
  contentArea?.addEventListener('click', (e) => {
    const target = e.target as HTMLElement;

    // Handle Toggle Star
    const starBtn = target.closest('[data-action="toggle-star"]');
    if (starBtn) {
      const itemRow = starBtn.closest('[data-id]');
      if (itemRow) {
        const id = parseInt(itemRow.getAttribute('data-id')!);
        toggleStar(id);
      }
      return;
    }

    // Handle Scrape
    const scrapeBtn = target.closest('[data-action="scrape"]');
    if (scrapeBtn) {
      const itemRow = scrapeBtn.closest('[data-id]');
      if (itemRow) {
        const id = parseInt(itemRow.getAttribute('data-id')!);
        scrapeItem(id);
      }
      return;
    }

    // Handle Item interaction (mark as read on click title or row)
    const itemTitle = target.closest('[data-action="open"]');
    const itemRow = target.closest('.feed-item');
    if (itemRow && !itemTitle) { // Clicking the row itself (but not the link)
      // We can add "expand" logic here if we want but v2 shows it by default if loaded
      // For now, let's just mark as read if it's unread
      const id = parseInt(itemRow.getAttribute('data-id')!);
      const item = store.items.find(i => i._id === id);
      if (item && !item.read) {
        updateItem(id, { read: true });
      }
    }
  });
}

// --- Rendering Functions ---

export function renderFeeds() {
  const { feeds, activeFeedId } = store;
  const feedListEl = document.getElementById('feed-list');
  if (!feedListEl) return;
  feedListEl.innerHTML = feeds.map((feed: Feed) => `
    <li class="${feed._id === activeFeedId ? 'active' : ''}">
      <a href="/v3/feed/${feed._id}" data-nav="feed" data-value="${feed._id}">
        ${feed.title || feed.url}
      </a>
    </li>
  `).join('');
}

export function renderTags() {
  const { tags, activeTagName } = store;
  const tagListEl = document.getElementById('tag-list');
  if (!tagListEl) return;
  tagListEl.innerHTML = tags.map((tag: Category) => `
    <li class="${tag.title === activeTagName ? 'active' : ''}">
      <a href="/v3/tag/${encodeURIComponent(tag.title)}" data-nav="tag" data-value="${tag.title}">
        ${tag.title}
      </a>
    </li>
  `).join('');
}

export function renderFilters() {
  const { filter } = store;
  const filterListEl = document.getElementById('filter-list');
  if (!filterListEl) return;
  filterListEl.querySelectorAll('li').forEach(el => {
    el.classList.toggle('active', el.getAttribute('data-filter') === filter);
  });
}

export function renderItems() {
  const { items, loading } = store;
  const contentArea = document.getElementById('content-area');
  if (!contentArea || router.getCurrentRoute().path === '/settings') return;

  if (loading && items.length === 0) {
    contentArea.innerHTML = '<p class="loading">Loading items...</p>';
    return;
  }

  if (items.length === 0) {
    contentArea.innerHTML = '<p class="empty">No items found.</p>';
    return;
  }

  contentArea.innerHTML = `
    <ul class="item-list">
      ${items.map((item: Item) => createFeedItem(item)).join('')}
    </ul>
    ${store.hasMore ? '<div id="load-more-sentinel" class="loading-more">Loading more...</div>' : ''}
  `;

  // Setup infinite scroll
  const sentinel = document.getElementById('load-more-sentinel');
  if (sentinel) {
    const observer = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting && !store.loading && store.hasMore) {
        loadMore();
      }
    }, { threshold: 0.1 });
    observer.observe(sentinel);
  }
}

export function renderSettings() {
  const contentArea = document.getElementById('content-area');
  if (!contentArea) return;
  contentArea.innerHTML = `
        <div class="settings-view">
            <h2>Settings</h2>
            <section class="settings-section">
                <h3>Theme</h3>
                <div class="theme-options" id="theme-options">
                    <button class="${store.theme === 'light' ? 'active' : ''}" data-theme="light">Light</button>
                    <button class="${store.theme === 'dark' ? 'active' : ''}" data-theme="dark">Dark</button>
                </div>
            </section>
            <section class="settings-section">
                <h3>Font</h3>
                <select id="font-selector">
                    <option value="default" ${store.fontTheme === 'default' ? 'selected' : ''}>Default (Palatino)</option>
                    <option value="serif" ${store.fontTheme === 'serif' ? 'selected' : ''}>Serif (Georgia)</option>
                    <option value="sans" ${store.fontTheme === 'sans' ? 'selected' : ''}>Sans-Serif (Helvetica)</option>
                    <option value="mono" ${store.fontTheme === 'mono' ? 'selected' : ''}>Monospace</option>
                </select>
            </section>
        </div>
    `;

  // Attach settings listeners
  const themeOptions = document.getElementById('theme-options');
  themeOptions?.addEventListener('click', (e) => {
    const btn = (e.target as HTMLElement).closest('button');
    if (btn) {
      const theme = btn.getAttribute('data-theme')!;
      store.setTheme(theme);
      renderSettings(); // Re-render to show active
    }
  });

  const fontSelector = document.getElementById('font-selector') as HTMLSelectElement;
  fontSelector?.addEventListener('change', () => {
    store.setFontTheme(fontSelector.value);
  });
}

// --- Data Actions ---

export async function toggleStar(id: number) {
  const item = store.items.find(i => i._id === id);
  if (item) {
    updateItem(id, { starred: !item.starred });
  }
}

export async function scrapeItem(id: number) {
  const item = store.items.find(i => i._id === id);
  if (!item) return;

  try {
    const res = await apiFetch(`/api/item/${id}/content`);
    if (res.ok) {
      const data = await res.json();
      if (data.full_content) {
        updateItem(id, { full_content: data.full_content });
      }
    }
  } catch (err) {
    console.error('Failed to fetch full content', err);
  }
}

export async function updateItem(id: number, updates: Partial<Item>) {
  try {
    const res = await apiFetch(`/api/item/${id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(updates)
    });
    if (res.ok) {
      const item = store.items.find(i => i._id === id);
      if (item) {
        Object.assign(item, updates);
        // Selective DOM update to avoid full re-render
        const el = document.querySelector(`.feed-item[data-id="${id}"]`);
        if (el) {
          if (updates.read !== undefined) el.classList.toggle('read', updates.read);
          if (updates.starred !== undefined) {
            const starBtn = el.querySelector('.star-btn');
            if (starBtn) {
              starBtn.classList.toggle('is-starred', updates.starred);
              starBtn.classList.toggle('is-unstarred', !updates.starred);
              starBtn.setAttribute('title', updates.starred ? 'Unstar' : 'Star');
            }
          }
          if (updates.full_content) {
            // If full content was scraped, we might need to update description or re-render chunk
            renderItems(); // Full re-render is safer for content injection
          }
        }
      }
    }
  } catch (err) {
    console.error('Failed to update item', err);
  }
}

export async function fetchFeeds() {
  const res = await apiFetch('/api/feed/');
  if (res.ok) {
    const feeds = await res.json();
    store.setFeeds(feeds);
  }
}

export async function fetchTags() {
  const res = await apiFetch('/api/tag');
  if (res.ok) {
    const tags = await res.json();
    store.setTags(tags);
  }
}

export async function fetchItems(feedId?: string, tagName?: string, append: boolean = false) {
  store.setLoading(true);
  try {
    const params = new URLSearchParams();
    if (feedId) params.append('feed_id', feedId);
    if (tagName) params.append('tag', tagName);
    if (store.searchQuery) params.append('q', store.searchQuery);
    if (store.filter === 'starred' || store.filter === 'all') {
      params.append('read_filter', 'all');
    }
    if (store.filter === 'starred') {
      params.append('starred', 'true');
    }

    if (append && store.items.length > 0) {
      params.append('max_id', String(store.items[store.items.length - 1]._id));
    }

    const res = await apiFetch(`/api/stream?${params.toString()}`);
    if (res.ok) {
      const items = await res.json();
      store.setHasMore(items.length >= 50);
      store.setItems(items, append);
    }
  } finally {
    store.setLoading(false);
  }
}

export async function loadMore() {
  const route = router.getCurrentRoute();
  fetchItems(route.params.feedId, route.params.tagName, true);
}

export async function logout() {
  await apiFetch('/api/logout', { method: 'POST' });
  window.location.href = '/login/';
}

// --- App Logic ---

function handleRoute() {
  const route = router.getCurrentRoute();

  const filterFromQuery = route.query.get('filter') as FilterType;
  store.setFilter(filterFromQuery || 'unread');

  const qFromQuery = route.query.get('q');
  if (qFromQuery !== null) {
    store.setSearchQuery(qFromQuery);
  }

  if (route.path === '/settings') {
    renderSettings();
    return;
  }

  if (route.path === '/feed' && route.params.feedId) {
    const id = parseInt(route.params.feedId);
    store.setActiveFeed(id);
    fetchItems(route.params.feedId);
  } else if (route.path === '/tag' && route.params.tagName) {
    store.setActiveTag(route.params.tagName);
    fetchItems(undefined, route.params.tagName);
  } else {
    store.setActiveFeed(null);
    store.setActiveTag(null);
    fetchItems();
  }
}

// Keyboard shortcuts
window.addEventListener('keydown', (e) => {
  if (['INPUT', 'TEXTAREA'].includes((e.target as any).tagName)) return;

  switch (e.key) {
    case 'j':
      navigateItems(1);
      break;
    case 'k':
      navigateItems(-1);
      break;
    case 'r':
      if (activeItemId) {
        const item = store.items.find(i => i._id === activeItemId);
        if (item) updateItem(item._id, { read: !item.read });
      }
      break;
    case 's':
      if (activeItemId) {
        const item = store.items.find(i => i._id === activeItemId);
        if (item) updateItem(item._id, { starred: !item.starred });
      }
      break;
    case '/':
      e.preventDefault();
      document.getElementById('search-input')?.focus();
      break;
  }
});

function navigateItems(direction: number) {
  if (store.items.length === 0) return;
  let index = store.items.findIndex(i => i._id === activeItemId);
  index += direction;
  if (index >= 0 && index < store.items.length) {
    activeItemId = store.items[index]._id;
    const el = document.querySelector(`.feed-item[data-id="${activeItemId}"]`);
    if (el) el.scrollIntoView({ block: 'nearest' });
    // Optional: mark as read when keyboard navigating
    if (!store.items[index].read) updateItem(activeItemId, { read: true });
    // Since we are in 2-pane, we just scroll to it.
  } else if (index === -1) {
    activeItemId = store.items[0]._id;
    const el = document.querySelector(`.feed-item[data-id="${activeItemId}"]`);
    if (el) el.scrollIntoView({ block: 'nearest' });
  }
}

// Subscribe to store
store.on('feeds-updated', renderFeeds);
store.on('tags-updated', renderTags);
store.on('active-feed-updated', renderFeeds);
store.on('active-tag-updated', renderTags);
store.on('filter-updated', renderFilters);
store.on('search-updated', () => {
  const searchInput = document.getElementById('search-input') as HTMLInputElement;
  if (searchInput && searchInput.value !== store.searchQuery) {
    searchInput.value = store.searchQuery;
  }
  handleRoute();
});
store.on('theme-updated', () => {
  if (!appEl) appEl = document.querySelector<HTMLDivElement>('#app');
  if (appEl) {
    appEl.className = `theme-${store.theme} font-${store.fontTheme}`;
  }
});

store.on('items-updated', renderItems);
store.on('loading-state-changed', renderItems);

// Subscribe to router
router.addEventListener('route-changed', handleRoute);

// Compatibility app object (empty handlers, since we use delegation)
window.app = {
  navigate: (path: string) => router.navigate(path)
};

// Start
// Start
export async function init() {
  const authRes = await apiFetch('/api/auth');
  if (!authRes || authRes.status === 401) {
    window.location.href = '/login/';
    return;
  }

  renderLayout();
  renderFilters();
  try {
    await Promise.all([fetchFeeds(), fetchTags()]);
  } catch (err) {
    console.error('Initial fetch failed', err);
  }
  handleRoute();
}

// Only auto-init if not in a test environment
if (typeof window !== 'undefined' && !(window as any).__VITEST__) {
  init();
}