Skip to content
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
3 changes: 3 additions & 0 deletions examples/cra-example/react-showroom.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,7 @@ module.exports = defineConfig({
theme: {
title: 'CRA 5 Example',
},
experiments: {
interactions: true,
},
});
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { InteractionBlock } from 'react-showroom/client';

```tsx frame
<div className="flex items-center gap-3">
<Button>Hello</Button>
<Button variant="primary">Primary</Button>
<Button variant="outline">Outline</Button>
</div>
```

<InteractionBlock testName="works" />
13 changes: 13 additions & 0 deletions examples/cra-example/src/components/button.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { render, screen } from '@testing-library/react';
import { Button } from './button';

test('Button defined', () => {
expect(Button).toBeDefined();
});

describe('<Button />', () => {
it('works', () => {
render(<Button>Hello</Button>);
expect(screen.getByText('Hello')).toBeVisible();
});
});
2 changes: 1 addition & 1 deletion examples/react-example/src/components/button.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ import { Button } from './button';

describe('<Button />', () => {
it('works', () => {
render(<Button>Hello</Button>);
render(<Button variant="primary">Hello</Button>);
});
});
57 changes: 57 additions & 0 deletions packages/core/src/acorn-ast.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import type { Node } from 'acorn';

export interface LiteralNode extends Node {
type: 'Literal';
value: string;
raw: string;
}

export interface IdentifierNode extends Node {
type: 'Identifier';
name: string;
}

export interface ImportSpecifierNode extends Node {
type: 'ImportSpecifier';
imported: IdentifierNode;
local: IdentifierNode;
}

export interface ImportNamespaceSpecifierNode extends Node {
type: 'ImportNamespaceSpecifier';
local: IdentifierNode;
}

export interface ImportDefaultSpecifierNode extends Node {
type: 'ImportDefaultSpecifier';
local: IdentifierNode;
}

export interface ImportDeclarationNode extends Node {
type: 'ImportDeclaration';
source: LiteralNode;
specifiers: Array<
| ImportSpecifierNode
| ImportNamespaceSpecifierNode
| ImportDefaultSpecifierNode
>;
}

export interface MemberExpressionNode extends Node {
type: 'MemberExpression';
object: IdentifierNode;
property: IdentifierNode;
}

export interface ExpressionStatementNode extends Node {
type: 'ExpressionStatement';
expression: {
arguments: Array<Node>;
callee: Node;
};
}

export interface ProgramNode extends Node {
type: 'Program';
body: Array<Node>;
}
67 changes: 10 additions & 57 deletions packages/core/src/compile-script.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
import { Node, Options, parse } from 'acorn';
import * as walk from 'acorn-walk';
import { getSafeName } from './get-safe-name';
import type * as esbuild from 'esbuild';
import type {
ExpressionStatementNode,
ImportDeclarationNode,
ImportDefaultSpecifierNode,
ImportNamespaceSpecifierNode,
ImportSpecifierNode,
MemberExpressionNode,
ProgramNode,
} from './acorn-ast';
import { ReactShowroomFeatureCompilation } from './compilation';
import { getSafeName } from './get-safe-name';

