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

WIP: Static rendering #330

Open
wants to merge 22 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
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
65 changes: 30 additions & 35 deletions bin/styleguidist.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,28 @@ function printStyleguidistError(errors) {
process.exit(1);
}

function printCompilationDone(stats, isServer) {
isServer = isServer || false;
const messages = formatWebpackMessages(stats.toJson({}, true));

if (isServer && !messages.errors.length && !messages.warnings.length) {
console.log(chalk.green('Compiled successfully!'));
console.log();
}

// If errors exist, only show errors.
if (messages.errors.length) {
printStyleguidistError(messages.errors);
printErrors('Failed to compile.', messages.errors, stats.compilation.errors, chalk.red);
return;
}

// Show warnings if no errors were found.
if (messages.warnings.length) {
printErrors('Compiled with warnings.', messages.warnings, stats.compilation.warnings, chalk.yellow);
}
}

function verbose(header, object) {
/* istanbul ignore if */
if (argv.verbose) {
Expand Down Expand Up @@ -113,23 +135,12 @@ function commandBuild() {
});

printWebpackConfigFile(config.webpackConfigFile);
verbose('Webpack config:', compiler.options);
verbose('Webpack static config:', compiler.compilers[0].options);
verbose('Webpack client config:', compiler.compilers[1].options);

// Custom error reporting
compiler.plugin('done', function(stats) {
const messages = formatWebpackMessages(stats.toJson({}, true));

// If errors exist, only show errors.
if (messages.errors.length) {
printStyleguidistError(messages.errors);
printErrors('Failed to compile.', messages.errors, stats.compilation.errors, chalk.red);
process.exit(1);
}

// Show warnings if no errors were found.
if (messages.warnings.length) {
printErrors('Compiled with warnings.', messages.warnings, stats.compilation.warnings, chalk.yellow);
}
compiler.plugin('done', function(multiStats) {
multiStats.stats.forEach(stats => printCompilationDone(stats, false));
});
}

Expand Down Expand Up @@ -166,33 +177,17 @@ function commandServer() {
});

printWebpackConfigFile(config.webpackConfigFile);
verbose('Webpack config:', compiler.options);
verbose('Webpack static config:', compiler.compilers[0].options);
verbose('Webpack client config:', compiler.compilers[1].options);

// Show message when Webpack is recompiling the bundle
compiler.plugin('invalid', function() {
console.log('Compiling…');
});

// Custom error reporting
compiler.plugin('done', function(stats) {
const messages = formatWebpackMessages(stats.toJson({}, true));

if (!messages.errors.length && !messages.warnings.length) {
console.log(chalk.green('Compiled successfully!'));
console.log();
}

// If errors exist, only show errors.
if (messages.errors.length) {
printStyleguidistError(messages.errors);
printErrors('Failed to compile.', messages.errors, stats.compilation.errors, chalk.red);
return;
}

// Show warnings if no errors were found.
if (messages.warnings.length) {
printErrors('Compiled with warnings.', messages.warnings, stats.compilation.warnings, chalk.yellow);
}
compiler.plugin('done', function(multiStats) {
multiStats.stats.forEach(stats => printCompilationDone(stats, true));
});
}

Expand Down
107 changes: 10 additions & 97 deletions loaders/__tests__/styleguide-loader.spec.js
Original file line number Diff line number Diff line change
@@ -1,124 +1,38 @@
import vm from 'vm';
import path from 'path';
import { readFileSync } from 'fs';
import noop from 'lodash/noop';
import styleguideLoader from '../styleguide-loader';

const file = './test/components/Button/Button.js';

/* eslint-disable quotes */

it('should return valid, parsable JS', () => {
const result = styleguideLoader.pitch.call({
request: file,
_styleguidist: {
sections: [{ components: '../../test/components/**/*.js' }],
configDir: __dirname,
getExampleFilename: () => 'Readme.md',
getComponentPathLine: filepath => filepath,
},
addContextDependency: noop,
}, readFileSync(file, 'utf8'));
expect(result).toBeTruthy();
expect(new vm.Script(result)).not.toThrowError(SyntaxError);
});
const configDir = path.resolve(__dirname, '../../test');

it('should return correct component paths: glob', () => {
it('should return valid, parsable JS', () => {
const result = styleguideLoader.pitch.call({
request: file,
_styleguidist: {
sections: [{ components: 'components/**/*.js' }],
configDir: path.resolve(__dirname, '../../test'),
getExampleFilename: () => 'Readme.md',
getComponentPathLine: filepath => filepath,
},
addContextDependency: noop,
}, readFileSync(file, 'utf8'));
expect(result).toBeTruthy();
expect(new vm.Script(result)).not.toThrowError(SyntaxError);
expect(result).toMatch(`'filepath': 'components/Button/Button.js'`);
expect(result).toMatch(`'filepath': 'components/Placeholder/Placeholder.js'`);
});

it('should return correct component paths: function returning absolute paths', () => {
const result = styleguideLoader.pitch.call({
request: file,
_styleguidist: {
sections: [{
components: () => ([
`${__dirname}/components/Button/Button.js`,
`${__dirname}/components/Placeholder/Placeholder.js`,
]),
}],
configDir: __dirname,
configDir,
getExampleFilename: () => 'Readme.md',
getComponentPathLine: filepath => filepath,
},
addContextDependency: noop,
}, readFileSync(file, 'utf8'));
addContextDependency: () => {},
});
expect(result).toBeTruthy();
expect(new vm.Script(result)).not.toThrowError(SyntaxError);
expect(result).toMatch(`'filepath': 'components/Button/Button.js'`);
expect(result).toMatch(`'filepath': 'components/Placeholder/Placeholder.js'`);
});

it('should return correct component paths: function returning relative paths', () => {
const result = styleguideLoader.pitch.call({
request: file,
_styleguidist: {
sections: [{
components: () => ([
'components/Button/Button.js',
'components/Placeholder/Placeholder.js',
]),
}],
configDir: __dirname,
getExampleFilename: () => 'Readme.md',
getComponentPathLine: filepath => filepath,
},
addContextDependency: noop,
}, readFileSync(file, 'utf8'));
expect(result).toBeTruthy();
expect(new vm.Script(result)).not.toThrowError(SyntaxError);
expect(result).toMatch(`'filepath': 'components/Button/Button.js'`);
expect(result).toMatch(`'filepath': 'components/Placeholder/Placeholder.js'`);
});

it('should filter out components without examples if skipComponentsWithoutExample=true', () => {
const result = styleguideLoader.pitch.call({
request: file,
_styleguidist: {
sections: [{
components: () => ([
'components/Button/Button.js',
'components/RandomButton/RandomButton.js',
]),
}],
configDir: path.resolve(__dirname, '../../test'),
skipComponentsWithoutExample: true,
getExampleFilename: componentPath => path.join(path.dirname(componentPath), 'Readme.md'),
getComponentPathLine: filepath => filepath,
},
addContextDependency: noop,
}, readFileSync(file, 'utf8'));
expect(result).toBeTruthy();
expect(new vm.Script(result)).not.toThrowError(SyntaxError);
expect(result).toMatch(`'filepath': 'components/Button/Button.js'`);
expect(result.includes('RandomButton.js')).toBeFalsy();
});

it('should add context dependencies to webpack from contextDependencies config option', () => {
const contextDependencies = ['foo', 'bar'];
const addContextDependency = jest.fn();
styleguideLoader.pitch.call({
request: file,
_styleguidist: {
sections: [{ components: 'components/**/*.js' }],
configDir: __dirname,
sections: [],
configDir,
contextDependencies,
},
addContextDependency,
}, readFileSync(file, 'utf8'));
});
expect(addContextDependency).toHaveBeenCalledTimes(2);
expect(addContextDependency).toBeCalledWith(contextDependencies[0]);
expect(addContextDependency).toBeCalledWith(contextDependencies[1]);
Expand All @@ -127,15 +41,14 @@ it('should add context dependencies to webpack from contextDependencies config o
it('should add common parent folder of all components to context dependencies', () => {
const addContextDependency = jest.fn();
styleguideLoader.pitch.call({
request: file,
_styleguidist: {
sections: [{ components: 'components/**/*.js' }],
configDir: path.resolve(__dirname, '../../test'),
configDir,
getExampleFilename: () => 'Readme.md',
getComponentPathLine: filepath => filepath,
},
addContextDependency,
}, readFileSync(file, 'utf8'));
});
expect(addContextDependency).toHaveBeenCalledTimes(1);
expect(addContextDependency).toBeCalledWith(expect.stringMatching(/test\/components\/$/));
});
53 changes: 8 additions & 45 deletions loaders/styleguide-loader.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,9 @@
'use strict';

const pick = require('lodash/pick');
const commonDir = require('common-dir');
const generate = require('escodegen').generate;
const toAst = require('to-ast');
const getAllComponentsWithExamples = require('./utils/getAllComponentsWithExamples');
const getAllContentPages = require('./utils/getAllContentPages');
const getComponentFilesFromSections = require('./utils/getComponentFilesFromSections');
const getSections = require('./utils/getSections');
const filterComponentsWithExample = require('./utils/filterComponentsWithExample');

/* eslint-disable no-console */

// Config options that should be passed to the client
const CLIENT_CONFIG_OPTIONS = [
'title',
'highlightTheme',
'showCode',
'showSidebar',
'previewDelay',
'theme',
'styles',
];
const getStyleguide = require('./utils/getStyleguide');

module.exports = function() {};
module.exports.pitch = function() {
Expand All @@ -31,51 +13,32 @@ module.exports.pitch = function() {
}

const config = this._styleguidist;
const styleguide = getStyleguide(config);

let sections = getSections(config.sections, config);
if (config.skipComponentsWithoutExample) {
sections = filterComponentsWithExample(sections);
}

const allComponentFiles = getComponentFilesFromSections(config.sections, config.configDir);
const allContentPages = getAllContentPages(sections);
const allComponentsWithExamples = getAllComponentsWithExamples(sections);

const welcomeScreen = {
// Nothing to show in the style guide
components: allContentPages.length === 0 && allComponentFiles.length === 0,
// All component have no example files
examples: allContentPages.length === 0 && allComponentFiles.length > 0 && allComponentsWithExamples.length === 0,
};

/* eslint-disable no-console */
/* istanbul ignore if */
if (config.verbose) {
console.log();
console.log('Loading components:');
console.log(allComponentFiles.join('\n'));
console.log(styleguide.allComponentFiles.join('\n'));
console.log();
}
/* eslint-enable */

// Setup Webpack context dependencies to enable hot reload when adding new files
if (config.contextDependencies) {
config.contextDependencies.forEach(dir => this.addContextDependency(dir));
}
else if (allComponentFiles.length > 0) {
else if (styleguide.allComponentFiles.length > 0) {
// Use common parent directory of all components as a context
this.addContextDependency(commonDir(allComponentFiles));
this.addContextDependency(commonDir(styleguide.allComponentFiles));
}

const styleguide = {
config: pick(config, CLIENT_CONFIG_OPTIONS),
welcomeScreen,
sections,
};

return `
if (module.hot) {
module.hot.accept([])
}

module.exports = ${generate(toAst(styleguide))}
`;
`;
};
Loading