docs:更新文档

This commit is contained in:
张益铭
2021-03-01 15:06:11 +08:00
parent 1542135ab0
commit 9064b372e8
5835 changed files with 904126 additions and 161722 deletions

View File

@@ -0,0 +1,5 @@
export declare const Content: {
setup(): () => import("vue").VNode<import("vue").RendererNode, import("vue").RendererElement, {
[key: string]: any;
}> | null;
};

View File

@@ -0,0 +1,13 @@
import { h } from 'vue';
import { useRoute } from '../router';
import { usePrefetch } from '../composables/preFetch';
export const Content = {
setup() {
const route = useRoute();
if (process.env.NODE_ENV === 'production') {
// in prod mode, enable intersectionObserver based pre-fetch.
usePrefetch();
}
return () => (route.component ? h(route.component) : null);
}
};

View File

@@ -0,0 +1,55 @@
<template>
<div class="debug" :class="{ open }" @click="open = !open">
<pre>debug</pre>
<pre>$page {{ $page }}</pre>
<pre>$siteByRoute {{ $siteByRoute }}</pre>
<pre>$site {{ $site }}</pre>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const open = ref(false)
return {
open
}
}
}
</script>
<style>
.debug {
box-sizing: border-box;
position: fixed;
z-index: 999;
cursor: pointer;
bottom: 0;
right: 0;
width: 80px;
height: 30px;
padding: 5px;
overflow: hidden;
color: #eeeeee;
transition: all .15s ease;
background-color: rgba(0,0,0,0.85);
}
.debug.open {
width: 500px;
height: 100%;
margin-top: 0;
padding: 0 0;
overflow: scroll;
}
.debug pre {
font-family: Hack, monospace;
font-size: 13px;
margin: 0;
padding: 5px 10px;
border-bottom: 1px solid #eee;
}
</style>

View File

@@ -0,0 +1,4 @@
import { Ref } from 'vue';
import { SiteData } from '../../../../types/shared';
import { Route } from '../router';
export declare function useUpdateHead(route: Route, siteDataByRouteRef: Ref<SiteData>): void;

View File

@@ -0,0 +1,57 @@
import { watchEffect } from 'vue';
export function useUpdateHead(route, siteDataByRouteRef) {
const metaTags = Array.from(document.querySelectorAll('meta'));
let isFirstUpdate = true;
const updateHeadTags = (newTags) => {
if (process.env.NODE_ENV === 'production' && isFirstUpdate) {
// in production, the initial meta tags are already pre-rendered so we
// skip the first update.
isFirstUpdate = false;
return;
}
metaTags.forEach((el) => document.head.removeChild(el));
metaTags.length = 0;
if (newTags && newTags.length) {
newTags.forEach((headConfig) => {
const el = createHeadElement(headConfig);
document.head.appendChild(el);
metaTags.push(el);
});
}
};
watchEffect(() => {
const pageData = route.data;
const siteData = siteDataByRouteRef.value;
const pageTitle = pageData && pageData.title;
document.title = (pageTitle ? pageTitle + ` | ` : ``) + siteData.title;
updateHeadTags([
['meta', { charset: 'utf-8' }],
[
'meta',
{
name: 'viewport',
content: 'width=device-width,initial-scale=1'
}
],
[
'meta',
{
name: 'description',
content: siteData.description
}
],
...siteData.head,
...((pageData && pageData.frontmatter.head) || [])
]);
});
}
function createHeadElement([tag, attrs, innerHTML]) {
const el = document.createElement(tag);
for (const key in attrs) {
el.setAttribute(key, attrs[key]);
}
if (innerHTML) {
el.innerHTML = innerHTML;
}
return el;
}

View File

@@ -0,0 +1 @@
export declare function usePrefetch(): void;

View File

