@bbq-chat/widgets-angular 1.0.1 → 1.0.2

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.
@@ -1,400 +0,0 @@
1
- import {
2
- Component,
3
- Input,
4
- Output,
5
- EventEmitter,
6
- ElementRef,
7
- AfterViewInit,
8
- OnInit,
9
- OnDestroy,
10
- OnChanges,
11
- SimpleChanges,
12
- ViewChild,
13
- ComponentRef,
14
- EmbeddedViewRef,
15
- TemplateRef,
16
- Injector,
17
- createComponent,
18
- EnvironmentInjector,
19
- Inject,
20
- } from '@angular/core';
21
- import { CommonModule } from '@angular/common';
22
- import {
23
- SsrWidgetRenderer,
24
- WidgetEventManager,
25
- ChatWidget,
26
- } from '@bbq-chat/widgets';
27
- import { WidgetRegistryService } from './widget-registry.service';
28
- import {
29
- WidgetTemplateContext,
30
- isHtmlRenderer,
31
- isComponentRenderer,
32
- isTemplateRenderer,
33
- } from './custom-widget-renderer.types';
34
- import {
35
- WIDGET_EVENT_MANAGER_FACTORY,
36
- SSR_WIDGET_RENDERER,
37
- widgetEventManagerFactoryProvider,
38
- ssrWidgetRendererFactory,
39
- WidgetEventManagerFactory,
40
- } from './widget-di.tokens';
41
-
42
- /**
43
- * Angular component for rendering chat widgets
44
- *
45
- * This component handles rendering of chat widgets using the BbQ ChatWidgets library.
46
- * It manages widget lifecycle, event handling, and cleanup.
47
- *
48
- * Supports three types of custom widget renderers:
49
- * 1. HTML function renderers (return HTML strings)
50
- * 2. Angular Component renderers (render as dynamic components)
51
- * 3. Angular TemplateRef renderers (render as embedded views)
52
- *
53
- * @example
54
- * ```typescript
55
- * <bbq-widget-renderer
56
- * [widgets]="messageWidgets"
57
- * (widgetAction)="handleWidgetAction($event)">
58
- * </bbq-widget-renderer>
59
- * ```
60
- */
61
- @Component({
62
- selector: 'bbq-widget-renderer',
63
- standalone: true,
64
- imports: [CommonModule],
65
- providers: [
66
- { provide: WIDGET_EVENT_MANAGER_FACTORY, useFactory: widgetEventManagerFactoryProvider },
67
- { provide: SSR_WIDGET_RENDERER, useFactory: ssrWidgetRendererFactory },
68
- ],
69
- template: `
70
- <div #widgetContainer class="bbq-widgets-container" (click)="handleClick($event)">
71
- @for (item of widgetItems; track item.index) {
72
- @if (item.isHtml) {
73
- <div class="bbq-widget" [innerHTML]="item.html"></div>
74
- } @else {
75
- <div class="bbq-widget" #dynamicWidget></div>
76
- }
77
- }
78
- </div>
79
- `,
80
- styles: [
81
- `
82
- .bbq-widgets-container {
83
- margin-top: 0.5rem;
84
- }
85
-
86
- .bbq-widget {
87
- margin-bottom: 0.5rem;
88
- }
89
- `,
90
- ],
91
- })
92
- export class WidgetRendererComponent
93
- implements OnInit, AfterViewInit, OnDestroy, OnChanges
94
- {
95
- /**
96
- * Array of widgets to render
97
- */
98
- @Input() widgets: ChatWidget[] | null | undefined;
99
-
100
- /**
101
- * Emits when a widget action is triggered
102
- */
103
- @Output() widgetAction = new EventEmitter<{
104
- actionName: string;
105
- payload: unknown;
106
- }>();
107
-
108
- @ViewChild('widgetContainer', { static: false })
109
- containerRef!: ElementRef<HTMLDivElement>;
110
-
111
- protected widgetItems: Array<{
112
- index: number;
113
- widget: ChatWidget;
114
- isHtml: boolean;
115
- html?: string;
116
- }> = [];
117
-
118
- protected eventManager?: WidgetEventManager;
119
- protected isViewInitialized = false;
120
- protected dynamicComponents: Array<ComponentRef<any>> = [];
121
- protected dynamicViews: Array<EmbeddedViewRef<WidgetTemplateContext>> = [];
122
-
123
- constructor(
124
- @Inject(SSR_WIDGET_RENDERER) protected renderer: SsrWidgetRenderer,
125
- @Inject(WIDGET_EVENT_MANAGER_FACTORY) protected eventManagerFactory: WidgetEventManagerFactory,
126
- protected widgetRegistry: WidgetRegistryService,
127
- protected injector: Injector,
128
- protected environmentInjector: EnvironmentInjector
129
- ) {}
130
-
131
- ngOnInit() {
132
- // this.updateWidgetHtml();
133
- }
134
-
135
- ngOnChanges(changes: SimpleChanges) {
136
- if (changes['widgets']) {
137
- this.updateWidgetHtml();
138
- }
139
- }
140
-
141
- ngAfterViewInit() {
142
- this.updateWidgetHtml();
143
- this.isViewInitialized = true;
144
- this.setupEventHandlers();
145
- // Render dynamic components/templates after view init
146
- this.renderDynamicWidgets();
147
- }
148
-
149
- ngOnDestroy() {
150
- this.cleanup();
151
- }
152
-
153
- /**
154
- * Base implementation for updating the rendered HTML for the current widgets.
155
- *
156
- * Subclasses may override this method to customize how widgets are rendered
157
- * (for example, to inject additional markup or perform preprocessing).
158
- *
159
- * Since this is the base implementation, overriding implementations are not
160
- * required to call `super.updateWidgetHtml()`.
161
- */
162
- protected updateWidgetHtml() {
163
- if (!this.widgets || this.widgets.length === 0) {
164
- this.widgetItems = [];
165
- return;
166
- }
167
-
168
- this.widgetItems = this.widgets.map((widget, index) => {
169
- const customRenderer = this.widgetRegistry.getRenderer(widget.type);
170
-
171
- // Check template renderer first (most specific)
172
- if (customRenderer && isTemplateRenderer(customRenderer)) {
173
- return {
174
- index,
175
- widget,
176
- isHtml: false,
177
- };
178
- }
179
-
180
- // Check component renderer second
181
- if (customRenderer && isComponentRenderer(customRenderer)) {
182
- return {
183
- index,
184
- widget,
185
- isHtml: false,
186
- };
187
- }
188
-
189
- // Check HTML function renderer last (most general, matches any function)
190
- if (customRenderer && isHtmlRenderer(customRenderer)) {
191
- return {
192
- index,
193
- widget,
194
- isHtml: true,
195
- html: customRenderer(widget),
196
- };
197
- }
198
-
199
- // Default: render using the BbQ library renderer
200
- return {
201
- index,
202
- widget,
203
- isHtml: true,
204
- html: this.renderer.renderWidget(widget),
205
- };
206
- });
207
-
208
- // After view updates, reinitialize widgets only if view is already initialized
209
- if (this.isViewInitialized) {
210
- setTimeout(() => {
211
- this.setupEventHandlers();
212
- this.renderDynamicWidgets();
213
- }, 0);
214
- }
215
- }
216
-
217
- /**
218
- * Render dynamic components and templates for custom widgets
219
- */
220
- protected renderDynamicWidgets() {
221
- if (!this.containerRef?.nativeElement) return;
222
-
223
- // Use microtask to ensure Angular has completed change detection
224
- Promise.resolve().then(() => {
225
- if (!this.containerRef?.nativeElement) return;
226
-
227
- // Clean up existing dynamic components and views
228
- this.cleanupDynamicWidgets();
229
-
230
- const container = this.containerRef.nativeElement;
231
- // Query all widget divs without the data-rendered filter
232
- const dynamicWidgetDivs = Array.from(
233
- container.querySelectorAll('.bbq-widget')
234
- ) as HTMLElement[];
235
-
236
- let dynamicIndex = 0;
237
- this.widgetItems.forEach((item) => {
238
- if (!item.isHtml) {
239
- const customRenderer = this.widgetRegistry.getRenderer(item.widget.type);
240
-
241
- if (!customRenderer) return;
242
-
243
- const targetDiv = dynamicWidgetDivs[dynamicIndex];
244
- if (!targetDiv) return;
245
-
246
- // Clear the div content before rendering
247
- targetDiv.innerHTML = '';
248
-
249
- if (isComponentRenderer(customRenderer)) {
250
- this.renderComponent(customRenderer, item.widget, targetDiv);
251
- } else if (isTemplateRenderer(customRenderer)) {
252
- this.renderTemplate(customRenderer, item.widget, targetDiv);
253
- }
254
-
255
- dynamicIndex++;
256
- }
257
- });
258
- });
259
- }
260
-
261
- /**
262
- * Render an Angular component for a custom widget
263
- *
264
- * Note: This method safely assigns properties to component instances
265
- * by checking for property existence at runtime. This approach is necessary
266
- * because we cannot statically verify that all components implement
267
- * the CustomWidgetComponent interface.
268
- */
269
- protected renderComponent(
270
- componentType: any,
271
- widget: ChatWidget,
272
- targetElement: HTMLElement
273
- ) {
274
- // Create the component using Angular's createComponent API
275
- const componentRef = createComponent(componentType, {
276
- environmentInjector: this.environmentInjector,
277
- elementInjector: this.injector,
278
- });
279
-
280
- // Safely set component inputs if they exist
281
- const instance = componentRef.instance;
282
- if (instance && typeof instance === 'object') {
283
- // Set widget property if it exists in the prototype chain
284
- if ('widget' in instance) {
285
- (instance as any).widget = widget;
286
- }
287
-
288
- // Set widgetAction callback if it exists in the prototype chain
289
- if ('widgetAction' in instance) {
290
- (instance as any).widgetAction = (actionName: string, payload: unknown) => {
291
- this.widgetAction.emit({ actionName, payload });
292
- };
293
- }
294
- }
295
-
296
- // Attach the component's host view to the target element
297
- targetElement.appendChild(componentRef.location.nativeElement);
298
-
299
- // Store reference for cleanup
300
- this.dynamicComponents.push(componentRef);
301
-
302
- // Trigger change detection (use optional chaining for safety)
303
- componentRef.changeDetectorRef?.detectChanges();
304
- }
305
-
306
- /**
307
- * Render an Angular template for a custom widget
308
- */
309
- protected renderTemplate(
310
- templateRef: TemplateRef<WidgetTemplateContext>,
311
- widget: ChatWidget,
312
- targetElement: HTMLElement
313
- ) {
314
- const context: WidgetTemplateContext = {
315
- $implicit: widget,
316
- widget: widget,
317
- emitAction: (actionName: string, payload: unknown) => {
318
- this.widgetAction.emit({ actionName, payload });
319
- },
320
- };
321
-
322
- const viewRef = templateRef.createEmbeddedView(context);
323
-
324
- // Attach the view's DOM nodes to the target element
325
- viewRef.rootNodes.forEach((node: Node) => {
326
- targetElement.appendChild(node);
327
- });
328
-
329
- // Store reference for cleanup
330
- this.dynamicViews.push(viewRef);
331
-
332
- // Trigger change detection
333
- viewRef.detectChanges();
334
- }
335
-
336
- /**
337
- * Cleanup dynamic components and views
338
- */
339
- protected cleanupDynamicWidgets() {
340
- this.dynamicComponents.forEach((componentRef) => {
341
- componentRef.destroy();
342
- });
343
- this.dynamicComponents = [];
344
-
345
- this.dynamicViews.forEach((viewRef) => {
346
- viewRef.destroy();
347
- });
348
- this.dynamicViews = [];
349
- }
350
-
351
- private setupEventHandlers() {
352
- if (!this.containerRef?.nativeElement) return;
353
-
354
- // Cleanup old resources before setting up new ones
355
- this.cleanup();
356
-
357
- const container = this.containerRef.nativeElement;
358
-
359
- // Create a custom action handler that emits events
360
- const actionHandler = {
361
- handle: async (action: string, payload: any) => {
362
- this.widgetAction.emit({ actionName: action, payload });
363
- },
364
- };
365
-
366
- // Use the injected factory to create an event manager with the component-specific action handler
367
- this.eventManager = this.eventManagerFactory(actionHandler);
368
- this.eventManager.attachHandlers(container);
369
- }
370
-
371
- handleClick(event: MouseEvent) {
372
- const target = event.target as HTMLElement;
373
- // Only trigger actions on non-form buttons and clickable elements (cards)
374
- // Don't trigger on input elements or form buttons (let WidgetEventManager handle those)
375
- const button = target.tagName === 'BUTTON' ? target : target.closest('button');
376
- if (button && !button.closest('[data-widget-type="form"]')) {
377
- const actionName = button.getAttribute('data-action');
378
- if (actionName) {
379
- try {
380
- const payloadStr = button.getAttribute('data-payload');
381
- const payload = payloadStr ? JSON.parse(payloadStr) : {};
382
- this.widgetAction.emit({ actionName, payload });
383
- } catch (err) {
384
- console.error('Failed to parse widget action payload:', err);
385
- }
386
- }
387
- }
388
- }
389
-
390
- /**
391
- * Cleanup all resources including event listeners.
392
- */
393
- private cleanup() {
394
- // Cleanup dynamic widgets first
395
- this.cleanupDynamicWidgets();
396
-
397
- // Cleanup event manager
398
- this.eventManager = undefined;
399
- }
400
- }
package/tsconfig.json DELETED
@@ -1,34 +0,0 @@
1
- {
2
- "compileOnSave": false,
3
- "compilerOptions": {
4
- "baseUrl": "./",
5
- "outDir": "./dist/out-tsc",
6
- "forceConsistentCasingInFileNames": true,
7
- "strict": true,
8
- "noImplicitReturns": true,
9
- "noFallthroughCasesInSwitch": true,
10
- "sourceMap": true,
11
- "declaration": true,
12
- "downlevelIteration": true,
13
- "experimentalDecorators": true,
14
- "moduleResolution": "node",
15
- "importHelpers": true,
16
- "target": "ES2022",
17
- "module": "ES2022",
18
- "lib": [
19
- "ES2022",
20
- "dom"
21
- ],
22
- "skipLibCheck": true,
23
- "skipDefaultLibCheck": true,
24
- "paths": {
25
- "@bbq-chat/widgets": ["../js/dist"]
26
- }
27
- },
28
- "angularCompilerOptions": {
29
- "enableI18nLegacyMessageIdFormat": false,
30
- "strictInjectionParameters": true,
31
- "strictInputAccessModifiers": true,
32
- "strictTemplates": true
33
- }
34
- }