docs/.vitepress/theme/components/themerepo/ThemeRepos.vue

ba4f23d3bab9e2bb3b8efdb22317c8cc8f353ec5
wotaku/docs/.vitepress/theme/components/themerepo/ThemeRepos.vue history · blame · raw

622 lines · 16058 bytes

  1<script setup lang="ts">
  2import { refDebounced, useMediaQuery } from '@vueuse/core'
  3import { computed, onMounted, onUnmounted, ref } from 'vue'
  4import {
  5  DEFAULT_THEME,
  6  resolveThemeColors
  7} from '../../../../ext/themeRepos/defaults'
  8import type {
  9  ManaTheme,
 10  ThemeRepoEntry
 11} from '../../../../ext/themeRepos/types'
 12import { SEARCH_DEBOUNCE_MS, STATUS_TICK_MS } from '../extrepo/constants'
 13import { screens } from './screens'
 14import ThemeFilterMenu from './ThemeFilterMenu.vue'
 15import ThemePreview from './ThemePreview.vue'
 16import ThemeRow from './ThemeRow.vue'
 17
 18type ThemeIndexEntry = {
 19  name?: string
 20  author?: string | { name?: string }
 21  url?: string
 22}
 23type ThemeFile = {
 24  theme?: { name?: string; colors?: { values?: Record<string, string> } }
 25}
 26type LoadedTheme = ManaTheme & { raw: string }
 27type ThemeGroup = { author: string; themes: LoadedTheme[] }
 28
 29const props = withDefaults(defineProps<{ themes?: ThemeRepoEntry[] }>(), {
 30  themes: () => []
 31})
 32
 33const themes = ref<LoadedTheme[]>([])
 34const loading = ref(props.themes.length > 0)
 35const loadFailed = ref(false)
 36const selectedKey = ref<string | null>(null)
 37const screenIndex = ref(0)
 38const isPhone = useMediaQuery('(max-width: 767px)')
 39
 40const previewTheme = computed(
 41  () =>
 42    themes.value.find(theme => theme.raw === selectedKey.value) ??
 43      DEFAULT_THEME
 44)
 45const screen = computed(() => screens[screenIndex.value] ?? screens[0])
 46const groups = computed<ThemeGroup[]>(() => {
 47  const byAuthor = new Map<string, LoadedTheme[]>()
 48  for (const theme of themes.value) {
 49    const author = theme.author?.trim() || 'Unknown'
 50    const list = byAuthor.get(author)
 51    if (list) list.push(theme)
 52    else byAuthor.set(author, [theme])
 53  }
 54  return [...byAuthor.entries()]
 55    .map(([author, list]) => ({
 56      author,
 57      themes: [...list].sort((a, b) => a.name.localeCompare(b.name))
 58    }))
 59    .sort((a, b) => a.author.localeCompare(b.author))
 60})
 61
 62const openGroups = ref<Set<string>>(new Set())
 63const knownAuthors = new Set<string>()
 64const query = ref('')
 65const debouncedQuery = refDebounced(query, SEARCH_DEBOUNCE_MS)
 66const mainColorsOnly = ref(true)
 67const bigSwatches = ref(!isPhone.value)
 68
 69const isSearching = computed(() => debouncedQuery.value.trim().length > 0)
 70const filteredGroups = computed<ThemeGroup[]>(() => {
 71  const q = debouncedQuery.value.trim().toLowerCase()
 72  if (!q) return groups.value
 73  return groups.value
 74    .map(group => ({
 75      author: group.author,
 76      themes: group.themes.filter(theme =>
 77        theme.name.toLowerCase().includes(q) ||
 78        group.author.toLowerCase().includes(q)
 79      )
 80    }))
 81    .filter(group => group.themes.length > 0)
 82})
 83const searchPlaceholder = computed(() =>
 84  themes.value.length
 85    ? `Search themes (${themes.value.length})…`
 86    : 'Search themes…'
 87)
 88
 89function toggleGroup(author: string): void {
 90  const next = new Set(openGroups.value)
 91  if (next.has(author)) next.delete(author)
 92  else next.add(author)
 93  openGroups.value = next
 94}
 95
 96function isGroupOpen(author: string): boolean {
 97  return isSearching.value || openGroups.value.has(author)
 98}
 99
