docs/.vitepress/theme/components/Feedback.vue

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

678 lines · 17174 bytes

  1<!--
  2  All Rights Reserved
  3
  4  Copyright (c) 2025 taskylizard
  5
  6  All rights reserved. This code and its associated files may not be copied, modified, distributed, sublicensed, or used in any form, in whole or in part, without prior written permission from the copyright holder.
  7-->
  8<script setup lang="ts">
  9import { useRouter, withBase } from 'vitepress'
 10import { computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
 11import {
 12  feedbackOptions,
 13  type FeedbackType,
 14  getFeedbackOption
 15} from '../../types/Feedback'
 16import { resolvePrompts } from '../../utils/promptConfig'
 17
 18const props = defineProps<{
 19  heading?: string
 20}>()
 21
 22const sluggify = (text: string) =>
 23  text
 24    .toLowerCase()
 25    .replace(/[^a-z0-9_]+/g, '-')
 26    .replace(/--+/g, '-')
 27    .replace(/(^-+|-+$)/g, '')
 28    .substring(0, 60)
 29
 30const getURL = (heading: string) =>
 31  `https://wotaku.wiki${withBase(router.route.path)}#${sluggify(heading)}`
 32
 33const router = useRouter()
 34
 35/**
 36 * Resolve the prompt pool once on mount.
 37 * Re-evaluates reactively if the route changes (SPA navigation).
 38 */
 39const promptPool = computed(() => resolvePrompts(router.route.path))
 40
 41function getPrompt(): string {
 42  const pool = promptPool.value
 43  return pool[Math.floor(Math.random() * pool.length)]
 44}
 45
 46const loading = ref<boolean>(false)
 47const error = ref<unknown>(null)
 48const success = ref<boolean>(false)
 49
 50// Generate or retrieve stable visitor ID from localStorage
 51function getVisitorId(): string {
 52  const key = 'wotaku_visitor_id'
 53  let id = localStorage.getItem(key)
 54  if (!id || id.length !== 32) {
 55    id = crypto.randomUUID().replace(/-/g, '').slice(0, 32)
 56    localStorage.setItem(key, id)
 57  }
 58  return id
 59}
 60
 61const isDisabled = computed(() => {
 62  return (
 63    !feedback.type ||
 64    !feedback.content.length ||
 65    feedback.content.length < 5 ||
 66    feedback.content.length > 2000
 67  )
 68})
 69
 70// prettier-ignore
 71const feedback = reactive<
 72  Pick<FeedbackType, 'content' | 'page'> & Partial<Pick<FeedbackType, 'type' | 'name'>>
 73>({
 74  page: getURL(props.heading!),
 75  content: '',
 76  name: '',
 77  type: undefined
 78})
 79
 80async function handleSubmit() {
 81  if (!feedback.type) return
 82  loading.value = true
 83  success.value = true
 84  error.value = null
 85
 86  const body = {
 87    content: feedback.content,
 88    type: feedback.type!,
 89    page: feedback.page,
 90    visitorId: getVisitorId(),
 91    ...(props.heading && { heading: props.heading }),
 92    ...(feedback.name && { name: feedback.name })
 93  }
 94
 95  try {
 96    const response = await fetch('https://wotaku-feedback.duckling.workers.dev/api/feedback', {
 97      method: 'POST',
 98      headers: {
 99        'Content-Type': 'application/json'
100      },
101      body: JSON.stringify(body)
102    })
103
104    const data = await response.json()
105    if (data.error) {
106      success.value = false
107      error.value = data.error
108    }
109  } catch (err) {
110    success.value = false
111    error.value = err
112  } finally {
113    loading.value = false
114  }
115}
116
117const isCardShown = ref<boolean>(false)
118const prompt = computed(() => getPrompt())
119const toggleCard = () => {
120  isCardShown.value = !isCardShown.value
121  if (!isCardShown.value && success.value) {
122    success.value = false
123    feedback.content = ''
124    feedback.type = undefined
125    error.value = null
126  }
127}
128
129const typeOpen = ref<boolean>(false)
130const typeRootRef = ref<HTMLDivElement>()
131const typePlaceholder = {
132  label: 'Feedback type',
133  icon: undefined as string | undefined,
134  value: undefined
135} as const
136const selectedType = computed(
137  () => (feedback.type ? getFeedbackOption(feedback.type) : undefined) ?? typePlaceholder
138)
139
140function selectFeedbackType(type: FeedbackType['type']) {
141  feedback.type = type
142  typeOpen.value = false
143}
144
145function onTypeDocClick(e: MouseEvent) {
146  if (typeRootRef.value && !typeRootRef.value.contains(e.target as Node)) {
147    typeOpen.value = false
148  }
149}
150
151// Success celebration: floating twemoji, single ~3s burst with random lanes.
152// Pick an icon + depth layer here; size/opacity/timing derive from the layer.
153type CelebrateLayer = 'front' | 'mid' | 'back'
154
155const CELEBRATE_ICONS: { icon: string; layer: CelebrateLayer }[] = [
156  { icon: 'i-twemoji-red-heart', layer: 'front' },
157  { icon: 'i-twemoji-growing-heart', layer: 'front' },
158  { icon: 'i-twemoji-green-heart', layer: 'front' },
159  { icon: 'i-twemoji-yellow-heart', layer: 'mid' },
160  { icon: 'i-twemoji-folded-hands', layer: 'mid' },
161  { icon: 'i-twemoji-purple-heart', layer: 'mid' },
162  { icon: 'i-twemoji-beating-heart', layer: 'mid' },
163  { icon: 'i-twemoji-orange-heart', layer: 'back' },
164  { icon: 'i-twemoji-blue-heart', layer: 'back' },
165  { icon: 'i-twemoji-brown-heart', layer: 'back' },
166  { icon: 'i-twemoji-white-heart', layer: 'back' },
167  { icon: 'i-twemoji-black-heart', layer: 'back' },
168  { icon: 'i-twemoji-sparkling-heart', layer: 'back' },
169  { icon: 'i-twemoji-glowing-star', layer: 'back' }
170]
171
172const LAYER_STYLE = {
173  front: { minSize: 24, maxSize: 30, minOpacity: 0.95, maxOpacity: 1, z: 2, blur: '0px', minDuration: 1.9, maxDuration: 2.1 },
174  mid: { minSize: 16, maxSize: 22, minOpacity: 0.8, maxOpacity: 0.9, z: 0, blur: '0px', minDuration: 2, maxDuration: 2.3 },
175  back: { minSize: 12, maxSize: 15, minOpacity: 0.4, maxOpacity: 0.55, z: 0, blur: '1px', minDuration: 2.1, maxDuration: 2.3 }
176} as const
177
178interface CelebrationParticle {
179  icon: string
180  left: string
181  delay: string
182  duration: string
183  size: string
184  opacity: string
185  z: number
186  blur: string
187}
188
189function makeParticle(
190  def: (typeof CELEBRATE_ICONS)[number],
191  index: number,
192  randomize: boolean
193): CelebrationParticle {
194  const style = LAYER_STYLE[def.layer]
195  const pick = (min: number, max: number) =>
196    randomize ? min + Math.random() * (max - min) : (min + max) / 2
197  return {
198    icon: def.icon,
199    left: randomize
200      ? `${(2 + Math.random() * 92).toFixed(1)}%`
201      : `${(((index + 0.5) / CELEBRATE_ICONS.length) * 100).toFixed(1)}%`,
202    delay: `${pick(0, 0.7).toFixed(2)}s`,
203    duration: `${pick(style.minDuration, style.maxDuration).toFixed(2)}s`,
204    size: `${Math.round(pick(style.minSize, style.maxSize))}px`,
205    opacity: `${pick(style.minOpacity, style.maxOpacity).toFixed(2)}`,
206    z: style.z,
207    blur: style.blur
208  }
209}
210
211const celebrationIcons = ref<CelebrationParticle[]>(
212  CELEBRATE_ICONS.map((def, i) => makeParticle(def, i, false))
213)
214
215function rollCelebration() {
216  celebrationIcons.value = CELEBRATE_ICONS.map((def, i) => makeParticle(def, i, true))
217}
218
219watch(success, (v) => {
220  if (v) rollCelebration()
221})
222
223onMounted(() => {
224  document.addEventListener('click', onTypeDocClick, true)
225  if (success.value) rollCelebration()
226})
227onUnmounted(() => document.removeEventListener('click', onTypeDocClick, true))
228</script>
229
230<template>
231  <template v-if="props.heading">
232    <button
233      @click="toggleCard()"
234      class="bg-$vp-c-default-soft text-primary border-$vp-c-default-soft hover:border-primary ml-3 inline-flex h-7 items-center justify-center whitespace-nowrap rounded-md border-2 border-solid px-1.5 py-3.5 text-sm font-medium transition-all duration-300 sm:h-6"
235      style="vertical-align: middle"
236    >
237      <span
238        :class="isCardShown === false ? `i-lucide:mail` : `i-lucide:mail-x`"
239      />
240    </button>
241  </template>
242  <template v-else>
243    <button
244      class="bg-$vp-c-default-soft text-primary px2 py1 border-$vp-c-default-soft hover:border-primary mt-2 select-none rounded border-2 border-solid font-bold transition-all duration-300"
245      @click="toggleCard()"
246    >
247      <span
248        :class="isCardShown === false
249        ? `i-lucide:mail mr-2`
250        : `i-lucide:mail-x mr-2`"
251      />
252      <span>Send Feedback</span>
253    </button>
254  </template>
255
256  <Transition name="fade" mode="out-in">
257    <div v-if="isCardShown" class="feedback-wrap">
258      <Transition name="fade" mode="out-in">
259        <div v-if="!success">
260          <textarea
261            v-model="feedback.content"
262            autofocus
263            class="feedback-textarea"
264            :placeholder="prompt"
265          />
266
267          <div class="feedback-row">
268            <input
269              v-model="feedback.name"
270              maxlength="50"
271              class="feedback-name"
272              placeholder="Name (optional)"
273            />
274            <div
275              ref="typeRootRef"
276              class="fb-type-select"
277              :class="{ 'fb-type-select--open': typeOpen }"
278            >
279              <button
280                type="button"
281                class="fb-type-trigger"
282                :class="{ 'fb-type-trigger--placeholder': !feedback.type }"
283                aria-haspopup="listbox"
284                :aria-expanded="typeOpen"
285                :aria-label="`Feedback type: ${selectedType.label}`"
286                @click="typeOpen = !typeOpen"
287              >
288                <span v-if="selectedType.icon" :class="selectedType.icon" class="fb-type-icon" aria-hidden="true" />
289                <span class="fb-type-label">{{ selectedType.label }}</span>
290                <span
291                  class="fb-type-chevron i-lucide:chevron-down"
292                  :class="{ 'fb-type-chevron--open': typeOpen }"
293                  aria-hidden="true"
294                />
295              </button>
296
297              <div v-show="typeOpen" class="fb-type-options" role="listbox">
298                <button
299                  v-for="item in feedbackOptions"
300                  :key="item.value"
301                  type="button"
302                  role="option"
303                  class="fb-type-option"
304                  :class="{ 'fb-type-option--selected': feedback.type === item.value }"
305                  :aria-selected="feedback.type === item.value"
306                  :aria-label="item.label"
307                  @click="selectFeedbackType(item.value)"
308                >
309                  <span :class="item.icon" class="fb-type-icon" aria-hidden="true" />
310                  <span class="fb-type-label">{{ item.label }}</span>
311                </button>
312              </div>
313            </div>
314            <button
315              type="submit"
316              class="feedback-send"
317              :disabled="isDisabled || loading"
318              @click="handleSubmit()"
319            >
320              {{ loading ? 'Sending...' : 'Send' }}
321              <span class="i-lucide:mail-check" />
322            </button>
323          </div>
324          <p v-if="error" class="text-red-400 text-sm mt-1">
325            Failed to send: {{ String(error) }}
326          </p>
327          <div class="tip custom-block mt-2">
328            <p class="custom-block-title">README</p>
329            <p>
330              Read the
331              <a href="https://i.wotaku.wiki/p/rules" target="_blank" rel="noopener noreferrer"><strong>RULES</strong></a>
332              before submitting URLs. If you want a reply to your feedback,
333              feel free to join our
334              <a href="https://discord.gg/wZMuSGpZ8s" target="_blank" rel="noopener noreferrer">Discord server.</a>
335            </p>
336          </div>
337        </div>
338        <div v-else class="feedback-success">
339          <p class="heading">Thanks for your feedback!</p>
340          <span
341            v-for="(item, i) in celebrationIcons"
342            :key="i"
343            class="fb-celebrate"
344            :class="item.icon"
345            aria-hidden="true"
346            :style="{
347              left: item.left,
348              width: item.size,
349              height: item.size,
350              zIndex: item.z,
351              filter: `blur(${item.blur})`,
352              '--fb-peak': item.opacity,
353              animationDelay: item.delay,
354              animationDuration: item.duration
355            }"
356          />
357        </div>
358      </Transition>
359    </div>
360  </Transition>
361</template>
362
363<style scoped lang="css">
364.btn {
365  border: 1px solid var(--vp-c-divider);
366  background-color: var(--vp-c-bg);
367  border-radius: 8px;
368  transition: border-color 0.25s, background-color 0.25s;
369  display: inline-block;
370  font-size: 14px;
371  font-weight: 500;
372  line-height: 1.5;
373  margin: 0;
374  padding: 0.375rem 0.75rem;
375  text-align: center;
376  vertical-align: middle;
377  white-space: nowrap;
378}
379
380.btn:disabled {
381  opacity: 0.5;
382}
383
384.btn:hover {
385  border-color: var(--vp-c-brand);
386}
387
388.btn-primary {
389  color: #fff;
390  background-color: var(--vp-c-brand);
391  border-color: var(--vp-c-brand);
392}
393
394.btn-primary:hover {
395  background-color: var(--vp-c-brand-darker);
396  border-color: var(--vp-c-brand-darker);
397}
398
399.heading {
400  font-size: 1.2rem;
401  font-weight: 700;
402}
403
404.desc {
405  display: block;
406  font-size: 12px;
407  color: var(--vp-c-text-2);
408}
409
410.prompt-text {
411  display: block;
412  font-size: 10px;
413  color: var(--vp-c-text-2);
414  opacity: 0.75;
415}
416
417.feedback-wrap {
418  width: 100%;
419  margin-top: 1rem;
420}
421
422.feedback-textarea,
423.feedback-name,
424.fb-type-trigger {
425  border: 2px solid var(--vp-c-brand-soft);
426  border-radius: 12px;
427  background-color: var(--vp-c-bg-alt);
428  color: var(--vp-c-text-1);
429  font-size: 14px;
430  outline: none;
431  transition: border-color 0.25s, box-shadow 0.25s;
432}
433
434.feedback-textarea:hover,
435.feedback-name:hover,
436.fb-type-trigger:hover {
437  border-color: var(--vp-c-brand-1);
438}
439
440.feedback-textarea:focus,
441.feedback-name:focus,
442.fb-type-select--open .fb-type-trigger {
443  border-color: var(--vp-c-brand-1);
444  box-shadow: 0 0 0 2px var(--vp-c-brand-soft);
445}
446
447.feedback-textarea {
448  width: 100%;
449  min-height: 160px;
450  padding: 0.75rem 0.9rem;
451  resize: vertical;
452}
453
454.feedback-textarea::placeholder {
455  font-size: 14px;
456  color: var(--vp-c-text-2);
457  opacity: 0.55;
458}
459
460.feedback-name::placeholder {
461  font-size: 14px;
462  color: var(--vp-c-text-2);
463  opacity: 0.55;
464}
465
466.feedback-row {
467  display: grid;
468  grid-template-columns: 1fr 1fr auto;
469  gap: 8px;
470  margin-top: 8px;
471  align-items: stretch;
472}
473
474@media (max-width: 640px) {
475  .feedback-row {
476    grid-template-columns: 1fr;
477  }
478}
479
480.feedback-name {
481  width: 100%;
482  padding: 0.5rem 0.75rem;
483  line-height: 1.4;
484}
485
486.fb-type-select {
487  position: relative;
488  width: 100%;
489}
490
491.fb-type-trigger {
492  display: flex;
493  align-items: center;
494  gap: 8px;
495  width: 100%;
496  height: 100%;
497  min-height: 0;
498  padding: 0.5rem 0.75rem;
499  line-height: 1.4;
500  cursor: pointer;
501}
502
503.fb-type-icon {
504  flex-shrink: 0;
505  width: 16px;
506  height: 16px;
507}
508
509.fb-type-label {
510  flex: 1;
511  text-align: left;
512  white-space: nowrap;
513  overflow: hidden;
514  text-overflow: ellipsis;
515}
516
517.fb-type-trigger--placeholder .fb-type-icon,
518.fb-type-trigger--placeholder .fb-type-label {
519  opacity: 0.55;
520}
521
522.fb-type-chevron {
523  flex-shrink: 0;
524  width: 16px;
525  height: 16px;
526  color: var(--vp-c-text-2);
527  transition: transform 0.2s ease;
528}
529
530.fb-type-chevron--open {
531  transform: rotate(180deg);
532}
533
534.fb-type-options {
535  position: absolute;
536  z-index: 20;
537  top: calc(100% + 6px);
538  left: 0;
539  right: 0;
540  max-height: 240px;
541  overflow-y: auto;
542  overscroll-behavior: contain;
543  display: grid;
544  grid-template-columns: repeat(2, 1fr);
545  gap: 2px;
546  padding: 4px;
547  border-radius: 12px;
548  border: 2px solid var(--vp-c-brand-1);
549  background: var(--vp-c-bg-elv);
550  box-shadow: var(--vp-shadow-2);
551}
552
553.fb-type-option {
554  display: flex;
555  align-items: center;
556  gap: 8px;
557  padding: 5px 8px;
558  border-radius: 8px;
559  border: none;
560  background: transparent;
561  cursor: pointer;
562  color: var(--vp-c-text-1);
563  font-size: 13px;
564  width: 100%;
565  transition: background-color 0.15s;
566}
567
568.fb-type-option:hover,
569.fb-type-option:focus-visible {
570  background-color: var(--vp-c-brand-soft);
571  outline: none;
572}
573
574.fb-type-option--selected {
575  background-color: var(--vp-c-brand-soft);
576}
577
578.fb-type-option--selected .fb-type-label {
579  font-weight: 600;
580}
581
582.feedback-send {
583  display: inline-flex;
584  align-items: center;
585  justify-content: center;
586  gap: 0.4rem;
587  padding: 0.5rem 1rem;
588  border: 2px solid var(--vp-c-brand-1);
589  border-radius: 12px;
590  background-color: var(--vp-c-brand-1);
591  color: #fff;
592  font-size: 14px;
593  font-weight: 600;
594  line-height: 1.4;
595  white-space: nowrap;
596  cursor: pointer;
597  transition: filter 0.25s, opacity 0.25s;
598}
599
600:global(html.dark) .feedback-send {
601  color: #000;
602}
603
604.feedback-send:hover:not(:disabled) {
605  filter: brightness(1.1);
606}
607
608.feedback-send:disabled {
609  opacity: 0.5;
610  cursor: not-allowed;
611}
612
613.feedback-success {
614  border: 2px solid var(--vp-c-brand-1);
615  border-radius: 12px;
616  background-color: var(--vp-c-bg-alt);
617  color: var(--vp-c-text-1);
618  display: flex;
619  align-items: center;
620  justify-content: center;
621  text-align: center;
622  min-height: 120px;
623  padding: 1rem;
624  box-shadow: 0 0 0 2px var(--vp-c-brand-soft);
625  position: relative;
626  overflow: hidden;
627}
628
629.feedback-success .heading {
630  margin: 0;
631  position: relative;
632  z-index: 1;
633}
634
635.fb-celebrate {
636  position: absolute;
637  bottom: -28px;
638  opacity: 0;
639  pointer-events: none;
640  animation-name: fb-float-up;
641  animation-timing-function: linear;
642  animation-iteration-count: 1;
643}
644
645@keyframes fb-float-up {
646  0% {
647    transform: translateY(0);
648    opacity: 0;
649  }
650  15% {
651    opacity: var(--fb-peak, 0.9);
652  }
653  70% {
654    opacity: var(--fb-peak, 0.9);
655  }
656  100% {
657    transform: translateY(-160px);
658    opacity: 0;
659  }
660}
661
662@media (prefers-reduced-motion: reduce) {
663  .fb-celebrate {
664    animation: none;
665    display: none;
666  }
667}
668
669.fade-enter-active,
670.fade-leave-active {
671  transition: opacity 0.25s ease;
672}
673
674.fade-enter-from,
675.fade-leave-to {
676  opacity: 0;
677}
678</style>