valaxy 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,6 +3,7 @@ import { useValaxyI18n } from 'valaxy'
3
3
  import { computed } from 'vue'
4
4
  import { useI18n } from 'vue-i18n'
5
5
  import { useSiteConfig } from '../config'
6
+ import { decodePath } from '../utils/path'
6
7
 
7
8
  withDefaults(defineProps<{
8
9
  url?: string
@@ -40,7 +41,7 @@ const licenseHtml = computed(() => {
40
41
  {{ t('post.copyright.link') + t('symbol.colon') }}
41
42
  </strong>
42
43
  <a :href="url" target="_blank" :title="t('post.copyright.link')">
43
- {{ decodeURI(url) }}
44
+ {{ decodePath(url) }}
44
45
  </a>
45
46
  </li>
46
47
  <li class="post-copyright-license">
@@ -4,6 +4,7 @@ import { computed, unref } from 'vue'
4
4
 
5
5
  import { useRoute } from 'vue-router'
6
6
  import collections from '#valaxy/blog/collections'
7
+ import { decodePath } from '../utils/path'
7
8
  import { usePageList } from './post'
8
9
 
9
10
  export interface PostCollectionInfo {
@@ -42,8 +43,9 @@ export function useCollections() {
42
43
  export function useCollection() {
43
44
  const route = useRoute()
44
45
  const collectionId = computed(() => {
45
- if (route.path.startsWith('/collections/')) {
46
- return route.path.split('/')[2] // 获取集合 ID
46
+ const path = decodePath(route.path)
47
+ if (path.startsWith('/collections/')) {
48
+ return path.split('/')[2] // 获取集合 ID
47
49
  }
48
50
  return ''
49
51
  })
@@ -70,10 +72,12 @@ export function useCollectionPosts(collectionKey: MaybeRef<string>) {
70
72
  if (!key)
71
73
  return []
72
74
 
75
+ // page paths are percent-encoded, collection and item keys are raw
73
76
  const prefix = `/collections/${key}/`
74
- const pages = pageList.value.filter(
75
- p => p.path?.startsWith(prefix) && p.path !== prefix && !p.path.endsWith('/'),
76
- )
77
+ const pages = pageList.value.filter((p) => {
78
+ const path = p.path ? decodePath(p.path) : ''
79
+ return path.startsWith(prefix) && path !== prefix && !path.endsWith('/')
80
+ })
77
81
 
78
82
  // Sort by collection items order if available
79
83
  const col = collections.value.find(c => c.key === key)
@@ -84,8 +88,8 @@ export function useCollectionPosts(collectionKey: MaybeRef<string>) {
84
88
  .map((item, idx) => [item.key, idx]),
85
89
  )
86
90
  return pages.toSorted((a, b) => {
87
- const aSlug = a.path?.split('/').pop() || ''
88
- const bSlug = b.path?.split('/').pop() || ''
91
+ const aSlug = decodePath(a.path || '').split('/').pop() || ''
92
+ const bSlug = decodePath(b.path || '').split('/').pop() || ''
89
93
  const aIdx = orderMap.get(aSlug) ?? Infinity
90
94
  const bIdx = orderMap.get(bSlug) ?? Infinity
91
95
  if (aIdx === bIdx)
@@ -105,7 +109,7 @@ export function useCollectionPosts(collectionKey: MaybeRef<string>) {
105
109
  */
106
110
  export function usePostCollections(postPath: MaybeRef<string>): ComputedRef<PostCollectionInfo[]> {
107
111
  return computed(() => {
108
- const path = stripTrailingSlash(unref(postPath))
112
+ const path = stripTrailingSlash(decodePath(unref(postPath)))
109
113
  if (!path)
110
114
  return []
111
115
 
@@ -121,7 +125,7 @@ export function usePostCollections(postPath: MaybeRef<string>): ComputedRef<Post
121
125
  break
122
126
  }
123
127
  // Match internal link items (non-http)
124
- if (item.link && !/^https?:\/\//.test(item.link) && stripTrailingSlash(item.link) === path) {
128
+ if (item.link && !/^https?:\/\//.test(item.link) && stripTrailingSlash(decodePath(item.link)) === path) {
125
129
  result.push({ collection: col, itemIndex: i })
126
130
  break
127
131
  }
@@ -36,6 +36,12 @@ function getCryptoDeriveKey(keyMaterial: CryptoKey, salt: BufferSource) {
36
36
  )
37
37
  }
38
38
 
39
+ /**
40
+ * Decrypt ciphertext produced by `encryptContent` (valaxy/node).
41
+ *
42
+ * `ciphertext` must be base64. Earlier versions passed a binary string (one
43
+ * char per byte), which no longer decrypts.
44
+ */
39
45
  export function useDecrypt() {
40
46
  const siteConfig = useSiteConfig()
41
47
 
@@ -51,7 +57,8 @@ export function useDecrypt() {
51
57
  const keyMaterial = await getKeyMaterial(password)
52
58
  const key = await getCryptoDeriveKey(keyMaterial, salt)
53
59
 
54
- const ciphertextData = Uint8Array.from(ciphertext, c => c.charCodeAt(0))
60
+ // ciphertext is base64, see `encryptContent` in node/utils/encrypt.ts
61
+ const ciphertextData = Uint8Array.from(atob(ciphertext), c => c.charCodeAt(0))
55
62
 
56
63
  const decrypted = await window.crypto.subtle.decrypt(
57
64
  {
@@ -24,6 +24,25 @@ function getAbsoluteTop(element: HTMLElement): number {
24
24
  return offsetTop
25
25
  }
26
26
 
27
+ function safeDecode(value: string): string {
28
+ try {
29
+ return decodeURIComponent(value)
30
+ }
31
+ catch {
32
+ return value
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Themes render outline links either as plain `#id` anchors or as RouterLinks
38
+ * whose href includes the page path, so compare decoded hashes instead of hrefs.
39
+ */
40
+ function findLinkByHash(container: HTMLElement, hash: string): HTMLAnchorElement | null {
41
+ const target = safeDecode(hash)
42
+ return [...container.querySelectorAll<HTMLAnchorElement>('a[href*="#"]')]
43
+ .find(link => safeDecode(link.hash) === target) ?? null
44
+ }
45
+
27
46
  export function useActiveAnchor(
28
47
  container: Ref<HTMLElement>,
29
48
  marker: Ref<HTMLElement>,
@@ -118,14 +137,7 @@ export function useActiveAnchor(
118
137
  if (prevActiveLink)
119
138
  prevActiveLink.classList.remove('active')
120
139
 
121
- if (hash == null) {
122
- prevActiveLink = null
123
- }
124
- else {
125
- prevActiveLink = container.value.querySelector(
126
- `a[href="${decodeURIComponent(hash)}"]`,
127
- )
128
- }
140
+ prevActiveLink = hash ? findLinkByHash(container.value, hash) : null
129
141
 
130
142
  const activeLink = prevActiveLink
131
143
  checkActiveLinkInViewport()
package/client/index.d.ts CHANGED
@@ -2,7 +2,6 @@ import type { Ref } from 'vue'
2
2
  import type { Post } from '../types'
3
3
 
4
4
  import './shims.d'
5
- import '../vendor/layouts/client'
6
5
  // Import vue-router RouteMeta augmentation
7
6
  import '../types/vue-router.d'
8
7
 
@@ -4,7 +4,7 @@ Vue components in this dir are used as layouts.
4
4
 
5
5
  By default, `default.vue` will be used unless an alternative is specified in the route meta.
6
6
 
7
- With [vue-router](https://router.vuejs.org/) file-based routing and [`vite-plugin-vue-layouts-next`](https://github.com/loicduong/vite-plugin-vue-layouts-next), you can specify the layout in the page's SFCs like this:
7
+ With [vue-router](https://router.vuejs.org/) file-based routing and Valaxy's layout system (`virtual:generated-layouts`), you can specify the layout in the page's SFCs like this:
8
8
 
9
9
  ```html
10
10
  <route lang="yaml">
package/client/main.ts CHANGED
@@ -4,7 +4,7 @@ import { dataSymbol, initValaxyConfig, valaxyConfigSymbol } from 'valaxy'
4
4
  import { setupLayouts } from 'virtual:generated-layouts'
5
5
  import { createSSRApp, createApp as vueCreateApp } from 'vue'
6
6
  import { createMemoryHistory, createRouter, createWebHistory } from 'vue-router'
7
- import { routes as autoRoutes } from 'vue-router/auto-routes'
7
+ import { routes as autoRoutes, handleHotUpdate } from 'vue-router/auto-routes'
8
8
 
9
9
  // import App from '/@valaxyjs/App.vue'
10
10
  import App from './App.vue'
@@ -19,25 +19,12 @@ import '#valaxy/styles'
19
19
 
20
20
  const valaxyConfig = initValaxyConfig()
21
21
 
22
- const routes = [...autoRoutes]
23
-
24
- const { redirectRoutes, useVueRouter } = valaxyConfig.value.runtimeConfig.redirects
25
- if (useVueRouter)
26
- routes.push(...redirectRoutes)
27
-
28
- // fix chinese path
29
- routes.forEach((i) => {
30
- i?.children?.forEach((j: { path: string }) => {
31
- j.path = encodeURI(j.path)
32
- })
33
- })
34
-
35
22
  /**
36
23
  * Flatten nested routes so that `setupLayouts` can wrap every leaf route.
37
24
  *
38
25
  * `vue-router/vite` (file-based routing) generates nested route trees for subdirectories
39
26
  * (e.g. `pages/zh/guide/foo.md` → `{ path: '/zh', children: [{ path: 'guide', children: … }] }`).
40
- * `vite-plugin-vue-layouts-next`' `setupLayouts` only wraps **top-level** routes,
27
+ * `setupLayouts` (`virtual:generated-layouts`) only wraps **top-level** routes,
41
28
  * so nested children would miss the layout wrapper entirely.
42
29
  *
43
30
  * This function extracts every leaf (component-bearing or redirect) route into a flat
@@ -81,11 +68,29 @@ function filterDraft(routes: any[]) {
81
68
  })
82
69
  }
83
70
 
84
- // not filter hide for ssg
85
- export const routesWithLayout = setupLayouts(import.meta.env.DEV
86
- ? flattenRoutes(routes)
87
- : filterDraft(flattenRoutes(routes)),
88
- )
71
+ /**
72
+ * Turn the routes generated by `vue-router/vite` into the ones valaxy registers.
73
+ * Also used on HMR, when `vue-router/auto-routes` hands over freshly generated routes.
74
+ */
75
+ function resolveRoutes(generatedRoutes: any[]) {
76
+ const routes = [...generatedRoutes]
77
+
78
+ const { redirectRoutes, useVueRouter } = valaxyConfig.value.runtimeConfig.redirects
79
+ if (useVueRouter)
80
+ routes.push(...redirectRoutes)
81
+
82
+ // Non-ASCII file names (e.g. `pages/posts/中文.md`) need no extra handling here:
83
+ // `vue-router/vite` already percent-encodes static path segments, and encoding
84
+ // them again makes the route unreachable from its real URL.
85
+
86
+ // not filter hide for ssg
87
+ return setupLayouts(import.meta.env.DEV
88
+ ? flattenRoutes(routes)
89
+ : filterDraft(flattenRoutes(routes)),
90
+ )
91
+ }
92
+
93
+ export const routesWithLayout = resolveRoutes(autoRoutes)
89
94
 
90
95
  if (import.meta.env.DEV)
91
96
  setupValaxyDevTools()
@@ -117,6 +122,16 @@ export function createValaxyApp(options: CreateValaxyAppOptions = {}): ValaxySSG
117
122
  },
118
123
  })
119
124
 
125
+ // Without a registered router, `vue-router/auto-routes` reloads the page on every page edit.
126
+ if (import.meta.hot) {
127
+ handleHotUpdate(router, (newRoutes) => {
128
+ // vue-router has just added the raw generated routes, replace them with resolved ones
129
+ router.clearRoutes()
130
+ for (const route of resolveRoutes(newRoutes))
131
+ router.addRoute(route)
132
+ })
133
+ }
134
+
120
135
  const head = createHead ? createHead() : undefined
121
136
 
122
137
  app.use(router)
@@ -12,10 +12,10 @@ import type { ComputedRef } from 'vue'
12
12
  import type { Router } from 'vue-router'
13
13
  import type { PageDataPayload } from '../../types'
14
14
  import type { ValaxySSGContext } from '../setups'
15
- import { ensureSuffix } from '@antfu/utils'
16
15
  import { useStorage } from '@vueuse/core'
17
16
  import { nextTick, watch } from 'vue'
18
17
  import { createI18n } from 'vue-i18n'
18
+ import { isSamePagePath } from '../utils/path'
19
19
 
20
20
  // @ts-expect-error virtual
21
21
  import valaxyMessages from '/@valaxyjs/locales'
@@ -37,10 +37,7 @@ import valaxyMessages from '/@valaxyjs/locales'
37
37
  // import en from '../../../../../demo/yun/locales/en.yml'
38
38
 
39
39
  function shouldHotReload(payload: PageDataPayload): boolean {
40
- const payloadPath = payload.path.replace(/(?:(^|\/)index)?\.md$/, '$1')
41
- const locationPath = location.pathname
42
- .replace(/(?:(^|\/)index)?\.html$/, '')
43
- return ensureSuffix('/', encodeURI(payloadPath)) === ensureSuffix('/', encodeURI(locationPath))
40
+ return isSamePagePath(payload.path, location.pathname, import.meta.env.BASE_URL)
44
41
  }
45
42
 
46
43
  // init i18n, by valaxy config
@@ -89,13 +86,25 @@ export async function install({ app, router }: ValaxySSGContext, config: Compute
89
86
  function handleHMR(router: Router): void {
90
87
  // update route.data on HMR updates of active page
91
88
  if (import.meta.hot) {
89
+ let lastPayload: PageDataPayload | undefined
90
+
92
91
  import.meta.hot.on('valaxy:pageData', (payload: PageDataPayload) => {
93
92
  if (shouldHotReload(payload)) {
93
+ lastPayload = payload
94
94
  window.$pageData = payload.pageData
95
95
 
96
96
  // console.log(payload.pageData.headers)
97
97
  Object.assign(router.currentRoute.value.meta, payload.pageData)
98
98
  }
99
99
  })
100
+
101
+ // The routes HMR in `main.ts` re-navigates to the current page with a fresh
102
+ // `meta`, which may happen after the payload above was applied.
103
+ router.afterEach((to) => {
104
+ if (lastPayload && shouldHotReload(lastPayload))
105
+ Object.assign(to.meta, lastPayload.pageData)
106
+ else
107
+ lastPayload = undefined
108
+ })
100
109
  }
101
110
  }
package/client/shims.d.ts CHANGED
@@ -6,6 +6,26 @@ declare module 'virtual:valaxy-cover-components' {
6
6
  export default components
7
7
  }
8
8
 
9
+ // Generated by `node/plugins/layouts.ts`, runtime in `client/utils/layouts.ts`
10
+ declare module 'virtual:generated-layouts' {
11
+ import type { Component, ComputedRef } from 'vue'
12
+ import type { Router, RouteRecordNormalized, RouteRecordRaw } from 'vue-router'
13
+
14
+ type LayoutName = string | false
15
+ type LayoutProps = Record<string, unknown>
16
+
17
+ /** Layout components by normalized name; lazy entries are loader functions. */
18
+ export const layouts: Record<string, Component | (() => Promise<{ default: Component } | Component>)>
19
+ export function createGetRoutes(router: Router, withLayout: true): RouteRecordNormalized[]
20
+ export function createGetRoutes(router: Router, withLayout?: false): () => RouteRecordNormalized[]
21
+ /** Wrap routes in the layout resolved from `meta.layout` (or the default layout). */
22
+ export function setupLayouts(routes: readonly RouteRecordRaw[]): RouteRecordRaw[]
23
+ /** Change the current page's layout until the router navigates to another path. */
24
+ export function setPageLayout(name: LayoutName | null | undefined, props?: LayoutProps): void
25
+ /** Reactive name of the current route's layout, `false` when it renders without one. */
26
+ export function useLayout(): ComputedRef<LayoutName>
27
+ }
28
+
9
29
  declare module '/@valaxyjs/config' {
10
30
  const config: string
11
31
  export default config