Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add fields and examples #1

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions lib/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,25 @@ const DEFAULT_DOC_CONFIG = {
objectFieldsDesc: '其中,各个字段的含义如下:',
props: {
type: '类型',
format: 'Format',
description: '描述',
level: '级别'
}
level: '级别',
examples: 'Examples',
},
},
'en-US': {
objectFieldsDesc: 'The meaning of each field is as follows:',
props: {
type: 'Type',
format: 'Format',
description: 'Description',
level: 'level'
}
}
}
level: 'level',
examples: 'Examples',
},
},
},
}

module.exports = {
DEFAULT_DOC_CONFIG
DEFAULT_DOC_CONFIG,
}
96 changes: 72 additions & 24 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,20 @@
const path = require('path')
const merge = require('lodash.merge')
const yaml = require('js-yaml')
const { ensureDirSync, existsSync, writeFile, readFile } = require('fs-extra')
const { DEFAULT_DOC_CONFIG } = require('./config')
const escapeHTML = str =>
(str || '').replace(
/[&<>'"]/g,
tag =>
({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
"'": '&#39;',
'"': '&quot;',
}[tag])
)

/**
* Get a simple i18n function.
Expand Down Expand Up @@ -128,15 +141,15 @@ async function batchTransform({
cwd = process.cwd(),
locale,
write = true,
configs = []
configs = [],
}) {
return Promise.all(
configs.map(config => {
return transform({
cwd,
write,
locale,
...config
...config,
})
})
)
Expand All @@ -146,7 +159,7 @@ async function batchTransform({
* Transform JSON Schema to markdown.
*
* @param {string} cwd
* @param {array|obkect} src
* @param {array|object} src
* @return {Promise<void>}
*/

Expand All @@ -158,7 +171,7 @@ async function transform({
frontmatter = '',
heading = '',
outputPath,
write = true
write = true,
}) {
const abSchemaPath = normalizePath(cwd, schemaPath)
delete require.cache[abSchemaPath]
Expand Down Expand Up @@ -186,30 +199,28 @@ async function transform({
if (heading) {
heading = '\n\n' + heading
}

const markdown = `${frontmatter ? `${frontmatter}\n\n` : ''}# ${title}

${description}
${heading ? `${heading}\n` : ''}
${Object.keys(properties)
.map(key => {
return getPropertyContent({
key,
property: properties[key],
$i18n: $$,
extraContent: mergedContentObject[key]
})
.map(key => {
return getPropertyContent({
key,
property: properties[key],
$i18n: $$,
extraContent: mergedContentObject[key],
})
.join('\n\n')}
})
.join('\n\n')}
`.trim()

console.log(write)
if (write && outputPath) {
const abOutputPath = normalizePath(cwd, outputPath)
console.log(`generate doc for ${schemaPath}`)
ensureDirSync(path.dirname(abOutputPath))
await writeFile(abOutputPath, markdown, 'utf-8')
}

return markdown
}

Expand Down Expand Up @@ -238,38 +249,75 @@ function getPropertyContent({ key, property, $i18n, extraContent = '' }) {
const { props = {} } = doc
const extraPropsContent = Object.keys(props)
.reduce((memo, propKey) => {
memo.push(`- ${$i18n(`props.${propKey}`)}: ${props[propKey]}`)
memo.push(`- ${$i18n(`props.${propKey}`)}: ${escapeHTML(props[propKey])}`)
return memo
}, [])
.join('\n')

/**
* Inject extra property description for object-typed property.
*/
if (isObjectProperty(property)) {
if (isObjectProperty(property) && property.properties) {
console.log(property.properties)
extraContent =
`
${$i18n('objectFieldsDesc')}:

${Object.keys(property.properties)
.map(key => {
return `- \`${key}\`: ${property.properties[key].description}`
})
.join('-')}
.map(key => {
return `- \`${key}\`: ${escapeHTML(property.properties[key].description)}`
})
.join('-')}
` + extraContent
}

let propertyValueFormat = ''
if (property.format) {
propertyValueFormat = `- ${$i18n(`props.format`)}: ${property.format}`
}

return `
## ${key}

- ${$i18n(`props.type`)}: \`${resolveTypeText(property)}\`
- ${$i18n(`props.description`)}: ${property.description}
- ${$i18n(`props.description`)}: ${escapeHTML(property.description)}
${propertyValueFormat}
${extraPropsContent}

${getPropertyExamples(property, $i18n)}
${extraContent}
`.trim()
}

/**
* Get examples text for property
*
* @param {object} property
* @param {format} "yaml" | "json"
* @return {string}
*/
function getPropertyExamples(property, $i18n) {
if (property.examples) {
// check if this is an object and display in code block. otherwise, display inline
let examplesMarkdown = ''
if (property.examples) {
if (typeof property.examples[0] == 'object') {
examplesMarkdown = property.examples
.map(example => '``` yaml\n' + yaml.dump(example) + '\n```\n')
.join('\n')
} else {
// not an object. render as tags
examplesMarkdown = property.examples
.map(example => '`' + example + '`')
.join(' ')
}
}

return `
- ${$i18n(`props.examples`)}:
${examplesMarkdown}
`
}
}
/**
* Get display text for type.
*
Expand All @@ -287,7 +335,7 @@ function resolveTypeText(property, wrap = false) {
type = property.enum.map(v => `"${v}"`).join(' | ')
}

if (isObjectProperty(property)) {
if (isObjectProperty(property) && property.properties) {
type = `{ ${Object.keys(property.properties)
.map(
propKey =>
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"license": "MIT",
"dependencies": {
"fs-extra": "^8.1.0",
"js-yaml": "^4.1.0",
"lodash.merge": "^4.6.2"
},
"devDependencies": {
Expand Down
Loading