@@ -0,0 +1,88 @@
// Customized pre-fetch for page chunks based on
// https://github.com/GoogleChromeLabs/quicklink
import { onMounted, onUnmounted, onUpdated } from 'vue';
import { inBrowser, pathToFile } from '../utils';
const hasFetched = new Set();
const createLink = () => document.createElement('link');
const viaDOM = (url) => {
const link = createLink();
link.rel = `prefetch`;
link.href = url;
document.head.appendChild(link);
};
const viaXHR = (url) => {
const req = new XMLHttpRequest();
req.open('GET', url, (req.withCredentials = true));
req.send();
};
let link;
const doFetch = inBrowser &&
(link = createLink()) &&
link.relList &&
link.relList.supports &&
link.relList.supports('prefetch')
? viaDOM
: viaXHR;
export function usePrefetch() {
if (!inBrowser) {
return;
}
if (!window.IntersectionObserver) {
return;
}
let conn;
if ((conn = navigator.connection) &&
(conn.saveData || /2g/.test(conn.effectiveType))) {
// Don't prefetch if using 2G or if Save-Data is enabled.
return;
}
const rIC = window.requestIdleCallback || setTimeout;
let observer = null;
const observeLinks = () => {
if (observer) {
observer.disconnect();
}
observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const link = entry.target;
observer.unobserve(link);
const { pathname } = link;
if (!hasFetched.has(pathname)) {
hasFetched.add(pathname);
const pageChunkPath = pathToFile(pathname);
doFetch(pageChunkPath);
}
}
});
});
rIC(() => {
document.querySelectorAll('.vitepress-content a').forEach((link) => {
const { target, hostname, pathname } = link;
if (
// only prefetch same page navigation, since a new page will load
// the lean js chunk instead.
target !== `_blank` &&
// only prefetch inbound links
hostname === location.hostname) {
if (pathname !== location.pathname) {
observer.observe(link);
}
else {
// No need to prefetch chunk for the current page, but also mark
// it as already fetched. This is because the initial page uses its
// lean chunk, and if we don't mark it, navigation to another page
// with a link back to the first page will fetch its full chunk
// which isn't needed.
hasFetched.add(pathname);
}
}
});
});
};
onMounted(observeLinks);
onUpdated(observeLinks);
onUnmounted(() => {
observer && observer.disconnect();
});
}

View File

@@ -0,0 +1,5 @@
import { Ref } from 'vue';
import { SiteData } from '../../../../types/shared';
export declare type SiteDataRef<T = any> = Ref<SiteData<T>>;
export declare const siteDataRef: Ref<SiteData>;
export declare function useSiteData<T = any>(): Ref<SiteData<T>>;

View File

@@ -0,0 +1,13 @@
import serialized from '@siteData';
import { ref, readonly } from 'vue';
const parse = (data) => readonly(JSON.parse(data));
export const siteDataRef = ref(parse(serialized));
export function useSiteData() {
return siteDataRef;
}
// hmr
if (import.meta.hot) {
import.meta.hot.acceptDeps('/@siteData', (m) => {
siteDataRef.value = parse(m.default);
});
}

View File

@@ -0,0 +1,9 @@
export declare function useSiteDataByRoute(route?: import("../router").Route): import("vue").ComputedRef<{
themeConfig: any;
locales: {};
lang: string;
title: string;
description: string;
base: string;
head: import("../../../../types/shared").HeadConfig[];
}>;

View File

@@ -0,0 +1,9 @@
import { computed } from 'vue';
import { resolveSiteDataByRoute } from '/@shared/config';
import { siteDataRef } from './siteData';
import { useRoute } from '../router';
export function useSiteDataByRoute(route = useRoute()) {
return computed(() => {
return resolveSiteDataByRoute(siteDataRef.value, route.path);
});
}

8
node_modules/vitepress/dist/client/app/exports.d.ts generated vendored Normal file
View File

@@ -0,0 +1,8 @@
export * from './theme';
export { useSiteData } from './composables/siteData';
export { useSiteDataByRoute } from './composables/siteDataByRoute';
export { useRouter, useRoute, Router, Route } from './router';
export { Content } from './components/Content';
import { ComponentOptions } from 'vue';
declare const Debug: ComponentOptions<{}, any, any, any, any, any, any, any>;
export { Debug };

13
node_modules/vitepress/dist/client/app/exports.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
// exports in this file are exposed to themes and md files via 'vitepress'
// so the user can do `import { useRoute, useSiteData } from 'vitepress'`
// theme types
export * from './theme';
// composables
export { useSiteData } from './composables/siteData';
export { useSiteDataByRoute } from './composables/siteDataByRoute';
export { useRouter, useRoute } from './router';
// components
export { Content } from './components/Content';
import _Debug from './components/Debug.vue';
const Debug = _Debug;
export { Debug };

4
node_modules/vitepress/dist/client/app/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,4 @@
export declare function createApp(): {
app: import("vue").App<Element>;
router: import("./router").Router;
};

2
node_modules/vitepress/dist/client/app/index.html generated vendored Normal file
View File

@@ -0,0 +1,2 @@
<div id="app"></div>
<script type="module" src="/@app/index.js"></script>

93
node_modules/vitepress/dist/client/app/index.js generated vendored Normal file
View File

