-
-
Notifications
You must be signed in to change notification settings - Fork 521
Expand file tree
/
Copy pathuse-content.js
More file actions
90 lines (79 loc) · 1.98 KB
/
use-content.js
File metadata and controls
90 lines (79 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { useEffect } from 'preact/hooks';
import { useLocation } from 'preact-iso';
import { createTitle } from './page-title';
import { getContent } from './content.js';
import { useLanguage } from './i18n';
import {
useResource,
createCacheKey,
setupCacheEntry,
CACHE
} from './use-resource.js';
/**
* Correct the few site paths that differ from the markdown file name/structure
*
* @param {string} path
* @returns {string}
*/
export function getContentPath(path) {
if (path == '/') return '/index';
if (path == '/tutorial') return '/tutorial/index';
return path;
}
/**
* @param {string} path
* @returns {import('./../types.d.ts').ContentData}
*/
export function useContent(path) {
const [lang] = useLanguage();
const contentPath = getContentPath(path);
/** @type {import('./../types.d.ts').ContentData} */
const { html, meta } = useResource(() => getContent([lang, contentPath]), [
lang,
contentPath
]);
useTitle(meta.title);
useDescription(meta.description || '');
return { html, meta };
}
/**
* @param {string} path
*/
export function prefetchContent(path) {
const lang = document.documentElement.lang;
const contentPath = getContentPath(path);
const fetch = () => getContent([lang, contentPath]);
const cacheKey = createCacheKey(fetch, [lang, contentPath]);
if (CACHE.has(cacheKey)) return;
setupCacheEntry(fetch, cacheKey);
}
/**
* Set `document.title`
* @param {string} title
*/
export function useTitle(title) {
const { url } = useLocation();
if (typeof window === 'undefined') {
globalThis.title = createTitle(title);
}
useEffect(() => {
if (title) {
document.title = createTitle(title);
}
}, [title, url]);
}
/**
* Set the meta description tag content
* @param {string} text
*/
export function useDescription(text) {
if (typeof window === 'undefined') {
globalThis.description = text;
}
useEffect(() => {
const el = document.querySelector('meta[name=description]');
if (text && el) {
el.setAttribute('content', text);
}
}, [text]);
}