Skip to content

Commit

Permalink
chore(react): refactor generate-react-exports (#725)
Browse files Browse the repository at this point in the history
* Simplifies the logic of `generate-react-exports.js` as types are
inferred, removing the need of generics
* Simplifies the React export making it more readable
```tsx
/**
 * @tag bl-textarea
 * @summary Baklava Textarea component
 */
export const BlTextarea = React.lazy(() =>
  customElements.whenDefined("bl-textarea").then(() => ({
    default: createComponent({
      react: React,
      displayName: "BlTextarea",
      tagName: "bl-textarea",
      elementClass: customElements.get("bl-textarea") as Constructor<BlTextarea>,
      events: {
        onBlInput: "bl-input" as EventName<BlTextareaInput>,
        onBlChange: "bl-change" as EventName<BlTextareaChange>,
        onBlInvalid: "bl-invalid" as EventName<BlTextareaInvalid>,
      },
    }),
  }))
);
```

---------

Co-authored-by: Aykut Saraç <[email protected]>
  • Loading branch information
AykutSarac and Aykut Saraç authored Oct 27, 2023
1 parent caa388c commit 43b5208
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 30 deletions.
1 change: 1 addition & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"trailingComma": "es5",
"useTabs": false,
"importOrder": [
"^react",
"^lit",
"<THIRD_PARTY_MODULES>",
"^[./]",
Expand Down
20 changes: 19 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
"serve": "node scripts/build.js --serve",
"storybook:dev": "storybook dev -p 1994",
"lint": "npm-run-all -s lint:*",
"lint:tsc": "tsc --noEmit",
"lint:tsc": "tsc --noEmit --project ./tsconfig.json",
"lint:eslint": "eslint src",
"lint:style": "stylelint src/**/*.css",
"lint:prettier": "prettier --check src",
Expand Down
53 changes: 27 additions & 26 deletions scripts/generate-react-exports.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { pascalCase } from "pascal-case";
import path from "path";
import { format } from "prettier";
import { fileURLToPath } from "url";

import prettierConfig from "../.prettierrc.json" assert { type: "json" };
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

Expand All @@ -24,43 +24,41 @@ const baklavaReactFileParts = [];

for (const module of customElementsModules) {
const { declarations, path } = module;
const componentDeclaration = declarations.find(declaration => declaration.customElement === true);
const { events, name: componentName, tagName: fileName, jsDoc } = componentDeclaration;
const component = declarations.find(declaration => declaration.customElement === true);
const { name: componentName, tagName: fileName } = component;

const eventNames =
events?.reduce((acc, curr) => {
acc[getReactEventName(curr.name)] = curr.name;
return acc;
}, {}) || {};
const eventNames = (component.events || []).map(event => {
const reactEvent = getReactEventName(event.name);
const reactEventName = `${componentName}${reactEvent.split("onBl")[1]}`;
return `${reactEvent}: '${event.name}' as EventName<${reactEventName}>`;
}).join(',\n');

const eventTypes =
events?.map(event => {
const eventName = getReactEventName(event.name);
const eventType = cleanGenericTypes(componentDeclaration.typeParameters, event.type.text);
const predefinedEventName = `${componentName}${eventName.split("onBl")[1]}`;
component.events?.forEach(event => {
const eventName = getReactEventName(event.name);
const eventType = cleanGenericTypes(component.typeParameters, event.type.text);
const predefinedEventName = `${componentName}${eventName.split("onBl")[1]}`;

eventStatements.push(`export declare type ${predefinedEventName} = ${eventType};`);
return `${eventName}: EventName<${predefinedEventName}>`;
}) || [];
eventStatements.push(`export declare type ${predefinedEventName} = ${eventType};`);
});

const importPath = path.replace(/^src\//, "").replace(/\.ts$/, "");
const typeName = componentName + "Type";
const formattedEventTypes = eventTypes.length ? `, {${eventTypes.join(", ")}}` : "";
const componentType = `${typeName}${formattedEventTypes}`;

importStatements.push(`import type ${typeName} from "./${importPath}";`);
exportStatements.push(`export declare type ${componentName} = ${typeName}`);
importStatements.push(`export type ${componentName} = import("./${importPath}").default;`);

const jsDoc = component.jsDoc || "";

const source = `
${jsDoc || ""}
${jsDoc}
export const ${componentName} = React.lazy(() =>
customElements.whenDefined('${fileName}').then(() => ({
default: createComponent<${componentType}>({
default: createComponent({
react: React,
displayName: "${componentName}",
tagName: "${fileName}",
elementClass: customElements.get("${fileName}"),
events: ${JSON.stringify(eventNames)},
elementClass: customElements.get("${fileName}") as Constructor<${componentName}>,
events: {
${eventNames}
},
})
}))
);
Expand All @@ -76,16 +74,19 @@ function getReactEventName(baklavaEventName) {
}

function writeBaklavaReactFile(fileContentParts) {
const constructorType = `type Constructor<T> = { new (): T };`;

const content = [
`/* eslint-disable @typescript-eslint/ban-ts-comment */`,
`// @ts-nocheck`,
...importStatements,
...eventStatements,
constructorType,
...exportStatements,
...fileContentParts,
].join("\n\n");

const formattedContent = format(content, { parser: "typescript" });
const formattedContent = format(content, Object.assign(prettierConfig, { parser: "typescript" }));
const outputPath = `${__dirname}/../src/baklava-react.ts`;
fs.writeFileSync(outputPath, formattedContent);
}
Expand Down
3 changes: 1 addition & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,5 @@
}
]
},
"include": ["./src/**/*.ts", "./src/**/*/*.test.ts"],
"exclude": []
"include": ["src"],
}

0 comments on commit 43b5208

Please sign in to comment.