Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add Lit blueprint #2111

Merged
merged 2 commits into from
Oct 26, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ src/components.d.ts
src/components/*/readme.md
src/global/core/components/*/readme.md
convenience/generate-component/boilerplate/readme.md
convenience/generate-component/boilerplate/component.tsx
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line is required because prettier strips the apexes before the component name at line 57

react-library
23 changes: 23 additions & 0 deletions convenience/generate-component/boilerplate/component.e2e.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { assert, expect, fixture } from '@open-wc/testing';
import { html } from 'lit/static-html.js';
import { EventSpy, waitForLitRender } from '../../global/testing';
import { __nameUpperCase__ } from './__name__';

describe('__name__', () => {
let element: __nameUpperCase__;

beforeEach(async () => {
element = await fixture(html`<__name__></__name__>`);
});

it('renders', async () => {
assert.instanceOf(element, __nameUpperCase__);
});

it('emits on click', async () => {
const myEventNameSpy = new EventSpy(__nameUpperCase__.events.myEventName);
element.click();
await waitForLitRender(element);
expect(myEventNameSpy.count).to.be.equal(1);
});
});
13 changes: 13 additions & 0 deletions convenience/generate-component/boilerplate/component.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
@use '../../global/styles' as sbb;

// Default component properties, defined for :host. Properties which can not
// travel the shadow boundary are defined through this mixin
@include sbb.host-component-properties;

:host {
--__name__-some-color-var: var(--color-black-default);
}

.__name__ {
color: var(--__name__-some-color-var);
}
17 changes: 17 additions & 0 deletions convenience/generate-component/boilerplate/component.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { expect, fixture } from '@open-wc/testing';
import { html } from 'lit/static-html.js';
import './__name__';

describe('__name__', () => {
it('renders', async () => {
const root = await fixture(html`<__name__ my-prop="Label"></__name__>`);

expect(root).dom.to.be.equal(`<__name__ my-prop="Label"></__name__>`);

expect(root).shadowDom.to.be.equal(`
<div class="__name__">
Label
</div>
`);
});
});
55 changes: 55 additions & 0 deletions convenience/generate-component/boilerplate/component.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/** @jsx h */
import { h, JSX } from 'jsx-dom';
import readme from './readme.md?raw';
import { withActions } from '@storybook/addon-actions/decorator';
import type { Meta, StoryObj, ArgTypes, Args, Decorator } from '@storybook/web-components';
import type { InputType } from '@storybook/types';
import { __nameUpperCase__ } from './__name__';
import './__name__';

const myProp: InputType = {
control: {
type: 'text',
},
};

const defaultArgTypes: ArgTypes = {
'my-prop': myProp,
};

const defaultArgs: Args = {
'my-prop': 'Label',
};

const Template = ({ ...args }): JSX.Element => <__name__ {...args}></__name__>;

export const Default: StoryObj = {
render: Template,
argTypes: defaultArgTypes,
args: { ...defaultArgs },
};

const meta: Meta = {
decorators: [
(Story) => (
<div style={{ padding: '2rem' }}>
<Story />
</div>
),
withActions as Decorator,
],
parameters: {
actions: {
handles: [__nameUpperCase__.events.myEventName],
},
backgrounds: {
disable: true,
},
docs: {
extractComponentDescription: () => readme,
},
},
title: 'components/__name__',
};

export default meta;
59 changes: 59 additions & 0 deletions convenience/generate-component/boilerplate/component.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { CSSResult, html, LitElement, nothing, TemplateResult, PropertyValues } from 'lit';
jeripeierSBB marked this conversation as resolved.
Show resolved Hide resolved
import { customElement, property, state } from 'lit/decorators.js';
import { ConnectedAbortController, EventEmitter } from '../../global/eventing';
import Style from './__name__.scss?lit&inline';

/**
* @slot unnamed - Use this to document a slot.
*/
@customElement('__name__')
export class __nameUpperCase__ extends LitElement {
public static override styles: CSSResult = Style;
public static readonly events: Record<string, string> = {
myEventName: 'my-event-name',
} as const;

/** myProp documentation */
@property({ attribute: 'my-prop', reflect: true }) public myProp: string;

/** _myState documentation */
@state() private _myState = false;

private _abort = new ConnectedAbortController(this);
private _fileChangedEvent: EventEmitter<any> = new EventEmitter(this, __nameUpperCase__.events.myEventName);
jeripeierSBB marked this conversation as resolved.
Show resolved Hide resolved

private _onClickFn(): void {
this._fileChangedEvent.emit();
}

public override connectedCallback(): void {
super.connectedCallback();
const signal = this._abort.signal;
this.addEventListener('click', () => this._onClickFn(), { signal });
// do stuff
}

public override willUpdate(changedProperties: PropertyValues<this>): void {
if (changedProperties.has('myProp')) {
// do stuff
}
}

public override disconnectedCallback(): void {
super.disconnectedCallback();
// do stuff
}

protected override render(): TemplateResult {
return html`
<div class="__name__">${this._myState ? html`<slot></slot>` : nothing} ${this.myProp}</div>
`;
}
}

