@docusaurus/plugin-content-docs 0.0.0-6001 → 0.0.0-6004

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.
@@ -0,0 +1,273 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ import { useMemo } from 'react';
8
+ import { matchPath, useLocation } from '@docusaurus/router';
9
+ import renderRoutes from '@docusaurus/renderRoutes';
10
+ import { useActivePlugin, useActiveDocContext, useLatestVersion, } from '@docusaurus/plugin-content-docs/client';
11
+ import { isSamePath } from '@docusaurus/theme-common/internal';
12
+ import { uniq } from '@docusaurus/theme-common';
13
+ import { useDocsPreferredVersion } from './docsPreferredVersion';
14
+ import { useDocsVersion } from './docsVersion';
15
+ import { useDocsSidebar } from './docsSidebar';
16
+ export function useDocById(id) {
17
+ const version = useDocsVersion();
18
+ if (!id) {
19
+ return undefined;
20
+ }
21
+ const doc = version.docs[id];
22
+ if (!doc) {
23
+ throw new Error(`no version doc found by id=${id}`);
24
+ }
25
+ return doc;
26
+ }
27
+ /**
28
+ * Pure function, similar to `Array#find`, but works on the sidebar tree.
29
+ */
30
+ export function findSidebarCategory(sidebar, predicate) {
31
+ for (const item of sidebar) {
32
+ if (item.type === 'category') {
33
+ if (predicate(item)) {
34
+ return item;
35
+ }
36
+ const subItem = findSidebarCategory(item.items, predicate);
37
+ if (subItem) {
38
+ return subItem;
39
+ }
40
+ }
41
+ }
42
+ return undefined;
43
+ }
44
+ /**
45
+ * Best effort to assign a link to a sidebar category. If the category doesn't
46
+ * have a link itself, we link to the first sub item with a link.
47
+ */
48
+ export function findFirstSidebarItemCategoryLink(item) {
49
+ if (item.href && !item.linkUnlisted) {
50
+ return item.href;
51
+ }
52
+ for (const subItem of item.items) {
53
+ const link = findFirstSidebarItemLink(subItem);
54
+ if (link) {
55
+ return link;
56
+ }
57
+ }
58
+ return undefined;
59
+ }
60
+ /**
61
+ * Best effort to assign a link to a sidebar item.
62
+ */
63
+ export function findFirstSidebarItemLink(item) {
64
+ if (item.type === 'link' && !item.unlisted) {
65
+ return item.href;
66
+ }
67
+ if (item.type === 'category') {
68
+ return findFirstSidebarItemCategoryLink(item);
69
+ }
70
+ // Other items types, like "html"
71
+ return undefined;
72
+ }
73
+ /**
74
+ * Gets the category associated with the current location. Should only be used
75
+ * on category index pages.
76
+ */
77
+ export function useCurrentSidebarCategory() {
78
+ const { pathname } = useLocation();
79
+ const sidebar = useDocsSidebar();
80
+ if (!sidebar) {
81
+ throw new Error('Unexpected: cant find current sidebar in context');
82
+ }
83
+ const categoryBreadcrumbs = getSidebarBreadcrumbs({
84
+ sidebarItems: sidebar.items,
85
+ pathname,
86
+ onlyCategories: true,
87
+ });
88
+ const deepestCategory = categoryBreadcrumbs.slice(-1)[0];
89
+ if (!deepestCategory) {
90
+ throw new Error(`${pathname} is not associated with a category. useCurrentSidebarCategory() should only be used on category index pages.`);
91
+ }
92
+ return deepestCategory;
93
+ }
94
+ const isActive = (testedPath, activePath) => typeof testedPath !== 'undefined' && isSamePath(testedPath, activePath);
95
+ const containsActiveSidebarItem = (items, activePath) => items.some((subItem) => isActiveSidebarItem(subItem, activePath));
96
+ /**
97
+ * Checks if a sidebar item should be active, based on the active path.
98
+ */
99
+ export function isActiveSidebarItem(item, activePath) {
100
+ if (item.type === 'link') {
101
+ return isActive(item.href, activePath);
102
+ }
103
+ if (item.type === 'category') {
104
+ return (isActive(item.href, activePath) ||
105
+ containsActiveSidebarItem(item.items, activePath));
106
+ }
107
+ return false;
108
+ }
109
+ export function isVisibleSidebarItem(item, activePath) {
110
+ switch (item.type) {
111
+ case 'category':
112
+ return (isActiveSidebarItem(item, activePath) ||
113
+ item.items.some((subItem) => isVisibleSidebarItem(subItem, activePath)));
114
+ case 'link':
115
+ // An unlisted item remains visible if it is active
116
+ return !item.unlisted || isActiveSidebarItem(item, activePath);
117
+ default:
118
+ return true;
119
+ }
120
+ }
121
+ export function useVisibleSidebarItems(items, activePath) {
122
+ return useMemo(() => items.filter((item) => isVisibleSidebarItem(item, activePath)), [items, activePath]);
123
+ }
124
+ /**
125
+ * Get the sidebar the breadcrumbs for a given pathname
126
+ * Ordered from top to bottom
127
+ */
128
+ function getSidebarBreadcrumbs({ sidebarItems, pathname, onlyCategories = false, }) {
129
+ const breadcrumbs = [];
130
+ function extract(items) {
131
+ for (const item of items) {
132
+ if ((item.type === 'category' &&
133
+ (isSamePath(item.href, pathname) || extract(item.items))) ||
134
+ (item.type === 'link' && isSamePath(item.href, pathname))) {
135
+ const filtered = onlyCategories && item.type !== 'category';
136
+ if (!filtered) {
137
+ breadcrumbs.unshift(item);
138
+ }
139
+ return true;
140
+ }
141
+ }
142
+ return false;
143
+ }
144
+ extract(sidebarItems);
145
+ return breadcrumbs;
146
+ }
147
+ /**
148
+ * Gets the breadcrumbs of the current doc page, based on its sidebar location.
149
+ * Returns `null` if there's no sidebar or breadcrumbs are disabled.
150
+ */
151
+ export function useSidebarBreadcrumbs() {
152
+ const sidebar = useDocsSidebar();
153
+ const { pathname } = useLocation();
154
+ const breadcrumbsOption = useActivePlugin()?.pluginData.breadcrumbs;
155
+ if (breadcrumbsOption === false || !sidebar) {
156
+ return null;
157
+ }
158
+ return getSidebarBreadcrumbs({ sidebarItems: sidebar.items, pathname });
159
+ }
160
+ /**
161
+ * "Version candidates" are mostly useful for the layout components, which must
162
+ * be able to work on all pages. For example, if a user has `{ type: "doc",
163
+ * docId: "intro" }` as a navbar item, which version does that refer to? We
164
+ * believe that it could refer to at most three version candidates:
165
+ *
166
+ * 1. The **active version**, the one that the user is currently browsing. See
167
+ * {@link useActiveDocContext}.
168
+ * 2. The **preferred version**, the one that the user last visited. See
169
+ * {@link useDocsPreferredVersion}.
170
+ * 3. The **latest version**, the "default". See {@link useLatestVersion}.
171
+ *
172
+ * @param docsPluginId The plugin ID to get versions from.
173
+ * @returns An array of 1~3 versions with priorities defined above, guaranteed
174
+ * to be unique and non-sparse. Will be memoized, hence stable for deps array.
175
+ */
176
+ export function useDocsVersionCandidates(docsPluginId) {
177
+ const { activeVersion } = useActiveDocContext(docsPluginId);
178
+ const { preferredVersion } = useDocsPreferredVersion(docsPluginId);
179
+ const latestVersion = useLatestVersion(docsPluginId);
180
+ return useMemo(() => uniq([activeVersion, preferredVersion, latestVersion].filter(Boolean)), [activeVersion, preferredVersion, latestVersion]);
181
+ }
182
+ /**
183
+ * The layout components, like navbar items, must be able to work on all pages,
184
+ * even on non-doc ones where there's no version context, so a sidebar ID could
185
+ * be ambiguous. This hook would always return a sidebar to be linked to. See
186
+ * also {@link useDocsVersionCandidates} for how this selection is done.
187
+ *
188
+ * @throws This hook throws if a sidebar with said ID is not found.
189
+ */
190
+ export function useLayoutDocsSidebar(sidebarId, docsPluginId) {
191
+ const versions = useDocsVersionCandidates(docsPluginId);
192
+ return useMemo(() => {
193
+ const allSidebars = versions.flatMap((version) => version.sidebars ? Object.entries(version.sidebars) : []);
194
+ const sidebarEntry = allSidebars.find((sidebar) => sidebar[0] === sidebarId);
195
+ if (!sidebarEntry) {
196
+ throw new Error(`Can't find any sidebar with id "${sidebarId}" in version${versions.length > 1 ? 's' : ''} ${versions.map((version) => version.name).join(', ')}".
197
+ Available sidebar ids are:
198
+ - ${allSidebars.map((entry) => entry[0]).join('\n- ')}`);
199
+ }
200
+ return sidebarEntry[1];
201
+ }, [sidebarId, versions]);
202
+ }
203
+ /**
204
+ * The layout components, like navbar items, must be able to work on all pages,
205
+ * even on non-doc ones where there's no version context, so a doc ID could be
206
+ * ambiguous. This hook would always return a doc to be linked to. See also
207
+ * {@link useDocsVersionCandidates} for how this selection is done.
208
+ *
209
+ * @throws This hook throws if a doc with said ID is not found.
210
+ */
211
+ export function useLayoutDoc(docId, docsPluginId) {
212
+ const versions = useDocsVersionCandidates(docsPluginId);
213
+ return useMemo(() => {
214
+ const allDocs = versions.flatMap((version) => version.docs);
215
+ const doc = allDocs.find((versionDoc) => versionDoc.id === docId);
216
+ if (!doc) {
217
+ const isDraft = versions
218
+ .flatMap((version) => version.draftIds)
219
+ .includes(docId);
220
+ // Drafts should be silently filtered instead of throwing
221
+ if (isDraft) {
222
+ return null;
223
+ }
224
+ throw new Error(`Couldn't find any doc with id "${docId}" in version${versions.length > 1 ? 's' : ''} "${versions.map((version) => version.name).join(', ')}".
225
+ Available doc ids are:
226
+ - ${uniq(allDocs.map((versionDoc) => versionDoc.id)).join('\n- ')}`);
227
+ }
228
+ return doc;
229
+ }, [docId, versions]);
230
+ }
231
+ // TODO later read version/route directly from context
232
+ /**
233
+ * The docs plugin creates nested routes, with the top-level route providing the
234
+ * version metadata, and the subroutes creating individual doc pages. This hook
235
+ * will match the current location against all known sub-routes.
236
+ *
237
+ * @param props The props received by `@theme/DocRoot`
238
+ * @returns The data of the relevant document at the current location, or `null`
239
+ * if no document associated with the current location can be found.
240
+ */
241
+ export function useDocRootMetadata({ route }) {
242
+ const location = useLocation();
243
+ const versionMetadata = useDocsVersion();
244
+ const docRoutes = route.routes;
245
+ const currentDocRoute = docRoutes.find((docRoute) => matchPath(location.pathname, docRoute));
246
+ if (!currentDocRoute) {
247
+ return null;
248
+ }
249
+ // For now, the sidebarName is added as route config: not ideal!
250
+ const sidebarName = currentDocRoute.sidebar;
251
+ const sidebarItems = sidebarName
252
+ ? versionMetadata.docsSidebars[sidebarName]
253
+ : undefined;
254
+ const docElement = renderRoutes(docRoutes);
255
+ return {
256
+ docElement,
257
+ sidebarName,
258
+ sidebarItems,
259
+ };
260
+ }
261
+ /**
262
+ * Filter items we don't want to display on the doc card list view
263
+ * @param items
264
+ */
265
+ export function filterDocCardListItems(items) {
266
+ return items.filter((item) => {
267
+ const canHaveLink = item.type === 'category' || item.type === 'link';
268
+ if (canHaveLink) {
269
+ return !!findFirstSidebarItemLink(item);
270
+ }
271
+ return true;
272
+ });
273
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ import { type ReactNode } from 'react';
8
+ import type { PropVersionMetadata } from '@docusaurus/plugin-content-docs';
9
+ /**
10
+ * Provide the current version's metadata to your children.
11
+ */
12
+ export declare function DocsVersionProvider({ children, version, }: {
13
+ children: ReactNode;
14
+ version: PropVersionMetadata | null;
15
+ }): JSX.Element;
16
+ /**
17
+ * Gets the version metadata of the current doc page.
18
+ */
19
+ export declare function useDocsVersion(): PropVersionMetadata;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ import React, { useContext } from 'react';
8
+ import { ReactContextError } from '@docusaurus/theme-common/internal';
9
+ const Context = React.createContext(null);
10
+ /**
11
+ * Provide the current version's metadata to your children.
12
+ */
13
+ export function DocsVersionProvider({ children, version, }) {
14
+ return <Context.Provider value={version}>{children}</Context.Provider>;
15
+ }
16
+ /**
17
+ * Gets the version metadata of the current doc page.
18
+ */
19
+ export function useDocsVersion() {
20
+ const version = useContext(Context);
21
+ if (version === null) {
22
+ throw new ReactContextError('DocsVersionProvider');
23
+ }
24
+ return version;
25
+ }
@@ -5,6 +5,14 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
  import type { UseDataOptions } from '@docusaurus/types';
8
+ export { useDocById, findSidebarCategory, findFirstSidebarItemLink, isActiveSidebarItem, isVisibleSidebarItem, useVisibleSidebarItems, useSidebarBreadcrumbs, useDocsVersionCandidates, useLayoutDoc, useLayoutDocsSidebar, useDocRootMetadata, useCurrentSidebarCategory, filterDocCardListItems, } from './docsUtils';
9
+ export { useDocsPreferredVersion } from './docsPreferredVersion';
10
+ export { DocSidebarItemsExpandedStateProvider, useDocSidebarItemsExpandedState, } from './docSidebarItemsExpandedState';
11
+ export { DocsVersionProvider, useDocsVersion } from './docsVersion';
12
+ export { DocsSidebarProvider, useDocsSidebar } from './docsSidebar';
13
+ export { DocProvider, useDoc, type DocContextValue } from './doc';
14
+ export { useDocsPreferredVersionByPluginId, DocsPreferredVersionContextProvider, } from './docsPreferredVersion';
15
+ export { useDocsContextualSearchTags, getDocsVersionSearchTag, } from './docsSearch';
8
16
  export type ActivePlugin = {
9
17
  pluginId: string;
10
18
  pluginData: GlobalPluginData;
@@ -7,6 +7,14 @@
7
7
  import { useLocation } from '@docusaurus/router';
8
8
  import { useAllPluginInstancesData, usePluginData, } from '@docusaurus/useGlobalData';
9
9
  import { getActivePlugin, getLatestVersion, getActiveVersion, getActiveDocContext, getDocVersionSuggestions, } from './docsClientUtils';
10
+ export { useDocById, findSidebarCategory, findFirstSidebarItemLink, isActiveSidebarItem, isVisibleSidebarItem, useVisibleSidebarItems, useSidebarBreadcrumbs, useDocsVersionCandidates, useLayoutDoc, useLayoutDocsSidebar, useDocRootMetadata, useCurrentSidebarCategory, filterDocCardListItems, } from './docsUtils';
11
+ export { useDocsPreferredVersion } from './docsPreferredVersion';
12
+ export { DocSidebarItemsExpandedStateProvider, useDocSidebarItemsExpandedState, } from './docSidebarItemsExpandedState';
13
+ export { DocsVersionProvider, useDocsVersion } from './docsVersion';
14
+ export { DocsSidebarProvider, useDocsSidebar } from './docsSidebar';
15
+ export { DocProvider, useDoc } from './doc';
16
+ export { useDocsPreferredVersionByPluginId, DocsPreferredVersionContextProvider, } from './docsPreferredVersion';
17
+ export { useDocsContextualSearchTags, getDocsVersionSearchTag, } from './docsSearch';
10
18
  // Important to use a constant object to avoid React useEffect executions etc.
11
19
  // see https://github.com/facebook/docusaurus/issues/5089
12
20
  const StableEmptyObject = {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@docusaurus/plugin-content-docs",
3
- "version": "0.0.0-6001",
3
+ "version": "0.0.0-6004",
4
4
  "description": "Docs plugin for Docusaurus.",
5
5
  "main": "lib/index.js",
6
6
  "sideEffects": false,
@@ -35,14 +35,15 @@
35
35
  },
36
36
  "license": "MIT",
37
37
  "dependencies": {
38
- "@docusaurus/core": "0.0.0-6001",
39
- "@docusaurus/logger": "0.0.0-6001",
40
- "@docusaurus/mdx-loader": "0.0.0-6001",
41
- "@docusaurus/module-type-aliases": "0.0.0-6001",
42
- "@docusaurus/types": "0.0.0-6001",
43
- "@docusaurus/utils": "0.0.0-6001",
44
- "@docusaurus/utils-common": "0.0.0-6001",
45
- "@docusaurus/utils-validation": "0.0.0-6001",
38
+ "@docusaurus/core": "0.0.0-6004",
39
+ "@docusaurus/logger": "0.0.0-6004",
40
+ "@docusaurus/mdx-loader": "0.0.0-6004",
41
+ "@docusaurus/module-type-aliases": "0.0.0-6004",
42
+ "@docusaurus/theme-common": "0.0.0-6004",
43
+ "@docusaurus/types": "0.0.0-6004",
44
+ "@docusaurus/utils": "0.0.0-6004",
45
+ "@docusaurus/utils-common": "0.0.0-6004",
46
+ "@docusaurus/utils-validation": "0.0.0-6004",
46
47
  "@types/react-router-config": "^5.0.7",
47
48
  "combine-promises": "^1.1.0",
48
49
  "fs-extra": "^11.1.1",
@@ -66,5 +67,5 @@
66
67
  "engines": {
67
68
  "node": ">=18.0"
68
69
  },
69
- "gitHead": "17774ee60e041b816785ddc45ef63e01d746d8e3"
70
+ "gitHead": "70e1069f65cbb7416b20d8e828293b3d537cc3de"
70
71
  }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import React, {useMemo, type ReactNode, useContext} from 'react';
9
+ import {ReactContextError} from '@docusaurus/theme-common/internal';
10
+ import type {PropDocContent} from '@docusaurus/plugin-content-docs';
11
+
12
+ /**
13
+ * The React context value returned by the `useDoc()` hook.
14
+ * It contains useful data related to the currently browsed doc.
15
+ */
16
+ export type DocContextValue = Pick<
17
+ PropDocContent,
18
+ 'metadata' | 'frontMatter' | 'toc' | 'assets' | 'contentTitle'
19
+ >;
20
+
21
+ const Context = React.createContext<DocContextValue | null>(null);
22
+
23
+ /**
24
+ * Note: we don't use `PropDoc` as context value on purpose. Metadata is
25
+ * currently stored inside the MDX component, but we may want to change that in
26
+ * the future. This layer is a good opportunity to decouple storage from
27
+ * consuming API, potentially allowing us to provide metadata as both props and
28
+ * route context without duplicating the chunks in the future.
29
+ */
30
+ function useContextValue(content: PropDocContent): DocContextValue {
31
+ return useMemo(
32
+ () => ({
33
+ metadata: content.metadata,
34
+ frontMatter: content.frontMatter,
35
+ assets: content.assets,
36
+ contentTitle: content.contentTitle,
37
+ toc: content.toc,
38
+ }),
39
+ [content],
40
+ );
41
+ }
42
+
43
+ /**
44
+ * This is a very thin layer around the `content` received from the MDX loader.
45
+ * It provides metadata about the doc to the children tree.
46
+ */
47
+ export function DocProvider({
48
+ children,
49
+ content,
50
+ }: {
51
+ children: ReactNode;
52
+ content: PropDocContent;
53
+ }): JSX.Element {
54
+ const contextValue = useContextValue(content);
55
+ return <Context.Provider value={contextValue}>{children}</Context.Provider>;
56
+ }
57
+
58
+ /**
59
+ * Returns the data of the currently browsed doc. Gives access to the doc's MDX
60
+ * Component, front matter, metadata, TOC, etc. When swizzling a low-level
61
+ * component (e.g. the "Edit this page" link) and you need some extra metadata,
62
+ * you don't have to drill the props all the way through the component tree:
63
+ * simply use this hook instead.
64
+ */
65
+ export function useDoc(): DocContextValue {
66
+ const doc = useContext(Context);
67
+ if (doc === null) {
68
+ throw new ReactContextError('DocProvider');
69
+ }
70
+ return doc;
71
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import React, {type ReactNode, useMemo, useState, useContext} from 'react';
9
+ import {ReactContextError} from '@docusaurus/theme-common/internal';
10
+
11
+ type ContextValue = {
12
+ /**
13
+ * The item that the user last opened, `null` when there's none open. On
14
+ * initial render, it will always be `null`, which doesn't necessarily mean
15
+ * there's no category open (can have 0, 1, or many being initially open).
16
+ */
17
+ expandedItem: number | null;
18
+ /**
19
+ * Set the currently expanded item, when the user opens one. Set the value to
20
+ * `null` when the user closes an open category.
21
+ */
22
+ setExpandedItem: (a: number | null) => void;
23
+ };
24
+
25
+ const EmptyContext: unique symbol = Symbol('EmptyContext');
26
+ const Context = React.createContext<ContextValue | typeof EmptyContext>(
27
+ EmptyContext,
28
+ );
29
+
30
+ /**
31
+ * Should be used to wrap one sidebar category level. This provider syncs the
32
+ * expanded states of all sibling categories, and categories can choose to
33
+ * collapse itself if another one is expanded.
34
+ */
35
+ export function DocSidebarItemsExpandedStateProvider({
36
+ children,
37
+ }: {
38
+ children: ReactNode;
39
+ }): JSX.Element {
40
+ const [expandedItem, setExpandedItem] = useState<number | null>(null);
41
+ const contextValue = useMemo(
42
+ () => ({expandedItem, setExpandedItem}),
43
+ [expandedItem],
44
+ );
45
+
46
+ return <Context.Provider value={contextValue}>{children}</Context.Provider>;
47
+ }
48
+
49
+ export function useDocSidebarItemsExpandedState(): ContextValue {
50
+ const value = useContext(Context);
51
+ if (value === EmptyContext) {
52
+ throw new ReactContextError('DocSidebarItemsExpandedStateProvider');
53
+ }
54
+ return value;
55
+ }