@rpcbase/router 0.8.0 → 0.10.0

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rpcbase/router",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "type": "module",
5
5
  "main": "./src/index.ts",
6
6
  "scripts": {
@@ -23,6 +23,8 @@
23
23
  }
24
24
  }
25
25
  },
26
- "dependencies": {},
26
+ "dependencies": {
27
+ "react-router": "7.6.0"
28
+ },
27
29
  "devDependencies": {}
28
30
  }
package/src/index.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from "react-router"
2
2
  export * from "./loadRoute"
3
+ export * from "./useApplyMeta"
@@ -0,0 +1,71 @@
1
+ import { useEffect } from "react"
2
+ import { useLocation } from "react-router"
3
+
4
+ export const useApplyMeta = () => {
5
+ const location = useLocation()
6
+
7
+ useEffect(() => {
8
+ const loadMeta = async () => {
9
+ let defaultTitle = ""
10
+ let defaultMeta = []
11
+ let pagesMeta = {}
12
+
13
+ try {
14
+ const module = await import("@/static/meta")
15
+ defaultTitle = module.defaultTitle || defaultTitle
16
+ defaultMeta = module.defaultMeta || defaultMeta
17
+ pagesMeta = module.pagesMeta || pagesMeta
18
+ } catch (error) {
19
+ if (import.meta.env.MODE !== "production") {
20
+ console.warn(
21
+ "Failed to load meta data from '@/static/meta'.",
22
+ error
23
+ )
24
+ }
25
+ return
26
+ }
27
+
28
+ let pageMeta = pagesMeta[location.pathname]
29
+
30
+ if (!pageMeta) {
31
+ pageMeta = { title: defaultTitle, meta: defaultMeta }
32
+ }
33
+
34
+ document.title = pageMeta.title
35
+
36
+ // Remove previous dynamically inserted tags
37
+ document.querySelectorAll("[data-react-meta]").forEach((tag) => tag.remove())
38
+
39
+ // Inject new tags
40
+ pageMeta.meta.forEach((meta) => {
41
+ const metaElement = document.createElement("meta")
42
+ metaElement.setAttribute("data-react-meta", "true")
43
+
44
+ // Set all attributes from the meta object
45
+ Object.entries(meta).forEach(([key, value]) => {
46
+ if (value) {
47
+ metaElement.setAttribute(key, value.toString())
48
+ }
49
+ })
50
+
51
+ document.head.appendChild(metaElement)
52
+ })
53
+
54
+ // Update canonical link
55
+ const canonicalUrl = `${window.location.origin}${location.pathname}`
56
+
57
+ const existingCanonical = document.querySelector("link[rel=\"canonical\"]")
58
+ if (existingCanonical) {
59
+ existingCanonical.remove()
60
+ }
61
+
62
+ const canonicalLink = document.createElement("link")
63
+ canonicalLink.setAttribute("rel", "canonical")
64
+ canonicalLink.setAttribute("href", canonicalUrl)
65
+ canonicalLink.setAttribute("data-react-meta", "true")
66
+ document.head.appendChild(canonicalLink)
67
+ }
68
+
69
+ loadMeta()
70
+ }, [location.pathname])
71
+ }