yamlのプレビューあれこれ
Tip
生成AIのプロンプトなどでyamlを使う機会が増えたので、yamlのプレビューを整理してみた
まずは普通にDocusaurusのコード表示
- 短いyamlならmarkdownファイル内に書いてしまったほうが楽なので、その場合はこれで十分
コードはコチラ
```yaml title='sample1.yaml' showLineNumbers
story-overview:
title: タイトル
description: '説明文'
prologue-summary:
description: 'プロローグ'
key-events:
- キーイベント1
- キーイベント2
```
sample1.yaml
story-overview:
title: タイトル
description: '説明文'
prologue-summary:
description: 'プロローグ'
key-events:
- キーイベント1
- キーイベント2
CodeBlockタグで表示する場合
- デカいyamlとか別ファイルへ切り出したいときはこの方法
- yamlを別ファイルにし、importして表示する
- Docusaurusの場合、staticへ置いて静的ファイルとして取り込むのが楽
raw
と書いているようにnpmのraw-loader
が必要pnpm add -D raw-loader
- importしてyamlファイルを
<CodeBlock></CodeBlock>
で括ることで表示できる
コードはコチラ
import CodeBlock from '@theme/CodeBlock';
import sampleYaml from '@site/static/data/sample.yaml?raw';
<CodeBlock className='language-yaml' title='sample2.yaml' showLineNumbers>
{sampleYaml}
</CodeBlock>
/static/data/sample.yaml
story-overview:
title: 'タイトル(static/data/sample.yaml)'
description: '説明文'
prologue-summary:
description: 'プロローグ、static内のyamlを取り込んで表示'
key-events:
- キーイベントa
- キーイベントb
sample2.yaml
story-overview:
title: 'title(static/data/sample.yaml)'
description: 'If you see this, it means sample.yaml is loaded.'
prologue-summary:
description: 'Prologue'
key-events:
- key event A
- key event B
chapter-1:
title: 'chapter-1'
description: 'Chapter 1'
characters:
- actor 1
- actor 2
TreeViewerコンポーネント作成版
- yamlは長くなることがままあるので、折りたたんで表示できるようにコンポーネントを作成
- デフォルトで2階層以降を折りたたんで表示する
- 色とかフォントはデフォルト(react-json-tree)のまま
- 気が向いたら手を加える
コードはコチラ
import YamlTreeViewer from '@site/src/components/YamlTreeViewer';
<YamlTreeViewer filePath='/data/sample.yaml' expandLevel={3} />
または
<YamlTreeViewer filePath={useBaseUrl('/data/sample.yaml')} expandLevel={3} />
docs/docusaurus/yaml-preview.mdx
/**
npm in use.
- react-json-tree: `pnpm add -D react-json-tree`
*/
import { useEffect, useState } from 'react';
import { parse } from 'yaml';
import { JSONTree } from 'react-json-tree';
/**
* @param {Object} props
* @param {string} props.filePath 公開URL(useBaseUrlの利用を推奨)
* @param {number} [props.expandLevel=2] 初期展開する階層
*/
export default function YamlTreeViewer({ filePath, expandLevel = 2 }) {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
fetch(filePath)
.then((r) => {
if (!r.ok) throw new Error(`${r.status} ${r.statusText}`);
return r.text();
})
.then((src) => setData(parse(src)))
.catch((e) => setError(e.message));
},[filePath]);
if (error) return <p style={{ color: 'red' }}>Failed to load: {error}</p>;
if (!data) return <p>Loading…</p>;
return (
<div className='yaml-tree'>
<JSONTree
data={data}
hideRoot // 「root {1}」を消す
shouldExpandNodeInitially={(_k, _v, lvl) => lvl < expandLevel}
/>
</div>
);
}
Loading…
Note
- react-json-treeを使ってるけど、ちょっとクセが強い
- 文字列はシングルクォーテーションで括っているのだけど、表示するときにはダブルクォーテーションに変更されてしまう
- 一度parseしてから表示しているのだろうから、わからなくもないけどソースに近い形で表示してほしいと思うところ
- まぁ利用時に問題がでればその時に考える