@stoplight/elements-dev-portal 3.0.11 → 3.0.12-beta-0.2

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.
Files changed (107) hide show
  1. package/.storybook/main.js +6 -0
  2. package/.storybook/manager.js +1 -0
  3. package/.storybook/preview.jsx +46 -0
  4. package/dist/LICENSE +190 -0
  5. package/dist/README.md +22 -0
  6. package/{index.esm.js → dist/index.esm.js} +8 -2
  7. package/{index.js → dist/index.js} +8 -2
  8. package/{index.mjs → dist/index.mjs} +8 -2
  9. package/dist/package.json +51 -0
  10. package/dist/version.d.ts +1 -0
  11. package/{web-components.min.js → dist/web-components.min.js} +1 -1
  12. package/jest.config.js +10 -0
  13. package/package.json +71 -17
  14. package/src/__fixtures__/branches.json +28 -0
  15. package/src/__fixtures__/node-content.json +257 -0
  16. package/src/__fixtures__/table-of-contents.json +144 -0
  17. package/src/components/BranchSelector/BranchSelector.spec.tsx +61 -0
  18. package/src/components/BranchSelector/BranchSelector.stories.tsx +41 -0
  19. package/src/components/BranchSelector/BranchSelector.tsx +50 -0
  20. package/src/components/BranchSelector/index.tsx +1 -0
  21. package/src/components/DevPortalProvider/index.tsx +25 -0
  22. package/src/components/Forbidden.tsx +11 -0
  23. package/src/components/Loading.tsx +9 -0
  24. package/src/components/NodeContent/NodeContent.spec.tsx +128 -0
  25. package/src/components/NodeContent/NodeContent.stories.tsx +60 -0
  26. package/src/components/NodeContent/NodeContent.tsx +235 -0
  27. package/src/components/NodeContent/index.tsx +1 -0
  28. package/src/components/NotFound.tsx +11 -0
  29. package/src/components/Search/Search.stories.tsx +151 -0
  30. package/src/components/Search/Search.tsx +161 -0
  31. package/src/components/Search/SearchOverlay.tsx +88 -0
  32. package/src/components/Search/index.tsx +1 -0
  33. package/src/components/TableOfContents/TableOfContents.stories.tsx +68 -0
  34. package/src/components/TableOfContents/TableOfContents.tsx +54 -0
  35. package/src/components/TableOfContents/index.tsx +1 -0
  36. package/src/components/UpgradeToStarter.tsx +22 -0
  37. package/src/consts.ts +32 -0
  38. package/src/containers/StoplightProject.spec.tsx +78 -0
  39. package/src/containers/StoplightProject.stories.tsx +28 -0
  40. package/src/containers/StoplightProject.tsx +269 -0
  41. package/src/handlers/__tests__/getBranches.test.ts +30 -0
  42. package/src/handlers/__tests__/getNodeContent.test.ts +35 -0
  43. package/src/handlers/__tests__/getNodes.test.ts +38 -0
  44. package/src/handlers/__tests__/getTableOfContents.test.ts +34 -0
  45. package/src/handlers/__tests__/getWorkspace.test.ts +30 -0
  46. package/src/handlers/getBranches.ts +27 -0
  47. package/src/handlers/getNodeContent.ts +53 -0
  48. package/src/handlers/getNodes.ts +69 -0
  49. package/src/handlers/getTableOfContents.ts +30 -0
  50. package/src/handlers/getWorkspace.ts +27 -0
  51. package/src/hooks/__tests__/dataFetching.spec.tsx +42 -0
  52. package/src/hooks/useGetBranches.ts +17 -0
  53. package/src/hooks/useGetNodeContent.ts +24 -0
  54. package/src/hooks/useGetNodes.ts +34 -0
  55. package/src/hooks/useGetTableOfContents.ts +17 -0
  56. package/src/hooks/useGetWorkspace.tsx +13 -0
  57. package/src/index.ts +25 -0
  58. package/src/styles.css +1 -0
  59. package/src/types.ts +85 -0
  60. package/src/version.ts +2 -0
  61. package/src/web-components/__stories__/StoplightProject.stories.tsx +33 -0
  62. package/src/web-components/components.ts +19 -0
  63. package/src/web-components/index.ts +3 -0
  64. package/tsconfig.build.json +18 -0
  65. package/tsconfig.json +7 -0
  66. package/web-components.config.js +1 -0
  67. package/version.d.ts +0 -1
  68. /package/{components → dist/components}/BranchSelector/BranchSelector.d.ts +0 -0
  69. /package/{components → dist/components}/BranchSelector/BranchSelector.spec.d.ts +0 -0
  70. /package/{components → dist/components}/BranchSelector/BranchSelector.stories.d.ts +0 -0
  71. /package/{components → dist/components}/BranchSelector/index.d.ts +0 -0
  72. /package/{components → dist/components}/DevPortalProvider/index.d.ts +0 -0
  73. /package/{components → dist/components}/Forbidden.d.ts +0 -0
  74. /package/{components → dist/components}/Loading.d.ts +0 -0
  75. /package/{components → dist/components}/NodeContent/NodeContent.d.ts +0 -0
  76. /package/{components → dist/components}/NodeContent/NodeContent.spec.d.ts +0 -0
  77. /package/{components → dist/components}/NodeContent/NodeContent.stories.d.ts +0 -0
  78. /package/{components → dist/components}/NodeContent/index.d.ts +0 -0
  79. /package/{components → dist/components}/NotFound.d.ts +0 -0
  80. /package/{components → dist/components}/Search/Search.d.ts +0 -0
  81. /package/{components → dist/components}/Search/Search.stories.d.ts +0 -0
  82. /package/{components → dist/components}/Search/SearchOverlay.d.ts +0 -0
  83. /package/{components → dist/components}/Search/index.d.ts +0 -0
  84. /package/{components → dist/components}/TableOfContents/TableOfContents.d.ts +0 -0
  85. /package/{components → dist/components}/TableOfContents/TableOfContents.stories.d.ts +0 -0
  86. /package/{components → dist/components}/TableOfContents/index.d.ts +0 -0
  87. /package/{components → dist/components}/UpgradeToStarter.d.ts +0 -0
  88. /package/{consts.d.ts → dist/consts.d.ts} +0 -0
  89. /package/{containers → dist/containers}/StoplightProject.d.ts +0 -0
  90. /package/{containers → dist/containers}/StoplightProject.spec.d.ts +0 -0
  91. /package/{containers → dist/containers}/StoplightProject.stories.d.ts +0 -0
  92. /package/{handlers → dist/handlers}/getBranches.d.ts +0 -0
  93. /package/{handlers → dist/handlers}/getNodeContent.d.ts +0 -0
  94. /package/{handlers → dist/handlers}/getNodes.d.ts +0 -0
  95. /package/{handlers → dist/handlers}/getTableOfContents.d.ts +0 -0
  96. /package/{handlers → dist/handlers}/getWorkspace.d.ts +0 -0
  97. /package/{hooks → dist/hooks}/useGetBranches.d.ts +0 -0
  98. /package/{hooks → dist/hooks}/useGetNodeContent.d.ts +0 -0
  99. /package/{hooks → dist/hooks}/useGetNodes.d.ts +0 -0
  100. /package/{hooks → dist/hooks}/useGetTableOfContents.d.ts +0 -0
  101. /package/{hooks → dist/hooks}/useGetWorkspace.d.ts +0 -0
  102. /package/{index.d.ts → dist/index.d.ts} +0 -0
  103. /package/{styles.min.css → dist/styles.min.css} +0 -0
  104. /package/{types.d.ts → dist/types.d.ts} +0 -0
  105. /package/{web-components → dist/web-components}/components.d.ts +0 -0
  106. /package/{web-components → dist/web-components}/index.d.ts +0 -0
  107. /package/{web-components.min.js.LICENSE.txt → dist/web-components.min.js.LICENSE.txt} +0 -0