@@ -0,0 +1,93 @@
import { createApp as createClientApp, createSSRApp } from 'vue';
import { createRouter, RouterSymbol } from './router';
import { useUpdateHead } from './composables/head';
import { Content } from './components/Content';
import Debug from './components/Debug.vue';
import Theme from '/@theme/index';
import { inBrowser, pathToFile } from './utils';
import { useSiteDataByRoute } from './composables/siteDataByRoute';
import { siteDataRef } from './composables/siteData';
const NotFound = Theme.NotFound || (() => '404 Not Found');
export function createApp() {
let isInitialPageLoad = inBrowser;
let initialPath;
const router = createRouter((path) => {
let pageFilePath = pathToFile(path);
if (isInitialPageLoad) {
initialPath = pageFilePath;
}
// use lean build if this is the initial page load or navigating back
// to the initial loaded path (the static vnodes already adopted the
// static content on that load so no need to re-fetch the page)
if (isInitialPageLoad || initialPath === pageFilePath) {
pageFilePath = pageFilePath.replace(/\.js$/, '.lean.js');
}
if (inBrowser) {
isInitialPageLoad = false;
// in browser: native dynamic import
return import(/*@vite-ignore*/ pageFilePath);
}
else {
// SSR, sync require
return require(pageFilePath);
}
}, NotFound);
// update route.data on HMR updates of active page
if (import.meta.hot) {
// hot reload pageData
import.meta.hot.on('vitepress:pageData', (payload) => {
if (payload.path.replace(/(\bindex)?\.md$/, '') ===
location.pathname.replace(/(\bindex)?\.html$/, '')) {
router.route.data = payload.pageData;
}
});
}
const app = process.env.NODE_ENV === 'production'
? createSSRApp(Theme.Layout)
: createClientApp(Theme.Layout);
app.provide(RouterSymbol, router);
app.component('Content', Content);
app.component('Debug', process.env.NODE_ENV === 'production' ? () => null : Debug);
const siteDataByRouteRef = useSiteDataByRoute(router.route);
if (inBrowser) {
// dynamically update head tags
useUpdateHead(router.route, siteDataByRouteRef);
}
Object.defineProperties(app.config.globalProperties, {
$site: {
get() {
return siteDataRef.value;
}
},
$siteByRoute: {
get() {
return siteDataByRouteRef.value;
}
},
$page: {
get() {
return router.route.data;
}
},
$theme: {
get() {
return siteDataByRouteRef.value.themeConfig;
}
}
});
if (Theme.enhanceApp) {
Theme.enhanceApp({
app,
router,
siteData: siteDataByRouteRef
});
}
return { app, router };
}
if (inBrowser) {
const { app, router } = createApp();
// wait unitl page component is fetched before mounting
router.go().then(() => {
app.mount('#app');
});
}

20
node_modules/vitepress/dist/client/app/router.d.ts generated vendored Normal file
View File

@@ -0,0 +1,20 @@
import type { Component, InjectionKey } from 'vue';
import { PageData } from '../../../types/shared';
export interface Route {
path: string;
data: PageData;
component: Component | null;
}
export interface Router {
route: Route;
go: (href?: string) => Promise<void>;
}
export declare const RouterSymbol: InjectionKey<Router>;
interface PageModule {
__pageData: string;
default: Component;
}
export declare function createRouter(loadPageModule: (path: string) => PageModule | Promise<PageModule>, fallbackComponent?: Component): Router;
export declare function useRouter(): Router;
export declare function useRoute(): Route;
export {};

148
node_modules/vitepress/dist/client/app/router.js generated vendored Normal file
View File

