docs/.vitepress/configs/index.ts

02e414723768fbba6aee64aa8af493ec43891ab7
wotaku/docs/.vitepress/configs/index.ts
Duck meme02e4147237 5 months ago

222 lines · 7113 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 */
  8import {
  9  PageProperties,
 10  PagePropertiesMarkdownSection
 11} from '@nolebase/vitepress-plugin-page-properties/vite'
 12import { fileURLToPath, URL } from 'node:url'
 13import UnoCSS from 'unocss/vite'
 14import Devtools from 'vite-plugin-vue-devtools'
 15import type { DefaultTheme, Plugin, UserConfig } from 'vitepress'
 16import { hostname, sidebar, siteConfig } from './constants'
 17import { generateImages, generateMeta } from './hooks'
 18import { configureMarkdown } from './markdown'
 19import { aliases, defs, movePlugin } from './markdown/emoji'
 20
 21const GIT_COMMIT = process.env.NODE_ENV === 'development'
 22  ? 'dev'
 23  /** Github actions commit hash */
 24  : (process.env.GITHUB_SHA ??
 25    /** Commit hash from git */
 26    (await (await import('tinyexec'))
 27      .x('git', ['rev-parse', 'HEAD'])
 28      .then((result) => result.stdout.trim())) ??
 29    'dev')
 30
 31// Default term splitter, used for every field except the whole-URL `urls` field.
 32const SPACE_OR_PUNCT = /[\n\r\p{Z}\p{P}]+/u
 33
 34export const shared: UserConfig<DefaultTheme.Config> = {
 35  ...siteConfig,
 36  transformHead: async (context) => generateMeta(context, hostname),
 37  buildEnd: async (context) => {
 38    await generateImages(context)
 39  },
 40  markdown: {
 41    emoji: { defs, shortcuts: aliases },
 42    config(md) {
 43      configureMarkdown(md)
 44    }
 45  },
 46  themeConfig: {
 47    search: {
 48      options: {
 49        miniSearch: {
 50          // Dedicated `urls` field: each URL is one whole token so a pasted
 51          // URL matches exactly. Other fields keep default behaviour.
 52          options: {
 53            fields: ['title', 'titles', 'text', 'urls'],
 54            storeFields: ['title', 'titles'],
 55
 56            extractField(document, fieldName) {
 57              if (fieldName === 'urls') {
 58                const html = document.text ?? ''
 59                const out = []
 60                const re = /data-search-urls="([^"]*)"/g
 61                let m
 62                while ((m = re.exec(html))) {
 63                  out.push(
 64                    m[1]
 65                      .replace(/&#10;/g, '\n')
 66                      .replace(/&quot;/g, '"')
 67                      .replace(/&lt;/g, '<')
 68                      .replace(/&gt;/g, '>')
 69                      .replace(/&amp;/g, '&')
 70                  )
 71                }
 72                return out.join('\n')
 73              }
 74              return document[fieldName] ?? ''
 75            },
 76
 77            tokenize(text, fieldName) {
 78              if (fieldName === 'urls') {
 79                return text.split('\n').map((u) => u.trim()).filter(Boolean)
 80              }
 81              return text.split(SPACE_OR_PUNCT).filter(Boolean)
 82            },
 83
 84            processTerm(term, fieldName) {
 85              if (fieldName === 'urls') return term || false
 86              return term.toLowerCase() || false
 87            }
 88          },
 89
 90          searchOptions: {
 91            combineWith: 'AND',
 92            fuzzy: false,
 93            boost: { title: 4, titles: 2, text: 1, urls: 5 },
 94            // @ts-ignore
 95            boostDocument: (
 96              _,
 97              term,
 98              storedFields: Record<string, string | string[]>
 99            ) => {
100              const titles = (storedFields?.titles as string[])
101                .filter((t) => Boolean(t))
102                .map((t) => t.toLowerCase())
103              // Uprate if term appears in titles. Add bonus for higher levels (i.e. lower index)
104              const titleIndex = titles
105                .map((t, i) => (t?.includes(term) ? i : -1))
106                .find((i) => i >= 0) ?? -1
107              if (titleIndex >= 0) return 10000 - titleIndex
108
109              return 1
110            }
111          }
112        },
113        detailedView: true,
114
115        // Inject every URL from the page source into the rendered HTML so the
116        // `urls` field above can index them. Build-time only.
117        // Note: defining _render makes us responsible for the `search: false`
118        // frontmatter opt-out, checked after renderAsync (env isn't ready before).
119        async _render(src, env, md) {
120          const html = await md.renderAsync(src, env)
121          if (env.frontmatter?.search === false) return ''
122
123          const urls = new Set<string>()
124          const re = /https?:\/\/[^\s)<>'"`\]]+/g
125          let m: RegExpExecArray | null
126          while ((m = re.exec(src))) {
127            urls.add(m[0].replace(/[).,]+$/, ''))
128          }
129          if (!urls.size) return html
130
131          const blob = [...urls]
132            .join('\n')
133            .replace(/&/g, '&amp;')
134            .replace(/"/g, '&quot;')
135            .replace(/</g, '&lt;')
136            .replace(/>/g, '&gt;')
137            .replace(/\n/g, '&#10;')
138
139          return `${html}\n<span class="search-url-index" data-search-urls="${blob}" hidden></span>`
140        }
141      },
142      provider: 'local'
143    },
144    logo: { src: '/asset/fav.svg' },
145    sidebar,
146    // nav,
147    socialLinks: [
148      { icon: 'github', link: 'https://github.com/wotakumoe/Wotaku' },
149      { icon: 'discord', link: 'https://discord.gg/vShRGx8ZBC' }
150    ],
151    footer: {
152      message:
153        `<a href="https://github.com/wotakumoe">The Wotaku Team</a> <span class="divider">|</span> <a href="https://github.com/wotakumoe/Wotaku/commit/${GIT_COMMIT}">${
154          GIT_COMMIT.slice(
155            0,
156            7
157          )
158        }</a>`,
159      copyright: 'made with love and eepy energy'
160    }
161  },
162  vite: {
163    experimental: {
164      enableNativePlugin: true
165    },
166    optimizeDeps: {
167      exclude: [
168        '@nolebase/vitepress-plugin-enhanced-readabilities/client',
169        '@nolebase/vitepress-plugin-page-properties/client'
170      ]
171    },
172    ssr: {
173      noExternal: [
174        '@nolebase/vitepress-plugin-enhanced-readabilities',
175        '@nolebase/vitepress-plugin-page-properties',
176        '@nolebase/ui',
177        '@fmhy/components'
178      ]
179    },
180    plugins: [
181      Devtools(),
182      PageProperties(),
183      PagePropertiesMarkdownSection(),
184      UnoCSS({
185        configFile: '../unocss.config.ts'
186      }),
187      {
188        name: 'custom:adjust-order',
189        configResolved(c) {
190          movePlugin(
191            c.plugins as unknown as Plugin[],
192            'vitepress',
193            'before',
194            'unocss:transformers:pre'
195          )
196          movePlugin(
197            c.plugins as unknown as Plugin[],
198            'custom:tooltip-loader',
199            'before',
200            'vitepress'
201          )
202        }
203      }
204    ],
205    resolve: {
206      alias: [
207        {
208          find: /^.*\/VPBadge\.vue$/,
209          replacement: fileURLToPath(
210            new URL('../theme/components/Badge.vue', import.meta.url)
211          )
212        },
213        {
214          find: /^.*\/VPNavBarSearch\.vue$/,
215          replacement: fileURLToPath(
216            new URL('../theme/components/NavBarSearch.vue', import.meta.url)
217          )
218        }
219      ]
220    }
221  }
222}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form