Skip to content

Commit

Permalink
Load redocly in both theme and plugin (#269)
Browse files Browse the repository at this point in the history
  • Loading branch information
rohit-gohri authored Feb 10, 2023
1 parent 29d3967 commit bba785a
Show file tree
Hide file tree
Showing 19 changed files with 1,620 additions and 1,520 deletions.
7 changes: 7 additions & 0 deletions .changeset/chatty-jars-tan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'docusaurus-plugin-redoc': minor
'docusaurus-theme-redoc': minor
'redocusaurus': minor
---

Fully support redocly.yaml for setting all theme options
5 changes: 5 additions & 0 deletions .changeset/cyan-dancers-rule.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'docusaurus-theme-redoc': patch
---

Fix types exports of theme package
23 changes: 6 additions & 17 deletions packages/docusaurus-plugin-redoc/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@ import type { OpenAPISpec } from 'redoc/typings/types';
import {
formatProblems,
getTotals,
Config,
bundle,
loadConfig,
stringifyYaml,
Document,
NormalizedProblem,
Expand All @@ -25,13 +23,14 @@ import {
PluginOptionsWithDefault,
DEFAULT_OPTIONS,
} from './options';
import { SpecProps, ApiDocProps } from './types/common';
import type { SpecProps, ApiDocProps } from './types/common';
import { loadSpecWithConfig } from './loadSpec';
import { loadRedoclyConfig } from './loadRedoclyConfig';

// eslint-disable-next-line @typescript-eslint/no-var-requires
const version = require('../package.json').version;

export { PluginOptions };
export { PluginOptions, loadRedoclyConfig };

export default function redocPlugin(
context: LoadContext,
Expand Down Expand Up @@ -61,19 +60,9 @@ export default function redocPlugin(
return {
name: 'docusaurus-plugin-redoc',
async loadContent() {
let redoclyConfig: Config;

if (config) {
if (typeof config === 'string') {
redoclyConfig = await loadConfig({
configPath: config,
});
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
redoclyConfig = new Config(config as any);
}
} else {
redoclyConfig = await loadConfig();
const redoclyConfig = await loadRedoclyConfig(config);
if (redoclyConfig.configFile) {
filesToWatch.push(redoclyConfig.configFile);
}

let bundledSpec: Document, problems: NormalizedProblem[];
Expand Down
22 changes: 22 additions & 0 deletions packages/docusaurus-plugin-redoc/src/loadRedoclyConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Config, loadConfig } from '@redocly/openapi-core';

export async function loadRedoclyConfig(
config?: string | unknown,
): Promise<Config> {
let redoclyConfig: Config;

if (config) {
if (typeof config === 'string') {
redoclyConfig = await loadConfig({
configPath: config,
});
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
redoclyConfig = new Config(config as any);
}
} else {
redoclyConfig = await loadConfig();
}

return redoclyConfig;
}
1 change: 0 additions & 1 deletion packages/docusaurus-plugin-redoc/src/types/common.d.ts

This file was deleted.

1 change: 1 addition & 0 deletions packages/docusaurus-plugin-redoc/src/types/common.ts
1 change: 1 addition & 0 deletions packages/docusaurus-theme-redoc/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
},
"homepage": "https://github.com/rohit-gohri/redocusaurus/tree/main/packages/docusaurus-theme-redoc#readme",
"dependencies": {
"@redocly/openapi-core": "1.0.0-beta.123",
"clsx": "^1.2.1",
"copyfiles": "^2.4.1",
"lodash": "^4.17.21",
Expand Down
4 changes: 2 additions & 2 deletions packages/docusaurus-theme-redoc/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { getGlobalData } from './redocData';
// eslint-disable-next-line import/no-extraneous-dependencies, import/order
import webpack from 'webpack';

export { ThemeOptions, GlobalData };
export type { ThemeOptions, GlobalData };

export default function redocTheme(
context: LoadContext,
Expand Down Expand Up @@ -41,7 +41,7 @@ export default function redocTheme(
},
async contentLoaded({ actions }) {
const { setGlobalData } = actions;
const globalData = getGlobalData(options);
const globalData = await getGlobalData(options);

setGlobalData(globalData);
},
Expand Down
33 changes: 29 additions & 4 deletions packages/docusaurus-theme-redoc/src/redocData.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { RedocRawOptions } from 'redoc';
import merge from 'lodash/merge';
import { Config, loadConfig } from '@redocly/openapi-core';
import { GlobalData, RedocThemeOverrides, ThemeOptions } from './types/options';

const defaultOptions: Partial<RedocRawOptions> = {
Expand Down Expand Up @@ -140,12 +141,36 @@ export function getRedocThemes(
};
}

export function getGlobalData({
export async function getGlobalData({
primaryColor,
primaryColorDark = primaryColor,
theme: customTheme,
theme: customThemeDeprecated,
options,
}: ThemeOptions): GlobalData {
}: ThemeOptions): Promise<GlobalData> {
let redoclyOptions: Config['theme']['openapi'];

if (options) {
if (typeof options === 'string') {
redoclyOptions = (
await loadConfig({
configPath: options,
})
).theme.openapi;
} else {
redoclyOptions = new Config({
theme: {
openapi: options,
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any).theme.openapi;
}
} else {
redoclyOptions = (await loadConfig()).theme.openapi;
}
const customTheme = {
...redoclyOptions?.theme,
...customThemeDeprecated,
};
const overrides = getDefaultTheme(primaryColor, customTheme);
const overridesDark = getDefaultTheme(primaryColorDark, customTheme);

Expand All @@ -156,7 +181,7 @@ export function getGlobalData({
darkTheme,
options: {
...defaultOptions,
...options,
...redoclyOptions,
},
};
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { RedocRawOptions } from 'redoc';
import type { RedocRawOptions, RedocProps } from 'redoc';

export type RecursivePartial<T> = {
[P in keyof T]?: T[P] extends (infer U)[]
Expand All @@ -13,6 +13,7 @@ export type RedocThemeOverrides = RecursivePartial<
>;

export interface ThemeOptions {
id?: string;
/**
* Primary Color to pass to Redoc Theme,
* ideally this should be all the customization you need
Expand All @@ -26,20 +27,22 @@ export interface ThemeOptions {
primaryColorDark?: string;
/**
* Options to pass to redoc
* @deprecated
* @see https://github.com/redocly/redoc#redoc-options-object
*/
options?: Partial<Omit<RedocRawOptions, 'theme'>>;
options?: string | Partial<Omit<RedocRawOptions, 'theme'>>;
/**
* Options to pass to override RedocThemeObject if you
* want to customize the theme yourself.
* **NOTE:** This will overwrite the dark/light mode fixes added in `redocusaurus`
* @deprecated
* @see https://github.com/Redocly/redoc#redoc-theme-object
*/
theme?: Partial<RedocRawOptions['theme']>;
}

export type GlobalData = {
options: NonNullable<ThemeOptions['options']>;
options: RedocProps['store']['rawOptions'];
darkTheme: Partial<RedocRawOptions['theme']>;
lightTheme: Partial<RedocRawOptions['theme']>;
};
43 changes: 29 additions & 14 deletions packages/redocusaurus/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import type { ThemeOptions } from 'docusaurus-theme-redoc';
export interface PresetOptions {
id?: string;
debug?: boolean;
/**
* Path to the Redocly config file `redocly.yaml`
*/
config?: string;
specs: PluginOptions[];
theme?: ThemeOptions;
}
Expand All @@ -19,7 +23,7 @@ export default function preset(
},
) {
let specsArray: PluginOptions[] = [];
const { debug = false, specs, theme = {} } = opts;
const { debug = false, specs, theme = {}, config } = opts;
if (debug) {
console.error('[REDOCUSAURUS] Options:', opts);
}
Expand All @@ -36,32 +40,43 @@ export default function preset(
const id = opts.id ? `-${opts.id}` : '';
const themeId = `theme-redoc${id}`;

const config = {
const resolvedPreset: {
themes: readonly (readonly [string, ThemeOptions])[];
plugins: readonly (readonly [string, PluginOptions])[];
} = {
themes: [
[
require.resolve('docusaurus-theme-redoc'),
{
id: themeId,
options: config,
...theme,
},
],
],
plugins: [
...specsArray.map((pluginOpts, index) => [
require.resolve('docusaurus-plugin-redoc'),
{
...pluginOpts,
themeId,
id: pluginOpts.id || `plugin-redoc${id}-${index}`,
debug,
},
]),
...specsArray.map(
(pluginOpts, index) =>
[
require.resolve('docusaurus-plugin-redoc'),
{
config,
...pluginOpts,
themeId,
id: pluginOpts.id || `plugin-redoc${id}-${index}`,
debug,
},
] as const,
),
],
};
} as const;

if (debug) {
console.error('[REDOCUSAURUS] Final:', JSON.stringify(config, null, 2));
console.error(
'[REDOCUSAURUS] Final:',
JSON.stringify(resolvedPreset, null, 2),
);
}

return config;
return resolvedPreset;
}
27 changes: 23 additions & 4 deletions website/docs/getting-started/Installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ yarn add redocusaurus
presets: [
// .. Your other presets' config
'@docusaurus/preset-classic',
// Redocusaurus config
[
'redocusaurus',
{
Expand Down Expand Up @@ -83,9 +82,9 @@ yarn add redocusaurus
};
```

The API Doc will be available at the path specific by `route`. To skip adding a
route altogether just don't set the `route` property. You will still be
able to reference schema elements manually using [Schema Imports](/docs/guides/schema-imports) or create Custom React Pages using the data and theme components.
The API Doc will be available at the path specific by `route`. To skip adding a route altogether just don't set the `route` property.
You will still be able to reference schema elements manually using [Schema Imports](/docs/guides/schema-imports) or create Custom React Pages using the data and theme components.
If you have a [`redocly.yaml`](https://redocly.com/docs/cli/configuration/) it will be loaded automatically.
## Options
Expand All @@ -96,3 +95,23 @@ An **array** of plugin options, see [plugin options](./plugin-options.md) for in
### theme
Pass options to customize the theme, see [theme options](./theme-options.md) for individual option details.
### config (optional)
> type: string
Redocly config to bundle file and provide options to. You can provide a custom path to a `redocly.yaml` file, if not provided then it will try to load it from the root of your project if it exists.
Example: [redocly.yaml](https://github.com/rohit-gohri/redocusaurus/blob/main/website/redocly.yaml)
Reference: <https://redocly.com/docs/cli/configuration/>. Only supports options marked as "Supported in Redoc CE".
:::important
When setting the `redocly.yaml` config, you website renders correctly only once it is built and run with the following commands:
```bash
npm run build
npm run serve
```
When running the website locally, with `npm start`, some error messages can be displayed.
:::
19 changes: 5 additions & 14 deletions website/docs/getting-started/plugin-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,10 @@ Route URL at which docs would be available, this will use the theme component `@

An object to pass as layout props. Useful to set title/description of the page. See all properties available [here](https://github.com/rohit-gohri/redocusaurus/blob/main/packages/docusaurus-plugin-redoc/src/options.ts#L3).

### config (optional, string or object: redoclyConfig)
### config (optional)

Redocly config to bundle file. You can provide a custom path to a `redocly.yaml` file, if not provided then it will try to load it from the root of your project if it exists.

See: <https://redocly.com/docs/cli/configuration/configuration-file/>

:::important
When setting the `redocly.yaml` config, you website renders correctly only once it is built and run with the following commands:

```bash
$ npm run build
$ npm run serve
```

When running the website locally, with `npm start`, some error messages can be displayed.
:::caution
Deprecated: Use `redocly.yaml` to specify theme. See [example](https://github.com/rohit-gohri/redocusaurus/blob/main/website/redocly.yaml).
:::

Same as config option in [root options](./Installation.md#config-optional) but specific for loading data.
25 changes: 18 additions & 7 deletions website/docs/getting-started/theme-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,28 @@ This value will be used as `colors.primary.main` in the `themes` option. Must be
Optional way to change the highlighted color used by Redoc in dark mode. Defaults to `primaryColor` if not set.
This value will be used as `colors.primary.main` in the `themes` option. Must be an actual color value and not a css variable.

### options (optional, object)
### theme (optional, object)

Override redoc options passed to [RedocStandalone](https://redoc.ly/docs/redoc/quickstart/react/) component. See the defaults [here](https://github.com/rohit-gohri/redocusaurus/blob/main/packages/docusaurus-theme-redoc/src/redocData.ts#L5-L12).
:::caution
Deprecated: Use `redocly.yaml` to specify theme. See [example](https://github.com/rohit-gohri/redocusaurus/blob/main/website/redocly.yaml).
:::

Available properties [here](https://github.com/Redocly/redoc#redoc-options-object).
You cannot set theme property using this property, use `theme` option below instead.
Override the redoc theme object passed to Redoc. See the defaults [here](https://github.com/Redocly/redoc#redoc-theme-object).

### theme (optional, object)
:::caution
Note: You should not override any color using this property, as it will be the same value for dark and light themes.
:::

Override the redoc theme object passed to Redoc. See the default [here](https://github.com/Redocly/redoc#redoc-theme-object).
### options (optional, object)

:::caution
Note: You should not override any color using this property, as it will be the same value for dark and light themes.
Deprecated: Use `redocly.yaml` to specify `theme.options`. See [example](https://github.com/rohit-gohri/redocusaurus/blob/main/website/redocly.yaml).
:::

Override redoc options passed to [RedocStandalone](https://redoc.ly/docs/redoc/quickstart/react/) component. See the defaults [here](https://github.com/rohit-gohri/redocusaurus/blob/main/packages/docusaurus-theme-redoc/src/redocData.ts#L5-L12).

Available properties [here](https://redocly.com/docs/api-reference-docs/configuration/functionality/#featuresopenapi-schema).

You cannot set theme property using this property, use `theme` option above instead.

Auto loaded from `redocly.yaml` if present.
Loading

1 comment on commit bba785a

@vercel
Copy link

@vercel vercel bot commented on bba785a Feb 10, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.