@stencil/angular-output-target 0.4.0-3 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,51 @@
1
1
  # @stencil/angular-output-target
2
2
 
3
- This is an output plugin for stencil.
3
+ Stencil can generate Angular component wrappers for your web components. This allows your Stencil components to be used within an Angular application. The benefits of using Stencil's component wrappers over the standard web components include:
4
+
5
+ - Angular component wrappers will be detached from change detection, preventing unnecessary repaints of your web component.
6
+ - Web component events will be converted to RxJS observables to align with Angular's @Output() and will not emit across component boundaries.
7
+ - Optionally, form control web components can be used as control value accessors with Angular's reactive forms or [ngModel].
8
+
9
+ For a detailed guide on how to add the angular output target to a project, visit: https://stenciljs.com/docs/angular.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ npm install @stencil/angular-output-target
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ In your `stencil.config.ts` add the following configuration to the `outputTargets` section:
20
+
21
+ ```ts
22
+ import { Config } from '@stencil/core';
23
+ import { angularOutputTarget } from '@stencil/angular-output-target';
24
+
25
+ export const config: Config = {
26
+ namespace: 'demo',
27
+ outputTargets: [
28
+ angularOutputTarget({
29
+ componentCorePackage: 'component-library',
30
+ directivesProxyFile: '../component-library-angular/src/directives/proxies.ts',
31
+ directivesArrayFile: '../component-library-angular/src/directives/index.ts',
32
+ }),
33
+ {
34
+ type: 'dist',
35
+ esmLoaderPath: '../loader',
36
+ },
37
+ ],
38
+ };
39
+ ```
40
+
41
+ ## Config Options
42
+
43
+ | Property | Description |
44
+ | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
45
+ | `componentCorePackage` | The NPM package name of your Stencil component library. This package is used as a dependency for your Angular wrappers. |
46
+ | `directivesProxyFile` | The output file of all the component wrappers generated by the output target. This file path should point to a location within your Angular library/project. |
47
+ | `directivesArrayFile` | The output file of a constant of all the generated component wrapper classes. Used for easily declaring and exporting the generated components from an `NgModule`. This file path should point to a location within your Angular library/project. |
48
+ | `valueAccessorConfigs` | The configuration object for how individual web components behave with Angular control value accessors. |
49
+ | `excludeComponents` | An array of tag names to exclude from generating component wrappers for. This is helpful when have a custom framework implementation of a specific component or need to extend the base component wrapper behavior. |
50
+ | `includeImportCustomElements` | If `true`, the output target will import the custom element instance and register it with the Custom Elements Registry when the component is imported inside of a user's app. This can only be used with the [Custom Elements Bundle](https://stenciljs.com/docs/custom-elements) and will not work with lazy loaded components. |
51
+ | `customElementsDir` | This is the directory where the custom elements are imported from when using the [Custom Elements Bundle](https://stenciljs.com/docs/custom-elements). Defaults to the `components` directory. Only applies when `includeImportCustomElements` is `true`. |
@@ -4,46 +4,40 @@ import { fromEvent } from 'rxjs';
4
4
 
5
5
  export const proxyInputs = (Cmp: any, inputs: string[]) => {
6
6
  const Prototype = Cmp.prototype;
7
- inputs.forEach(item => {
7
+ inputs.forEach((item) => {
8
8
  Object.defineProperty(Prototype, item, {
9
9
  get() {
10
10
  return this.el[item];
11
11
  },
12
12
  set(val: any) {
13
13
  this.z.runOutsideAngular(() => (this.el[item] = val));
14
- }
14
+ },
15
15
  });
16
16
  });
17
17
  };
18
18
 
19
19
  export const proxyMethods = (Cmp: any, methods: string[]) => {
20
20
  const Prototype = Cmp.prototype;
21
- methods.forEach(methodName => {
21
+ methods.forEach((methodName) => {
22
22
  Prototype[methodName] = function () {
23
23
  const args = arguments;
24
- return this.z.runOutsideAngular(() =>
25
- this.el[methodName].apply(this.el, args)
26
- );
24
+ return this.z.runOutsideAngular(() => this.el[methodName].apply(this.el, args));
27
25
  };
28
26
  });
29
27
  };
30
28
 
31
29
  export const proxyOutputs = (instance: any, el: any, events: string[]) => {
32
- events.forEach(eventName => instance[eventName] = fromEvent(el, eventName));
33
- }
30
+ events.forEach((eventName) => (instance[eventName] = fromEvent(el, eventName)));
31
+ };
34
32
 
35
33
  export const defineCustomElement = (tagName: string, customElement: any) => {
36
- if (
37
- customElement !== undefined &&
38
- typeof customElements !== 'undefined' &&
39
- !customElements.get(tagName)
40
- ) {
34
+ if (customElement !== undefined && typeof customElements !== 'undefined' && !customElements.get(tagName)) {
41
35
  customElements.define(tagName, customElement);
42
36
  }
43
- }
37
+ };
44
38
 
45
39
  // tslint:disable-next-line: only-arrow-functions
46
- export function ProxyCmp(opts: { defineCustomElementFn?: () => void, inputs?: any; methods?: any }) {
40
+ export function ProxyCmp(opts: { defineCustomElementFn?: () => void; inputs?: any; methods?: any }) {
47
41
  const decorator = function (cls: any) {
48
42
  const { defineCustomElementFn, inputs, methods } = opts;
49
43
 
@@ -1,2 +1,22 @@
1
- import type { ComponentCompilerMeta } from '@stencil/core/internal';
2
- export declare const createComponentDefinition: (componentCorePackage: string, distTypesDir: string, rootDir: string, includeImportCustomElements?: boolean, customElementsDir?: string) => (cmpMeta: ComponentCompilerMeta) => string;
1
+ import type { ComponentCompilerEvent } from '@stencil/core/internal';
2
+ /**
3
+ * Creates an Angular component declaration from formatted Stencil compiler metadata.
4
+ *
5
+ * @param tagName The tag name of the component.
6
+ * @param inputs The inputs of the Stencil component (e.g. ['myInput']).
7
+ * @param outputs The outputs/events of the Stencil component. (e.g. ['myOutput']).
8
+ * @param methods The methods of the Stencil component. (e.g. ['myMethod']).
9
+ * @param includeImportCustomElements Whether to define the component as a custom element.
10
+ * @returns The component declaration as a string.
11
+ */
12
+ export declare const createAngularComponentDefinition: (tagName: string, inputs: readonly string[], outputs: readonly string[], methods: readonly string[], includeImportCustomElements?: boolean) => string;
13
+ /**
14
+ * Creates the component interface type definition.
15
+ * @param tagNameAsPascal The tag name as PascalCase.
16
+ * @param events The events to generate the interface properties for.
17
+ * @param componentCorePackage The component core package.
18
+ * @param includeImportCustomElements Whether to include the import for the custom element definition.
19
+ * @param customElementsDir The custom elements directory.
20
+ * @returns The component interface type definition as a string.
21
+ */
22
+ export declare const createComponentTypeDefinition: (tagNameAsPascal: string, events: readonly ComponentCompilerEvent[], componentCorePackage: string, includeImportCustomElements?: boolean, customElementsDir?: string | undefined) => string;
@@ -1,101 +1,134 @@
1
- import { dashToPascalCase, normalizePath } from './utils';
2
- export const createComponentDefinition = (componentCorePackage, distTypesDir, rootDir, includeImportCustomElements = false, customElementsDir = 'components') => (cmpMeta) => {
3
- // Collect component meta
4
- const inputs = [
5
- ...cmpMeta.properties.filter((prop) => !prop.internal).map((prop) => prop.name),
6
- ...cmpMeta.virtualProperties.map((prop) => prop.name),
7
- ].sort();
8
- const outputs = cmpMeta.events.filter((ev) => !ev.internal).map((prop) => prop);
9
- const methods = cmpMeta.methods.filter((method) => !method.internal).map((prop) => prop.name);
10
- // Process meta
1
+ import { createComponentEventTypeImports, dashToPascalCase, formatToQuotedList } from './utils';
2
+ /**
3
+ * Creates an Angular component declaration from formatted Stencil compiler metadata.
4
+ *
5
+ * @param tagName The tag name of the component.
6
+ * @param inputs The inputs of the Stencil component (e.g. ['myInput']).
7
+ * @param outputs The outputs/events of the Stencil component. (e.g. ['myOutput']).
8
+ * @param methods The methods of the Stencil component. (e.g. ['myMethod']).
9
+ * @param includeImportCustomElements Whether to define the component as a custom element.
10
+ * @returns The component declaration as a string.
11
+ */
12
+ export const createAngularComponentDefinition = (tagName, inputs, outputs, methods, includeImportCustomElements = false) => {
13
+ const tagNameAsPascal = dashToPascalCase(tagName);
14
+ const hasInputs = inputs.length > 0;
11
15
  const hasOutputs = outputs.length > 0;
12
- // Generate Angular @Directive
13
- const directiveOpts = [
14
- `selector: \'${cmpMeta.tagName}\'`,
15
- `changeDetection: ChangeDetectionStrategy.OnPush`,
16
- `template: '<ng-content></ng-content>'`,
17
- ];
18
- if (inputs.length > 0) {
19
- directiveOpts.push(`inputs: ['${inputs.join(`', '`)}']`);
16
+ const hasMethods = methods.length > 0;
17
+ // Formats the input strings into comma separated, single quoted values.
18
+ const formattedInputs = formatToQuotedList(inputs);
19
+ // Formats the output strings into comma separated, single quoted values.
20
+ const formattedOutputs = formatToQuotedList(outputs);
21
+ // Formats the method strings into comma separated, single quoted values.
22
+ const formattedMethods = formatToQuotedList(methods);
23
+ const proxyCmpOptions = [];
24
+ if (includeImportCustomElements) {
25
+ const defineCustomElementFn = `define${tagNameAsPascal}`;
26
+ proxyCmpOptions.push(`\n defineCustomElementFn: ${defineCustomElementFn}`);
20
27
  }
21
- const tagNameAsPascal = dashToPascalCase(cmpMeta.tagName);
22
- const outputsInterface = new Set();
23
- const outputReferenceRemap = {};
24
- outputs.forEach((output) => {
25
- Object.entries(output.complexType.references).forEach(([reference, refObject]) => {
26
- // Add import line for each local/import reference, and add new mapping name.
27
- // `outputReferenceRemap` should be updated only if the import interface is set in outputsInterface,
28
- // this will prevent global types to be remapped.
29
- const remappedReference = `I${cmpMeta.componentClassName}${reference}`;
30
- if (refObject.location === 'local' || refObject.location === 'import') {
31
- outputReferenceRemap[reference] = remappedReference;
32
- let importLocation = componentCorePackage;
33
- if (componentCorePackage !== undefined) {
34
- const dirPath = includeImportCustomElements ? `/${customElementsDir || 'components'}` : '';
35
- importLocation = `${normalizePath(componentCorePackage)}${dirPath}`;
36
- }
37
- outputsInterface.add(`import type { ${reference} as ${remappedReference} } from '${importLocation}';`);
38
- }
39
- });
40
- });
41
- const componentEvents = [
42
- '' // Empty first line
43
- ];
44
- // Generate outputs
45
- outputs.forEach((output, index) => {
46
- componentEvents.push(` /**
47
- * ${output.docs.text} ${output.docs.tags.map((tag) => `@${tag.name} ${tag.text}`)}
48
- */`);
49
- /**
50
- * The original attribute contains the original type defined by the devs.
51
- * This regexp normalizes the reference, by removing linebreaks,
52
- * replacing consecutive spaces with a single space, and adding a single space after commas.
53
- **/
54
- const outputTypeRemapped = Object.entries(outputReferenceRemap).reduce((type, [src, dst]) => {
55
- return type
56
- .replace(new RegExp(`^${src}$`, 'g'), `${dst}`)
57
- .replace(new RegExp(`([^\\w])${src}([^\\w])`, 'g'), (v, p1, p2) => [p1, dst, p2].join(''));
58
- }, output.complexType.original
59
- .replace(/\n/g, ' ')
60
- .replace(/\s{2,}/g, ' ')
61
- .replace(/,\s*/g, ', '));
62
- componentEvents.push(` ${output.name}: EventEmitter<CustomEvent<${outputTypeRemapped.trim()}>>;`);
63
- if (index === outputs.length - 1) {
64
- // Empty line to push end `}` to new line
65
- componentEvents.push('\n');
66
- }
67
- });
68
- const lines = [
69
- '',
70
- `${[...outputsInterface].join('\n')}
71
- export declare interface ${tagNameAsPascal} extends Components.${tagNameAsPascal} {${componentEvents.length > 1 ? componentEvents.join('\n') : ''}}
72
-
73
- ${getProxyCmp(cmpMeta.tagName, includeImportCustomElements, inputs, methods)}
28
+ if (hasInputs) {
29
+ proxyCmpOptions.push(`\n inputs: [${formattedInputs}]`);
30
+ }
31
+ if (hasMethods) {
32
+ proxyCmpOptions.push(`\n methods: [${formattedMethods}]`);
33
+ }
34
+ /**
35
+ * Notes on the generated output:
36
+ * - We disable @angular-eslint/no-inputs-metadata-property, so that
37
+ * Angular does not complain about the inputs property. The output target
38
+ * uses the inputs property to define the inputs of the component instead of
39
+ * having to use the @Input decorator (and manually define the type and default value).
40
+ */
41
+ const output = `@ProxyCmp({${proxyCmpOptions.join(',')}\n})
74
42
  @Component({
75
- ${directiveOpts.join(',\n ')}
43
+ selector: '${tagName}',
44
+ changeDetection: ChangeDetectionStrategy.OnPush,
45
+ template: '<ng-content></ng-content>',
46
+ // eslint-disable-next-line @angular-eslint/no-inputs-metadata-property
47
+ inputs: [${formattedInputs}],
76
48
  })
77
- export class ${tagNameAsPascal} {`,
78
- ];
79
- lines.push(' protected el: HTMLElement;');
80
- lines.push(` constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
49
+ export class ${tagNameAsPascal} {
50
+ protected el: HTMLElement;
51
+ constructor(c: ChangeDetectorRef, r: ElementRef, protected z: NgZone) {
81
52
  c.detach();
82
- this.el = r.nativeElement;`);
83
- if (hasOutputs) {
84
- lines.push(` proxyOutputs(this, this.el, ['${outputs.map((output) => output.name).join(`', '`)}']);`);
53
+ this.el = r.nativeElement;${hasOutputs
54
+ ? `
55
+ proxyOutputs(this, this.el, [${formattedOutputs}]);`
56
+ : ''}
57
+ }
58
+ }`;
59
+ return output;
60
+ };
61
+ /**
62
+ * Sanitizes and formats the component event type.
63
+ * @param componentClassName The class name of the component (e.g. 'MyComponent')
64
+ * @param event The Stencil component event.
65
+ * @returns The sanitized event type as a string.
66
+ */
67
+ const formatOutputType = (componentClassName, event) => {
68
+ /**
69
+ * The original attribute contains the original type defined by the devs.
70
+ * This regexp normalizes the reference, by removing linebreaks,
71
+ * replacing consecutive spaces with a single space, and adding a single space after commas.
72
+ */
73
+ return Object.entries(event.complexType.references)
74
+ .filter(([_, refObject]) => refObject.location === 'local' || refObject.location === 'import')
75
+ .reduce((type, [src, dst]) => {
76
+ const renamedType = `I${componentClassName}${type}`;
77
+ return (renamedType
78
+ .replace(new RegExp(`^${src}$`, 'g'), `${dst}`)
79
+ // Capture all instances of the `src` field surrounded by non-word characters on each side and join them.
80
+ .replace(new RegExp(`([^\\w])${src}([^\\w])`, 'g'), (v, p1, p2) => [p1, dst, p2].join('')));
81
+ }, event.complexType.original
82
+ .replace(/\n/g, ' ')
83
+ .replace(/\s{2,}/g, ' ')
84
+ .replace(/,\s*/g, ', '));
85
+ };
86
+ /**
87
+ * Creates a formatted comment block based on the JS doc comment.
88
+ * @param doc The compiler jsdoc.
89
+ * @returns The formatted comment block as a string.
90
+ */
91
+ const createDocComment = (doc) => {
92
+ if (doc.text.trim().length === 0 && doc.tags.length === 0) {
93
+ return '';
85
94
  }
86
- lines.push(` }`);
87
- lines.push(`}`);
88
- return lines.join('\n');
95
+ return `/**
96
+ * ${doc.text}${doc.tags.length > 0 ? ' ' : ''}${doc.tags.map((tag) => `@${tag.name} ${tag.text}`)}
97
+ */`;
98
+ };
99
+ /**
100
+ * Creates the component interface type definition.
101
+ * @param tagNameAsPascal The tag name as PascalCase.
102
+ * @param events The events to generate the interface properties for.
103
+ * @param componentCorePackage The component core package.
104
+ * @param includeImportCustomElements Whether to include the import for the custom element definition.
105
+ * @param customElementsDir The custom elements directory.
106
+ * @returns The component interface type definition as a string.
107
+ */
108
+ export const createComponentTypeDefinition = (tagNameAsPascal, events, componentCorePackage, includeImportCustomElements = false, customElementsDir) => {
109
+ const publicEvents = events.filter((ev) => !ev.internal);
110
+ const eventTypeImports = createComponentEventTypeImports(tagNameAsPascal, publicEvents, {
111
+ componentCorePackage,
112
+ includeImportCustomElements,
113
+ customElementsDir,
114
+ });
115
+ const eventTypes = publicEvents.map((event) => {
116
+ const comment = createDocComment(event.docs);
117
+ let eventName = event.name;
118
+ if (event.name.includes('-')) {
119
+ // If an event name includes a dash, we need to wrap it in quotes.
120
+ // https://github.com/ionic-team/stencil-ds-output-targets/issues/212
121
+ eventName = `'${event.name}'`;
122
+ }
123
+ return `${comment.length > 0 ? ` ${comment}` : ''}
124
+ ${eventName}: EventEmitter<CustomEvent<${formatOutputType(tagNameAsPascal, event)}>>;`;
125
+ });
126
+ const interfaceDeclaration = `export declare interface ${tagNameAsPascal} extends Components.${tagNameAsPascal} {`;
127
+ const typeDefinition = (eventTypeImports.length > 0 ? `${eventTypeImports + '\n\n'}` : '') +
128
+ `${interfaceDeclaration}${eventTypes.length === 0
129
+ ? '}'
130
+ : `
131
+ ${eventTypes.join('\n')}
132
+ }`}`;
133
+ return typeDefinition;
89
134
  };
90
- function getProxyCmp(tagName, includeCustomElement, inputs, methods) {
91
- const hasInputs = inputs.length > 0;
92
- const hasMethods = methods.length > 0;
93
- const proxMeta = [
94
- `defineCustomElementFn: ${includeCustomElement ? 'define' + dashToPascalCase(tagName) : 'undefined'}`
95
- ];
96
- if (hasInputs)
97
- proxMeta.push(`inputs: ['${inputs.join(`', '`)}']`);
98
- if (hasMethods)
99
- proxMeta.push(`methods: ['${methods.join(`', '`)}']`);
100
- return `@ProxyCmp({\n ${proxMeta.join(',\n ')}\n})`;
101
- }
@@ -1,15 +1,12 @@
1
1
  import { EOL } from 'os';
2
2
  import path from 'path';
3
3
  export default async function generateValueAccessors(compilerCtx, components, outputTarget, config) {
4
- if (!Array.isArray(outputTarget.valueAccessorConfigs) ||
5
- outputTarget.valueAccessorConfigs.length === 0) {
4
+ if (!Array.isArray(outputTarget.valueAccessorConfigs) || outputTarget.valueAccessorConfigs.length === 0) {
6
5
  return;
7
6
  }
8
7
  const targetDir = path.dirname(outputTarget.directivesProxyFile);
9
8
  const normalizedValueAccessors = outputTarget.valueAccessorConfigs.reduce((allAccessors, va) => {
10
- const elementSelectors = Array.isArray(va.elementSelectors)
11
- ? va.elementSelectors
12
- : [va.elementSelectors];
9
+ const elementSelectors = Array.isArray(va.elementSelectors) ? va.elementSelectors : [va.elementSelectors];
13
10
  const type = va.type;
14
11
  let allElementSelectors = [];
15
12
  let allEventTargets = [];