packages/icons/docs/generate.js
#!/usr/bin/node
/**
* Docgen script.
*
* After creating a temporary snapshot of the icon library React app, this script
* parses the static HTML and adds the icon table to the README.md file in the
* package root.
*/
const cheerio = require( 'cheerio' ),
{ readFileSync, writeFileSync, rmSync, mkdirSync } = require( 'fs' ),
BUILD_DIR = 'raw';
rmSync( BUILD_DIR, { force: true, recursive: true } );
mkdirSync( BUILD_DIR );
const $ = cheerio.load( readFileSync( 'docs/build/index.html', 'utf8' ) );
let docs = `<table>
<thead>
<tr>
<th>Icon</th>
<th>ID</th>
<th>Usage</th>
</tr>
</thead>
<tbody>`;
$( '#app div' ).each( ( i, el ) => {
const id = $( el ).attr( 'id' );
writeFileSync( `${ BUILD_DIR }/${ id }.svg`, $( el ).html() );
docs += `
<tr>
<td><img src="${ BUILD_DIR }/${ id }.svg" width="48" height="48" alt="${ id } icon" /></td>
<td>${ id }</td>
<td><code><Icon icon={ ${ id } } /></code></td>
</tr>
`;
} );
docs += `</tbody>
</table>`;
const readmeFile = 'README.md',
readmeContents = readFileSync( readmeFile, 'utf8' ),
startToken = '<!-- START TOKEN(Autogenerated Icon Gallery) -->',
endToken = '<!-- END TOKEN(Autogenerated Icon Gallery) -->',
docsToken = '<!-- DOCS TOKEN -->';
let newReadme = [],
addLine = true;
readmeContents.split( '\n' ).forEach( ( line ) => {
if ( line === startToken ) {
newReadme.push( line );
newReadme.push( docsToken );
addLine = false;
} else if ( line === endToken ) {
addLine = true;
}
if ( addLine ) {
newReadme.push( line );
}
} );
newReadme = newReadme.join( '\n' );
writeFileSync( readmeFile, newReadme.replace( docsToken, `\n${ docs }\n` ) );