Skip to content

Commit

Permalink
feat: initial impl of next.js wrapper for the swc
Browse files Browse the repository at this point in the history
  • Loading branch information
jianliao authored and Westbrook committed May 25, 2023
1 parent 5fc9b30 commit af911e0
Show file tree
Hide file tree
Showing 3 changed files with 327 additions and 76 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@
"lit-analyzer": "^1.2.1",
"mocha-junit-reporter": "^2.0.2",
"netlify-cli": "^12.9.2",
"next": "^13.4.1",
"node-fetch": "^3.1.0",
"npm-run-all": "^4.1.5",
"patch-package": "^6.4.7",
Expand Down
279 changes: 203 additions & 76 deletions scripts/cem-plugin-react-wrapper.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,32 @@ function genTsconfigJson() {
function genPackageJson(
componentName,
dependencyPkgName,
dependencyPkgVersion
dependencyPkgVersion,
isIconPkg = false
) {
return `{
"name": "@swc-react/${componentName}",
"version": "${dependencyPkgVersion}",
"publishConfig": {
"access": "public"
},
"description": "React wrapper of the ${dependencyPkgName} component",
"description": "React and Next.js wrapper of the ${dependencyPkgName} component",
"license": "Apache-2.0",
"author": "",
"main": "index.js",
"type": "module",${
isIconPkg
? ''
: `\n"exports": {
".": {
"development": "./index.dev.js",
"default": "./index.js"
},
"./next": {
"development": "./next.dev.js",
"default": "./next.js"
}
},`
}
"files": [
"**/*.d.ts",
"**/*.js",
Expand All @@ -73,6 +87,9 @@ function genPackageJson(
"dependencies": {
"@lit-labs/react": "^1.1.1",
"${dependencyPkgName}": "${dependencyPkgVersion}"
},
"peerDependencies": {
"next": "^13.4.1 || latest",
}
}`;
}
Expand Down Expand Up @@ -135,75 +152,56 @@ async function getEvents(decl, declMap, events) {
}

/**
* CEM package will invoke this callback function.
*
* @param {*} exclude array of excluded component class name
* @param {*} outDir root output directory for generated code
* @param {*} prettierConfig prettier library configuration
* Generate React wrapper component source code in typescript.
*/
export default function genReactWrapper({
exclude = [],
outDir = 'legacy',
prettierConfig = {},
} = {}) {
return {
name: 'react-wrapper',
async packageLinkPhase({ customElementsManifest }) {
const { name: pkgName, version: pkgVersion } = JSON.parse(
await readFile(`${process.cwd()}/package.json`)
);
const { modules } = customElementsManifest;
const declMap = new Map(
modules.flatMap((m) =>
m.declarations.map((decl) => [decl.name, decl])
)
);
const components = modules.flatMap((m) =>
m.declarations.filter(
(decl) =>
!exclude.includes(decl.name) &&
(decl.customElement || decl.tagName)
)
);
async function genReactComponentSourceCode(modules, exclude, pkgName) {
const declMap = new Map(
modules.flatMap((m) => m.declarations.map((decl) => [decl.name, decl]))
);

if (components.length === 0) {
return;
}
const components = modules.flatMap((m) =>
m.declarations.filter(
(decl) =>
!exclude.includes(decl.name) &&
(decl.customElement || decl.tagName)
)
);

const componentImports = [];
if (components.length === 0) {
return;
}

const componentImports = [];

const fileImports = modules
.filter(
(m) =>
m.exports.length === 1 &&
m.exports.some(
(exp) => exp.kind === 'custom-element-definition'
)
const fileImports = modules
.filter(
(m) =>
m.exports.length === 1 &&
m.exports.some(
(exp) => exp.kind === 'custom-element-definition'
)
.map(
(m) =>
`import '${pkgName}/${m.path?.replace('.ts', '.js')}';`
);
)
.map((m) => `import '${pkgName}/${m.path?.replace('.ts', '.js')}';`);

const reactComponents = [];
const reactComponents = [];

for (let component of components) {
componentImports.push(
`import { ${component.name} as Sp${component.name} } from '${pkgName}';`
);
for (let component of components) {
componentImports.push(
`import { ${component.name} as Sp${component.name} } from '${pkgName}';`
);

const reactComponent = {};
reactComponent.name = `${component.name}`;
reactComponent.swcComponentName = `Sp${component.name}`;
reactComponent.elementName = component.tagName;
const events = [];
await getEvents(component, declMap, events);
reactComponent.events = uniqueBy(events.flat(), 'name');
const reactComponent = {};
reactComponent.name = `${component.name}`;
reactComponent.swcComponentName = `Sp${component.name}`;
reactComponent.elementName = component.tagName;
const events = [];
await getEvents(component, declMap, events);
reactComponent.events = uniqueBy(events.flat(), 'name');

reactComponents.push(reactComponent);
}
reactComponents.push(reactComponent);
}

const componentSrc = `/*
const componentSrc = `/*
Copyright 2022 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
Expand All @@ -217,11 +215,10 @@ governing permissions and limitations under the License.
import * as React from 'react';
import { createComponent } from '@lit-labs/react';${
reactComponents.flatMap((component) => component.events)
.length > 0
? "\nimport type { EventName } from '@lit-labs/react';"
: ''
}
reactComponents.flatMap((component) => component.events).length > 0
? "\nimport type { EventName } from '@lit-labs/react';"
: ''
}
${componentImports.reduce((pre, cur) => pre + cur + '\n', '')}
${fileImports.reduce((pre, cur) => pre + cur + '\n', '')}
Expand Down Expand Up @@ -256,6 +253,88 @@ ${reactComponents.reduce(
''
)}
`;
return componentSrc;
}

/**
* Generate Next.js wrapper component source code in typescript.
*/
async function genNextComponentSourceCode(modules, exclude) {
const elements = modules.flatMap((m) => {
return m.declarations
.filter(
(d) => d.customElement && d.tagName && !exclude.includes(d.name)
)
.map((d) => {
return {
name: d.name,
tagName: d.tagName,
import: `import { ${d.name} as Sp${d.name} } from '.';`,
};
});
});

const nextWrapperSource = `/*
Copyright 2023 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
import { ComponentProps } from 'react';
import dynamic from 'next/dynamic';
${elements.reduce((pre, element) => pre + element.import + '\n', '')}
${elements.reduce(
(pre, element) =>
pre +
`export const ${element.name} = dynamic<JSX.LibraryManagedAttributes<typeof Sp${element.name}, ComponentProps<typeof Sp${element.name}>>>(() => import('.').then(({${element.name}}) => ${element.name}), { ssr: false });` +
'\n',
''
)}`;

return nextWrapperSource;
}

/**
* CEM package will invoke this callback function.
*
* @param {*} exclude array of excluded component class name
* @param {*} outDir root output directory for generated code
* @param {*} prettierConfig prettier library configuration
*/
export default function genWrappers({
exclude = [],
outDir = 'legacy',
prettierConfig = {},
} = {}) {
return {
name: 'react-wrapper',
async packageLinkPhase({ customElementsManifest }) {
const { name: pkgName, version: pkgVersion } = JSON.parse(
await readFile(`${process.cwd()}/package.json`)
);
const { modules } = customElementsManifest;
const reactComponentSrc = await genReactComponentSourceCode(
modules,
exclude,
pkgName
);

if (!reactComponentSrc) {
return;
}

const nextComponentSrc = await genNextComponentSourceCode(
modules,
exclude
);

const componentShortName = pkgName.replace(
'@spectrum-web-components/',
Expand All @@ -265,7 +344,14 @@ ${reactComponents.reduce(
const componentPath = resolve(`${outDir}/${componentShortName}`);
await outputFile(
resolve(`${componentPath}/index.ts`),
prettier.format(componentSrc, {
prettier.format(reactComponentSrc, {
parser: 'typescript',
...prettierConfig,
})
);
await outputFile(
resolve(`${componentPath}/next.ts`),
prettier.format(nextComponentSrc, {
parser: 'typescript',
...prettierConfig,
})
Expand Down Expand Up @@ -294,9 +380,9 @@ ${reactComponents.reduce(
/* Icon wrapper generation ============================================= */

/**
* Generate Icon component
* Generate React wrapper for Icon component
*/
function genIconComponent(component, id, iconElementName, iconPkg) {
function genIconReactComponent(component, id, iconElementName, iconPkg) {
const componentAliasName = `Sp${component}`;
return `/*
Copyright 2022 Adobe. All rights reserved.
Expand All @@ -322,6 +408,33 @@ export type ${component}Type = ${componentAliasName};
`;
}

/**
* Generate Next.js wrapper for Icon component
*/
function genIconNextComponent(displayName) {
return `/*
Copyright 2022 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
import dynamic from 'next/dynamic';
import { ComponentType } from 'react';
import type { Icon${displayName}Type } from '../${displayName}';
export const Icon${displayName}: ComponentType<Partial<Icon${displayName}Type> | { slot: string }> = dynamic<Partial<Icon${displayName}Type> | { slot: string }>(
() => import('../${displayName}').then((m) => m.Icon${displayName} as any),
{ ssr: false}
);
`;
}

/**
* Core entry function
*/
Expand All @@ -343,18 +456,29 @@ export async function generateIconWrapper(iconType) {
`react/${iconType}/${componentName}.ts`
),
prettier.format(
genIconComponent(
genIconReactComponent(
`Icon${componentName}`,
`Icon${id}`,
iconElementName,
`${iconType}`
),
{
parser: 'babel',
parser: 'typescript',
...prettierConfig,
}
)
);
await outputFile(
resolve(
__dirname,
'..',
`react/${iconType}/next/${componentName}.ts`
),
prettier.format(genIconNextComponent(Case.pascal(id)), {
parser: 'typescript',
...prettierConfig,
})
);
}

const { name: pkgName, version: pkgVersion } = await readJSON(
Expand All @@ -363,10 +487,13 @@ export async function generateIconWrapper(iconType) {

await outputFile(
resolve(__dirname, '..', `react/${iconType}/package.json`),
prettier.format(genPackageJson(iconType, pkgName, pkgVersion), {
parser: 'json',
...prettierConfig,
})
prettier.format(
genPackageJson(iconType, pkgName, pkgVersion, true),
{
parser: 'json',
...prettierConfig,
}
)
);

await outputFile(
Expand Down
Loading

0 comments on commit af911e0

Please sign in to comment.