100function applyThemes(list: LoadedTheme[]): void {
101  themes.value = list
102  const next = new Set(openGroups.value)
103  for (const group of groups.value) {
104    if (!knownAuthors.has(group.author)) {
105      knownAuthors.add(group.author)
106      next.add(group.author)
107    }
108  }
109  openGroups.value = next
110}
111
112async function fetchJson<T>(url: string, noCache = false): Promise<T> {
113  const res = await fetch(url, noCache ? { cache: 'no-cache' } : undefined)
114  if (!res.ok) throw new Error(`${res.status} ${res.statusText}`)
115  return res.json()
116}
117
118async function loadRepo(
119  entry: ThemeRepoEntry,
120  noCache = false
121): Promise<LoadedTheme[]> {
122  if (!entry.raw) return []
123
124  const index = await fetchJson<{ themes?: ThemeIndexEntry[] }>(entry.raw, true)
125  const results = await Promise.allSettled(
126    (index.themes ?? [])
127      .filter((item): item is ThemeIndexEntry & { url: string } =>
128        Boolean(item.url)
129      )
130      .map(async item => {
131        const file = await fetchJson<ThemeFile>(item.url, noCache)
132        const values = file.theme?.colors?.values
133        const name = item.name ?? file.theme?.name
134        return values && name
135          ? {
136            name,
137            author: typeof item.author === 'string'
138              ? item.author
139              : item.author?.name,
140            colors: resolveThemeColors(values),
141            raw: item.url
142          }
143          : null
144      })
145  )
146
147  return results
148    .map(result => result.status === 'fulfilled' ? result.value : null)
149    .filter((theme): theme is LoadedTheme => theme !== null)
150}
151
152async function fetchThemes(noCache = false): Promise<{
153  themes: LoadedTheme[]
154  failed: boolean
155}> {
156  const results = await Promise.allSettled(
157    props.themes.map(entry => loadRepo(entry, noCache))
158  )
159  const unique = new Map<string, LoadedTheme>()
160  for (
161    const theme of results.flatMap(r => r.status === 'fulfilled' ? r.value : [])
162  ) {
163    unique.set(theme.raw, theme)
164  }
165  return {
166    themes: [...unique.values()].sort((a, b) => a.name.localeCompare(b.name)),
167    failed: results.some(r => r.status === 'rejected')
168  }
169}
170
171async function load(): Promise<void> {
172  if (props.themes.length === 0) return
173
174  loadFailed.value = false
175  try {
176    const result = await fetchThemes()
177    applyThemes(result.themes)
178    loadFailed.value = result.failed
179  } finally {
180    loading.value = false
181  }
182}
183
184const refreshing = ref(false)
185const refreshFailed = ref(false)
186const ticked = ref(false)
187let tickTimer: ReturnType<typeof setTimeout> | undefined
188
189onUnmounted(() => {
190  if (tickTimer) clearTimeout(tickTimer)
191})
192
193async function refresh(): Promise<void> {
194  if (refreshing.value) return
195
196  refreshing.value = true
197  refreshFailed.value = false
198  try {
199    const result = await fetchThemes(true)
200    if (result.failed || result.themes.length === 0) {
201      refreshFailed.value = true
202      return
203    }
204    applyThemes(result.themes)
205  } finally {
206    refreshing.value = false
207  }
208}
209
210const busy = computed(() => loading.value || refreshing.value)
211const failed = computed(() => loadFailed.value || refreshFailed.value)
212const statusIcon = computed(() => {
213  if (busy.value) return 'i-lucide:loader-circle'
214  if (failed.value) return 'i-lucide:x'
215  if (ticked.value) return 'i-lucide:check'
216  return 'i-lucide:refresh-cw'
217})
218const statusTitle = computed(() => {
219  if (loading.value) return 'Loading themes…'
220  if (refreshing.value) return 'Refreshing themes…'
221  if (failed.value) return 'Loading failed — click to retry'
222  if (ticked.value) return 'Themes refreshed'
223  return 'Refresh themes'
224})
225
226async function onStatusClick(): Promise<void> {
227  if (busy.value) return
228  if (loadFailed.value) {
229    loading.value = true
230    await load()
231    return
232  }
233
234  ticked.value = false
235  if (tickTimer) clearTimeout(tickTimer)
236  await refresh()
237  if (!refreshFailed.value) {
238    ticked.value = true
239    tickTimer = setTimeout(() => {
240      ticked.value = false
241    }, STATUS_TICK_MS)
242  }
243}
244
245onMounted(load)
246
247function showScreen(delta: number): void {
248  screenIndex.value = (screenIndex.value + delta + screens.length) %
249    screens.length
250}
251
252function toggleTheme(theme: LoadedTheme): void {
253  selectedKey.value = selectedKey.value === theme.raw ? null : theme.raw
254}
255</script>
256
257<template>
258  <div class="theme-repos">
259    <div class="theme-toolbar">
260      <div class="theme-search">
261        <span class="i-lucide:search" />
262        <input v-model="query" type="text" :placeholder="searchPlaceholder" />
263        <button
264          type="button"
265          class="theme-search-clear"
266          :disabled="!query"
267          title="Clear search"
268          aria-label="Clear search"
269          @click="query = ''"
270        >
271          <span class="i-lucide:x" />
272        </button>
273      </div>
274      <button
275        type="button"
276        class="theme-status-btn"
277        :class="{
278          spinning: busy,
279          'is-failed': !busy && failed,
280          'is-ok': !busy && !failed && ticked
281        }"
282        :disabled="busy"
283        :title="statusTitle"
284        aria-label="Reload theme data"
285        @click="onStatusClick"
286      >
287        <span :class="statusIcon" />
288      </button>
289      <ThemeFilterMenu
290        v-model="mainColorsOnly"
291        :big-swatches="bigSwatches"
292        @update:big-swatches="bigSwatches = $event"
293      />
294    </div>
295
296    <div v-if="themes.length" class="theme-showcase">
297      <div class="theme-stage">
298        <ThemePreview
299          :theme="previewTheme"
300          :screen="screen"
301          @prev="showScreen(-1)"
302          @next="showScreen(1)"
303        />
304      </div>
305
306      <div class="theme-panel">
307        <div
308          class="theme-list"
309          :class="{ 'theme-list-open': isPhone && selectedKey }"
310        >
311          <p
312            v-if="isSearching && filteredGroups.length === 0"
313            class="theme-repos-empty"
314          >
315            No themes match your search.
316          </p>
317          <div
318            v-for="group in filteredGroups"
319            :key="group.author"
320            class="theme-group"
321          >
322            <button
323              type="button"
324              class="theme-group-row"
325              :aria-expanded="isGroupOpen(group.author)"
326              @click="toggleGroup(group.author)"
327            >
328              <span class="theme-group-title">
329                <span class="theme-group-name">{{ group.author }}</span>
330                <span
331                  class="theme-group-count"
332                  :title="`${group.themes.length} theme${
333                    group.themes.length === 1 ? '' : 's'
334                  }`"
335                >{{ group.themes.length }}</span>
336              </span>
337              <span
338                class="theme-group-toggle i-lucide:chevron-down"
339                :class="{ open: isGroupOpen(group.author) }"
340              />
341            </button>
342            <template v-if="isGroupOpen(group.author)">
343              <template v-for="theme in group.themes" :key="theme.raw">
344                <ThemeRow
345                  :theme="theme"
346                  :selected="theme.raw === selectedKey"
347                  :main-only="mainColorsOnly"
348                  :big-swatches="bigSwatches"
349                  @select="toggleTheme(theme)"
350                />
351                <div
352                  v-if="isPhone && theme.raw === selectedKey"
353                  class="theme-dropdown"
354                >
355                  <ThemePreview
356                    :theme="theme"
357                    :screen="screen"
358                    @prev="showScreen(-1)"
359                    @next="showScreen(1)"
360                  />
361                </div>
362              </template>
363            </template>
364          </div>
365        </div>
366      </div>
367    </div>
368
369    <p v-else-if="loading" class="theme-repos-empty">Loading themes…</p>
370    <p v-else-if="loadFailed" class="theme-repos-empty">
371      Couldn't load themes from this repo.
372    </p>
373    <p v-else class="theme-repos-empty">No themes found.</p>
374  </div>
375</template>
376
377<style scoped>
378.theme-repos {
379  margin: 16px 0;
380  border: 1px solid var(--vp-c-divider);
381  border-radius: var(--radius-xl, 12px);
382  overflow: hidden;
383}
384.theme-toolbar {
385  display: flex;
386  flex-wrap: nowrap;
387  align-items: center;
388  gap: 8px;
389  padding: 10px;
390  background-color: var(--vp-c-bg-soft);
391  border-bottom: 1px solid var(--vp-c-divider);
392}
393.theme-search {
394  display: flex;
395  align-items: center;
396  gap: 6px;
397  flex: 1 1 auto;
398  min-width: 0;
399  padding: 6px 10px;
400  border-radius: 8px;
401  border: 1px solid var(--vp-c-divider);
402  background-color: var(--vp-c-bg);
403  color: var(--vp-c-text-2);
404}
405.theme-search input {
406  flex: 1;
407  min-width: 0;
408  border: none;
409  outline: none;
410  background: transparent;
411  color: var(--vp-c-text-1);
412  font-size: 13px;
413}
414.theme-search > span {
415  flex-shrink: 0;
416}
417.theme-search-clear {
418  display: flex;
419  align-items: center;
420  justify-content: center;
421  flex-shrink: 0;
422  padding: 0;
423  border: none;
424  border-radius: 0;
425  background: transparent;
426  color: var(--vp-c-text-1);
427  opacity: 0.55;
428  cursor: pointer;
429  transition: opacity 0.25s, transform 0.2s cubic-bezier(0.16, 1, 0.3, 1);
430}
431.theme-search-clear:hover:not(:disabled) {
432  opacity: 1;
433}
434.theme-search-clear:disabled {
435  opacity: 0.37;
436  cursor: default;
437}
438.theme-search-clear:not(:disabled):active {
439  transform: scale(0.94);
440}
441.theme-search-clear span {
442  font-size: 18px;
443}
444html.effects-disabled .theme-search-clear {
445  transition: none;
446}
447html.effects-disabled .theme-search-clear:active {
448  transform: none;
449}
450.theme-status-btn {
451  display: flex;
452  align-items: center;
453  justify-content: center;
454  flex-shrink: 0;
455  width: 30px;
456  height: 30px;
457  padding: 0;
458  border: none;
459  border-radius: 0;
460  background: transparent;
461  color: var(--vp-c-text-1);
462  opacity: 0.55;
463  cursor: pointer;
464  transition: opacity 0.25s;
465}
466.theme-status-btn:hover:not(:disabled) {
467  opacity: 1;
468}
469.theme-status-btn:disabled {
470  cursor: default;
471}
472.theme-status-btn span {
473  font-size: 15px;
474}
475.theme-status-btn.spinning span {
476  animation: theme-spin 1s linear infinite;
477}
478.theme-status-btn.is-failed {
479  color: var(--vp-c-red-2, #e5484d);
480  opacity: 1;
481}
482.theme-status-btn.is-ok {
483  color: var(--vp-c-green-1, #3dd68c);
484  opacity: 1;
485}
486@keyframes theme-spin {
487  to {
488    transform: rotate(360deg);
489  }
490}
491html.effects-disabled .theme-status-btn.spinning span {
492  animation: none;
493}
494.theme-showcase {
495  display: grid;
496  grid-template-columns: minmax(220px, 0.82fr) minmax(0, 1.18fr);
497  min-height: 100%;
498}
499.theme-stage {
500  display: flex;
501  flex-direction: column;
502  align-items: center;
503  justify-content: center;
504  gap: 10px;
505  padding: 34px;
506  background-color: var(--vp-c-bg-soft);
507  border-right: 1px solid var(--vp-c-divider);
508}
509.theme-panel {
510  position: relative;
511  min-width: 0;
512  min-height: 0;
513}
514.theme-list {
515  position: absolute;
516  inset: 0;
517  display: flex;
518  flex-direction: column;
519  justify-content: flex-start;
520  overflow-y: auto;
521}
522.theme-group + .theme-group {
523  border-top: 1px solid var(--vp-c-divider);
524}
525.theme-group-row {
526  display: flex;
527  align-items: center;
528  justify-content: space-between;
529  gap: 12px;
530  width: 100%;
531  padding: 10px 14px;
532  border: none;
533  background-color: var(--vp-c-bg-soft);
534  color: var(--vp-c-text-1);
535  font: inherit;
536  text-align: left;
537  cursor: pointer;
538}
539.theme-group-title {
540  display: flex;
541  align-items: center;
542  gap: 8px;
543  min-width: 0;
544}
545.theme-group-name {
546  min-width: 0;
547  font-size: 14px;
548  font-weight: 600;
549  color: var(--vp-c-text-1);
550  white-space: nowrap;
551  overflow: hidden;
552  text-overflow: ellipsis;
553}
554.theme-group-toggle {
555  color: var(--vp-c-text-1);
556  font-size: 18px;
557  transition: color 0.2s, transform 0.2s;
558}
559.theme-group-row:hover .theme-group-toggle {
560  color: var(--vp-c-brand-1);
561}
562.theme-group-toggle.open {
563  transform: rotate(180deg);
564}
565.theme-group-count {
566  display: inline-flex;
567  align-items: center;
568  justify-content: center;
569  min-width: 20px;
570  padding: 1px 6px;
571  border-radius: 6px;
572  border: 1px solid var(--vp-c-divider);
573  background-color: var(--vp-c-bg);
574  color: var(--vp-c-text-2);
575  font-size: 11px;
576  font-weight: 600;
577  line-height: 16px;
578  font-variant-numeric: tabular-nums;
579  flex-shrink: 0;
580}
581.theme-group .theme-row + .theme-row {
582  border-top: 1px solid var(--vp-c-divider);
583}
584.theme-dropdown {
585  display: flex;
586  flex-direction: column;
587  align-items: center;
588  padding: 30px 40px 22px;
589  background-color: var(--vp-c-bg-soft);
590}
591.theme-repos-empty {
592  margin: 0;
593  padding: 16px;
594  color: var(--vp-c-text-2);
595  font-size: 14px;
596}
597
598@media (max-width: 767px) {
599  .theme-showcase {
600    grid-template-columns: minmax(0, 1fr);
601  }
602  .theme-stage {
603    display: none;
604  }
605  .theme-panel {
606    position: static;
607  }
608  .theme-list {
609    position: static;
610    max-height: 60vh;
611    overflow-y: auto;
612    overscroll-behavior: contain;
613  }
614  .theme-dropdown {
615    border-top: 1px solid var(--vp-c-divider);
616    --theme-phone-width: min(250px, calc(40vh - 64px));
617  }
618  .theme-list-open {
619    max-height: 85vh;
620  }
621}
622</style>