react-cosmos
Version:
Sandbox for developing and testing UI components in isolation
51 lines (50 loc) • 1.98 kB
JavaScript
import { sortBy } from 'lodash-es';
import fs from 'node:fs/promises';
import path from 'node:path';
import { createRendererUrl, pickRendererUrl, removeFixtureNameExtension, removeFixtureNameSuffix, } from 'react-cosmos-core';
import { findUserModulePaths } from '../userModules/findUserModulePaths.js';
import { importKeyPath } from '../userModules/shared.js';
export const fixturesJsonPlugin = {
name: 'fixturesJson',
devServer({ config, app }) {
app.get('/cosmos.fixtures.json', async (_, res) => {
res.json(await createFixtureItems(config, 'dev'));
});
},
async export({ config }) {
const { exportPath } = config;
const json = await createFixtureItems(config, 'export');
await fs.writeFile(path.join(exportPath, 'cosmos.fixtures.json'), JSON.stringify(json, null, 2));
},
};
async function createFixtureItems(config, mode) {
const rendererUrl = pickRendererUrl(config.rendererUrl, mode);
if (!rendererUrl) {
return {
rendererUrl: null,
fixtures: [],
};
}
const { fixturesDir, fixtureFileSuffix } = config;
const { fixturePaths } = await findUserModulePaths(config);
const fixtures = fixturePaths.map(filePath => {
const relPath = importKeyPath(filePath, config.rootDir);
const fixtureId = { path: relPath };
return {
filePath: relPath,
cleanPath: cleanFixturePath(relPath, fixturesDir, fixtureFileSuffix),
rendererUrl: createRendererUrl(rendererUrl, fixtureId, true),
};
});
return {
rendererUrl,
fixtures: sortBy(fixtures, f => f.cleanPath.join('-')),
};
}
function cleanFixturePath(filePath, fixturesDir, fixtureSuffix) {
const paths = filePath.split('/').filter(p => p !== fixturesDir);
return [
...paths.slice(0, -1),
removeFixtureNameSuffix(removeFixtureNameExtension(paths[paths.length - 1]), fixtureSuffix),
];
}