@@ -0,0 +1,50 @@
1
+ import { FieldButton, Menu } from '@stoplight/mosaic';
2
+ import * as React from 'react';
3
+
4
+ import { Branch } from '../../types';
5
+
6
+ export type BranchSelectorProps = {
7
+ branchSlug: string;
8
+ branches: Branch[];
9
+ onChange: (branch: Branch) => void;
10
+ };
11
+
12
+ export const BranchSelector = ({ branchSlug, branches, onChange }: BranchSelectorProps) => {
13
+ const currentBranch = branches.find(branch => (!branchSlug ? branch.is_default : branch.slug === branchSlug));
14
+ const handleChange = React.useCallback(
15
+ (selectedSlug: React.ReactText) => {
16
+ const selectedBranch = branches.find(branch => branch.slug === selectedSlug);
17
+ if (selectedBranch) {
18
+ onChange(selectedBranch);
19
+ }
20
+ },
21
+ [onChange, branches],
22
+ );
23
+
24
+ return (
25
+ <Menu
26
+ aria-label="Versions"
27
+ placement="bottom left"
28
+ closeOnPress
29
+ matchTriggerWidth
30
+ renderTrigger={({ isOpen }) => (
31
+ <FieldButton w="full" icon="layer-group" px={4} h="md" active={isOpen} borderR={0} roundedR="none">
32
+ {currentBranch?.name || currentBranch?.slug || 'Choose a version'}
33
+ </FieldButton>
34
+ )}
35
+ items={[
36
+ {
37
+ type: 'option_group',
38
+ title: 'Versions',
39
+ onChange: handleChange,
40
+ value: currentBranch?.slug || '',
41
+ children: branches.map(branch => ({
42
+ title: branch.name || branch.slug,
43
+ value: branch.slug,
44
+ meta: branch.is_default ? 'Default' : undefined,
45
+ })),
46
+ },
47
+ ]}
48
+ />
49
+ );
50
+ };
@@ -0,0 +1 @@
1
+ export * from './BranchSelector';
@@ -0,0 +1,25 @@
1
+ import { withMosaicProvider, withPersistenceBoundary, withQueryClientProvider } from '@stoplight/elements-core';
2
+ import * as React from 'react';
3
+
4
+ export type DevPortalProviderProps = {
5
+ platformUrl?: string;
6
+ platformAuthToken?: string;
7
+ isLoggedIn?: boolean;
8
+ };
9
+
10
+ export const PlatformContext = React.createContext<DevPortalProviderProps>({ platformUrl: 'https://stoplight.io' });
11
+
12
+ const PlatformProvider: React.FC<DevPortalProviderProps> = ({
13
+ platformUrl = 'https://stoplight.io',
14
+ platformAuthToken,
15
+ isLoggedIn,
16
+ children,
17
+ }) => {
18
+ return (
19
+ <PlatformContext.Provider value={{ platformUrl, platformAuthToken, isLoggedIn }}>
20
+ {children}
21
+ </PlatformContext.Provider>
22
+ );
23
+ };
24
+
25
+ export const DevPortalProvider = withPersistenceBoundary(withQueryClientProvider(withMosaicProvider(PlatformProvider)));
@@ -0,0 +1,11 @@
1
+ import { Box, Flex, Heading, VStack } from '@stoplight/mosaic';
2
+ import React from 'react';
3
+
4
+ export const Forbidden = () => (
5
+ <Flex align="center" justify="center" flexGrow>
6
+ <VStack spacing={4} align="center">
7
+ <Heading size={1}>Forbidden</Heading>
8
+ <Box as="p">You don't have permission to access this resource</Box>
9
+ </VStack>
10
+ </Flex>
11
+ );
@@ -0,0 +1,9 @@
1
+ import { faCircleNotch } from '@fortawesome/free-solid-svg-icons';
2
+ import { Flex, Icon } from '@stoplight/mosaic';
3
+ import React from 'react';
4
+
5
+ export const Loading = () => (
6
+ <Flex justify="center" alignItems="center" w="full" minH="screen" color="muted">
7
+ <Icon icon={faCircleNotch} size="3x" spin />
8
+ </Flex>
9
+ );
@@ -0,0 +1,128 @@
1
+ import { CustomLinkComponent } from '@stoplight/elements-core';
2
+ import { fireEvent, render, screen } from '@testing-library/react';
3
+ import * as React from 'react';
4
+ import { MemoryRouter } from 'react-router-dom';
5
+
6
+ import nodeContent from '../../__fixtures__/node-content.json';
7
+ import { NodeContent } from './NodeContent';
8
+
9
+ const DummyLink: CustomLinkComponent = ({ children, ...propsRest }) => {
10
+ return <a {...propsRest}>{children}</a>;
11
+ };
12
+
13
+ const data = {
14
+ id: '35hsi28m3b2m0',
15
+ branch_node_id: -1,
16
+ type: 'article',
17
+ uri: '/docs/test.md',
18
+ slug: '35hsi28m3b2m0-header',
19
+ title: 'Header',
20
+ summary:
21
+ 'This is the main header section.\nThe beginning of an awesome article...\nLorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetu...',
22
+ project_id: 'cHJqOjQz',
23
+ branch_id: 'YnI6MjQw',
24
+ branch: 'main',
25
+ links: {},
26
+ outbound_edges: [
27
+ {
28
+ id: '35hsi28m3b2m0',
29
+ type: 'article',
30
+ slug: '35hsi28m3b2m0-header',
31
+ title: 'Header',
32
+ uri: '/docs/test.md',
33
+ },
34
+ ],
35
+ inbound_edges: [],
36
+ data: '---\nstoplight-id: 35hsi28m3b2m0\n---\n\n# Header\nThis is the main header section.\nThe beginning of an awesome article...\nLorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Naggggm quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,\n\n## Subheader\nThis is the subheader section. More ContentHere is some more dummy content to fill the page.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus lacinia odio vitae vestibulum vestibulum. Cras venenatis euismod malesuada.\nThe beginning of an awesome article...\nLorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Naggggm quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,\n### External\nLinkFor more information, visit Google.\nThe beginning of an awesome article...\nLorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Naggggm quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,\n\n[Go to header](#header)\n\n[Go to subheader](#subheader)\n\n<a href="https://www.google.com">Go to Google</a>',
37
+ };
38
+ describe(NodeContent.name, () => {
39
+ it('renders correctly', async () => {
40
+ const { unmount } = render(
41
+ <MemoryRouter>
42
+ <NodeContent node={nodeContent} Link={DummyLink} />
43
+ </MemoryRouter>,
44
+ );
45
+
46
+ expect(screen.getByRole('heading', { name: /create todo/i })).toBeInTheDocument();
47
+ expect(
48
+ await screen.findByText(
49
+ 'Markdown is supported in descriptions. Add information here for users to get accustomed to endpoints',
50
+ ),
51
+ ).toBeInTheDocument();
52
+
53
+ unmount();
54
+ });
55
+
56
+ it('shows TryIt by default', () => {
57
+ const { unmount } = render(
58
+ <MemoryRouter>
59
+ <NodeContent node={nodeContent} Link={DummyLink} />
60
+ </MemoryRouter>,
61
+ );
62
+
63
+ expect(screen.getByText(/send api request/i)).toBeInTheDocument();
64
+
65
+ unmount();
66
+ });
67
+
68
+ it('can hide TryIt', () => {
69
+ const { unmount } = render(
70
+ <MemoryRouter>
71
+ <NodeContent node={nodeContent} Link={DummyLink} hideTryIt />
72
+ </MemoryRouter>,
73
+ );
74
+
75
+ expect(screen.queryByText(/send api request/i)).not.toBeInTheDocument();
76
+
77
+ unmount();
78
+ });
79
+
80
+ it('can hide SecurityInfo', () => {
81
+ const { unmount } = render(
82
+ <MemoryRouter>
83
+ <NodeContent node={nodeContent} Link={DummyLink} hideSecurityInfo />
84
+ </MemoryRouter>,
85
+ );
86
+
87
+ expect(screen.getByRole('heading', { name: /create todo/i })).toBeInTheDocument();
88
+ expect(screen.queryByText(/API Key/i)).not.toBeInTheDocument();
89
+
90
+ unmount();
91
+ });
92
+ });
93
+
94
+ describe('NodeContent Component Navigation Links', () => {
95
+ const originalLocation = window.location;
96
+ beforeAll(() => {
97
+ delete (window as any).location;
98
+ (window as any).location = {
99
+ ...originalLocation,
100
+ pathname: data.slug,
101
+ };
102
+ });
103
+
104
+ it('renders links with correct href attributes and navigates to target sections on click', () => {
105
+ const { unmount } = render(
106
+ <MemoryRouter>
107
+ <NodeContent node={data} Link={DummyLink} hideSecurityInfo />
108
+ </MemoryRouter>,
109
+ );
110
+
111
+ const headerElement = screen.getByRole('link', { name: /Go to header/i });
112
+ const subheaderElement = screen.getByRole('link', { name: /Go to subheader/i });
113
+
114
+ expect(headerElement).toHaveAttribute('href', '#header');
115
+ expect(subheaderElement).toHaveAttribute('href', '#subheader');
116
+ fireEvent.click(headerElement);
117
+
118
+ expect(document.getElementById('header')).toBeInTheDocument();
119
+ fireEvent.click(subheaderElement);
120
+ expect(document.getElementById('subheader')).toBeInTheDocument();
121
+
122
+ unmount();
123
+
124
+ afterAll(() => {
125
+ window.location = originalLocation;
126
+ });
127
+ });
128
+ });
@@ -0,0 +1,60 @@
1
+ import { Story } from '@storybook/react';
2
+ import * as React from 'react';
3
+
4
+ import { useGetNodeContent } from '../../hooks/useGetNodeContent';
5
+ import { NodeContent } from './';
6
+
7
+ // Wrapper to show how to use the node content hook
8
+ const NodeContentWrapper = ({
9
+ nodeSlug,
10
+ projectId,
11
+ branchSlug,
12
+ }: {
13
+ nodeSlug: string;
14
+ projectId: string;
15
+ branchSlug?: string;
16
+ }) => {
17
+ const { data } = useGetNodeContent({ nodeSlug, projectId, branchSlug });
18
+
19
+ return data ? (
20
+ <NodeContent
21
+ node={data}
22
+ Link={({ children, ...props }) => {
23
+ return (
24
+ <a
25
+ onClick={() => {
26
+ console.log('Link clicked!', props);
27
+ }}
28
+ >
29
+ {children}
30
+ </a>
31
+ );
32
+ }}
33
+ />
34
+ ) : (
35
+ <>Loading</>
36
+ );
37
+ };
38
+
39
+ export default {
40
+ title: 'Public/NodeContent',
41
+ component: NodeContentWrapper,
42
+ argTypes: {
43
+ nodeSlug: { table: { category: 'Input' } },
44
+ projectId: { table: { category: 'Input' } },
45
+ branchSlug: { table: { category: 'Input' } },
46
+ platformUrl: { table: { category: 'Input' } },
47
+ },
48
+ args: {
49
+ nodeSlug: 'b3A6Mzg5NDM2-create-todo',
50
+ projectId: 'cHJqOjYwNjYx',
51
+ branchSlug: '',
52
+ platformUrl: 'https://stoplight.io',
53
+ },
54
+ };
55
+
56
+ export const Playground: Story<{ nodeSlug: string; projectId: string; branchSlug?: string }> = args => (
57
+ <NodeContentWrapper {...args} />
58
+ );
59
+
60
+ Playground.storyName = 'Create Todo';
@@ -0,0 +1,235 @@
1
+ import {
2
+ CustomLinkComponent,
3
+ Docs,
4
+ DocsProps,
5
+ LinkHeading,
6
+ MarkdownComponentsProvider,
7
+ MockingProvider,
8
+ ReferenceResolver,
9
+ RouterTypeContext,
10
+ } from '@stoplight/elements-core';
11
+ import { CustomComponentMapping } from '@stoplight/markdown-viewer';
12
+ import { dirname, resolve } from '@stoplight/path';
13
+ import { NodeType } from '@stoplight/types';
14
+ import * as React from 'react';
15
+ import { useLocation } from 'react-router-dom';
16
+
17
+ import { Node } from '../../types';
18
+
19
+ // Props shared with elements-core Docs component
20
+ type DocsBaseProps = Pick<
21
+ DocsProps,
22
+ 'tryItCorsProxy' | 'tryItCredentialsPolicy' | 'nodeHasChanged' | 'nodeUnsupported'
23
+ >;
24
+ type DocsLayoutProps = Pick<
25
+ Required<DocsProps>['layoutOptions'],
26
+ 'compact' | 'hideTryIt' | 'hideTryItPanel' | 'hideSamples' | 'hideExport' | 'hideSecurityInfo' | 'hideServerInfo'
27
+ >;
28
+
29
+ export type NodeContentProps = {
30
+ node: Node;
31
+ Link: CustomLinkComponent;
32
+
33
+ /**
34
+ * Allows to hide mocking button
35
+ */
36
+ hideMocking?: boolean;
37
+
38
+ /**
39
+ * Support for custom reference resolver
40
+ */
41
+ refResolver?: ReferenceResolver;
42
+
43
+ maxRefDepth?: number;
44
+
45
+ onExportRequest?: (type: 'original' | 'bundled') => void;
46
+ } & DocsBaseProps &
47
+ DocsLayoutProps;
48
+
49
+ export const NodeContent = ({
50
+ node,
51
+ Link,
52
+ hideMocking,
53
+ refResolver,
54
+ maxRefDepth,
55
+
56
+ // Docs base props
57
+ tryItCorsProxy,
58
+ tryItCredentialsPolicy,
59
+ nodeHasChanged,
60
+ nodeUnsupported,
61
+
62
+ // Docs layout props
63
+ compact,
64
+ hideTryIt,
65
+ hideSamples,
66
+ hideTryItPanel,
67
+ hideSecurityInfo,
68
+ hideServerInfo,
69
+
70
+ // Exporting
71
+ hideExport,
72
+ onExportRequest,
73
+ }: NodeContentProps) => {
74
+ return (
75
+ <NodeLinkContext.Provider value={[node, Link]}>
76
+ <MarkdownComponentsProvider
77
+ value={{
78
+ a: LinkComponent,
79
+ // These override the default markdown-viewer components and modifies the
80
+ // rendering of hash routing hrefs for headings in elements-core for the BaseArticleComponent
81
+ h2: ({ color, ...props }) => <LinkHeading size={2} {...props} />,
82
+ h3: ({ color, ...props }) => <LinkHeading size={3} {...props} />,
83
+ h4: ({ color, ...props }) => <LinkHeading size={4} {...props} />,
84
+ }}
85
+ >
86
+ <MockingProvider mockUrl={node.links.mock_url} hideMocking={hideMocking}>
87
+ <Docs
88
+ nodeType={node.type as NodeType}
89
+ nodeData={node.data}
90
+ nodeTitle={node.title}
91
+ disableProps={node?.disableProps}
92
+ layoutOptions={{
93
+ compact,
94
+ hideTryIt: hideTryIt,
95
+ hideTryItPanel: hideTryItPanel,
96
+ hideSamples,
97
+ hideSecurityInfo: hideSecurityInfo,
98
+ hideServerInfo: hideServerInfo,
99
+ hideExport:
100
+ hideExport ||
101
+ (node.links.export_url ?? node.links.export_original_file_url ?? node.links.export_bundled_file_url) ===
102
+ undefined,
103
+ }}
104
+ useNodeForRefResolving
105
+ refResolver={refResolver}
106
+ maxRefDepth={maxRefDepth}
107
+ tryItCorsProxy={tryItCorsProxy}
108
+ exportProps={
109
+ [NodeType.HttpService, NodeType.Model].includes(node.type as NodeType)
110
+ ? {
111
+ original: onExportRequest
112
+ ? { onPress: () => onExportRequest('original') }
113
+ : { href: node.links.export_original_file_url ?? node.links.export_url },
114
+ bundled: onExportRequest
115
+ ? { onPress: () => onExportRequest('bundled') }
116
+ : { href: node.links.export_bundled_file_url ?? getBundledUrl(node.links.export_url) },
117
+ }
118
+ : undefined
119
+ }
120
+ tryItCredentialsPolicy={tryItCredentialsPolicy}
121
+ nodeHasChanged={nodeHasChanged}
122
+ nodeUnsupported={nodeUnsupported}
123
+ />
124
+ </MockingProvider>
125
+ </MarkdownComponentsProvider>
126
+ </NodeLinkContext.Provider>
127
+ );
128
+ };
129
+
130
+ const NodeLinkContext = React.createContext<[Node, CustomLinkComponent] | undefined>(undefined);
131
+
132
+ const externalRegex = new RegExp('^(?:[a-z]+:)?//', 'i');
133
+ const LinkComponent: CustomComponentMapping['a'] = ({ children, href, title }) => {
134
+ console.log('LinkComponent href-----', href);
135
+ const ctx = React.useContext(NodeLinkContext);
136
+ const routerKind = React.useContext(RouterTypeContext);
137
+
138
+ const { pathname } = useLocation();
139
+ const route = pathname.split('#')[0];
140
+
141
+ try {
142
+ if (href && externalRegex.test(href)) {
143
+ const baseURL = window.location.host;
144
+ const hrefURL = new URL(href).host;
145
+
146
+ if (baseURL === hrefURL) {
147
+ // Open URL in same tab if domain match
148
+ return (
149
+ <a href={href} title={title ? title : undefined}>
150
+ {children}
151
+ </a>
152
+ );
153
+ }
154
+ return (
155
+ <a href={href} target="_blank" rel="noreferrer" title={title ? title : undefined}>
156
+ {children}
157
+ </a>
158
+ );
159
+ }
160
+ } catch (error) {
161
+ console.error(error);
162
+ }
163
+
164
+ if (href && ctx) {
165
+ const [node, Link] = ctx;
166
+ console.log('LinkComponent node-----', node);
167
+
168
+ // Resolve relative file URI with
169
+ const { fileUri } = getNodeUriParts(node.uri);
170
+ const { fileUri: hrefFileUri } = getNodeUriParts(href);
171
+
172
+ let resolvedUri;
173
+ if (hrefFileUri) {
174
+ // if the href is targeting another file, resolve it against the dir path of current file
175
+ resolvedUri = resolve(dirname(fileUri), href);
176
+ } else {
177
+ // If the href does not include a file, resolve it relative to the current file
178
+ resolvedUri = resolve(fileUri, href);
179
+ }
180
+
181
+ const [resolvedUriWithoutAnchor, hash] = resolvedUri.split('#');
182
+ const decodedUrl = decodeURIComponent(href);
183
+ const decodedResolvedUriWithoutAnchor = decodeURIComponent(resolvedUriWithoutAnchor);
184
+ const [pagePathWithoutHash] = pathname.split('#');
185
+
186
+ let edge = node.outbound_edges.find(
187
+ edge => edge.uri === decodedUrl || edge.uri === decodedResolvedUriWithoutAnchor,
188
+ );
189
+
190
+ if (!edge) {
191
+ edge = node.outbound_edges.find(edge => pagePathWithoutHash === `/${edge.slug}`);
192
+ }
193
+
194
+ if (edge) {
195
+ const slug = routerKind === 'hash' ? `#${route.replace(node.slug, edge.slug)}` : edge.slug;
196
+ return <Link to={`${slug}${hash ? `#${hash}` : ''}`}>{children}</Link>;
197
+ }
198
+ }
199
+
200
+ const fullHref = routerKind === 'hash' ? `#${route}${href}` : href;
201
+ return <a href={fullHref}>{children}</a>;
202
+ };
203
+
204
+ function getBundledUrl(url: string | undefined) {
205
+ if (url === undefined) return undefined;
206
+ const bundledUrl = new URL(url);
207
+ const searchParams = new URLSearchParams(bundledUrl.search);
208
+ searchParams.append('deref', 'optimizedBundle');
209
+ bundledUrl.search = searchParams.toString();
210
+ return bundledUrl.toString();
211
+ }
212
+
213
+ // Extract out just the file portion of the node URI
214
+ // This handles cases such as links to http_operation node uris, which include both the file + encoded pointer, e.g.
215
+ //
216
+ // /reference/openapi.json/paths/~1v2~1contact~1last_change/post#heading-anchor
217
+ // fileUri = /reference/openapi.json
218
+ // pointer = /paths/~1v2~1contact~1last_change/post#heading-anchor
219
+ export const getNodeUriParts = (uri: string): { fileUri: string; pointer: string } => {
220
+ // Check: added console for debugging purpose
221
+ console.log('getNodeUriParts uri-----', uri, 'typeof uri:', typeof uri);
222
+ // Guard against undefined or non-string input
223
+ if (!uri || typeof uri !== 'string') return { fileUri: '', pointer: '' };
224
+ const parts = uri.split(/(\.yaml|\.yml|\.json|\.md)/);
225
+ if (parts === undefined || void 0) {
226
+ return { fileUri: '', pointer: '' };
227
+ }
228
+ if (!parts || parts.length === 1) {
229
+ return { fileUri: '', pointer: parts[0] || '' };
230
+ }
231
+
232
+ const fileUri = `${parts[0] || ''}${parts[1] || ''}`;
233
+
234
+ return { fileUri, pointer: parts[2] || '' };
235
+ };
@@ -0,0 +1 @@
1
+ export * from './NodeContent';
@@ -0,0 +1,11 @@
1
+ import { Box, Flex, Heading, VStack } from '@stoplight/mosaic';
2
+ import React from 'react';
3
+
4
+ export const NotFound = () => (
5
+ <Flex align="center" justify="center" flexGrow>
6
+ <VStack spacing={4} align="center">
7
+ <Heading size={1}>Not Found</Heading>
8
+ <Box as="p">Could not find what you are looking for</Box>
9
+ </VStack>
10
+ </Flex>
11
+ );