Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/main' into remix-example
Browse files Browse the repository at this point in the history
  • Loading branch information
Nguyễn Thanh Sơn committed May 8, 2022
2 parents 2d7f300 + 8c27605 commit 79b2816
Show file tree
Hide file tree
Showing 11 changed files with 101 additions and 71 deletions.
9 changes: 9 additions & 0 deletions .all-contributorsrc
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,15 @@
"contributions": [
"bug"
]
},
{
"login": "makotot",
"name": "Makoto Tateno",
"avatar_url": "https://avatars.githubusercontent.com/u/1129027?v=4",
"profile": "https://github.com/makotot",
"contributions": [
"doc"
]
}
],
"contributorsPerLine": 7,
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,5 @@ build
presets
transforms
draft

coverage
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ Debug your Jest tests. Effortlessly. 🛠🖼

<!-- prettier-ignore-start -->
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-9-orange.svg?style=flat-square)](#contributors-)
[![All Contributors](https://img.shields.io/badge/all_contributors-10-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->
<!-- prettier-ignore-end -->

Expand Down Expand Up @@ -148,6 +148,7 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
<tr>
<td align="center"><a href="https://github.com/minhmo1620"><img src="https://avatars.githubusercontent.com/u/44143370?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Minh Nguyen </b></sub></a><br /><a href="https://github.com/nvh95/jest-preview/commits?author=minhmo1620" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/tinhvqbk"><img src="https://avatars.githubusercontent.com/u/26925018?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Kyle(Tình Vũ)</b></sub></a><br /><a href="https://github.com/nvh95/jest-preview/issues?q=author%3Atinhvqbk" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/makotot"><img src="https://avatars.githubusercontent.com/u/1129027?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Makoto Tateno</b></sub></a><br /><a href="https://github.com/nvh95/jest-preview/commits?author=makotot" title="Documentation">📖</a></td>
</tr>
</table>

Expand Down
61 changes: 61 additions & 0 deletions demo/__tests__/style.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { render } from '@testing-library/react';

import App from '../App';

describe('Style', () => {
it('should render CSS correctly in JSDOM', () => {
render(<App />);
// vanilla CSS
// Global CSS
// TODO: Global CSS is saved into the `.cache` folder, so we can't assert it directly within the JSDOM
// Imported CSS
expect(document.documentElement.outerHTML).toContain(
'<link rel="stylesheet" href="/demo/App.css">',
);
expect(document.documentElement.outerHTML).toContain(
'<link rel="stylesheet" href="/demo/assets/css/App.css">',
);

// styled-components
expect(document.documentElement.outerHTML).toContain(
'<style data-styled="active" data-styled-version="5.3.5">.dgihId{color:red;}</style>',
);

// CSS Modules
// Global
// TODO: not implemented yet
// Import
expect(document.documentElement.outerHTML)
.toContain(`<style type=\"text/css\">._cssModule_16r0j_1 {
color: green;
}
</style>`);

// Sass
// Global
// TODO: Global SCSS is saved into the `.cache` folder, not in the JSDOM, need to find a way to test it
// Import
expect(document.documentElement.outerHTML)
.toContain(`header .imported-sass {
text-transform: uppercase;
}`);
expect(document.documentElement.outerHTML)
.toContain(`header .imported-sass {
color: pink;
}</style><style type="text/css">._cssModule_16r0j_1 {
color: green;
}`);
// import ~
// TODO: Not implemented yet
// loadPaths
// TODO: Not implemented yet

// Can see images
expect(document.documentElement.outerHTML).toContain(
`<img src="/logo.svg" class="App-logo" alt="logo">`,
);
expect(document.documentElement.outerHTML).toContain(
`<img src="/demo/assets/images/logo.svg" class="logo2" alt="logo2">`,
);
});
});
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ module.exports = {
'demo/**/*.{js,jsx,ts,tsx}',
'!demo/**/*.d.ts',
'!demo/mocks/**',
// TODO: To report coverage in `src`. They are compiled to `dist` so it's difficult to report coverage directly
],
coveragePathIgnorePatterns: [],
setupFilesAfterEnv: ['./config/jest/setupTests.js'],
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,10 @@
"preview": "vite preview",
"server": "node server/previewServer.js",
"server:watch": "nodemon server/previewServer.js",
"test:only": "NODE_ENV=test jest --watch --no-cache",
"test:dev": "NODE_ENV=test jest --watch --no-cache App",
"test:ci": "NODE_ENV=test jest",
"clearCache": "rimraf node_modules/.cache/jest-preview && jest --clearCache",
"test": "npm-run-all -p server test:only",
"test": "npm-run-all -p server test:dev",
"prettier": "prettier server src --check",
"prettier:fix": "npm run prettier -- --write",
"sort": "npx sort-package-json",
Expand Down
21 changes: 13 additions & 8 deletions server/previewServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@ const port = process.env.PORT || 3336;
const wsPort = Number(port) + 1;

const CACHE_DIRECTORY = './node_modules/.cache/jest-preview';
const HTML_BASENAME = 'index.html';
const HTML_PATH = path.join(CACHE_DIRECTORY, HTML_BASENAME);
const HEAD_BASENAME = 'head.html';
const HEAD_PATH = path.join(CACHE_DIRECTORY, HEAD_BASENAME);
const BODY_BASENAME = 'body.html';
const BODY_PATH = path.join(CACHE_DIRECTORY, BODY_BASENAME);
const PUBLIC_CONFIG_BASENAME = 'cache-public.config';
const PUBLIC_CONFIG_PATH = path.join(CACHE_DIRECTORY, PUBLIC_CONFIG_BASENAME);
const FAV_ICON_PATH = './node_modules/jest-preview/server/favicon.ico';
Expand Down Expand Up @@ -51,7 +53,7 @@ wss.on('connection', function connection(ws) {
});
});

const watcher = chokidar.watch([HTML_PATH, PUBLIC_CONFIG_PATH], {
const watcher = chokidar.watch([BODY_PATH, PUBLIC_CONFIG_PATH], {
// ignored: ['**/node_modules/**', '**/.git/**'],
ignoreInitial: true,
ignorePermissionErrors: true,
Expand All @@ -60,7 +62,8 @@ const watcher = chokidar.watch([HTML_PATH, PUBLIC_CONFIG_PATH], {

function handleFileChange(filePath) {
const basename = path.basename(filePath);
if (basename === HTML_BASENAME) {
// Do not need to watch for HEAD_BASENAME, since we write head.html before body.html
if (basename === BODY_BASENAME) {
wss.clients.forEach((client) => {
if (client.readyState === 1) {
client.send(JSON.stringify({ type: 'reload' }));
Expand Down Expand Up @@ -116,7 +119,7 @@ app.use('/', (req, res) => {
.readFileSync(path.join(__dirname, './ws-client.js'), 'utf-8')
.replace(/\$PORT/g, wsPort);

if (!fs.existsSync(HTML_PATH)) {
if (!fs.existsSync(BODY_PATH)) {
// Make it looks nice
return res.end(`<!DOCTYPE html>
<html>
Expand All @@ -135,7 +138,8 @@ preview.debug();
<script>${reloadScriptContent}</script>
</html>`);
}
const html = fs.readFileSync(HTML_PATH, 'utf8');
const head = fs.readFileSync(HEAD_PATH, 'utf8');
const body = fs.readFileSync(BODY_PATH, 'utf8');
// TODO2: How do we preserve the order of importing css file?
// For now I think it's not very important, but this is the room for improvement in next versions
let css = '';
Expand All @@ -158,9 +162,10 @@ preview.debug();
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, viewport-fit=cover">
${css}
${head}
</head>
<body>
${html}
${body}
</body>
<script>${reloadScriptContent}</script>
</html>`;
Expand All @@ -170,7 +175,7 @@ ${css}
const server = http.createServer(app);

server.listen(port, () => {
if (fs.existsSync(HTML_PATH)) {
if (fs.existsSync(BODY_PATH)) {
// Remove old preview
const files = fs.readdirSync(CACHE_DIRECTORY);
files.forEach((file) => {
Expand Down
25 changes: 7 additions & 18 deletions src/preview.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import fs from 'fs';
import path from 'path';
import { getStyle } from './styled-components';
import { CACHE_FOLDER } from './constants';

export function debug(element: Element = document.body): void {
Expand All @@ -10,21 +9,11 @@ export function debug(element: Element = document.body): void {
});
}

// If user use styled-components
if (getStyle) {
// TODO: We can send this data via websocket instead of writing to disk
fs.writeFileSync(
path.join(CACHE_FOLDER, 'jp-styled-components.css'),
getStyle(),
{
encoding: 'utf-8',
flag: 'w',
},
);
}

fs.writeFileSync(path.join(CACHE_FOLDER, 'index.html'), element.outerHTML, {
encoding: 'utf-8',
flag: 'w',
});
const headChildrenOnly = [...document.head.children].reduce(
(prev, current) => prev + current.outerHTML,
'',
);
fs.writeFileSync(path.join(CACHE_FOLDER, 'head.html'), headChildrenOnly);
// Always save head.html to disk before body.html, so we don't need to watch head.html
fs.writeFileSync(path.join(CACHE_FOLDER, 'body.html'), element.outerHTML);
}
36 changes: 0 additions & 36 deletions src/styled-components.ts

This file was deleted.

9 changes: 4 additions & 5 deletions src/transform.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import fs from 'fs';
import path from 'path';
import camelcase from 'camelcase';

Expand Down Expand Up @@ -57,7 +56,7 @@ export function processCss(src: string, filename: string): string {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = relativeCssPath;
document.body.appendChild(link);
document.head.appendChild(link);
module.exports = JSON.stringify(relativeCssPath);`;
}
Expand All @@ -83,7 +82,7 @@ module.exports = JSON.stringify(relativeCssPath);`;

// We can use that if we opt-in to ESM. But it's not common use case right now (2022)
// So our approach is making CSS Modules a "CSS-in-JS" solution.
// CSS Modules will be compiled at run time then inject to the document.body
// CSS Modules will be compiled at run time then inject to the document.head
// One notable note is that `postcss-modules` is an async postcss plugin
// We have to use Singleton design pattern to make it works asynchronously.
function processCSSModules(src: string, filename: string): string {
Expand Down Expand Up @@ -113,7 +112,7 @@ postcss(
const style = document.createElement('style');
style.type = 'text/css';
style.appendChild(document.createTextNode(result.css));
document.body.appendChild(style);
document.head.appendChild(style);
});
module.exports = exportedTokens;`;
Expand All @@ -133,6 +132,6 @@ function processSass(src: string, filename: string): string {

return `const style = document.createElement('style');
style.appendChild(document.createTextNode(${JSON.stringify(cssResult)}));
document.body.appendChild(style);
document.head.appendChild(style);
module.exports = {}`;
}
1 change: 0 additions & 1 deletion website/docs/advanced-guides/code-transform.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ You should use [Pre-configured transformation](/docs/getting-started/installatio

For examples:

````js
```javascript
// config/jest/cssTransform.js
'use strict';
Expand Down

0 comments on commit 79b2816

Please sign in to comment.