From 5a08db79def3ea98793c2be78f43c93f6b43a663 Mon Sep 17 00:00:00 2001 From: David Picksley Date: Mon, 11 May 2026 16:22:37 +0100 Subject: [PATCH 1/2] Added Generating Lightning Component Skill --- .../generating-lightning-component/SKILL.md | 421 ++++++++++++++++++ 1 file changed, 421 insertions(+) create mode 100644 skills/generating-lightning-component/SKILL.md diff --git a/skills/generating-lightning-component/SKILL.md b/skills/generating-lightning-component/SKILL.md new file mode 100644 index 0000000..b25279e --- /dev/null +++ b/skills/generating-lightning-component/SKILL.md @@ -0,0 +1,421 @@ +--- +name: generating-lightning-component +description: "Generate Salesforce Lightning Web Components (LWC) and supporting component bundle files. Use when the user asks to create, build, scaffold, generate, implement, refactor, or review an LWC, Lightning Web Component, UI component, Flow screen component LWC, Lightning App Builder component, Experience Cloud component, Agentforce-capable component, or any lwc/**/*.js, .html, .css, .js-meta.xml bundle. Also trigger for @wire, Lightning Data Service, Apex/GraphQL data access from LWC, Lightning Message Service, SLDS styling, accessibility, or Jest tests. Do NOT trigger for Apex-only implementation, Flow XML generation, Aura components, Visualforce, Lightning app metadata, or unrelated Salesforce metadata." +--- + +# Generating Lightning Components + +## Goal + +Generate production-ready Salesforce Lightning Web Components (LWC) with the correct bundle structure, metadata exposure, data access pattern, accessibility, styling, security, and test approach. + +This skill uses the **PICKLES Framework** as the architectural checklist for LWC design: + +- **P**rototype — clarify the user journey and expected UI states before writing code. +- **I**ntegrate — choose the correct data access pattern. +- **C**omposition — split the component into sensible parent/child boundaries. +- **K**inetics — define events, interactions, loading states, and state transitions. +- **L**ibraries — prefer Salesforce platform APIs, base Lightning components, and LDS before custom code. +- **E**xecution — optimise rendering, lifecycle usage, and browser performance. +- **S**ecurity — enforce CRUD/FLS, sharing, LWS-safe JavaScript, and safe error handling. + +**Attribution:** PICKLES Framework by **David Picksley**. Reference: https://www.salesforceben.com/the-ideal-framework-for-architecting-salesforce-lightning-web-components/ + +## When to Use This Skill + +Use this skill when the task involves: + +- Creating or modifying a Lightning Web Component bundle. +- Creating files under `force-app/main/default/lwc/{componentName}/`. +- Generating `.js`, `.html`, `.css`, `.js-meta.xml`, or Jest test files for an LWC. +- Exposing an LWC to Lightning App Builder, Record Pages, Home Pages, Experience Cloud, Flow screens, or Agentforce. +- Building UI that reads or writes Salesforce data. +- Using Lightning Data Service, UI API, Apex, GraphQL, Lightning Message Service, or platform events from an LWC. +- Creating accessible, SLDS-aligned, responsive component markup. +- Creating Jest tests for an LWC. + +Do not use this skill for: + +- Apex-only classes or triggers. Delegate to `generating-apex`. +- Apex test classes. Delegate to `generating-apex-test`. +- Flow XML generation. Delegate to `generating-flow`. +- Aura components or Visualforce pages. +- Lightning App metadata generation without an LWC bundle. + +## Required Inputs + +Gather or infer the following before authoring: + +- Component purpose and user outcome. +- Target surface: + - `lightning__RecordPage` + - `lightning__AppPage` + - `lightning__HomePage` + - `lightning__Tab` + - `lightning__FlowScreen` + - `lightning__ExperiencePage` + - `lightning__Agentforce` + - other supported target +- Component API name in camelCase. +- Whether the component needs a public property exposed through `.js-meta.xml`. +- Data source: + - no Salesforce data + - Lightning Data Service / UI API + - Apex controller + - GraphQL wire adapter + - Lightning Message Service + - external service through Apex +- Required UX states: + - initial + - loading + - populated + - empty + - error + - saving + - success +- Whether Jest tests are required. +- Any existing project conventions, shared components, utility modules, or styling rules. + +If the user gives a clear request, generate immediately. Do not ask unnecessary follow-up questions. Make a sensible default and document it in the report. + +## Component Bundle Deliverables + +Default bundle path: + +```text +force-app/main/default/lwc/{componentName}/ +``` + +Generate the relevant files: + +```text +{componentName}.html +{componentName}.js +{componentName}.js-meta.xml +{componentName}.css # only when styling is needed +__tests__/{componentName}.test.js # when tests are requested or expected +``` + +Optional supporting files: + +```text +{componentName}.svg +{componentName}.json +utils.js +constants.js +``` + +Do not generate unused files. Keep the bundle minimal. + +## Workflow + +All steps are sequential. Do not skip validation just because the component looks simple. + +### Phase 1 — Design with PICKLES + +1. **Prototype** + - Restate the component goal in one sentence. + - Identify the target user and the expected interaction. + - List the required UI states. + +2. **Integrate** + - Choose the smallest correct data access pattern. + - Prefer platform-native data APIs before custom Apex. + - Use Apex only when business logic, aggregation, complex SOQL, DML orchestration, callouts, or security-wrapped server behaviour is required. + +3. **Composition** + - Decide whether this should be one component or a parent/child set. + - Split child components only when they have a distinct responsibility or reuse value. + - Keep public APIs narrow and explicit. + +4. **Kinetics** + - Define the event contract before coding. + - Prefer parent-child events for local communication. + - Use Lightning Message Service only for cross-DOM or unrelated component communication. + - Include loading, disabled, empty, and error states. + +5. **Libraries** + - Prefer Lightning base components over custom HTML controls. + - Prefer Lightning Data Service/UI API for simple record operations. + - Use SLDS utility classes and styling hooks rather than hardcoded styling. + +6. **Execution** + - Avoid unnecessary work in lifecycle hooks. + - Avoid setting reactive state in `renderedCallback()` unless guarded. + - Debounce user input for search/filter behaviours. + - Avoid large DOM renders; paginate or virtualise when needed. + +7. **Security** + - Do not expose unsafe HTML. + - Do not trust client-side validation alone. + - Ensure Apex used by the component enforces sharing, CRUD/FLS, and safe error handling. + - Avoid hardcoded IDs, secrets, object assumptions, and user-specific values. + +### Phase 2 — Author + +Create the component files using these rules. + +#### JavaScript Rules + +- Use `LightningElement` from `lwc`. +- Use `@api` only for true public component properties. +- Do not mutate `@api` input values directly. +- Use private state for internal mutations. +- Use getters for derived template state. +- Use `@wire` for reactive read-only data. +- Use imperative Apex or UI API functions for explicit actions, saves, and DML. +- Store wired results if `refreshApex()` is required. +- Always handle both `data` and `error` paths. +- Normalise errors into user-safe strings. +- Avoid `console.log()` in generated production code. +- Avoid global DOM queries. Query only within `this.template`. +- Clean up timers, subscriptions, and listeners in `disconnectedCallback()`. + +#### HTML Rules + +- Use Lightning base components where available. +- Use `lwc:if`, `lwc:elseif`, and `lwc:else`; do not use legacy `if:true` / `if:false`. +- Every `for:each` item must have a stable key. Never use array index as the key. +- Include accessible labels, alternative text, assistive text, and ARIA attributes where needed. +- Do not place complex logic in the template when a getter is clearer. +- Include visible error and empty states. + +#### CSS Rules + +- Do not hardcode brand colours unless the user explicitly requests it. +- Prefer SLDS classes, design tokens, and styling hooks. +- Keep CSS scoped to the component. +- Do not use brittle selectors against Salesforce-owned DOM. +- Support responsive layout where the component can appear in narrow regions. + +#### Metadata Rules + +Every LWC bundle must include `{componentName}.js-meta.xml`. + +- Set `isExposed` based on whether the component is intended for builder/runtime placement. +- Include only the targets the user needs. +- For `lightning__RecordPage`, include supported objects when known. +- Expose configurable properties only when useful for admins/builders. +- Use a current project API version unless the repository convention says otherwise. + +Default metadata shape: + +```xml + + + 66.0 + true + Component Label + Short description of the component. + + lightning__RecordPage + + +``` + +### Phase 3 — Test + +When generating or modifying meaningful logic, create or update Jest tests. + +Test at least: + +- component renders successfully +- loading state +- populated state +- empty state +- error state +- user interaction/event dispatch +- Apex/wire/UI API success and error paths, where applicable + +Jest file location: + +```text +force-app/main/default/lwc/{componentName}/__tests__/{componentName}.test.js +``` + +Testing rules: + +- Clean up the DOM after each test. +- Mock Apex, UI API, LDS, GraphQL, and LMS boundaries. +- Await render cycles after state changes. +- Assert user-visible behaviour rather than private implementation details. +- Do not rely on Salesforce org data. + +### Phase 4 — Validate + +Before reporting completion, attempt the relevant validation commands. + +Preferred commands: + +```bash +npm test -- --runInBand {componentName}.test.js +sf project deploy start --source-dir force-app/main/default/lwc/{componentName} --dry-run +``` + +If the project has custom scripts, use the repository convention instead. + +If validation tools are unavailable, state that clearly in the report and explain what was not run. + +## Data Access Decision Matrix + +| Need | Preferred Pattern | Notes | +|---|---|---| +| Display one record | Lightning Data Service / UI API | Use `getRecord` or record form base components. | +| Simple create/edit/view form | Base record form components | Prefer `lightning-record-form`, `lightning-record-edit-form`, or `lightning-record-view-form`. | +| Reactive read-only data | `@wire` | Use LDS, UI API, GraphQL, or cacheable Apex. | +| User-triggered save/action | Imperative call | Use UI API or Apex depending on complexity. | +| Complex SOQL/business logic | Apex | Apex must enforce sharing, CRUD/FLS, and safe errors. | +| Related graph-shaped data | GraphQL wire adapter | Useful for related records and reducing over-fetching. | +| Cross-page/component communication | Lightning Message Service | Use only when parent-child events are insufficient. | +| External API | Apex callout via Named Credential | Never call external services with secrets from client JavaScript. | + +## Event Rules + +Use the smallest event scope that works. + +Preferred event: + +```javascript +this.dispatchEvent(new CustomEvent('select', { + detail: { recordId: this.recordId } +})); +``` + +Rules: + +- Event names must be lowercase and not prefixed with `on`. +- Use primitive or copied object data in `detail`. +- Avoid `bubbles: true, composed: true` unless the event must cross component boundaries. +- Document public event contracts in the component comments or final report. + +## Apex Boundary Rules + +When Apex is required: + +- Create or update the Apex via `generating-apex`. +- The Apex class must use a sharing declaration. +- Read-only methods used with `@wire` must be `@AuraEnabled(cacheable=true)`. +- Mutating methods must not be cacheable. +- Apex must enforce CRUD/FLS. +- Apex must return DTOs/wrappers when that is cleaner than exposing raw SObjects. +- Apex must throw user-safe `AuraHandledException` messages for expected UI errors. +- Apex tests are required and must be handled by `generating-apex-test`. + +## Accessibility Rules + +Hard-stop if generated markup would violate these basics: + +- Interactive elements must be keyboard accessible. +- Icon-only buttons must have alternative text or assistive text. +- Inputs must have labels. +- Loading states must be communicated. +- Error messages must be visible and associated with the relevant UI where possible. +- Modal/dialog patterns must manage focus correctly. +- Do not use colour alone to communicate meaning. + +## Security Rules + +Hard-stop if the component would require unsafe behaviour: + +- Do not use `lwc:dom="manual"` unless the user explicitly needs it and the risk is explained. +- Do not inject unsanitised HTML. +- Do not store credentials, tokens, secrets, or API keys in the component. +- Do not bypass CRUD/FLS by moving sensitive decisions into client-side JavaScript. +- Do not hardcode IDs. +- Do not expose sensitive implementation errors to users. +- Do not use unsupported browser globals or libraries that conflict with Lightning Web Security. + +## Naming Conventions + +| Item | Convention | Example | +|---|---|---| +| Component folder | camelCase | `accountSummaryCard` | +| JavaScript class | PascalCase | `AccountSummaryCard` | +| Public property | camelCase | `recordId` | +| HTML attribute | kebab-case | `record-id` | +| Event name | lowercase | `recordselect` | +| CSS class | kebab-case | `summary-card` | +| Jest file | `{component}.test.js` | `accountSummaryCard.test.js` | + +## Output Expectations + +When finished, report in this order: + +```text +LWC work: +Component: +Files: +Pattern: +PICKLES: +Targets: +Data: +Events: +Accessibility: +Security: +Testing: +Validation: +Next step: +``` + +The report must be specific. Do not say "tests pass" unless tests were actually run. + +## Cross-Skill Integration + +| Need | Delegate To | Reason | +|---|---|---| +| Apex controller/service | `generating-apex` | Server-side logic and security. | +| Apex tests | `generating-apex-test` | Required Apex coverage and test-fix loop. | +| Flow XML generation | `generating-flow` | Declarative automation metadata. | +| Flow screen component wrapper | This skill + `generating-flow` if a Flow must also be generated | LWC owns UI; Flow owns orchestration. | +| Lightning app metadata | `generating-lightning-app` | App container metadata. | +| Deploy component bundle | deployment skill if available | Org rollout and validation. | + +## Examples + +### Example 1 — Record Page Summary Component + +User request: + +```text +Create an LWC for an Account record page that shows open Opportunities and lets the user refresh the list. +``` + +Expected approach: + +- Target: `lightning__RecordPage` +- Data: cacheable Apex or GraphQL, depending on project conventions +- UI states: loading, populated, empty, error +- Event: none unless parent communication is required +- Tests: mock data success/error and refresh interaction + +### Example 2 — Flow Screen Component + +User request: + +```text +Create a Flow screen LWC that lets a user select a Care Home and outputs the selected Account Id. +``` + +Expected approach: + +- Target: `lightning__FlowScreen` +- Public `@api` output property for selected record Id +- Use UI API or Apex depending on search/filtering needs +- Include keyboard-accessible selection behaviour +- Jest test event/output behaviour + +### Example 3 — App Builder Configurable Component + +User request: + +```text +Create an LWC admin can place on a Home Page with a configurable title and max number of records. +``` + +Expected approach: + +- Target: `lightning__HomePage` +- Expose `@api title` and `@api maxRecords` +- Define both properties in `.js-meta.xml` +- Validate defaults in JavaScript +- Test configured and default states From 0feab6c2aea88e1b8f26f89dd2b7e9e58631720e Mon Sep 17 00:00:00 2001 From: David Picksley Date: Mon, 11 May 2026 16:29:51 +0100 Subject: [PATCH 2/2] This skill is an original contribution for the Agentforce Vibes Library --- .../generating-lightning-component/SKILL.md | 651 +++++++++++------- 1 file changed, 404 insertions(+), 247 deletions(-) diff --git a/skills/generating-lightning-component/SKILL.md b/skills/generating-lightning-component/SKILL.md index b25279e..e2cbe90 100644 --- a/skills/generating-lightning-component/SKILL.md +++ b/skills/generating-lightning-component/SKILL.md @@ -1,71 +1,101 @@ --- name: generating-lightning-component -description: "Generate Salesforce Lightning Web Components (LWC) and supporting component bundle files. Use when the user asks to create, build, scaffold, generate, implement, refactor, or review an LWC, Lightning Web Component, UI component, Flow screen component LWC, Lightning App Builder component, Experience Cloud component, Agentforce-capable component, or any lwc/**/*.js, .html, .css, .js-meta.xml bundle. Also trigger for @wire, Lightning Data Service, Apex/GraphQL data access from LWC, Lightning Message Service, SLDS styling, accessibility, or Jest tests. Do NOT trigger for Apex-only implementation, Flow XML generation, Aura components, Visualforce, Lightning app metadata, or unrelated Salesforce metadata." +description: > + Generate, modify, review, harden, and test Salesforce Lightning Web Components (LWC). + Use when the user asks to create, build, scaffold, edit, refactor, review, or test an + LWC component bundle, or when work touches lwc/**/*.js, .html, .css, .js-meta.xml, + __tests__/*.test.js, wire service, Lightning Data Service, UI API, Apex integration, + GraphQL integration, Lightning Message Service, SLDS styling, accessibility, + performance, Flow screen components, Experience Cloud components, Lightning App Builder + exposure, or Agentforce-discoverable UI components. + Do NOT trigger for Apex-only implementation, Apex test classes, Flow XML generation, + Aura components, Visualforce pages, or deployment-only work. +license: MIT +metadata: + version: "1.0.0" + primary_source: "Jaganpro/sf-skills skills/sf-lwc" + original_author: "Jag Valaiyapathy" + contributors: + - "David Picksley, ThirdEye Consulting — PICKLES Framework" + scoring: "165 points across 8 categories, adapted from sf-lwc" --- -# Generating Lightning Components +# generating-lightning-component: Lightning Web Components Development -## Goal +Use this skill when the user needs **Lightning Web Components**: LWC bundles, wire patterns, Apex or GraphQL integration, Lightning Data Service, UI API, Lightning Message Service, SLDS styling, accessibility, performance work, Flow screen LWCs, Experience Cloud LWCs, or Jest unit tests. -Generate production-ready Salesforce Lightning Web Components (LWC) with the correct bundle structure, metadata exposure, data access pattern, accessibility, styling, security, and test approach. +This skill is primarily adapted from the `sf-lwc` skill by **Jag Valaiyapathy** and uses the **PICKLES Framework** by **David Picksley, Third Eye Consulting** as the core architecture method for planning robust LWCs. -This skill uses the **PICKLES Framework** as the architectural checklist for LWC design: +## Attribution -- **P**rototype — clarify the user journey and expected UI states before writing code. -- **I**ntegrate — choose the correct data access pattern. -- **C**omposition — split the component into sensible parent/child boundaries. -- **K**inetics — define events, interactions, loading states, and state transitions. -- **L**ibraries — prefer Salesforce platform APIs, base Lightning components, and LDS before custom code. -- **E**xecution — optimise rendering, lifecycle usage, and browser performance. -- **S**ecurity — enforce CRUD/FLS, sharing, LWS-safe JavaScript, and safe error handling. +This skill is based primarily on: -**Attribution:** PICKLES Framework by **David Picksley**. Reference: https://www.salesforceben.com/the-ideal-framework-for-architecting-salesforce-lightning-web-components/ +- **`sf-lwc` by Jag Valaiyapathy** + Source: `https://github.com/Jaganpro/sf-skills/tree/main/skills/sf-lwc` -## When to Use This Skill +It incorporates and preserves attribution for: -Use this skill when the task involves: +- **PICKLES Framework by David Picksley, Third Eye Consulting** + Reference: `https://www.salesforceben.com/the-ideal-framework-for-architecting-salesforce-lightning-web-components/` -- Creating or modifying a Lightning Web Component bundle. -- Creating files under `force-app/main/default/lwc/{componentName}/`. -- Generating `.js`, `.html`, `.css`, `.js-meta.xml`, or Jest test files for an LWC. -- Exposing an LWC to Lightning App Builder, Record Pages, Home Pages, Experience Cloud, Flow screens, or Agentforce. -- Building UI that reads or writes Salesforce data. -- Using Lightning Data Service, UI API, Apex, GraphQL, Lightning Message Service, or platform events from an LWC. -- Creating accessible, SLDS-aligned, responsive component markup. -- Creating Jest tests for an LWC. +Additional inspiration and reference sources from the original `sf-lwc` skill include official Salesforce documentation, LWC Recipes, SLDS guidance, James Simone's LWC/Jest patterns, Saurabh Samir's LWC directive work, and the source skill's own reference map. -Do not use this skill for: +## When This Skill Owns the Task -- Apex-only classes or triggers. Delegate to `generating-apex`. -- Apex test classes. Delegate to `generating-apex-test`. -- Flow XML generation. Delegate to `generating-flow`. -- Aura components or Visualforce pages. -- Lightning App metadata generation without an LWC bundle. +Use this skill when the work involves any of the following: -## Required Inputs +- `force-app/main/default/lwc/**` +- `lwc/**/*.js` +- `lwc/**/*.html` +- `lwc/**/*.css` +- `lwc/**/*.js-meta.xml` +- `lwc/**/__tests__/*.test.js` +- component scaffolding and bundle design +- Lightning App Builder component exposure +- Record Page, App Page, Home Page, Tab, Flow Screen, Experience Cloud, or Agentforce-discoverable component targets +- `@api`, `@wire`, decorators, reactive state, lifecycle hooks, or template directives +- Lightning Data Service, UI API, Apex, GraphQL, LMS, or external data via Apex +- SLDS 2, styling hooks, design tokens, dark mode readiness, responsive UI, or accessibility +- Jest tests for Lightning Web Components +- LWC performance, rendering behaviour, event contracts, or state management -Gather or infer the following before authoring: +Delegate elsewhere when the user is: -- Component purpose and user outcome. -- Target surface: +- writing Apex controllers, services, selectors, or business logic first → `generating-apex` +- writing Apex tests → `generating-apex-test` +- building Flow XML or declarative automation rather than an LWC screen component → `generating-flow` +- creating Lightning App metadata without LWC code → `generating-lightning-app` +- creating Flexipage metadata only → `generating-flexipage` +- deploying metadata only → deployment-specific skill if available +- creating custom objects, fields, tabs, permissions, list views, or validation rules → the matching metadata generation skill +- building Aura components or Visualforce pages → do not use this skill + +## Required Context to Gather First + +Ask for or infer: + +- component purpose and target user outcome +- component API name in camelCase +- target surface: - `lightning__RecordPage` - `lightning__AppPage` - `lightning__HomePage` - `lightning__Tab` - `lightning__FlowScreen` - `lightning__ExperiencePage` - - `lightning__Agentforce` - - other supported target -- Component API name in camelCase. -- Whether the component needs a public property exposed through `.js-meta.xml`. -- Data source: - - no Salesforce data - - Lightning Data Service / UI API - - Apex controller - - GraphQL wire adapter + - other supported target in the current org/project +- whether the component must run in Flow, App Builder, Experience Cloud, mobile, console, or dashboard contexts +- data source: + - none/static + - Lightning Data Service + - UI API + - Apex + - GraphQL - Lightning Message Service - - external service through Apex -- Required UX states: + - external system via Apex +- public properties to expose through `.js-meta.xml` +- events the component must emit or handle +- required UI states: - initial - loading - populated @@ -73,12 +103,14 @@ Gather or infer the following before authoring: - error - saving - success -- Whether Jest tests are required. -- Any existing project conventions, shared components, utility modules, or styling rules. + - disabled +- accessibility and styling expectations +- whether Jest tests are required +- relevant repository conventions, shared components, utility modules, local scripts, and API version -If the user gives a clear request, generate immediately. Do not ask unnecessary follow-up questions. Make a sensible default and document it in the report. +If the user gives enough detail to proceed, do not block on unnecessary questions. Make a sensible assumption, state it in the final report, and generate the component. -## Component Bundle Deliverables +## Default Bundle Shape Default bundle path: @@ -86,117 +118,126 @@ Default bundle path: force-app/main/default/lwc/{componentName}/ ``` -Generate the relevant files: +Generate only the files required for the task: ```text {componentName}.html {componentName}.js {componentName}.js-meta.xml -{componentName}.css # only when styling is needed -__tests__/{componentName}.test.js # when tests are requested or expected +{componentName}.css +__tests__/{componentName}.test.js ``` -Optional supporting files: +Optional files: ```text {componentName}.svg -{componentName}.json -utils.js constants.js +utils.js +fixtures.js ``` -Do not generate unused files. Keep the bundle minimal. +Do not generate unused files. Keep the component bundle focused. -## Workflow +## Recommended Workflow -All steps are sequential. Do not skip validation just because the component looks simple. +### 1. Choose the right architecture with PICKLES -### Phase 1 — Design with PICKLES +Use the **PICKLES** mindset before generating code: -1. **Prototype** - - Restate the component goal in one sentence. - - Identify the target user and the expected interaction. - - List the required UI states. +```text +P → Prototype │ Validate the user journey, UI states, and shape of the component +I → Integrate │ Choose the right data source: LDS, UI API, Apex, GraphQL, LMS, or API +C → Composition │ Structure parent/child components and communication boundaries +K → Kinetics │ Define interactions, events, loading states, and state transitions +L → Libraries │ Prefer platform APIs, base Lightning components, and SLDS +E → Execution │ Optimise rendering, lifecycle hooks, data volume, and browser behaviour +S → Security │ Enforce permissions, FLS, safe errors, LWS-safe code, and data protection +``` -2. **Integrate** - - Choose the smallest correct data access pattern. - - Prefer platform-native data APIs before custom Apex. - - Use Apex only when business logic, aggregation, complex SOQL, DML orchestration, callouts, or security-wrapped server behaviour is required. +### 2. Choose the right data access pattern -3. **Composition** - - Decide whether this should be one component or a parent/child set. - - Split child components only when they have a distinct responsibility or reuse value. - - Keep public APIs narrow and explicit. +| Need | Default pattern | Notes | +|---|---|---| +| Display one record | Lightning Data Service / `getRecord` | Prefer LDS/UI API before Apex. | +| Simple CRUD form | Base record form components | Use `lightning-record-form`, `lightning-record-edit-form`, or `lightning-record-view-form` when they meet the UX need. | +| Reactive read-only data | `@wire` | Use LDS, UI API, GraphQL, or cacheable Apex. | +| User-triggered save/action | Imperative UI API or Apex | Use for explicit button clicks, mutations, and DML paths. | +| Complex server query | Apex `@AuraEnabled(cacheable=true)` | For complex SOQL, aggregation, business rules, or DTO shaping. | +| Related graph data | GraphQL wire adapter | Useful for related records and pagination where supported. | +| Cross-DOM communication | Lightning Message Service | Use only when parent-child events are not enough. | +| External API | Apex callout via Named Credential | Never put secrets, tokens, or external credentials in client JavaScript. | -4. **Kinetics** - - Define the event contract before coding. - - Prefer parent-child events for local communication. - - Use Lightning Message Service only for cross-DOM or unrelated component communication. - - Include loading, disabled, empty, and error states. +### 3. Start from a pattern when useful -5. **Libraries** - - Prefer Lightning base components over custom HTML controls. - - Prefer Lightning Data Service/UI API for simple record operations. - - Use SLDS utility classes and styling hooks rather than hardcoded styling. +Use known component patterns when appropriate: -6. **Execution** - - Avoid unnecessary work in lifecycle hooks. - - Avoid setting reactive state in `renderedCallback()` unless guarded. - - Debounce user input for search/filter behaviours. - - Avoid large DOM renders; paginate or virtualise when needed. +- basic display component +- record summary card +- data table +- search/filter component +- modal/dialog +- Flow screen input/output component +- GraphQL component +- Lightning Message Service publisher/subscriber +- async notification component +- TypeScript-enabled component when the project supports it +- Jest test scaffolding -7. **Security** - - Do not expose unsafe HTML. - - Do not trust client-side validation alone. - - Ensure Apex used by the component enforces sharing, CRUD/FLS, and safe error handling. - - Avoid hardcoded IDs, secrets, object assumptions, and user-specific values. +Do not copy a pattern blindly. Adapt it to the actual target surface, data model, and user journey. -### Phase 2 — Author +### 4. Generate the component bundle -Create the component files using these rules. +#### JavaScript rules -#### JavaScript Rules - -- Use `LightningElement` from `lwc`. +- Import `LightningElement` from `lwc`. - Use `@api` only for true public component properties. - Do not mutate `@api` input values directly. - Use private state for internal mutations. - Use getters for derived template state. - Use `@wire` for reactive read-only data. +- Store wired results only when needed, such as for `refreshApex()`. - Use imperative Apex or UI API functions for explicit actions, saves, and DML. -- Store wired results if `refreshApex()` is required. - Always handle both `data` and `error` paths. - Normalise errors into user-safe strings. -- Avoid `console.log()` in generated production code. -- Avoid global DOM queries. Query only within `this.template`. +- Avoid `console.log()` in production code. +- Avoid broad DOM queries. Query only inside `this.template`. - Clean up timers, subscriptions, and listeners in `disconnectedCallback()`. +- Avoid setting reactive state inside `renderedCallback()` unless the operation is guarded against rerender loops. +- Debounce user input for search/filter behaviours. +- Prefer small pure helper functions for transformation logic. -#### HTML Rules +#### HTML rules - Use Lightning base components where available. -- Use `lwc:if`, `lwc:elseif`, and `lwc:else`; do not use legacy `if:true` / `if:false`. -- Every `for:each` item must have a stable key. Never use array index as the key. +- Use SLDS utility classes for layout and spacing. +- Use current LWC template directives such as `lwc:if`, `lwc:elseif`, and `lwc:else`; avoid legacy `if:true` / `if:false` in new code. +- Every `for:each` item must have a stable key. Never use the array index as the key. +- Keep complex logic out of the template. Move it to getters. - Include accessible labels, alternative text, assistive text, and ARIA attributes where needed. -- Do not place complex logic in the template when a getter is clearer. -- Include visible error and empty states. +- Include visible loading, empty, error, and success states. +- Do not rely on colour alone to communicate meaning. -#### CSS Rules +#### CSS rules -- Do not hardcode brand colours unless the user explicitly requests it. - Prefer SLDS classes, design tokens, and styling hooks. +- Avoid hardcoded colours unless the user explicitly requests them. - Keep CSS scoped to the component. -- Do not use brittle selectors against Salesforce-owned DOM. -- Support responsive layout where the component can appear in narrow regions. +- Do not target Salesforce-owned internal DOM. +- Support narrow containers and responsive layouts. +- Build with SLDS 2 and dark mode readiness where the project supports it. -#### Metadata Rules +#### Metadata rules Every LWC bundle must include `{componentName}.js-meta.xml`. +- Match the repository's configured API version. If no convention exists, use the current API version supported by the target org. - Set `isExposed` based on whether the component is intended for builder/runtime placement. - Include only the targets the user needs. - For `lightning__RecordPage`, include supported objects when known. - Expose configurable properties only when useful for admins/builders. -- Use a current project API version unless the repository convention says otherwise. +- Do not invent unsupported targets or capabilities. +- Only include Agentforce-specific targets/capabilities when the current project/org metadata supports them. Default metadata shape: @@ -213,7 +254,117 @@ Default metadata shape: ``` -### Phase 3 — Test +If the repo uses a different API version, follow the repo. + +### 5. Validate for frontend quality + +Before reporting completion, check: + +- component structure +- naming consistency +- data access pattern +- error handling +- loading/empty/success/error states +- SLDS 2 and dark mode readiness +- accessibility +- event contract +- performance and rerender safety +- security and Lightning Web Security compatibility +- Jest coverage when required +- metadata targets and exposed properties +- local preview/deploy readiness + +### 6. Hand off supporting backend, metadata, or deploy work + +Use the matching skill when the LWC needs non-LWC work: + +- Apex controller/service → `generating-apex` +- Apex test classes → `generating-apex-test` +- Flow XML/orchestration → `generating-flow` +- Flexipage placement → `generating-flexipage` +- Lightning app metadata → `generating-lightning-app` +- custom object/field/tab/permission/list view/validation metadata → matching metadata generation skill +- deployment → deployment-specific skill if available + +## High-Signal Rules + +- Prefer platform base components over reinventing controls. +- Prefer LDS/UI API/base record form components for straightforward record UI. +- Use `@wire` for reactive read-only use cases. +- Use imperative calls for explicit actions and DML paths. +- Use Apex only when business logic, complex queries, aggregation, external callouts, or server-side security enforcement are required. +- Keep component communication explicit and minimal. +- Use parent-child events for local communication. +- Use Lightning Message Service only for cross-DOM or unrelated component communication. +- Do not introduce inaccessible custom UI. +- Do not hardcode IDs, secrets, tokens, colours, object names, or user-specific values unless the user explicitly requires it. +- Do not bypass server-side security by moving sensitive decisions into client JavaScript. +- Do not use `lwc:dom="manual"` unless explicitly needed and the risk is explained. +- Do not inject unsanitised HTML. +- Do not expose raw exception details to users. +- Do not claim tests pass unless tests were actually run. + +## Event Contract Rules + +Use the smallest event scope that works. + +Preferred local event shape: + +```javascript +this.dispatchEvent(new CustomEvent('recordselect', { + detail: { recordId: this.recordId } +})); +``` + +Rules: + +- Event names must be lowercase. +- Do not prefix custom event names with `on`. +- Use primitives or copied object data in `detail`. +- Avoid `bubbles: true` and `composed: true` unless the event must cross component boundaries. +- Document public event contracts in the final report. + +## Apex Boundary Rules + +When Apex is required: + +- Delegate Apex generation to `generating-apex`. +- Apex must use an explicit sharing declaration. +- Read-only methods used with `@wire` must be `@AuraEnabled(cacheable=true)`. +- Mutating methods must not be cacheable. +- Apex must enforce CRUD/FLS. +- Apex should return DTOs/wrappers where this is cleaner than exposing raw SObjects. +- Expected UI errors should be converted into user-safe messages. +- Apex tests are required and should be handled by `generating-apex-test`. + +## Accessibility Rules + +Hard-stop if the generated component would violate these basics: + +- Interactive elements must be keyboard accessible. +- Icon-only buttons must have alternative text or assistive text. +- Inputs must have labels. +- Loading states must be communicated. +- Error messages must be visible. +- Modal/dialog patterns must manage focus correctly. +- Colour must not be the only indicator of status. +- Tables must use appropriate headers and accessible labels. +- Toasts or inline messages must explain what happened and what the user can do next. + +## Security Rules + +Hard-stop if the request requires unsafe behaviour: + +- no client-side secrets +- no unsafe HTML injection +- no unsanitised `lwc:dom="manual"` usage +- no hidden permission bypass +- no hardcoded sensitive IDs +- no raw stack traces shown to users +- no unsupported browser globals that conflict with Lightning Web Security +- no third-party libraries unless they are LWS-compatible and genuinely needed + +## Testing Rules When generating or modifying meaningful logic, create or update Jest tests. @@ -224,8 +375,11 @@ Test at least: - populated state - empty state - error state -- user interaction/event dispatch -- Apex/wire/UI API success and error paths, where applicable +- user interaction +- event dispatch +- wire success and error paths +- Apex/UI API/GraphQL boundary mocks where applicable +- Flow input/output behaviour for Flow screen components Jest file location: @@ -240,182 +394,185 @@ Testing rules: - Await render cycles after state changes. - Assert user-visible behaviour rather than private implementation details. - Do not rely on Salesforce org data. +- Do not claim Jest passed unless the command was run. -### Phase 4 — Validate +## Local Development Server Preview -Before reporting completion, attempt the relevant validation commands. +Where the project and Salesforce CLI support Local Dev, preview LWC components locally with hot reload: -Preferred commands: +```bash +# Preview LWC components in isolation +sf lightning dev component --target-org + +# Preview a Lightning Experience app locally +sf lightning dev app --target-org + +# Preview an Experience Cloud site locally +sf lightning dev site --target-org +``` + +Local Dev commands can be long-running preview processes and may require an active org connection for data and Apex callouts. If the command is unavailable in the user's CLI, state that clearly and use the repository's existing validation approach instead. + +## Validation Commands + +Prefer repository scripts when available. Otherwise use the closest relevant commands: ```bash npm test -- --runInBand {componentName}.test.js sf project deploy start --source-dir force-app/main/default/lwc/{componentName} --dry-run ``` -If the project has custom scripts, use the repository convention instead. +If validation tools are unavailable, state what could not be run. -If validation tools are unavailable, state that clearly in the report and explain what was not run. +## 165-Point Quality Score -## Data Access Decision Matrix +Use this score as a review aid. Do not pretend it is mathematically objective; it is a structured quality checklist adapted from the source `sf-lwc` skill. -| Need | Preferred Pattern | Notes | +| Category | Points | Focus | +|---|---:|---| +| Component Structure | 25 | file organisation, naming, bundle shape, metadata | +| Data Layer | 25 | wire service, LDS/UI API/Apex/GraphQL choice, error handling | +| UI/UX | 25 | SLDS 2, responsiveness, empty/loading/error/success states, dark mode readiness | +| Accessibility | 20 | WCAG, labels, ARIA, keyboard navigation, focus management | +| Testing | 20 | Jest coverage, mocks, async render patterns | +| Performance | 20 | lazy loading, debouncing, rerender safety, lifecycle discipline | +| Events | 15 | explicit event contracts, LMS only when appropriate | +| Security | 15 | FLS, CRUD, sharing, LWS-safe JavaScript, safe errors | + +Score meaning: + +| Score | Meaning | +|---:|---| +| 150+ | production-ready LWC bundle | +| 125–149 | strong component with minor polish left | +| 100–124 | functional but review recommended | +| < 100 | significant improvement needed | + +## Advanced and Release-Specific Features + +The source `sf-lwc` skill references modern and release-specific LWC capabilities such as TypeScript support, advanced directives, GraphQL mutations, and Agentforce discovery. + +Use these only when the current project, API version, Salesforce org, and official documentation support them. + +Do not introduce release-specific syntax or metadata just because it exists in a reference. Verify before use. + +Potential advanced areas: + +- TypeScript-enabled LWC projects +- GraphQL wire adapter and GraphQL mutations +- dynamic event/directive patterns where supported +- SLDS 2 uplift and dark mode readiness +- Agentforce-discoverable UI capabilities where metadata supports them + +## Reference Map + +When generating or reviewing an LWC, consider these reference categories from the original `sf-lwc` skill and its README/CREDITS. + +### Official Salesforce Documentation + +- Lightning Web Components Developer Guide +- Lightning Component Library +- Component bundle metadata / `.js-meta.xml` +- Wire service +- Lightning Data Service and UI API +- Apex wire methods +- GraphQL API for Salesforce +- Lightning Message Service +- Lightning Web Security +- Jest testing for Lightning Web Components +- SLDS and SLDS styling hooks +- Salesforce CLI and Local Dev + +### Community and Example Sources + +- `sf-lwc` skill by Jag Valaiyapathy +- PICKLES Framework by David Picksley, Third Eye Consulting +- LWC Recipes by Salesforce Trailhead Apps +- James Simone's advanced LWC and Jest patterns +- Saurabh Samir's LWC directive and dynamic attribute patterns + +### Original `sf-lwc` Reference Categories + +- component patterns +- SLDS design guide +- LWC best practices +- scoring and testing +- Jest testing +- accessibility guide +- performance guide +- state management +- template anti-patterns +- LMS guide +- Flow integration guide +- advanced features +- async notification patterns +- triangle pattern +- assets and templates + +Do not create broken local links to reference files unless those files are being included in the target repository. If this skill is submitted as a single `SKILL.md`, keep the reference map descriptive or link to stable external sources. + +## Cross-Skill Integration + +| Need | Delegate to | Reason | |---|---|---| -| Display one record | Lightning Data Service / UI API | Use `getRecord` or record form base components. | -| Simple create/edit/view form | Base record form components | Prefer `lightning-record-form`, `lightning-record-edit-form`, or `lightning-record-view-form`. | -| Reactive read-only data | `@wire` | Use LDS, UI API, GraphQL, or cacheable Apex. | -| User-triggered save/action | Imperative call | Use UI API or Apex depending on complexity. | -| Complex SOQL/business logic | Apex | Apex must enforce sharing, CRUD/FLS, and safe errors. | -| Related graph-shaped data | GraphQL wire adapter | Useful for related records and reducing over-fetching. | -| Cross-page/component communication | Lightning Message Service | Use only when parent-child events are insufficient. | -| External API | Apex callout via Named Credential | Never call external services with secrets from client JavaScript. | +| Apex controller or service | `generating-apex` | backend logic, DTOs, CRUD/FLS, callouts | +| Apex test class | `generating-apex-test` | Apex-side coverage and test-fix loops | +| Flow screen orchestration | `generating-flow` | declarative Flow metadata | +| Flexipage placement | `generating-flexipage` | page layout/container metadata | +| Lightning app metadata | `generating-lightning-app` | app container metadata | +| Custom object/field/tab/list view/permission/validation rule | matching metadata generation skill | supporting Salesforce metadata | +| Deploy component bundle | deployment skill if available | org rollout and validation | +| Agentforce-specific implementation | `developing-agentforce` where relevant | agent/action/discovery concerns beyond the LWC bundle | +| UI bundle frontend/app/site work | UI bundle skills where relevant | non-standard bundle delivery path | -## Event Rules +## Output Format -Use the smallest event scope that works. - -Preferred event: - -```javascript -this.dispatchEvent(new CustomEvent('select', { - detail: { recordId: this.recordId } -})); -``` - -Rules: - -- Event names must be lowercase and not prefixed with `on`. -- Use primitive or copied object data in `detail`. -- Avoid `bubbles: true, composed: true` unless the event must cross component boundaries. -- Document public event contracts in the component comments or final report. - -## Apex Boundary Rules - -When Apex is required: - -- Create or update the Apex via `generating-apex`. -- The Apex class must use a sharing declaration. -- Read-only methods used with `@wire` must be `@AuraEnabled(cacheable=true)`. -- Mutating methods must not be cacheable. -- Apex must enforce CRUD/FLS. -- Apex must return DTOs/wrappers when that is cleaner than exposing raw SObjects. -- Apex must throw user-safe `AuraHandledException` messages for expected UI errors. -- Apex tests are required and must be handled by `generating-apex-test`. - -## Accessibility Rules - -Hard-stop if generated markup would violate these basics: - -- Interactive elements must be keyboard accessible. -- Icon-only buttons must have alternative text or assistive text. -- Inputs must have labels. -- Loading states must be communicated. -- Error messages must be visible and associated with the relevant UI where possible. -- Modal/dialog patterns must manage focus correctly. -- Do not use colour alone to communicate meaning. - -## Security Rules - -Hard-stop if the component would require unsafe behaviour: - -- Do not use `lwc:dom="manual"` unless the user explicitly needs it and the risk is explained. -- Do not inject unsanitised HTML. -- Do not store credentials, tokens, secrets, or API keys in the component. -- Do not bypass CRUD/FLS by moving sensitive decisions into client-side JavaScript. -- Do not hardcode IDs. -- Do not expose sensitive implementation errors to users. -- Do not use unsupported browser globals or libraries that conflict with Lightning Web Security. - -## Naming Conventions - -| Item | Convention | Example | -|---|---|---| -| Component folder | camelCase | `accountSummaryCard` | -| JavaScript class | PascalCase | `AccountSummaryCard` | -| Public property | camelCase | `recordId` | -| HTML attribute | kebab-case | `record-id` | -| Event name | lowercase | `recordselect` | -| CSS class | kebab-case | `summary-card` | -| Jest file | `{component}.test.js` | `accountSummaryCard.test.js` | - -## Output Expectations - -When finished, report in this order: +When finishing LWC work, report in this order: ```text LWC work: Component: -Files: Pattern: -PICKLES: +Files: Targets: -Data: +Data access: Events: +PICKLES: +Quality score: Accessibility: Security: Testing: Validation: +Assumptions: Next step: ``` The report must be specific. Do not say "tests pass" unless tests were actually run. -## Cross-Skill Integration +## Example Requests -| Need | Delegate To | Reason | -|---|---|---| -| Apex controller/service | `generating-apex` | Server-side logic and security. | -| Apex tests | `generating-apex-test` | Required Apex coverage and test-fix loop. | -| Flow XML generation | `generating-flow` | Declarative automation metadata. | -| Flow screen component wrapper | This skill + `generating-flow` if a Flow must also be generated | LWC owns UI; Flow owns orchestration. | -| Lightning app metadata | `generating-lightning-app` | App container metadata. | -| Deploy component bundle | deployment skill if available | Org rollout and validation. | - -## Examples - -### Example 1 — Record Page Summary Component - -User request: +Use this skill for requests like: ```text -Create an LWC for an Account record page that shows open Opportunities and lets the user refresh the list. +Create a data table LWC for Account records with search and pagination. ``` -Expected approach: - -- Target: `lightning__RecordPage` -- Data: cacheable Apex or GraphQL, depending on project conventions -- UI states: loading, populated, empty, error -- Event: none unless parent communication is required -- Tests: mock data success/error and refresh interaction - -### Example 2 — Flow Screen Component - -User request: - ```text -Create a Flow screen LWC that lets a user select a Care Home and outputs the selected Account Id. +Build a Flow screen component that outputs the selected Care Home Account Id. ``` -Expected approach: - -- Target: `lightning__FlowScreen` -- Public `@api` output property for selected record Id -- Use UI API or Apex depending on search/filtering needs -- Include keyboard-accessible selection behaviour -- Jest test event/output behaviour - -### Example 3 — App Builder Configurable Component - -User request: - ```text -Create an LWC admin can place on a Home Page with a configurable title and max number of records. +Refactor this LWC to use LDS instead of Apex. ``` -Expected approach: +```text +Add Jest tests for this LWC's loading, data, empty, and error states. +``` -- Target: `lightning__HomePage` -- Expose `@api title` and `@api maxRecords` -- Define both properties in `.js-meta.xml` -- Validate defaults in JavaScript -- Test configured and default states +```text +Make this component SLDS 2 ready and accessible. +``` + +```text +Create a Lightning Message Service publisher/subscriber component pair. +```