declare global {
interface HTMLElementTagNameMap {
// eslint-disable-next-line @typescript-eslint/naming-convention
'__name__': __nameUpperCase__;
}
}
118 changes: 118 additions & 0 deletions convenience/generate-component/index.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import { join, relative } from 'path';
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The script has been adapted from the old one, changing it to .mts and adapting imports, etc.

import { existsSync, mkdirSync, promises, readFileSync, Stats, writeFileSync } from 'fs';

const config = {
boilerplateComponentName: 'component',
boilerplateDirectory: 'convenience/generate-component/boilerplate',
sourceDirectory: 'src/components',
};

function convertKebabCaseToPascalCase(componentName: string): string {
const capitalize = (_string): string => _string.charAt(0).toUpperCase() + _string.slice(1);

const words = componentName.split('-');
const capitalized = words.map((word) => capitalize(word));

return capitalized.join('');
}

async function getBoilerplateFiles(
_sourceFiles: string,
_foundFiles: Array<string>,
): Array<string> {
try {
const sourceFiles: Promise<Array<string>> = await promises.readdir(
_sourceFiles || config.boilerplateDirectory,
);
const foundFiles: Array<string> = _foundFiles || [];

for await (const file of sourceFiles) {
const fromPath: string = join(_sourceFiles || config.boilerplateDirectory, file);
const stat: Stats = await promises.stat(fromPath);

if (stat.isFile()) {
foundFiles.push(fromPath);
} else if (stat.isDirectory()) {
await getBoilerplateFiles(fromPath, foundFiles);
}
}

return foundFiles;
} catch (e) {
// Catch anything bad that happens
console.error('There was an error iterating over the boilerplate files... ', e);
return [];
}
}

function createDirectories(targetDirectory: string): void {
mkdirSync(targetDirectory);
}

function copyFiles(
foundFiles: Array<string>,
componentName: string,
targetDirectory: string,
): void {
foundFiles.forEach((file) => {
try {
const fileData: string = readFileSync(file, 'utf8');

const fileDataWithCorrectName: string = fileData
.replace(/__name__/gu, componentName)
.replace(/__nameUpperCase__/gu, convertKebabCaseToPascalCase(componentName));

try {
const relativePath: string = relative(config.boilerplateDirectory, file);
const fileName: string = relativePath.replace(
`${config.boilerplateComponentName}.`,
`${componentName}.`,
);
const targetPath: string = `${targetDirectory}/${fileName}`;

writeFileSync(targetPath, fileDataWithCorrectName);
} catch (err) {
console.error(err);
}
} catch (err) {
console.log(`error processing boilerplate file ${file}: ${err}`);
}
});
}

async function createComponent(componentName): void {
if (!componentName) {
console.log(`
Please pass a component name like so: yarn generate my-component-name
`);
return;
}

// make sure we have a dash in the name and the "sbb" prefix
if (componentName.indexOf('sbb-') !== 0) {
console.log(
'component name must be in kebab case and must start with "sbb" prefix, eg: sbb-my-component-name',
);
return;
}

const targetDirectory: string = `${config.sourceDirectory}/${componentName}`;

// check if a component with the passed name does not already exist
if (existsSync(targetDirectory)) {
console.log(`A component with the name ${componentName} already exists`);
return;
}

const foundFiles: Array<string> = await getBoilerplateFiles();

if (foundFiles.length < 1) {
console.log('Could not find boilerplate files');
return;
}

createDirectories(targetDirectory);
copyFiles(foundFiles, componentName, targetDirectory);
}

await createComponent(process.argv[2]);
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"docs": "npm-run-all --sequential docs:manifest",
"docs:manifest": "custom-elements-manifest analyze",
"format": "prettier \"**/*\" --write --ignore-unknown",
"generate": "tsx convenience/generate-component/index.mts",
"integrity": "yarn format",
"lint": "npm-run-all --sequential lint:*",
"lint:ts": "eslint \"**/*.{ts,tsx}\"",
Expand Down
Loading