export interface ImportMapData {
name: string;
Expand Down Expand Up @@ -136,62 +145,6 @@ const insertRenderIfEndWithJsx = (code: string): string => {
const hasImports = (code: string): boolean =>
!!code.match(/import[\S\s]+?['"]([^'"]+)['"];?/m);

interface LiteralNode extends Node {
type: 'Literal';
value: string;
raw: string;
}

interface IdentifierNode extends Node {
type: 'Identifier';
name: string;
}

interface ImportSpecifierNode extends Node {
type: 'ImportSpecifier';
imported: IdentifierNode;
local: IdentifierNode;
}

interface ImportNamespaceSpecifierNode extends Node {
type: 'ImportNamespaceSpecifier';
local: IdentifierNode;
}

interface ImportDefaultSpecifierNode extends Node {
type: 'ImportDefaultSpecifier';
local: IdentifierNode;
}

interface ImportDeclarationNode extends Node {
type: 'ImportDeclaration';
source: LiteralNode;
specifiers: Array<
| ImportSpecifierNode
| ImportNamespaceSpecifierNode
| ImportDefaultSpecifierNode
>;
}

interface MemberExpressionNode extends Node {
type: 'MemberExpression';
object: IdentifierNode;
property: IdentifierNode;
}

interface ExpressionStatementNode extends Node {
type: 'ExpressionStatement';
expression: {
arguments: Array<Node>;
callee: Node;
};
}

interface ProgramNode extends Node {
type: 'Program';
body: Array<Node>;
}

const isExpressionNode = (node: Node): node is ExpressionStatementNode =>
node.type === 'ExpressionStatement';
const isMemberExpressionNode = (node: Node): node is MemberExpressionNode =>
Expand Down
138 changes: 138 additions & 0 deletions packages/core/src/compile-tests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import { Node, Options as AcornOptions, parse } from 'acorn';
import * as walk from 'acorn-walk';
import type { ImportDeclarationNode } from './acorn-ast';
import { stringToIdentifier } from './get-safe-name';

const ACORN_OPTIONS: AcornOptions = {
ecmaVersion: 2018,
sourceType: 'module',
};

export const compileTestsToMap = (source: string) => {
const testsMap: Record<string, string> = {};

let code = source;

const ast = parse(code, ACORN_OPTIONS);

let offset = 0;

walk.simple(ast, {
CallExpression: (callNode) => {
const node = callNode as CallExpressionNode;
if (node.callee.name === 'test' || node.callee.name === 'it') {
const name = node.arguments[0].value;

testsMap[name] = stringToIdentifier(name);

code =
code.substring(0, node.start + offset) +
code.substring(node.end + offset);
offset -= node.end - node.start;
}
},
});

return `export default {${Object.entries(testsMap)
.map(([fnName, encodedName]) => `['${fnName}']: '${encodedName}',`)
.join('\n')}
};`;
};

export const compileTests = (source: string) => {
const imports: Array<string> = [
`import { jest, expect } from 'react-showroom/client-dist/lib/test-globals.js';`,
];
let hasImportedReact = false;

const testsMap: Record<string, string> = {};

let code = source;

const ast = parse(code, ACORN_OPTIONS);

let offset = 0;

walk.simple(ast, {
ImportDeclaration: (n) => {
const node = n as ImportDeclarationNode;
const start = node.start + offset;
const end = node.end + offset;

if (node.source.value === 'react') {
hasImportedReact = true;
}

const statement = code.substring(start, end);
imports.push(statement);

code = code.substring(0, start) + code.substring(end);
offset -= statement.length;
},
CallExpression: (callNode) => {
const node = callNode as CallExpressionNode;
if (node.callee.name === 'test' || node.callee.name === 'it') {
const name = node.arguments[0].value;
const testCode = node.arguments[1];

testsMap[stringToIdentifier(name)] = code.substring(
testCode.start + offset,
testCode.end + offset
);

code =
code.substring(0, node.start + offset) +
code.substring(node.end + offset);
offset -= node.end - node.start;
}
},
});

return `${(hasImportedReact
? imports
: imports.concat(`import * as React from 'react';`)
).join('\n')}
${stripDescribe(code)}
${Object.entries(testsMap)
.map(
([fnName, fnExpression]) =>
`export const ${fnName} = async ${fnExpression};`
)
.join('\n')}`;
};

function stripDescribe(source: string) {
let code = source;

const ast = parse(code, {
ecmaVersion: 2018,
sourceType: 'module',
});

let offset = 0;

walk.simple(ast, {
CallExpression: (callNode) => {
const node = callNode as CallExpressionNode;
if (node.callee.name === 'describe') {
code =
code.substring(0, node.start + offset) +
code.substring(node.end + offset);
offset -= node.end - node.start;
}
},
});

return code;
}

interface CallExpressionNode extends Node {
callee: {
name: string;
} & Node;
arguments: Array<
{
value: string;
} & Node
>;
}
15 changes: 14 additions & 1 deletion packages/core/src/get-safe-name.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,21 @@
import { getSafeName } from './get-safe-name';
import { getSafeName, stringToIdentifier } from './get-safe-name';

test('getSafeName', () => {
expect(getSafeName('')).toBe('');
expect(getSafeName('react')).toBe('react');
expect(getSafeName('react-query')).toBe('reactQuery');
expect(getSafeName('@org/ui-lib')).toBe('org__uiLib');
});

test('stringToIdentifier', () => {
expect(stringToIdentifier('I have a dream')).toBe('_IHaveADream');
expect(stringToIdentifier('1st test')).toBe('_1stTest');
expect(stringToIdentifier('$ I love')).toBe('_$ILove');
expect(stringToIdentifier('_(nice)')).toBe('__nice');
expect(
stringToIdentifier(`I
love 1 and
3 $
`)
).toBe('_ILove1And3$');
});
12 changes: 12 additions & 0 deletions packages/core/src/get-safe-name.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,15 @@ export const getSafeName = (pkgName: string): string => {
.replace(/\//, '__')
.replace(/[^a-zA-Z\_]/g, '');
};

export const stringToIdentifier = (oriString: string): string => {
if (!oriString) {
return oriString;
}

return ('_' + oriString)
.replace(/(\s)([a-z])/g, function (_, __, x) {
return x.toUpperCase();
})
.replace(/[^A-Za-z0-9_$]/g, '');
};
3 changes: 2 additions & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export {
SUPPORTED_LANGUAGES,
} from './compilation';
export { compileScript, ImportMapData, Packages } from './compile-script';
export { compileTests, compileTestsToMap } from './compile-tests';
export { dedupeArray } from './dedupe-array';
export {
deviceDimensions,
Expand All @@ -18,7 +19,7 @@ export { decodeDisplayName, encodeDisplayName } from './display-name';
export { flattenArray, NestedArray } from './flatten-array';
export { callAll, noop } from './fn-lib';
export type { Callback } from './fn-lib';
export { getSafeName } from './get-safe-name';
export { getSafeName, stringToIdentifier } from './get-safe-name';
export { isEqualArray } from './is-equal-array';
export { omit, pick } from './object';
export { compileHtml } from './process-html';
Expand Down
Loading