@@ -0,0 +1,148 @@
import { reactive, inject, markRaw, nextTick, readonly } from 'vue';
export const RouterSymbol = Symbol();
// we are just using URL to parse the pathname and hash - the base doesn't
// matter and is only passed to support same-host hrefs.
const fakeHost = `http://a.com`;
const getDefaultRoute = () => ({
path: '/',
component: null,
// this will be set upon initial page load, which is before
// the app is mounted, so it's guaranteed to be avaiable in
// components
data: null
});
export function createRouter(loadPageModule, fallbackComponent) {
const route = reactive(getDefaultRoute());
const inBrowser = typeof window !== 'undefined';
function go(href = inBrowser ? location.href : '/') {
// ensure correct deep link so page refresh lands on correct files.
const url = new URL(href, fakeHost);
if (!url.pathname.endsWith('/') && !url.pathname.endsWith('.html')) {
url.pathname += '.html';
href = url.pathname + url.search + url.hash;
}
if (inBrowser) {
// save scroll position before changing url
history.replaceState({ scrollPosition: window.scrollY }, document.title);
history.pushState(null, '', href);
}
return loadPage(href);
}
let latestPendingPath = null;
async function loadPage(href, scrollPosition = 0) {
const targetLoc = new URL(href, fakeHost);
const pendingPath = (latestPendingPath = targetLoc.pathname);
try {
let page = loadPageModule(pendingPath);
// only await if it returns a Promise - this allows sync resolution
// on initial render in SSR.
if ('then' in page && typeof page.then === 'function') {
page = await page;
}
if (latestPendingPath === pendingPath) {
latestPendingPath = null;
const { default: comp, __pageData } = page;
if (!comp) {
throw new Error(`Invalid route component: ${comp}`);
}
route.path = pendingPath;
route.component = markRaw(comp);
route.data = readonly(JSON.parse(__pageData));
if (inBrowser) {
nextTick(() => {
if (targetLoc.hash && !scrollPosition) {
const target = document.querySelector(decodeURIComponent(targetLoc.hash));
if (target) {
scrollTo(target, targetLoc.hash);
return;
}
}
window.scrollTo(0, scrollPosition);
});
}
}
}
catch (err) {
if (!err.message.match(/fetch/)) {
console.error(err);
}
if (latestPendingPath === pendingPath) {
latestPendingPath = null;
route.path = pendingPath;
route.component = fallbackComponent ? markRaw(fallbackComponent) : null;
}
}
}
if (inBrowser) {
window.addEventListener('click', (e) => {
const link = e.target.closest('a');
if (link) {
const { href, protocol, hostname, pathname, hash, target } = link;
const currentUrl = window.location;
// only intercept inbound links
if (!e.ctrlKey &&
!e.shiftKey &&
!e.altKey &&
!e.metaKey &&
target !== `_blank` &&
protocol === currentUrl.protocol &&
hostname === currentUrl.hostname) {
e.preventDefault();
if (pathname === currentUrl.pathname) {
// scroll between hash anchors in the same page
if (hash && hash !== currentUrl.hash) {
history.pushState(null, '', hash);
// use smooth scroll when clicking on header anchor links
scrollTo(link, hash, link.classList.contains('header-anchor'));
}
}
else {
go(href);
}
}
}
}, { capture: true });
window.addEventListener('popstate', (e) => {
loadPage(location.href, (e.state && e.state.scrollPosition) || 0);
});
window.addEventListener('hashchange', (e) => {
e.preventDefault();
});
}
return {
route,
go
};
}
export function useRouter() {
const router = inject(RouterSymbol);
if (!router) {
throw new Error('useRouter() is called without provider.');
}
// @ts-ignore
return router;
}
export function useRoute() {
return useRouter().route;
}
function scrollTo(el, hash, smooth = false) {
const pageOffset = document.querySelector('.navbar')
.offsetHeight;
const target = el.classList.contains('.header-anchor')
? el
: document.querySelector(decodeURIComponent(hash));
if (target) {
const targetTop = target.offsetTop - pageOffset - 15;
// only smooth scroll if distance is smaller than screen height.
if (!smooth || Math.abs(targetTop - window.scrollY) > window.innerHeight) {
window.scrollTo(0, targetTop);
}
else {
window.scrollTo({
left: 0,
top: targetTop,
behavior: 'smooth'
});
}
}
}

13
node_modules/vitepress/dist/client/app/theme.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import { App, Ref, ComponentOptions } from 'vue';
import { Router } from './router';
import { SiteData } from '../../../types/shared';
export interface EnhanceAppContext {
app: App;
router: Router;
siteData: Ref<SiteData>;
}
export interface Theme {
Layout: ComponentOptions;
NotFound?: ComponentOptions;
enhanceApp?: (ctx: EnhanceAppContext) => void;
}

0
node_modules/vitepress/dist/client/app/theme.js generated vendored Normal file
View File

5
node_modules/vitepress/dist/client/app/utils.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
export declare const inBrowser: boolean;
/**
* Converts a url path to the corresponding js chunk filename.
*/
export declare function pathToFile(path: string): string;

32
node_modules/vitepress/dist/client/app/utils.js generated vendored Normal file
View File

@@ -0,0 +1,32 @@
export const inBrowser = typeof window !== 'undefined';
/**
* Converts a url path to the corresponding js chunk filename.
*/
export function pathToFile(path) {
let pagePath = path.replace(/\.html$/, '');
if (pagePath.endsWith('/')) {
pagePath += 'index';
}
if (import.meta.env.DEV) {
// awlays force re-fetch content in dev
pagePath += `.md?t=${Date.now()}`;
}
else {
// in production, each .md file is built into a .md.js file following
// the path conversion scheme.
// /foo/bar.html -> ./foo_bar.md
if (inBrowser) {
const base = import.meta.env.BASE_URL;
pagePath = pagePath.slice(base.length).replace(/\//g, '_') + '.md';
// client production build needs to account for page hash, which is
// injected directly in the page's html
const pageHash = __VP_HASH_MAP__[pagePath];
pagePath = `${base}_assets/${pagePath}.${pageHash}.js`;
}
else {
// ssr build uses much simpler name mapping
pagePath = `./${pagePath.slice(1).replace(/\//g, '_')}.md.js`;
}
}
return pagePath;
}