Skip to content

Commit

Permalink
chore(demo): integrated autogenerated docs into the demo (#490)
Browse files Browse the repository at this point in the history
  • Loading branch information
makhnatkin authored Nov 21, 2024
1 parent fbc977c commit 74790ff
Show file tree
Hide file tree
Showing 16 changed files with 154 additions and 20 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ build/
coverage/
storybook-static/
.eslintcache
demo/docs
106 changes: 106 additions & 0 deletions .storybook/addons/generateDocs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import * as fs from 'fs/promises';
import * as path from 'path';

const inputDir = path.join(__dirname, '../../docs');
const outputDir = path.join(__dirname, '../../demo/docs');

/**
* Converts a kebab-case string to camelCase
*/
const kebabToCamelCase = (str: string): string => {
return str.replace(/-./g, (match) => match.charAt(1).toUpperCase());
};

/**
* Generates the content for the MDX file
*/
const getContent = (title: string, updatedContent: string): string => `
{/*
This file is auto-generated. Any changes made to this file will be overwritten
*/}
import { Meta, Markdown } from '@storybook/blocks';
<Meta title="Docs / ${title}" />
<Markdown>{${JSON.stringify(updatedContent)}}</Markdown>
`;

/**
* Writes the MDX file to the specified path
*/
const generateMdxFile = async (
_: string,
outputFilePath: string,
title: string,
updatedContent: string,
): Promise<void> => {
const content = getContent(title, updatedContent);
await fs.writeFile(outputFilePath, content, 'utf8');
console.log(`Generated: ${outputFilePath}`);
};

const TITLE_MATCH = /^#####\s+(.*)$/m;

/**
* Clears the output directory
*/
const clearOutputDir = async (): Promise<void> => {
try {
await fs.rm(outputDir, {recursive: true, force: true});
console.log(`Cleared directory: ${outputDir}`);
} catch (error) {
console.error(`Failed to clear directory: ${outputDir}`, error);
throw error;
}
};

/**
* Generate MDX files from Markdown
*/
const generateDocs = async (): Promise<void> => {
console.log('Running docs:generate...');
try {
await clearOutputDir();
await fs.mkdir(outputDir, {recursive: true});

const files = await fs.readdir(inputDir);

for (const file of files) {
if (path.extname(file) === '.md') {
const inputFilePath = path.join(inputDir, file);
const content = await fs.readFile(inputFilePath, 'utf8');

const titleMatch = content.match(TITLE_MATCH);
if (!titleMatch) {
console.warn(`No title found in ${file}, skipping.`);
continue;
}

const title = titleMatch[1].trim();
const baseName = kebabToCamelCase(file.replace(/\.md$/, ''));
const outputFilePath = path.join(outputDir, `${baseName}.mdx`);

await generateMdxFile(inputFilePath, outputFilePath, title, content);
}
}
} catch (error) {
console.error('Error generating docs:', error);
throw error;
}
};

/**
* Custom storybook addon for generate docs
*/
export default {
name: 'generate-docs',
async managerEntries(entries: string[] = []): Promise<string[]> {
try {
await generateDocs();
} catch (error) {
console.error('Error running docs:generate:', error);
}
return entries;
},
};
10 changes: 6 additions & 4 deletions .storybook/main.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,31 @@
import webpack from 'webpack';
import type {StorybookConfig} from '@storybook/react-webpack5';

import pkg from '../package.json';

const config: StorybookConfig = {
framework: {
name: '@storybook/react-webpack5',
options: {},
},
stories: ['../demo/**/*.stories.@(js|jsx|ts|tsx)'],
stories: ['../demo/**/*.mdx', '../demo/**/*.stories.@(js|jsx|ts|tsx)'],
addons: [
'./addons/generateDocs',
'@storybook/preset-scss',
{name: '@storybook/addon-essentials', options: {backgrounds: false}},
'@storybook/addon-webpack5-compiler-babel',
'@storybook/addon-docs',
],
typescript: {
check: true,
reactDocgen: 'react-docgen-typescript'
reactDocgen: 'react-docgen-typescript',
},
webpackFinal(config) {
webpackFinal: (config) => {
config.plugins?.push(
new webpack.DefinePlugin({
__VERSION__: `'${pkg.version}-storybook'`,
}),
);

return config;
},
};
Expand Down
2 changes: 1 addition & 1 deletion .storybook/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const preview: Preview = {
},
options: {
storySort: {
order: ['Markdown Editor', ['Playground', 'Presets', '*'], '*'],
order: ['Docs', 'Markdown Editor', ['Playground', 'Presets', '*'], '*'],
},
},
controls: {
Expand Down
2 changes: 2 additions & 0 deletions docs/how-to-add-editor-with-create-react-app.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
##### Install / Create react app

## Installation Guide

### 1. Setting Up the Environment for the React Application
Expand Down
4 changes: 3 additions & 1 deletion docs/how-to-add-editor-with-nextjs.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
##### Install / NextJS

## Connection and Configuration
This document provides instructions for configuring Webpack and Turbopack to avoid issues related to the 'fs' module and for connecting the editor on the nextjs client side.
This document provides instructions for configuring Webpack and Turbopack to avoid issues related to the 'fs' module and for connecting the editor on the nextjs client side.

### Issue with 'fs' Module Not Found
In order for the `diplodoc/transform` process to function correctly, please add the [webpack resolve-fallbacks](https://webpack.js.org/configuration/resolve/#resolvefallback).
Expand Down
2 changes: 2 additions & 0 deletions docs/how-to-add-preview.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
##### Develop / Preview

## How to Add Preview for Markup Mode

### Add a Preview component
Expand Down
11 changes: 7 additions & 4 deletions docs/how-to-add-text-binding-extension-in-markdown.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
##### Develop / Extension with popup

## How to create an extension with popup for Markdown mode with text binding

Let's consider connecting an extension with text binding based on the Ghost extension — this is a test extension.
Let's consider connecting an extension with text binding based on the Ghost extension — this is a test extension.

To begin with, we need the plugin itself, which we can implement as follows:

Expand Down Expand Up @@ -49,7 +51,7 @@ class SpanWidget extends WidgetType {
export const GhostPopupPlugin = ViewPlugin.fromClass(
class implements PluginValue {
// The class allows you to implement the following methods: update, docViewUpdate, destroy.

decos: DecorationSet = Decoration.none;
readonly _view: EditorView;
readonly _renderItem;
Expand All @@ -63,7 +65,7 @@ export const GhostPopupPlugin = ViewPlugin.fromClass(
.createItem('ghost-popup-example-in-markup-mode', () => this.renderPopup());
}


// Called when transactions want to be applied to the view
update(update: ViewUpdate) {
if (update.docChanged || update.selectionSet) {
Expand Down Expand Up @@ -140,6 +142,7 @@ export const GhostPopupPlugin = ViewPlugin.fromClass(
Let's create a popup that will be linked to the text.

This is a simple component that takes a link and renders a popup in its place

```ts
// popup.ts
import React from 'react';
Expand Down Expand Up @@ -244,4 +247,4 @@ return <MarkdownEditorView
```

Now you can use the plugin!
You can also check out the GPT implementation or see the Ghost example on the Playground and in the code.
You can also check out the GPT implementation or see the Ghost example on the Playground and in the code.
11 changes: 7 additions & 4 deletions docs/how-to-connect-gpt-extensions.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
##### Connect / GPT

## How to connect GPT extensions to editor

First to integrate this extension, you need to use the following versions of the packages:
Expand All @@ -7,9 +9,10 @@ First to integrate this extension, you need to use the following versions of the

Features:

<img src="./assets/gifs/custom-prompt-preset-gpt.gif" width="470"/>
<img src="https://raw.githubusercontent.com/gravity-ui/markdown-editor/refs/heads/main/docs/assets/gifs/custom-prompt-preset-gpt.gif" width="470"/>


<img src="./assets/gifs/prompt-preset-gpt.gif" width="470"/>
<img src="https://raw.githubusercontent.com/gravity-ui/markdown-editor/refs/heads/main/docs/assets/gifs/prompt-preset-gpt.gif" width="470"/>

### 1. Add extension usage and extensions props

Expand Down Expand Up @@ -55,7 +58,7 @@ export const Editor: React.FC<EditorProps> = (props) => {
editor={mdEditor}
markupToolbarConfig={mToolbarConfig}
/>
};
};
```
### 2. Implementation ```gptWidgetProps```

Expand Down Expand Up @@ -139,7 +142,7 @@ export const gptWidgetProps: GptWidgetOptions = {
},
onLike: async () => {}, // function to track feedback for good
onDislike: async () => {}, // and bad GPT answers
};
};
```
### 3. Add extension to menubar and toolbar and command menu config for editor

Expand Down
4 changes: 3 additions & 1 deletion docs/how-to-connect-html-extension.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
## How to Connect the HTML Extensions in the Editor
##### Connect / Html block

## How to Connect the HTML Extension in the Editor

To integrate the HTML extensions in your editor, you will use the specified versions of the necessary packages. Here’s a detailed guide:

Expand Down
4 changes: 3 additions & 1 deletion docs/how-to-connect-latex-extension.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
## How to Connect the Latex Extensions in the Editor
##### Connect / Latex extension

## How to Connect the Latex Extension in the Editor

To integrate the LaTeX extension in your editor, you will use the specified versions of the necessary packages. Here’s a detailed guide:

Expand Down
4 changes: 3 additions & 1 deletion docs/how-to-connect-mermaid-extension.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
## How to Connect the Mermaid Extensions in the Editor
##### Connect / Mermaid Extension

## How to Connect the Mermaid Extension in the Editor

To integrate the Mermaid extension in your editor, you will use the specified versions of the necessary packages. Here’s a detailed guide.

Expand Down
2 changes: 2 additions & 0 deletions docs/how-to-create-extension.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
##### Develop / Extension creation

## How to Create Extension

Let us examine the process of creating an extension based on the Mermaid extension, which enables the insertion and manipulation of Mermaid diagrams.
Expand Down
5 changes: 4 additions & 1 deletion docs/how-to-customize-the-editor.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
##### Develop / Editor customization

## How to customize the editor
You can use CSS variables to make editor contents fit your own needs

| **Variable** | **Description** | **CSS Property Type** | **Default** |
| :---: | :---: | :---: | :---: |
| `--g-md-toolbar-padding` | Toolbar padding | padding | 0px |
| `--g-md-toolbar-sticky-padding` | Toolbar padding in sticky mode | padding | -4px |
| `--g-md-toolbar-sticky-inset` | Toolbar inset in sticky mode | inset | -4px |
| `--g-md-toolbar-sticky-offset` | Toolbar offset in sticky mode | top | 0px |
| `--g-md-editor-padding` | Editor contents padding | padding | 0px |
| `--g-md-editor-padding` | Editor contents padding | padding | 0px |
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -213,8 +213,10 @@
"@gravity-ui/stylelint-config": "4.0.1",
"@gravity-ui/tsconfig": "1.0.0",
"@gravity-ui/uikit": "6.11.0",
"@storybook/addon-docs": "8.4.1",
"@storybook/addon-essentials": "^8.4.1",
"@storybook/addon-webpack5-compiler-babel": "3.0.3",
"@storybook/blocks": "8.4.1",
"@storybook/cli": "^8.4.1",
"@storybook/preset-scss": "1.0.3",
"@storybook/react": "8.4.1",
Expand Down

0 comments on commit 74790ff

Please sign in to comment.