@creatio-devkit/common 0.832.1 → 0.833.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.
@@ -0,0 +1,1215 @@
1
+ # Remote Component Runtime AI Guide
2
+
3
+ **ATTENTION AI AGENT:** This is a directive instruction set, not documentation. Follow rules exactly.
4
+
5
+ **Audience:** AI assistant generating runtime part of a Creatio Freedom UI custom component.
6
+
7
+ **⚠️ CRITICAL - Reserved HTML Attribute Names:**
8
+ - **NEVER use `readonly` as @Input property name** - conflicts with native HTML attribute in Angular Custom Elements
9
+ - **Use `readOnly` (camelCase) instead** for readonly/editable state properties
10
+ - Other reserved names to avoid: `disabled`, `hidden`, `title`, `id`, `name`, `value` (use with caution or prefix)
11
+ - When in doubt, use camelCase variants: `isDisabled`, `isReadOnly`, `currentValue`
12
+
13
+ **Related guides:**
14
+ - **Design-time guide:** See REMOTE_COMPONENT_DESIGN_TIME_AI_GUIDE.md from @creatio-devkit/interface-designer package
15
+ - **Accessibility guide:** See WCAG_ACCESSIBILITY_AI_GUIDE.md from @creatio-devkit/common package (MANDATORY for all components)
16
+ - **Icon guide:** See ICON_REQUIREMENTS_AI_GUIDE.md from @creatio-devkit/common package
17
+
18
+ ---
19
+
20
+ ## 📝 Placeholder Registry
21
+
22
+ **INSTRUCTION:** Replace `{{PLACEHOLDERS}}` using this registry. NEVER leave placeholders unreplaced.
23
+
24
+ | Placeholder | Source | Transform | Example |
25
+ |-------------|--------|-----------|---------|
26
+ | `{{PREFIX}}` | `SESSION.prefix` | as-is | `usr` |
27
+ | `{{COMPONENT_NAME_KEBAB}}` | User input | kebab-case | `status-indicator` |
28
+ | `{{COMPONENT_NAME_PASCAL}}` | User input | PascalCase | `StatusIndicator` |
29
+ | `{{COMPONENT_NAME_UPPER}}` | User input | UPPER_SNAKE | `STATUS_INDICATOR` |
30
+ | `{{NAME}}` | Alias of `{{COMPONENT_NAME_KEBAB}}` | kebab-case | `status-indicator` |
31
+ | `{{PROJECT_NAME}}` | Nx project name | as-is | `lib.devkit.sample-remote-entry` |
32
+ | `{{MODULE_NAME}}` | Project context | as-is | `hello` |
33
+ | `{{PROPERTY_NAME}}` | Runtime @Input | camelCase | `visible` |
34
+ | `{{PROPERTY_TYPE}}` | Infer from default | TS type | `boolean` |
35
+ | `{{DEFAULT_VALUE}}` | Sensible default | as-is | `true` |
36
+
37
+ **Auto-Generation:**
38
+ ```
39
+ User: "Create StatusIndicator component"
40
+ → SESSION.component_name_kebab = "status-indicator"
41
+ → SESSION.component_name_pascal = "StatusIndicator"
42
+ → SESSION.component_name_upper = "STATUS_INDICATOR"
43
+ ```
44
+
45
+ ---
46
+
47
+ ## 🔄 Session State Machine
48
+
49
+ **Track state. Update after each action.**
50
+
51
+ ```yaml
52
+ SESSION_STATE:
53
+ phase: null # [config|generate|validate|complete]
54
+ prefix: null # From angular.json
55
+ component_name: null # User input (all forms)
56
+ scope: null # [runtime-only|runtime+designer]
57
+ files: [] # Generated files
58
+ validated: false
59
+ score: 0 # Confidence 0-100
60
+
61
+ TRANSITIONS:
62
+ null → config: Read angular.json, ask questions, set vars
63
+ config → generate: Create files, replace placeholders
64
+ generate → validate: Run lint/tests, check registration
65
+ validate → complete: Present to user
66
+ ```
67
+
68
+ ---
69
+
70
+ ## 🚨 Pre-Generation Checklist
71
+
72
+ **EXECUTE IN ORDER. DO NOT SKIP.**
73
+
74
+ ### ✅ Step 1: Determine Scope [BLOCKING]
75
+ **ORDER: 1/3 - Affects which guides to use**
76
+
77
+ ```typescript
78
+ // ASK if unclear:
79
+ "Should this component appear in Interface Designer toolbar? [Y/n]"
80
+
81
+ // STORE:
82
+ if (answer === "Y") {
83
+ SESSION.scope = "runtime+designer";
84
+ // MUST also read: REMOTE_COMPONENT_DESIGN_TIME_AI_GUIDE.md
85
+
86
+ // CRITICAL: Design-time dependency check
87
+ const packageJson = readJson('package.json');
88
+ const hasInterfaceDesignerDep = Boolean(
89
+ packageJson?.dependencies?.['@creatio/interface-designer'] ||
90
+ packageJson?.devDependencies?.['@creatio/interface-designer']
91
+ );
92
+
93
+ if (!hasInterfaceDesignerDep) {
94
+ INFORM_USER:
95
+ "Right panel (properties panel) requires @creatio/interface-designer, but it is missing in package.json.";
96
+ ASK_USER:
97
+ "Dependency @creatio/interface-designer is missing. Do you want me to add it to package.json now? [Y/n]";
98
+ RULE:
99
+ "NEVER modify package.json or run npm/yarn/pnpm install for @creatio/interface-designer without explicit user confirmation in the current turn.";
100
+ PROPOSE_INSTALL:
101
+ "Install it first? Example: npm i @creatio/interface-designer";
102
+ WAIT_FOR_CONFIRMATION_BEFORE_GENERATING_PANEL();
103
+
104
+ if (userAnswer !== "Y") {
105
+ SESSION.scope = "runtime-only";
106
+ RULE:
107
+ "If user declined dependency installation, DO NOT generate design-time files/properties panel even if panel requirements are present in task description.";
108
+ INFORM_USER:
109
+ "Proceeding with runtime-only component because @creatio/interface-designer is not available and installation was declined.";
110
+ }
111
+ }
112
+ } else {
113
+ SESSION.scope = "runtime-only";
114
+ // This guide only
115
+ }
116
+ ```
117
+
118
+ ---
119
+
120
+ ### ✅ Step 2: Extract Prefix [BLOCKING]
121
+ **ORDER: 2/3 - Must complete before generation**
122
+
123
+ ```bash
124
+ # ACTION:
125
+ rg -n "\"prefix\"" angular.json
126
+ # OR read file directly with PowerShell
127
+
128
+ # STORE:
129
+ SESSION.prefix = <result>
130
+
131
+ # VALIDATE:
132
+ if (SESSION.prefix === null) { SESSION.prefix = "usr"; }
133
+ if (SESSION.prefix === "crt") { → See ESCAPE HATCH #2 }
134
+
135
+ # VERIFY:
136
+ assert(SESSION.prefix !== null && SESSION.prefix !== "crt")
137
+ ```
138
+
139
+ **Edge case:** Multiple projects? → ESCAPE HATCH #1
140
+
141
+ ---
142
+
143
+ ### ✅ Step 3: Get Component Name [BLOCKING]
144
+ **ORDER: 3/3 - Required for placeholders**
145
+
146
+ ```typescript
147
+ // ACTION: Extract from user request
148
+ const userInput = "StatusIndicator"; // or "status indicator" or "status-indicator"
149
+
150
+ // TRANSFORM:
151
+ SESSION.component_name_kebab = toKebab(userInput); // "status-indicator"
152
+ SESSION.component_name_pascal = toPascal(userInput); // "StatusIndicator"
153
+ SESSION.component_name_upper = toUpperSnake(userInput); // "STATUS_INDICATOR"
154
+
155
+ // VERIFY:
156
+ assert(all transformations !== null)
157
+ ```
158
+
159
+ ---
160
+
161
+ **TRANSITION:**
162
+ ```typescript
163
+ if (Steps 1-3 complete) {
164
+ SESSION_STATE.phase = 'generate';
165
+ PROCEED_TO_TEMPLATES();
166
+ }
167
+ ```
168
+
169
+ ---
170
+
171
+ ## 🚪 Escape Hatches (Edge Cases)
172
+
173
+ ### ESCAPE HATCH #1: Multiple Projects in Monorepo
174
+ **DETECTION:** `(rg -n "\"prefix\"" angular.json | Measure-Object).Count > 1`
175
+
176
+ **SOLUTION:**
177
+ ```typescript
178
+ const prefixes = extractAllPrefixes(angular_json); // ["usr", "admin", "public"]
179
+
180
+ ASK_USER: `Found ${prefixes.length} projects with prefixes: ${prefixes.join(', ')}. Which project? [${prefixes[0]}]`
181
+
182
+ WAIT_FOR_ANSWER;
183
+
184
+ SESSION.prefix = USER_ANSWER || prefixes[0];
185
+ ```
186
+
187
+ ---
188
+
189
+ ### ESCAPE HATCH #2: User is Creatio Internal (crt prefix)
190
+ **DETECTION:** `SESSION.prefix === "crt"`
191
+
192
+ **SOLUTION:**
193
+ ```typescript
194
+ ASK_USER: "⚠️ 'crt' prefix is for Creatio internal only. Are you internal dev? [Y/n]"
195
+
196
+ if (answer === "Y") {
197
+ ALLOW_CRT_PREFIX();
198
+ WARN: "Using 'crt' - won't work in customer projects";
199
+ } else {
200
+ SESSION.prefix = "usr";
201
+ INFORM: "Changed to 'usr' for external compatibility";
202
+ }
203
+ ```
204
+
205
+ ---
206
+
207
+ ### ESCAPE HATCH #3: Component Exists
208
+ **DETECTION:** File exists at `src/app/view-elements/{{NAME}}/{{NAME}}.component.ts`
209
+
210
+ **SOLUTION:**
211
+ ```typescript
212
+ ASK_USER: "Component '{{NAME}}' exists. Choose action:"
213
+ OPTIONS:
214
+ 1. "Overwrite (⚠️ loses changes)"
215
+ 2. "Rename to '{{NAME}}-v2'"
216
+ 3. "Cancel"
217
+
218
+ EXECUTE_BASED_ON_CHOICE();
219
+ ```
220
+
221
+ ---
222
+
223
+ ### ESCAPE HATCH #4: No angular.json Found
224
+ **DETECTION:** `!fileExists('angular.json')`
225
+
226
+ **SOLUTION:**
227
+ ```typescript
228
+ SEARCH: Find angular.json up to 3 parent directories
229
+
230
+ if (FOUND) {
231
+ USE_THAT_PATH();
232
+ } else {
233
+ // Auto-detect workspace metadata first. Ask only if ambiguous.
234
+ SEARCH_FOR: 'workspace.json' or 'nx.json'
235
+ if (FOUND_WORKSPACE_METADATA) {
236
+ WARN: "angular.json not found. Using workspace metadata and fallback prefix 'usr' if needed";
237
+ SESSION.prefix = SESSION.prefix || "usr";
238
+ } else {
239
+ ASK_IF_AMBIGUOUS: "No workspace config found. Confirm fallback prefix 'usr'? [Y/n]"
240
+ SESSION.prefix = "usr";
241
+ }
242
+ }
243
+ ```
244
+
245
+ ---
246
+
247
+ ## 🧪 Dry-Run Mode
248
+
249
+ **EXECUTE before actual generation. Show user the plan.**
250
+
251
+ ```bash
252
+ # DRY RUN REPORT
253
+ ==================================================
254
+ Component: {{PREFIX}}-{{COMPONENT_NAME_KEBAB}}
255
+ Prefix: ${SESSION.prefix}
256
+ Scope: ${SESSION.scope}
257
+
258
+ Files to create:
259
+ ✓ src/app/view-elements/${NAME}/${NAME}.component.ts
260
+ ✓ src/app/view-elements/${NAME}/${NAME}.component.html
261
+ ✓ src/app/view-elements/${NAME}/${NAME}.component.scss
262
+ ✓ src/app/view-elements/${NAME}/${NAME}.component.spec.ts
263
+ ${SESSION.scope === 'runtime+designer' ? '✓ Design-time files' : ''}
264
+
265
+ Files to modify:
266
+ ✓ src/app/${MODULE}.module.ts (add registration)
267
+
268
+ Conflicts: ${CHECK_FOR_CONFLICTS()}
269
+
270
+ Ready to generate: ${CONFLICTS.length === 0 ? 'YES' : 'NO - resolve conflicts first'}
271
+ ==================================================
272
+
273
+ Proceed with generation? [Y/n]
274
+ ```
275
+
276
+ **If user confirms → proceed. If not → abort gracefully.**
277
+
278
+ ---
279
+
280
+ ## 📊 Confidence Self-Assessment
281
+
282
+ **CALCULATE before presenting code. Minimum 90/100 to proceed.**
283
+
284
+ **🚨 MANDATORY: Tests are BLOCKING requirement - cannot proceed without passing tests**
285
+
286
+ ```typescript
287
+ let CONFIDENCE = 0;
288
+
289
+ // Prefix extracted correctly? (+20)
290
+ if (SESSION.prefix !== null && SESSION.prefix !== 'crt') { CONFIDENCE += 20; }
291
+
292
+ // All placeholders replaced? (+20)
293
+ const unreplacedCount = countPlaceholders(generatedCode);
294
+ if (unreplacedCount === 0) { CONFIDENCE += 20; }
295
+
296
+ // Lint passed? (+20)
297
+ const lintResult = runSync('npm run lint -- --fix');
298
+ if (lintResult.exitCode === 0) { CONFIDENCE += 20; }
299
+
300
+ // 🚨 MANDATORY: Tests passed? (+20) - BLOCKING
301
+ const testResult = runSync('npm test');
302
+ const testFileExists = fileExists(`src/app/view-elements/${NAME}/${NAME}.component.spec.ts`);
303
+ if (testResult.exitCode === 0 && testFileExists) {
304
+ CONFIDENCE += 20;
305
+ } else {
306
+ ERROR: "❌ BLOCKING: Tests must be generated and pass before presenting code";
307
+ GENERATE_TESTS_IF_MISSING();
308
+ FIX_FAILING_TESTS();
309
+ RETRY();
310
+ }
311
+
312
+ // 🚨 MANDATORY: WCAG conformance audit against WCAG_ACCESSIBILITY_AI_GUIDE.md - BLOCKING
313
+ const wcagAuditResult = runWcagCodeAudit(generatedCode, 'WCAG_ACCESSIBILITY_AI_GUIDE.md');
314
+ const wcagPassed = wcagAuditResult.critical.length === 0 && wcagAuditResult.major.length === 0;
315
+ if (!wcagPassed) {
316
+ ERROR: `❌ BLOCKING: WCAG audit failed (critical: ${wcagAuditResult.critical.length}, major: ${wcagAuditResult.major.length})`;
317
+ FIX_WCAG_VIOLATIONS(wcagAuditResult);
318
+ RETRY();
319
+ }
320
+
321
+ // Custom element registration found? (+10)
322
+ const hasRegistration = /customElements\.define/.test(moduleCode);
323
+ if (hasRegistration) { CONFIDENCE += 10; }
324
+
325
+ // Decorators paired correctly? (+10)
326
+ const inputsMatch = countDecorators('@Input') === countDecorators('@CrtInput');
327
+ const outputsMatch = countDecorators('@Output') === countDecorators('@CrtOutput');
328
+ if (inputsMatch && outputsMatch) { CONFIDENCE += 10; }
329
+
330
+ SESSION_STATE.score = CONFIDENCE;
331
+
332
+ // DECISION:
333
+ if (CONFIDENCE >= 90) {
334
+ PRESENT_TO_USER();
335
+ } else if (CONFIDENCE >= 70) {
336
+ WARN: "⚠️ Medium confidence. Review before use.";
337
+ PRESENT_WITH_WARNING();
338
+ } else {
339
+ ERROR: "❌ Low confidence. Fixing issues...";
340
+ AUTO_FIX_AND_RETRY();
341
+ }
342
+ ```
343
+
344
+ ### WCAG Generation Checklist (MANDATORY)
345
+
346
+ **Apply these requirements DURING code generation, NOT after:**
347
+
348
+ **🚨 CRITICAL (Blocking) — Must include in EVERY component:**
349
+ ```yaml
350
+ ✅ Semantic HTML elements:
351
+ - Use <button> for clickable actions, NOT <div> with click handler
352
+ - Use <input>, <select>, <textarea> for form controls
353
+ - Use <label> for input labels with [for] or wrapping
354
+
355
+ ✅ Accessible names for ALL interactive elements:
356
+ - aria-label="descriptive text" OR visible text content
357
+ - NEVER leave buttons/inputs without accessible name
358
+
359
+ ✅ Keyboard support:
360
+ - @HostListener('keydown') for Enter/Space on custom interactive elements
361
+ - Proper tabindex management (0 for focusable, -1 for programmatic)
362
+ - Focus trap in modals (if applicable)
363
+
364
+ ✅ Form label association:
365
+ - <label [for]="uniqueInputId">Label text</label>
366
+ - OR <label><input />Label text</label>
367
+ - Generated unique IDs for inputs
368
+
369
+ ✅ ARIA state synchronization:
370
+ - [attr.aria-disabled]="disabled" synced with [disabled]
371
+ - [attr.aria-checked]="checked" for checkboxes/radio
372
+ - [attr.aria-expanded]="isOpen" for collapsibles
373
+ ```
374
+
375
+ **⚠️ IMPORTANT (Strongly recommended):**
376
+ ```yaml
377
+ ✅ Focus visibility:
378
+ - CSS :focus-visible styles
379
+ - Outline never set to 'none' without alternative
380
+
381
+ ✅ Color not sole indicator:
382
+ - Error states: use icon + color + text
383
+ - Status: use icon/text, not color only
384
+
385
+ ✅ Dynamic content announcements:
386
+ - aria-live="polite" for status messages
387
+ - aria-live="assertive" for errors
388
+ ```
389
+
390
+ **Self-check before presenting code:**
391
+ ```typescript
392
+ // AI internal validation:
393
+ const wcagChecks = {
394
+ hasSemanticHTML: code.includes('<button>') || code.includes('<input>'),
395
+ hasAccessibleNames: code.includes('aria-label') || hasVisibleText,
396
+ hasKeyboardSupport: code.includes('@HostListener(\'keydown\')'),
397
+ hasLabelAssociation: code.includes('[for]=') || code.includes('<label>'),
398
+ hasAriaSync: code.includes('[attr.aria-') && code.includes(']="'),
399
+ };
400
+
401
+ const allCriticalPassed = Object.values(wcagChecks).every(v => v);
402
+ if (!allCriticalPassed) {
403
+ REGENERATE_WITH_FIXES(); // Do NOT present to user
404
+ }
405
+ ```
406
+
407
+ **OUTPUT FORMAT:**
408
+ ```
409
+ 🎯 Generation Confidence: ${CONFIDENCE}/100
410
+
411
+ ${CONFIDENCE >= 90 ? '✅' : '⚠️'} Checks:
412
+ ${SESSION.prefix ? '✅' : '❌'} Prefix extracted: ${SESSION.prefix}
413
+ ${unreplacedCount === 0 ? '✅' : '❌'} Placeholders replaced: ${countTotal - unreplacedCount}/${countTotal}
414
+ ${lintPassed ? '✅' : '❌'} Lint passed
415
+ ${testFileExists ? '✅' : '❌'} Test file generated: ${testFileExists ? 'YES' : 'MISSING (BLOCKING)'}
416
+ ${testsPassed ? '✅' : '❌'} Tests passed: ${passedTests}/${totalTests} ${!testsPassed ? '(BLOCKING)' : ''}
417
+ ${wcagPassed ? '✅' : '❌'} WCAG audit (WCAG_ACCESSIBILITY_AI_GUIDE.md): ${wcagPassed ? 'Passed' : `Failed (critical: ${wcagAuditResult.critical.length}, major: ${wcagAuditResult.major.length})`}
418
+ ${hasRegistration ? '✅' : '❌'} Custom element registration: ${hasRegistration ? 'Found' : 'MISSING'}
419
+ ${decoratorsPaired ? '✅' : '❌'} Decorators paired correctly
420
+
421
+ ${CONFIDENCE >= 90 ? 'Ready to use ✅' : 'Review recommended ⚠️'}
422
+ ${!testFileExists || !testsPassed ? '🚨 BLOCKING: Must fix tests before proceeding' : ''}
423
+ ${!wcagPassed ? '🚨 BLOCKING: Must fix WCAG violations before proceeding' : ''}
424
+ ```
425
+
426
+ ---
427
+
428
+ ## 🔧 Component Templates & Real-World Examples
429
+
430
+ ### 📚 Template Categories
431
+
432
+ Components can be categorized by complexity:
433
+ 1. **Simple Display Components** - Display data with minimal interaction
434
+ 2. **Input Components** - Handle user input and emit changes
435
+ 3. **Data-Bound Components** - Connect to data sources
436
+
437
+ ---
438
+
439
+ ## 🎨 Component Icon Requirements
440
+
441
+ ```yaml
442
+ ✅ MANDATORY: Store icon SVG as a SEPARATE FILE (icon.svg)
443
+ ```
444
+
445
+ **Detailed specifications:** `ICON_REQUIREMENTS_AI_GUIDE.md`
446
+
447
+ ---
448
+
449
+ ## 📋 EXAMPLE 1: Simple Input Component with Two-Way Binding
450
+
451
+ **Use case:** Text input field with label and value change event
452
+
453
+ ```typescript
454
+ // FILE: src/lib/{{COMPONENT_NAME_KEBAB}}/{{COMPONENT_NAME_KEBAB}}.component.ts
455
+
456
+ import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output, ViewEncapsulation } from '@angular/core';
457
+ import { CrtInput, CrtInterfaceDesignerItem, CrtOutput, CrtViewElement } from '@creatio-devkit/common';
458
+
459
+ const ICON_SVG = '<svg>...</svg>'; // ⚠️ Create icon.svg file first, then inline here
460
+
461
+ @CrtInterfaceDesignerItem({
462
+ toolbarConfig: {
463
+ caption: '{{COMPONENT_NAME_PASCAL}}',
464
+ icon: ICON_SVG,
465
+ },
466
+ propertiesPanel: '{{PREFIX}}.{{COMPONENT_NAME_PASCAL}}Panel',
467
+ })
468
+ @CrtViewElement({
469
+ selector: '{{PREFIX}}-{{COMPONENT_NAME_KEBAB}}',
470
+ type: '{{PREFIX}}.{{COMPONENT_NAME_PASCAL}}',
471
+ })
472
+ @Component({
473
+ selector: '{{PREFIX}}-{{COMPONENT_NAME_KEBAB}}',
474
+ templateUrl: './{{COMPONENT_NAME_KEBAB}}.component.html',
475
+ changeDetection: ChangeDetectionStrategy.OnPush,
476
+ encapsulation: ViewEncapsulation.ShadowDom,
477
+ })
478
+ export class {{COMPONENT_NAME_PASCAL}}Component {
479
+ @Input()
480
+ @CrtInput()
481
+ public label = '';
482
+
483
+ @Input()
484
+ @CrtInput()
485
+ public value = '';
486
+
487
+ @Output()
488
+ @CrtOutput()
489
+ public readonly valueChange = new EventEmitter<string>();
490
+
491
+ protected onInput(event: Event): void {
492
+ const value = (event.target as HTMLInputElement).value;
493
+ this.valueChange.emit(value);
494
+ this.value = value;
495
+ }
496
+ }
497
+ ```
498
+
499
+ **HTML Template:**
500
+ ```html
501
+ <!-- FILE: src/lib/{{COMPONENT_NAME_KEBAB}}/{{COMPONENT_NAME_KEBAB}}.component.html -->
502
+ <label>
503
+ {{ label }}:
504
+ <input type="text" [value]="value" (input)="onInput($event)" />
505
+ </label>
506
+ ```
507
+
508
+ **Key patterns:**
509
+ - ✅ `@Input() + @CrtInput()` paired decorators for properties
510
+ - ✅ `@Output() + @CrtOutput()` paired decorators for events
511
+ - ✅ `ViewEncapsulation.ShadowDom` for runtime isolation
512
+ - ✅ `ChangeDetectionStrategy.OnPush` for performance
513
+ - ✅ Two-way binding pattern with `valueChange` event
514
+
515
+ ---
516
+
517
+ ## 📋 EXAMPLE 2: Display Component with Multiple Visual Properties
518
+
519
+ **Use case:** Label/text display with styling options and click event
520
+
521
+ ```typescript
522
+ // FILE: src/lib/{{COMPONENT_NAME_KEBAB}}/{{COMPONENT_NAME_KEBAB}}.component.ts
523
+
524
+ import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output, ViewEncapsulation } from '@angular/core';
525
+ import { CrtInput, CrtInterfaceDesignerItem, CrtOutput, CrtViewElement } from '@creatio-devkit/common';
526
+
527
+ const DEFAULT_TEXT = 'Default Label';
528
+ const ICON_SVG = '<svg>...</svg>'; // ⚠️ Create icon.svg file first, then inline here
529
+
530
+ @CrtInterfaceDesignerItem({
531
+ toolbarConfig: {
532
+ caption: 'Custom Label',
533
+ icon: ICON_SVG,
534
+ },
535
+ propertiesPanel: '{{PREFIX}}.{{COMPONENT_NAME_PASCAL}}Panel',
536
+ })
537
+ @CrtViewElement({
538
+ selector: '{{PREFIX}}-{{COMPONENT_NAME_KEBAB}}',
539
+ type: '{{PREFIX}}.{{COMPONENT_NAME_PASCAL}}',
540
+ })
541
+ @Component({
542
+ selector: '{{PREFIX}}-{{COMPONENT_NAME_KEBAB}}',
543
+ templateUrl: './{{COMPONENT_NAME_KEBAB}}.component.html',
544
+ styleUrls: ['./{{COMPONENT_NAME_KEBAB}}.component.scss'],
545
+ changeDetection: ChangeDetectionStrategy.OnPush,
546
+ encapsulation: ViewEncapsulation.ShadowDom,
547
+ })
548
+ export class {{COMPONENT_NAME_PASCAL}}Component {
549
+ @Input()
550
+ @CrtInput()
551
+ public visible = true;
552
+
553
+ @Input({ transform: (value: string | null | undefined) => value?.trim() || DEFAULT_TEXT })
554
+ @CrtInput()
555
+ public text: string = DEFAULT_TEXT;
556
+
557
+ @Input()
558
+ @CrtInput()
559
+ public color = 'black';
560
+
561
+ @Input()
562
+ @CrtInput()
563
+ public description: string;
564
+
565
+ @Output()
566
+ @CrtOutput()
567
+ public clicked = new EventEmitter<void>();
568
+
569
+ public onLabelClick(): void {
570
+ this.clicked.emit();
571
+ }
572
+ }
573
+ ```
574
+
575
+ **HTML Template:**
576
+ ```html
577
+ <!-- FILE: src/lib/{{COMPONENT_NAME_KEBAB}}/{{COMPONENT_NAME_KEBAB}}.component.html -->
578
+ @if (visible) {
579
+ <div class="custom-label" data-testid="custom-label">
580
+ @if (description) {
581
+ <div class="custom-label__description">{{ description }}</div>
582
+ }
583
+ <span class="custom-label__text" [style.color]="color">{{ text }}</span>
584
+ <button type="button" (click)="onLabelClick()">Action</button>
585
+ </div>
586
+ }
587
+ ```
588
+
589
+ **Key patterns:**
590
+ - ✅ Input transformers for data sanitization: `@Input({ transform: ... })`
591
+ - ✅ Conditional rendering with `@if` control flow
592
+ - ✅ Multiple styled properties (color, text, visibility)
593
+ - ✅ BEM-style CSS classes for styling
594
+ - ✅ Default value constants for consistency
595
+
596
+ ---
597
+
598
+ ## 🔄 Two-Way Data Binding for Data Source Integration
599
+
600
+ **CRITICAL REQUIREMENT:** Components with user-editable @Input properties MUST implement two-way data binding.
601
+
602
+ ### 📋 Core Requirements
603
+
604
+ **1. When Two-Way Binding is REQUIRED:**
605
+ - Component allows user to modify an @Input property through UI interaction
606
+ - Property should sync with Creatio Data Source
607
+
608
+ **2. When Two-Way Binding is NOT needed:**
609
+ - Component is display-only (no user input)
610
+ - Property is configuration-only (not bound to Data Source)
611
+
612
+ ### ✅ Mandatory Pattern
613
+
614
+ For EACH user-editable @Input property:
615
+
616
+ **A. Structure:**
617
+ ```typescript
618
+ // 1. Private field for internal state
619
+ private _propertyName: Type = defaultValue;
620
+
621
+ // 2. Public @Input for external binding
622
+ @Input()
623
+ @CrtInput()
624
+ public propertyName: Type = defaultValue;
625
+
626
+ // 3. @Output event with "Change" suffix
627
+ @Output()
628
+ @CrtOutput()
629
+ public readonly propertyNameChange = new EventEmitter<Type>();
630
+ ```
631
+
632
+ **B. Lifecycle:**
633
+ ```typescript
634
+ // 4. Implement OnChanges interface
635
+ export class MyComponent implements OnChanges {
636
+
637
+ // 5. Handle external changes (Data Source → Component)
638
+ ngOnChanges(changes: SimpleChanges): void {
639
+ if (changes['propertyName']) {
640
+ this._propertyName = this._normalize(changes['propertyName'].currentValue);
641
+ this._cdr.markForCheck();
642
+ }
643
+ }
644
+
645
+ // 6. Handle internal changes (Component → Data Source)
646
+ protected onPropertyChange(newValue: Type): void {
647
+ this._propertyName = this._normalize(newValue);
648
+ this.propertyName = this._propertyName; // Update @Input
649
+ this.propertyNameChange.emit(this._propertyName); // Emit event
650
+ this._cdr.markForCheck();
651
+ }
652
+ }
653
+ ```
654
+
655
+ ### 🚨 Critical Rules
656
+
657
+ **1. ALWAYS update THREE things on internal change:**
658
+ - `this._propertyName` (private state)
659
+ - `this.propertyName` (@Input property)
660
+ - `this.propertyNameChange.emit()` (event)
661
+
662
+ **2. For multiple editable properties:**
663
+ - Create SEPARATE @Output for EACH property
664
+ - Each property follows the same pattern independently
665
+
666
+ **3. DON'T use @Input setters:**
667
+ - Use `OnChanges` instead
668
+ - Setters are unreliable with Angular Custom Elements
669
+
670
+ **4. DON'T use complex objects as @Input:**
671
+ - Use flat primitive properties
672
+ - Creatio Data Source works with primitive types
673
+
674
+ ### ⚠️ Consequences of Missing Two-Way Binding
675
+
676
+ Without proper implementation:
677
+ - "Save" button won't appear when user modifies value
678
+ - Changes won't propagate to other bound UI fields
679
+ - Data won't persist to Data Source
680
+ - ViewModel won't detect modifications
681
+
682
+ ---
683
+
684
+ ## 📋 Component Registration in Module
685
+
686
+ **CRITICAL:** Components MUST be registered as custom elements.
687
+
688
+ ```typescript
689
+ // FILE: src/lib/{{MODULE_NAME}}.module.ts
690
+
691
+ import { CommonModule } from '@angular/common';
692
+ import { CUSTOM_ELEMENTS_SCHEMA, Injector, NgModule } from '@angular/core';
693
+ import { createCustomElement } from '@angular/elements';
694
+ import { bootstrapCrtModule, CrtModule, Type } from '@creatio-devkit/common';
695
+
696
+ import { {{COMPONENT_NAME_PASCAL}}Component } from './{{COMPONENT_NAME_KEBAB}}/{{COMPONENT_NAME_KEBAB}}.component';
697
+
698
+ @CrtModule({
699
+ viewElements: [{{COMPONENT_NAME_PASCAL}}Component],
700
+ })
701
+ @NgModule({
702
+ declarations: [{{COMPONENT_NAME_PASCAL}}Component],
703
+ imports: [CommonModule],
704
+ schemas: [CUSTOM_ELEMENTS_SCHEMA],
705
+ })
706
+ export class {{MODULE_NAME_PASCAL}}Module {
707
+ constructor(private injector: Injector) {
708
+ // CRITICAL: Registration MUST happen BEFORE bootstrapCrtModule
709
+ this.define('{{PREFIX}}-{{COMPONENT_NAME_KEBAB}}', {{COMPONENT_NAME_PASCAL}}Component);
710
+ }
711
+
712
+ private define(selector: string, component: Type): void {
713
+ if (!customElements.get(selector)) {
714
+ customElements.define(selector, createCustomElement(component, { injector: this.injector }));
715
+ }
716
+ }
717
+ }
718
+
719
+ // Bootstrap call
720
+ bootstrapCrtModule({{MODULE_NAME_PASCAL}}Module);
721
+ ```
722
+
723
+ **Key patterns:**
724
+ - ✅ `@CrtModule({ viewElements: [...] })` decorator
725
+ - ✅ `CUSTOM_ELEMENTS_SCHEMA` in schemas array
726
+ - ✅ Custom element registration in constructor
727
+ - ✅ Guard against duplicate registration with `customElements.get()`
728
+ - ✅ `bootstrapCrtModule()` call AFTER module definition
729
+
730
+ ---
731
+
732
+ ## 📋 Generation Checklist (Before Presenting)
733
+
734
+ **FINAL VALIDATION:**
735
+ **Command mode:** Use `npm` commands for standalone projects. Use `npx nx ...` only in Nx monorepo workspaces.
736
+
737
+ **🚨 MANDATORY: TEST GENERATION IS REQUIRED**
738
+ - Tests MUST be generated for ALL new components
739
+ - Tests MUST pass before code is presented to the user
740
+ - Tests MUST cover component initialization, inputs, outputs, and shadow DOM rendering
741
+ - If tests fail, FIX issues before presenting code
742
+
743
+ ```markdown
744
+ - [ ] SESSION.prefix extracted and stored
745
+ - [ ] All {{PLACEHOLDERS}} replaced
746
+ - [ ] Files generated: component.ts, .html, .scss, .spec.ts
747
+ - [ ] Module updated with customElements.define()
748
+ - [ ] Registration BEFORE bootstrapCrtModule()
749
+ - [ ] ViewEncapsulation.ShadowDom (NOT Emulated)
750
+ - [ ] Every @Input has @CrtInput
751
+ - [ ] Every @Output has @CrtOutput
752
+ - [ ] Tests use .shadowRoot for queries
753
+ - [ ] **MANDATORY: .spec.ts test file generated with comprehensive tests**
754
+ - [ ] **MANDATORY: All tests pass (npm test) before presenting code**
755
+ - [ ] **MANDATORY: Run WCAG code audit against WCAG_ACCESSIBILITY_AI_GUIDE.md**
756
+ - [ ] **MANDATORY: WCAG audit has 0 critical and 0 major violations (BLOCKING)**
757
+ - [ ] **MANDATORY: WCAG accessibility requirements met (see WCAG_ACCESSIBILITY_AI_GUIDE.md)**
758
+ - [ ] Accessibility: Semantic HTML used (button, input, label, etc.)
759
+ - [ ] Accessibility: All interactive elements have accessible names
760
+ - [ ] Accessibility: Keyboard support (Tab, Enter, Space, Escape)
761
+ - [ ] Accessibility: Focus management implemented correctly
762
+ - [ ] Accessibility: ARIA attributes for dynamic states
763
+ - [ ] Accessibility: Tests added to .spec.ts
764
+ - [ ] npm run build passed (component builds successfully)
765
+ - [ ] npm run lint -- --fix passed
766
+ - [ ] Confidence score >= 90
767
+ ```
768
+
769
+ **If ALL checked → PRESENT. If any unchecked → FIX first.**
770
+
771
+ ---
772
+
773
+ ## 🧪 Test Templates (MANDATORY)
774
+
775
+ **🚨 CRITICAL: You MUST generate .spec.ts file with comprehensive tests for EVERY component**
776
+
777
+ ### Template 1: Simple Component with @Input/@Output
778
+
779
+ Use this template for components with basic inputs, outputs, and simple rendering logic.
780
+
781
+ ```typescript
782
+ import { Component, ViewChild } from '@angular/core';
783
+ import { ComponentFixture, TestBed } from '@angular/core/testing';
784
+
785
+ import { Crt{{ComponentName}}Component } from './{{component-name}}.component';
786
+
787
+ // Test host wrapper to test component as it will be used
788
+ @Component({
789
+ template: `
790
+ <crt-{{component-name}}
791
+ [propertyOne]="propertyOne"
792
+ [propertyTwo]="propertyTwo"
793
+ (eventName)="onEventName($event)"
794
+ ></crt-{{component-name}}>
795
+ `,
796
+ })
797
+ class TestHostComponent {
798
+ public propertyOne = /* default value */;
799
+ public propertyTwo = /* default value */;
800
+ public readonly eventNameSpy = jest.fn();
801
+
802
+ @ViewChild(Crt{{ComponentName}}Component)
803
+ public readonly component: Crt{{ComponentName}}Component;
804
+
805
+ public onEventName(value: unknown): void {
806
+ this.eventNameSpy(value);
807
+ }
808
+ }
809
+
810
+ describe('Crt{{ComponentName}}Component', () => {
811
+ let fixture: ComponentFixture<TestHostComponent>;
812
+ let host: TestHostComponent;
813
+
814
+ function getNativeElement(): HTMLElement {
815
+ const result = fixture.nativeElement.querySelector('crt-{{component-name}}') as HTMLElement | null;
816
+ if (!result) {
817
+ throw new Error('crt-{{component-name}} element not found');
818
+ }
819
+ return result;
820
+ }
821
+
822
+ afterEach(() => {
823
+ jest.restoreAllMocks();
824
+ });
825
+
826
+ beforeEach(async () => {
827
+ await TestBed.configureTestingModule({
828
+ declarations: [Crt{{ComponentName}}Component, TestHostComponent],
829
+ }).compileComponents();
830
+
831
+ fixture = TestBed.createComponent(TestHostComponent);
832
+ host = fixture.componentInstance;
833
+ fixture.detectChanges();
834
+ });
835
+
836
+ it('should create', () => {
837
+ expect(host.component).toBeDefined();
838
+ });
839
+
840
+ // CRITICAL: Always test shadowRoot queries
841
+ describe('rendering', () => {
842
+ it('should render in shadow DOM', () => {
843
+ const element = getNativeElement();
844
+ expect(element.shadowRoot).not.toBeNull();
845
+ });
846
+
847
+ it('should render expected elements', () => {
848
+ const element = getNativeElement();
849
+ const targetElement = element.shadowRoot?.querySelector('[data-testid="your-element"]');
850
+ expect(targetElement).not.toBeNull();
851
+ });
852
+ });
853
+
854
+ // Test each @Input property
855
+ describe('propertyOne input', () => {
856
+ it('should have default value', () => {
857
+ expect(host.component.propertyOne).toBe(/* expected default */);
858
+ });
859
+
860
+ it('should update when input changes', () => {
861
+ host.propertyOne = /* new value */;
862
+ fixture.detectChanges();
863
+
864
+ const element = getNativeElement();
865
+ const targetElement = element.shadowRoot?.querySelector('[data-testid="target"]');
866
+ expect(targetElement?.textContent).toContain(/* expected text */);
867
+ });
868
+
869
+ it('should handle edge cases', () => {
870
+ // Test: null, undefined, empty string, etc.
871
+ host.propertyOne = null;
872
+ fixture.detectChanges();
873
+ // Assert expected behavior
874
+ });
875
+ });
876
+
877
+ // Test each @Output event
878
+ describe('eventName output', () => {
879
+ it('should emit event when triggered', () => {
880
+ const element = getNativeElement();
881
+ const button = element.shadowRoot?.querySelector('button') as HTMLButtonElement | null;
882
+
883
+ button?.click();
884
+
885
+ expect(host.eventNameSpy).toHaveBeenCalledTimes(1);
886
+ expect(host.eventNameSpy).toHaveBeenCalledWith(/* expected value */);
887
+ });
888
+
889
+ it('should emit multiple times', () => {
890
+ const element = getNativeElement();
891
+ const input = element.shadowRoot?.querySelector('input') as HTMLInputElement | null;
892
+
893
+ input.value = 'First';
894
+ input.dispatchEvent(new Event('input'));
895
+
896
+ input.value = 'Second';
897
+ input.dispatchEvent(new Event('input'));
898
+
899
+ expect(host.eventNameSpy).toHaveBeenCalledTimes(2);
900
+ expect(host.eventNameSpy).toHaveBeenNthCalledWith(1, 'First');
901
+ expect(host.eventNameSpy).toHaveBeenNthCalledWith(2, 'Second');
902
+ });
903
+ });
904
+
905
+ // Test input transformers if present
906
+ describe('input transformers', () => {
907
+ it('should transform input value', () => {
908
+ host.propertyTwo = /* value that needs transformation */;
909
+ fixture.detectChanges();
910
+
911
+ expect(host.component.propertyTwo).toBe(/* transformed value */);
912
+ });
913
+ });
914
+ });
915
+ ```
916
+
917
+ ### Template 2: Component with Async Operations
918
+
919
+ Use this template for components that fetch data, call APIs, or have async lifecycle methods.
920
+
921
+ ```typescript
922
+ import { ComponentFixture, TestBed } from '@angular/core/testing';
923
+ import { of, throwError } from 'rxjs';
924
+
925
+ import { Crt{{ComponentName}}Component } from './{{component-name}}.component';
926
+ import { YourService } from './your.service';
927
+
928
+ describe('Crt{{ComponentName}}Component (Async)', () => {
929
+ let component: Crt{{ComponentName}}Component;
930
+ let fixture: ComponentFixture<Crt{{ComponentName}}Component>;
931
+ let yourServiceMock: jest.Mocked<YourService>;
932
+
933
+ beforeEach(async () => {
934
+ yourServiceMock = {
935
+ fetchData: jest.fn(),
936
+ updateData: jest.fn(),
937
+ } as unknown as jest.Mocked<YourService>;
938
+
939
+ await TestBed.configureTestingModule({
940
+ declarations: [Crt{{ComponentName}}Component],
941
+ providers: [
942
+ { provide: YourService, useValue: yourServiceMock },
943
+ ],
944
+ }).compileComponents();
945
+
946
+ fixture = TestBed.createComponent(Crt{{ComponentName}}Component);
947
+ component = fixture.componentInstance;
948
+ });
949
+
950
+ afterEach(() => {
951
+ jest.restoreAllMocks();
952
+ });
953
+
954
+ describe('async data loading', () => {
955
+ it('should load data on init', async () => {
956
+ const mockData = { id: 1, name: 'Test' };
957
+ yourServiceMock.fetchData.mockReturnValue(of(mockData));
958
+
959
+ fixture.detectChanges(); // Triggers ngOnInit
960
+ await fixture.whenStable(); // Wait for async operations
961
+
962
+ expect(yourServiceMock.fetchData).toHaveBeenCalledTimes(1);
963
+ expect(component.data).toEqual(mockData);
964
+ });
965
+
966
+ it('should handle loading state', async () => {
967
+ yourServiceMock.fetchData.mockReturnValue(of({}));
968
+
969
+ expect(component.isLoading).toBe(false);
970
+
971
+ fixture.detectChanges();
972
+ expect(component.isLoading).toBe(true); // During fetch
973
+
974
+ await fixture.whenStable();
975
+ expect(component.isLoading).toBe(false); // After fetch
976
+ });
977
+
978
+ it('should handle errors gracefully', async () => {
979
+ const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => void 0);
980
+ yourServiceMock.fetchData.mockReturnValue(
981
+ throwError(() => new Error('Network error'))
982
+ );
983
+
984
+ fixture.detectChanges();
985
+ await fixture.whenStable();
986
+
987
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
988
+ expect.stringContaining('Network error')
989
+ );
990
+ expect(component.data).toBeNull(); // Or your error state
991
+ });
992
+ });
993
+
994
+ describe('async user interactions', () => {
995
+ it('should handle async save operation', async () => {
996
+ yourServiceMock.updateData.mockReturnValue(of({ success: true }));
997
+
998
+ await component.onSave();
999
+
1000
+ expect(yourServiceMock.updateData).toHaveBeenCalledTimes(1);
1001
+ expect(component.isSaving).toBe(false);
1002
+ });
1003
+ });
1004
+ });
1005
+ ```
1006
+
1007
+ ### Template 3: Component with Content Projection (slots)
1008
+
1009
+ ```typescript
1010
+ import { Component } from '@angular/core';
1011
+ import { ComponentFixture, TestBed } from '@angular/core/testing';
1012
+
1013
+ import { Crt{{ComponentName}}Component } from './{{component-name}}.component';
1014
+
1015
+ @Component({
1016
+ template: `
1017
+ <crt-{{component-name}}>
1018
+ <div slot="header">Header Content</div>
1019
+ <div slot="content">Main Content</div>
1020
+ <div slot="footer">Footer Content</div>
1021
+ </crt-{{component-name}}>
1022
+ `,
1023
+ })
1024
+ class TestHostWithSlotsComponent {}
1025
+
1026
+ describe('Crt{{ComponentName}}Component (Slots)', () => {
1027
+ let fixture: ComponentFixture<TestHostWithSlotsComponent>;
1028
+
1029
+ beforeEach(async () => {
1030
+ await TestBed.configureTestingModule({
1031
+ declarations: [Crt{{ComponentName}}Component, TestHostWithSlotsComponent],
1032
+ }).compileComponents();
1033
+
1034
+ fixture = TestBed.createComponent(TestHostWithSlotsComponent);
1035
+ fixture.detectChanges();
1036
+ });
1037
+
1038
+ it('should project header slot content', () => {
1039
+ const element = fixture.nativeElement.querySelector('crt-{{component-name}}');
1040
+ const headerSlot = element.shadowRoot?.querySelector('slot[name="header"]') as HTMLSlotElement | null;
1041
+ const assignedNodes = headerSlot?.assignedNodes() ?? [];
1042
+
1043
+ expect(assignedNodes.length).toBeGreaterThan(0);
1044
+ expect(assignedNodes[0].textContent).toContain('Header Content');
1045
+ });
1046
+
1047
+ it('should project content slot content', () => {
1048
+ const element = fixture.nativeElement.querySelector('crt-{{component-name}}');
1049
+ const contentSlot = element.shadowRoot?.querySelector('slot[name="content"]') as HTMLSlotElement | null;
1050
+ const assignedNodes = contentSlot?.assignedNodes() ?? [];
1051
+
1052
+ expect(assignedNodes.length).toBeGreaterThan(0);
1053
+ expect(assignedNodes[0].textContent).toContain('Main Content');
1054
+ });
1055
+
1056
+ it('should render default content when slot is empty', () => {
1057
+ // Create fixture without slot content
1058
+ const emptyFixture = TestBed.createComponent(Crt{{ComponentName}}Component);
1059
+ emptyFixture.detectChanges();
1060
+
1061
+ const element = emptyFixture.nativeElement;
1062
+ const defaultContent = element.shadowRoot?.querySelector('[data-testid="default-content"]');
1063
+ expect(defaultContent).not.toBeNull();
1064
+ });
1065
+ });
1066
+ ```
1067
+
1068
+ ### 🎯 Test Coverage Requirements
1069
+
1070
+ **MANDATORY test cases for ALL components:**
1071
+
1072
+ 1. **Component Creation** ✅
1073
+ - `should create` test
1074
+
1075
+ 2. **Shadow DOM** ✅ (CRITICAL for runtime components)
1076
+ - Verify `shadowRoot` exists
1077
+ - All queries MUST use `.shadowRoot?.querySelector()`
1078
+ - Never query directly on element without shadowRoot
1079
+
1080
+ 3. **@Input Properties** ✅
1081
+ - Default values
1082
+ - Value changes reflect in template
1083
+ - Edge cases (null, undefined, empty)
1084
+ - Input transformers if present
1085
+
1086
+ 4. **@Output Events** ✅
1087
+ - Events emit with correct values
1088
+ - Multiple emissions work correctly
1089
+ - Event handlers called
1090
+
1091
+ 5. **Conditional Rendering** ✅
1092
+ - `@if` conditions work correctly
1093
+ - `@for` loops render correct number of items
1094
+ - Hidden elements not in DOM
1095
+
1096
+ 6. **Async Operations** (if component has API calls)
1097
+ - Loading states
1098
+ - Success cases
1099
+ - Error handling
1100
+ - Use `await fixture.whenStable()`
1101
+
1102
+ 7. **Slots/Content Projection** (if component has slots)
1103
+ - Slot content projected correctly
1104
+ - Default fallback content shown when slot empty
1105
+ - Use `slot.assignedNodes()`
1106
+
1107
+ ### 🚨 Common Mistakes to AVOID
1108
+
1109
+ ```typescript
1110
+ // ❌ WRONG: Querying without shadowRoot
1111
+ const button = fixture.nativeElement.querySelector('button');
1112
+
1113
+ // ✅ CORRECT: Query through shadowRoot
1114
+ const element = fixture.nativeElement.querySelector('crt-component');
1115
+ const button = element.shadowRoot?.querySelector('button');
1116
+
1117
+ // ❌ WRONG: Not waiting for async operations
1118
+ fixture.detectChanges();
1119
+ expect(component.data).toBeDefined(); // May fail!
1120
+
1121
+ // ✅ CORRECT: Wait for async
1122
+ fixture.detectChanges();
1123
+ await fixture.whenStable();
1124
+ expect(component.data).toBeDefined();
1125
+
1126
+ // ❌ WRONG: Not testing edge cases
1127
+ it('should display text', () => {
1128
+ component.text = 'Hello';
1129
+ expect(component.text).toBe('Hello');
1130
+ });
1131
+
1132
+ // ✅ CORRECT: Test edge cases
1133
+ it('should handle null text', () => {
1134
+ component.text = null;
1135
+ expect(component.text).toBe(''); // or default value
1136
+ });
1137
+
1138
+ it('should handle empty string', () => {
1139
+ component.text = '';
1140
+ expect(component.text).toBe(''); // or default value
1141
+ });
1142
+ ```
1143
+
1144
+ ### 📝 Test File Naming Convention
1145
+
1146
+ - Runtime component: `{{component-name}}.component.spec.ts`
1147
+ - Example: `custom-input.component.spec.ts`
1148
+ - Location: Same directory as component file
1149
+
1150
+ ---
1151
+
1152
+ ## 📚 Quick Reference: Common Patterns
1153
+
1154
+ ### Pattern 1: Input with Default Value
1155
+ ```typescript
1156
+ @Input()
1157
+ @CrtInput()
1158
+ public myProperty = 'default value';
1159
+ ```
1160
+
1161
+ ### Pattern 2: Input with Transformer
1162
+ ```typescript
1163
+ @Input({ transform: (v: string) => v?.trim() || 'default' })
1164
+ @CrtInput()
1165
+ public text: string = 'default';
1166
+ ```
1167
+
1168
+ ### Pattern 3: Output Event
1169
+ ```typescript
1170
+ @Output()
1171
+ @CrtOutput()
1172
+ public readonly myEvent = new EventEmitter<MyType>();
1173
+ ```
1174
+
1175
+ ### Pattern 4: Conditional Rendering (Angular 17+)
1176
+ ```typescript
1177
+ @if (condition) {
1178
+ <div>Content</div>
1179
+ }
1180
+ ```
1181
+
1182
+ ### Pattern 5: List Iteration
1183
+ ```typescript
1184
+ @for (item of items; track item.id) {
1185
+ <div>{{ item.name }}</div>
1186
+ }
1187
+ ```
1188
+
1189
+ ### Pattern 6: Inline Styles in Component
1190
+ ```typescript
1191
+ @Component({
1192
+ styles: [`
1193
+ :host {
1194
+ display: block;
1195
+ }
1196
+ .my-class {
1197
+ color: red;
1198
+ }
1199
+ `],
1200
+ })
1201
+ ```
1202
+
1203
+ ### Pattern 7: Inline Template in Component
1204
+ ```typescript
1205
+ @Component({
1206
+ template: `
1207
+ <div class="wrapper">
1208
+ <h1>{{ title }}</h1>
1209
+ </div>
1210
+ `,
1211
+ })
1212
+ ```
1213
+
1214
+ ---
1215
+