diff --git a/package-lock.json b/package-lock.json index 7b8e804..c393ea5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,8 +9,8 @@ "version": "1.1.0", "license": "CC-BY-NC-4.0", "devDependencies": { - "@salesforce/webapp-template-app-react-sample-b2e-experimental": "1.107.3", - "@salesforce/webapp-template-app-react-sample-b2x-experimental": "1.107.3", + "@salesforce/webapp-template-app-react-sample-b2e-experimental": "1.109.1", + "@salesforce/webapp-template-app-react-sample-b2x-experimental": "1.109.1", "tsx": "^4.21.0" } }, @@ -732,20 +732,20 @@ } }, "node_modules/@salesforce/webapp-template-app-react-sample-b2e-experimental": { - "version": "1.107.3", - "resolved": "https://registry.npmjs.org/@salesforce/webapp-template-app-react-sample-b2e-experimental/-/webapp-template-app-react-sample-b2e-experimental-1.107.3.tgz", - "integrity": "sha512-9oLj1sxPS0Cwcr1VGGF27oI5kiPoNw/rN7cD4LEHqbsb0w91KOIh6j3O61LhBrWNKB572slk1woaVA9ai0IkNw==", + "version": "1.109.1", + "resolved": "https://registry.npmjs.org/@salesforce/webapp-template-app-react-sample-b2e-experimental/-/webapp-template-app-react-sample-b2e-experimental-1.109.1.tgz", + "integrity": "sha512-ju77WQp0dsIDroito/xgZrLI7DuIQfo8NgMLB8qVgnhE7Tssma8KAtqDHjK9HsmL/HTPlMXZUEhEqh8nJNq5Sw==", "dev": true, "license": "SEE LICENSE IN LICENSE.txt", "dependencies": { - "@salesforce/webapp-experimental": "^1.107.3", - "@salesforce/webapp-template-feature-react-global-search-experimental": "^1.107.3" + "@salesforce/webapp-experimental": "^1.109.1", + "@salesforce/webapp-template-feature-react-global-search-experimental": "^1.109.1" } }, "node_modules/@salesforce/webapp-template-app-react-sample-b2x-experimental": { - "version": "1.107.3", - "resolved": "https://registry.npmjs.org/@salesforce/webapp-template-app-react-sample-b2x-experimental/-/webapp-template-app-react-sample-b2x-experimental-1.107.3.tgz", - "integrity": "sha512-YpZxmiUlLntpWDDOZ7wBPgvo3nlq/8tpFZIxEfufyPi4jiwEa3D4KLQJvjN/KSHXP8YDoHyuIB2ZjYKIoRW1Ww==", + "version": "1.109.1", + "resolved": "https://registry.npmjs.org/@salesforce/webapp-template-app-react-sample-b2x-experimental/-/webapp-template-app-react-sample-b2x-experimental-1.109.1.tgz", + "integrity": "sha512-Pf4cC1fbDJ5o7gJlztDCArqimQN60+iCAxNpHHDsz8hHUBO2lteD5jK3I9WSPeoBDNm7VMOgLFIssWiGPvRlVg==", "dev": true, "license": "SEE LICENSE IN LICENSE.txt" }, diff --git a/package.json b/package.json index 767872a..ba03851 100644 --- a/package.json +++ b/package.json @@ -11,8 +11,8 @@ "registry": "https://registry.npmjs.org" }, "devDependencies": { - "@salesforce/webapp-template-app-react-sample-b2e-experimental": "1.107.3", - "@salesforce/webapp-template-app-react-sample-b2x-experimental": "1.107.3", + "@salesforce/webapp-template-app-react-sample-b2e-experimental": "1.109.1", + "@salesforce/webapp-template-app-react-sample-b2x-experimental": "1.109.1", "tsx": "^4.21.0" }, "scripts": { diff --git a/scripts/sync-webapp-skills.js b/scripts/sync-webapp-skills.js index c51e17f..67334da 100644 --- a/scripts/sync-webapp-skills.js +++ b/scripts/sync-webapp-skills.js @@ -1,8 +1,8 @@ #!/usr/bin/env node /** - * Sync webapp skills: pins @salesforce/webapp-template-app-react-sample-b2e-experimental - * to the latest npm version, runs npm install, then copies skills from - * dist/.a4drules/skills/ into skills/. Run from repo root. + * Sync webapp skills: pins b2e and b2x template packages to latest npm versions, + * runs npm install, then copies skills from dist/.a4drules/skills/ into skills/. + * Run from repo root. */ const fs = require('fs'); @@ -10,30 +10,39 @@ const path = require('path'); const { execSync } = require('child_process'); const { copyRecursive } = require('./lib/copy-recursive'); -const PACKAGE_NAME = '@salesforce/webapp-template-app-react-sample-b2e-experimental'; +const TEMPLATE_PACKAGES = [ + '@salesforce/webapp-template-app-react-sample-b2e-experimental', + '@salesforce/webapp-template-app-react-sample-b2x-experimental', +]; +const PACKAGE_NAME = TEMPLATE_PACKAGES[0]; // used for syncing skills const SKILLS_SRC = 'dist/.a4drules/skills'; const repoRoot = process.cwd(); const pkgPath = path.join(repoRoot, 'package.json'); const skillsDir = path.join(repoRoot, 'skills'); -// ── Pin to latest npm version ──────────────────────────────────────── +// ── Pin template packages to latest npm versions ──────────────────── const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')); -const current = (pkg.devDependencies || {})[PACKAGE_NAME]; -if (current && !current.startsWith('file:')) { +let pkgChanged = false; +for (const name of TEMPLATE_PACKAGES) { + const current = (pkg.devDependencies || {})[name]; + if (!current || current.startsWith('file:')) continue; let latest; try { - latest = execSync(`npm view ${PACKAGE_NAME} version`, { encoding: 'utf8' }).trim(); + latest = execSync(`npm view ${name} version`, { encoding: 'utf8' }).trim(); } catch (_) { - console.warn(`Could not resolve ${PACKAGE_NAME} on npm, using current version.`); - latest = current; + console.warn(`Could not resolve ${name} on npm, using current version.`); + continue; } if (current !== latest) { - console.log(`${PACKAGE_NAME}: ${current} -> ${latest}`); - pkg.devDependencies[PACKAGE_NAME] = latest; - fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n', 'utf8'); + console.log(`${name}: ${current} -> ${latest}`); + pkg.devDependencies[name] = latest; + pkgChanged = true; } } +if (pkgChanged) { + fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n', 'utf8'); +} // ── Install ────────────────────────────────────────────────────────── console.log('Installing dependencies...'); @@ -61,6 +70,11 @@ function addWebappPrefix(name) { return parts[0] + '-webapp-' + parts.slice(1).join('-'); } +/** Dirs in skills/ that look like synced webapp skills (e.g. *-webapp-*, creating-webapp). */ +function isSyncedWebappSkillDir(name) { + return name.includes('webapp'); +} + /** Set front matter `name` in SKILL.md to match the destination folder name. */ function setSkillFrontMatterName(skillDir, destName) { const skillPath = path.join(skillDir, 'SKILL.md'); @@ -70,11 +84,25 @@ function setSkillFrontMatterName(skillDir, destName) { fs.writeFileSync(skillPath, content, 'utf8'); } -const syncedDirs = []; -for (const srcName of fs.readdirSync(srcDir)) { - const src = path.join(srcDir, srcName); - if (!fs.statSync(src).isDirectory()) continue; +// ── Clean up: remove skills no longer in the package ─────────────────── +const srcNames = fs.readdirSync(srcDir).filter((name) => + fs.statSync(path.join(srcDir, name)).isDirectory() +); +const currentDestNames = new Set(srcNames.map(addWebappPrefix)); +for (const name of fs.readdirSync(skillsDir)) { + const dirPath = path.join(skillsDir, name); + if (!fs.statSync(dirPath).isDirectory()) continue; + if (!isSyncedWebappSkillDir(name)) continue; + if (currentDestNames.has(name)) continue; + fs.rmSync(dirPath, { recursive: true }); + console.log(`Removed skills/${name}/ (no longer in package)`); +} + +// ── Copy each skill from package ────────────────────────────────────── +const syncedDirs = []; +for (const srcName of srcNames) { + const src = path.join(srcDir, srcName); const destName = addWebappPrefix(srcName); const dest = path.join(skillsDir, destName); if (fs.existsSync(dest)) fs.rmSync(dest, { recursive: true }); diff --git a/skills/accessing-webapp-data/SKILL.md b/skills/accessing-webapp-data/SKILL.md index d17a5ec..e862745 100644 --- a/skills/accessing-webapp-data/SKILL.md +++ b/skills/accessing-webapp-data/SKILL.md @@ -149,6 +149,19 @@ const res = await sdk.fetch?.("/services/data/v65.0/chatter/users/me"); --- +## Clarifying Vague Data Requests + +When a user asks about data and the request is vague, **clarify before implementing**. Ask which of the following they want: + +- **Application code** — Add or modify code in a specific web app so the app performs the data interaction at runtime (e.g., GraphQL query in the React app) +- **Local SF CLI** — Run Salesforce CLI commands locally (e.g., `sf data query`, `sf data import tree`) to interact with the org from the terminal +- **Local example data** — Update or add local fixture/example data files (e.g., JSON in `data/`) for development or testing +- **Other** — Data export, report generation, setup script, etc. + +Do not assume. A request like "fetch accounts" could mean: (1) add a GraphQL query to the app, (2) run `sf data query` in the terminal, or (3) update sample data files. Confirm the intent before proceeding. + +--- + ## Decision Flow 1. **Need to query or mutate Salesforce records?** → Use GraphQL via the Data SDK. Invoke the `using-graphql` skill. diff --git a/skills/building-webapp-analytics-charts/SKILL.md b/skills/building-webapp-analytics-charts/SKILL.md deleted file mode 100644 index 8fb66c3..0000000 --- a/skills/building-webapp-analytics-charts/SKILL.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -name: building-webapp-analytics-charts -description: Add or change charts from raw data. Use when the user asks for a chart, graph, or analytics visualization from JSON/data. ---- - -# Analytics charts (workflow) - -When the user wants a chart or visualization from data, follow this workflow. Charts use **Recharts** via the **AnalyticsChart** component. - -## Dependencies - -Ensure the following package is installed in the project: - -```bash -npm install recharts -``` - -## 1. Interpret data type - -- **Time-series**: data over time or ordered (dates, timestamps). Use a line chart. Raw shape often has date-like keys and a numeric value. -- **Categorical**: data by category (labels, segments). Use a bar chart. Raw shape often has a category name and a numeric value. - -If the user says "over time", "trend", or uses date-like keys → time-series. If they say "by category", "by X", or use label-like keys → categorical. - -## 2. Map data to chart shape - -- **Time-series**: produce `[{ x: string, y: number }, ...]` (e.g. map `date`→`x`, `value`→`y`). -- **Categorical**: produce `[{ name: string, value: number }, ...]` (e.g. map `category`→`name`, `total`→`value`). - -See [schema-mapping.md](docs/schema-mapping.md) for examples. - -## 3. Choose theme - -- **red**: declining, loss, negative trend. -- **green**: growth, gain, positive trend. -- **neutral**: default or mixed. - -## 4. Generate and place the chart - -- Use **AnalyticsChart** with `chartType` (`"time-series"` or `"categorical"`), `data` (mapped array), `theme`, and optional `title`. Wrap in **ChartContainer** if the app uses it for chart blocks. -- Insert the chart inside the existing app (e.g. main content or a route), not as the entire page. diff --git a/skills/building-webapp-analytics-charts/docs/schema-mapping.md b/skills/building-webapp-analytics-charts/docs/schema-mapping.md deleted file mode 100644 index 4f1a1fa..0000000 --- a/skills/building-webapp-analytics-charts/docs/schema-mapping.md +++ /dev/null @@ -1,4 +0,0 @@ -# Schema mapping (Recharts) - -- **Time-series**: `{ x: string, y: number }` — e.g. map `date`→`x`, `value`→`y`. -- **Categorical**: `{ name: string, value: number }` — e.g. map `category`→`name`, `total`→`value`. diff --git a/skills/building-webapp-data-visualization/SKILL.md b/skills/building-webapp-data-visualization/SKILL.md index a677ec6..59978d1 100644 --- a/skills/building-webapp-data-visualization/SKILL.md +++ b/skills/building-webapp-data-visualization/SKILL.md @@ -46,8 +46,8 @@ Recharts is built on D3 and provides declarative React components. No additional Read the corresponding guide: -- **Bar chart** — use the **`building-analytics-charts`** skill in `feature-react-chart` (AnalyticsChart component for categorical data). -- **Line / area chart** — use the **`building-analytics-charts`** skill in `feature-react-chart` (AnalyticsChart component for time-series data). +- **Bar chart** — read `implementation/bar-line-chart.md` (categorical data) +- **Line / area chart** — read `implementation/bar-line-chart.md` (time-series data) - **Donut / pie chart** — read `implementation/donut-chart.md` - **Stat card with trend** — read `implementation/stat-card.md` - **Dashboard layout** — read `implementation/dashboard-layout.md` diff --git a/skills/building-webapp-data-visualization/implementation/bar-line-chart.md b/skills/building-webapp-data-visualization/implementation/bar-line-chart.md new file mode 100644 index 0000000..c094c8b --- /dev/null +++ b/skills/building-webapp-data-visualization/implementation/bar-line-chart.md @@ -0,0 +1,316 @@ +# Bar & Line / Area Chart — Implementation Guide + +Requires **recharts** (install from the web app directory; see SKILL.md Step 2). + +--- + +## Data shapes + +### Time-series (line / area chart) + +Use when data represents a trend over time or ordered sequence. + +```ts +interface TimeSeriesDataPoint { + x: string; // date or label on the x-axis + y: number; // numeric value +} +``` + +Map raw fields to this shape: e.g. `date` → `x`, `revenue` → `y`. + +### Categorical (bar chart) + +Use when data compares discrete categories. + +```ts +interface CategoricalDataPoint { + name: string; // category label + value: number; // numeric value +} +``` + +Map raw fields to this shape: e.g. `product` → `name`, `sales` → `value`. + +### How to decide + +| Signal | Type | +|--------|------| +| "over time", "trend", date-like keys | Time-series → line chart | +| "by category", "by X", label-like keys | Categorical → bar chart | + +--- + +## Theme colors + +Pick a theme based on the data's sentiment: + +| Theme | Stroke / Fill | When to use | +|-------|---------------|-------------| +| `green` | `#22c55e` | Growth, gain, positive trend | +| `red` | `#ef4444` | Decline, loss, negative trend | +| `neutral` | `#6366f1` | Default or mixed data | + +Define colors as constants — do not use inline hex values. + +```ts +const THEME_COLORS = { + red: "#ef4444", + green: "#22c55e", + neutral: "#6366f1", +} as const; + +type ChartTheme = keyof typeof THEME_COLORS; +``` + +--- + +## Line chart component + +Create at `components/LineChart.tsx` (or colocate with the page): + +```tsx +import React from "react"; +import { + LineChart as RechartsLineChart, + Line, + XAxis, + YAxis, + CartesianGrid, + Tooltip, + Legend, + ResponsiveContainer, +} from "recharts"; + +const THEME_COLORS = { + red: "#ef4444", + green: "#22c55e", + neutral: "#6366f1", +} as const; + +type ChartTheme = keyof typeof THEME_COLORS; + +interface TimeSeriesDataPoint { + x: string; + y: number; +} + +interface TimeSeriesChartProps { + data: TimeSeriesDataPoint[]; + theme?: ChartTheme; + title?: string; + className?: string; +} + +export function TimeSeriesChart({ + data, + theme = "neutral", + title, + className = "", +}: TimeSeriesChartProps) { + if (data.length === 0) { + return

No data to display

; + } + + const color = THEME_COLORS[theme]; + + return ( +
+ {title && ( +

+ {title} +

+ )} + + + + + + + + + + +
+ ); +} +``` + +--- + +## Bar chart component + +Create at `components/BarChart.tsx` (or colocate with the page): + +```tsx +import React from "react"; +import { + BarChart as RechartsBarChart, + Bar, + XAxis, + YAxis, + CartesianGrid, + Tooltip, + Legend, + ResponsiveContainer, +} from "recharts"; + +const THEME_COLORS = { + red: "#ef4444", + green: "#22c55e", + neutral: "#6366f1", +} as const; + +type ChartTheme = keyof typeof THEME_COLORS; + +interface CategoricalDataPoint { + name: string; + value: number; +} + +interface CategoricalChartProps { + data: CategoricalDataPoint[]; + theme?: ChartTheme; + title?: string; + className?: string; +} + +export function CategoricalChart({ + data, + theme = "neutral", + title, + className = "", +}: CategoricalChartProps) { + if (data.length === 0) { + return

No data to display

; + } + + const color = THEME_COLORS[theme]; + + return ( +
+ {title && ( +

+ {title} +

+ )} + + + + + + + + + + +
+ ); +} +``` + +--- + +## Area chart variant + +For a filled area chart (useful for volume-over-time), swap `Line` for `Area`: + +```tsx +import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from "recharts"; + + + + + + + + + + +``` + +--- + +## Chart container wrapper + +Wrap any chart in a styled card for consistent spacing: + +```tsx +import { Card } from "@/components/ui/card"; + +interface ChartContainerProps { + children: React.ReactNode; + className?: string; +} + +export function ChartContainer({ children, className = "" }: ChartContainerProps) { + return ( + + {children} + + ); +} +``` + +Usage: + +```tsx + + + +``` + +--- + +## Preparing raw data + +Map API responses to the expected shape before passing to the chart: + +```tsx +const timeSeriesData = useMemo( + () => apiRecords.map((r) => ({ x: r.date, y: r.revenue })), + [apiRecords], +); + +const categoricalData = useMemo( + () => apiRecords.map((r) => ({ name: r.product, value: r.sales })), + [apiRecords], +); +``` + +--- + +## Key Recharts concepts + +| Component | Purpose | +|-----------|---------| +| `ResponsiveContainer` | Wraps chart to fill parent width | +| `CartesianGrid` | Background grid lines | +| `XAxis` / `YAxis` | Axis labels; `dataKey` maps to the data field | +| `Tooltip` | Hover info | +| `Legend` | Series labels | +| `Line` | Line series; `type="monotone"` for smooth curves | +| `Bar` | Bar series; `radius` rounds top corners | +| `Area` | Filled area; `fillOpacity` controls transparency | + +--- + +## Accessibility + +- Always include a text legend (not just colors). +- Chart should be wrapped in a section with a visible heading. +- For critical data, provide a text summary or table alternative. +- Use sufficient color contrast between the chart stroke/fill and background. +- Consider `prefers-reduced-motion` for chart animations. + +--- + +## Common mistakes + +| Mistake | Fix | +|---------|-----| +| Missing `ResponsiveContainer` | Chart won't resize; always wrap | +| Fixed width/height on chart | Let `ResponsiveContainer` control sizing | +| No empty-data handling | Show "No data" message when `data.length === 0` | +| Inline colors | Extract to `THEME_COLORS` constant | +| Using raw Recharts for every chart type | Use `DonutChart` (see `donut-chart.md`) for pie/donut | diff --git a/skills/building-webapp-data-visualization/implementation/donut-chart.md b/skills/building-webapp-data-visualization/implementation/donut-chart.md index 24b48ab..1f20bdc 100644 --- a/skills/building-webapp-data-visualization/implementation/donut-chart.md +++ b/skills/building-webapp-data-visualization/implementation/donut-chart.md @@ -156,7 +156,7 @@ Keep chart colors consistent with the app's design system. Define them as consta ## Other chart types -For **bar charts** and **line charts**, use the `AnalyticsChart` component from `feature-react-chart` instead of raw Recharts. See the **`building-analytics-charts`** skill for usage. +For **bar charts** and **line / area charts**, see `bar-line-chart.md` in this directory. --- diff --git a/skills/building-webapp-react-components/SKILL.md b/skills/building-webapp-react-components/SKILL.md index e943f5e..8448424 100644 --- a/skills/building-webapp-react-components/SKILL.md +++ b/skills/building-webapp-react-components/SKILL.md @@ -68,13 +68,29 @@ Once you have identified the type and gathered answers to the clarifying questio --- -## Verification +## TypeScript Standards -Before completing, run from the web app directory `force-app/main/default/webapplications//` (use the actual app folder name): +- **Never use `any`** — use proper types, generics, or `unknown` with type guards. +- **Event handlers:** `(event: React.FormEvent): void` +- **State:** `useState(null)` — always provide the type parameter. +- **No unsafe assertions** (`obj as User`). Use type guards: + ```typescript + function isUser(obj: unknown): obj is User { + return typeof obj === 'object' && obj !== null && typeof (obj as User).id === 'string'; + } + ``` + +--- + +## Verification (MANDATORY) + +Before completing, run from the web app directory `force-app/main/default/webapplications//`: ```bash cd force-app/main/default/webapplications/ && npm run lint && npm run build ``` -- **Lint:** MUST result in 0 errors. Fix any ESLint or TypeScript issues. -- **Build:** MUST succeed. Resolve any compilation or Vite build failures before finishing. +- **Lint:** MUST result in 0 errors. +- **Build:** MUST succeed (includes TypeScript check). + +If either fails, fix the errors and re-run. Do not leave the session with failing quality gates. diff --git a/skills/creating-webapp/SKILL.md b/skills/creating-webapp/SKILL.md index 20c2e1a..b6f1ab6 100644 --- a/skills/creating-webapp/SKILL.md +++ b/skills/creating-webapp/SKILL.md @@ -11,7 +11,10 @@ paths: # Skills-First (MUST FOLLOW) -**Before writing any code or running any command**, search for relevant skills (`SKILL.md` files) that cover your task. Read the full skill and follow its instructions. Skills live in `.a4drules/skills/` and `feature/*/skills/`. See **webapp-skills-first.md** for the full protocol and a task-to-skill lookup table. +**Before writing any code or running any command**, search for relevant skills (`SKILL.md` files) that cover your task. Read the full skill and follow its instructions. Skills live in `.a4drules/skills/` and `feature/*/skills/`. + +- Do not write custom scripts or complex bash commands for a workflow already covered by a loaded skill. +- Only proceed with manual execution after confirming no relevant skill exists. # Deployment Order (MUST FOLLOW) @@ -91,6 +94,25 @@ Agents consistently miss these. **You must not leave them default.** | Root page content | Component at root route (often `Home` in `routes.tsx`) | +# React & TypeScript Constraints + +## Routing (React Router) + +Use a **single** router package. When using `createBrowserRouter` / `RouterProvider`, all imports MUST come from **`react-router`** — not `react-router-dom`. + +## Component Library + Styling + +- **shadcn/ui** for components: `import { Button } from '@/components/ui/button';` +- **Tailwind CSS** utility classes + +## URL & Path Handling + +Apps run behind dynamic base paths. Router navigation (``, `navigate()`) prefer absolute paths (`/x`). Non-router attributes (``) use dot-relative (`./x`) to resolve against ``. Prefer Vite `import` for static assets. + +## Module Restrictions + +React apps must NOT import Salesforce platform modules like `lightning/*` or `@wire` (LWC-only). For data access, invoke the **accessing-data** skill. + # Frontend Aesthetics **Avoid AI slop.** Make creative, distinctive frontends: diff --git a/skills/installing-webapp-features/SKILL.md b/skills/installing-webapp-features/SKILL.md index 42b124d..80bf7af 100644 --- a/skills/installing-webapp-features/SKILL.md +++ b/skills/installing-webapp-features/SKILL.md @@ -1,11 +1,11 @@ --- name: installing-webapp-features -description: Search, describe, and install pre-built UI features (authentication, shadcn components, navigation, charts, search, GraphQL, Agentforce AI) into Salesforce webapps. Use this when the user wants to add functionality to a webapp, or when determining what salesforce-provided features are available — whether prompted by the user or on your own initiative. Always check for an existing feature before building from scratch. +description: Search, describe, and install pre-built UI features (authentication, shadcn components, navigation, search, GraphQL, Agentforce AI) into Salesforce webapps. Use this when the user wants to add functionality to a webapp, or when determining what salesforce-provided features are available — whether prompted by the user or on your own initiative. Always check for an existing feature before building from scratch. --- # webapps-features-experimental CLI — Agent Reference -**Always check for an existing feature before building something yourself.** This CLI installs pre-built, tested feature packages into Salesforce webapps. Features range from foundational UI component libraries (shadcn/ui with Button, Card, Input, Table, etc.) to full-stack application capabilities like authentication (login, registration, password flows, session management, and Apex backend classes), global search, navigation menus, data visualization charts, GraphQL integrations, and Agentforce AI conversation UIs. Each feature ships as a complete implementation — including React components, context providers, route guards, and any required Salesforce server-side code — that already handles platform-specific concerns like Salesforce API integration, session management, and SFDX metadata structure. Building these from scratch is error-prone and unnecessary when a feature exists. **If no existing feature is found, ask the user before proceeding with a custom implementation — a relevant feature may exist under a different name or keyword.** +**Always check for an existing feature before building something yourself.** This CLI installs pre-built, tested feature packages into Salesforce webapps. Features range from foundational UI component libraries (shadcn/ui with Button, Card, Input, Table, etc.) to full-stack application capabilities like authentication (login, registration, password flows, session management, and Apex backend classes), global search, navigation menus, GraphQL integrations, and Agentforce AI conversation UIs. Each feature ships as a complete implementation — including React components, context providers, route guards, and any required Salesforce server-side code — that already handles platform-specific concerns like Salesforce API integration, session management, and SFDX metadata structure. Building these from scratch is error-prone and unnecessary when a feature exists. **If no existing feature is found, ask the user before proceeding with a custom implementation — a relevant feature may exist under a different name or keyword.** ``` npx @salesforce/webapps-features-experimental [options] diff --git a/skills/integrating-webapp-agentforce-conversation-client/SKILL.md b/skills/integrating-webapp-agentforce-conversation-client/SKILL.md deleted file mode 100644 index 8cdb5af..0000000 --- a/skills/integrating-webapp-agentforce-conversation-client/SKILL.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -name: integrating-webapp-agentforce-conversation-client -description: Embed an Agentforce conversation client (chat UI) into a React web application using the AgentforceConversationClient component. Use when the user wants to add or integrate a chat widget, chatbot, conversation client, agent chat, or conversational interface in a React app, or when they mention Agentforce chat, Agentforce widget, employee agent, travel agent, HR agent, or embedding a Salesforce agent. ALWAYS use this skill instead of building a chat UI from scratch. NEVER generate custom chat components, use third-party chat libraries, or implement chat with WebSockets or REST APIs. Do NOT use for Lightning Web Components (LWC), non-React frameworks. ---- - -# Embedded Agentforce chat (flat-prop API) - -Use this workflow whenever the user wants add or update Agentforce chat in React. - -## 1) Get agent id first - -Ask for the Salesforce agent id (18-char id starting with `0Xx`). Do not proceed without it. - -Placeholder convention for all examples in this file: - -`` - -## 2) Install package - -```bash -npm install @salesforce/webapp-template-feature-react-agentforce-conversation-client-experimental -``` - -## 3) Use component in app layout - -Render a single instance in the shared layout (alongside ``). - -```tsx -import { Outlet } from "react-router"; -import { AgentforceConversationClient } from "@salesforce/webapp-template-feature-react-agentforce-conversation-client-experimental"; - -export default function AppLayout() { - return ( - <> - - - - ); -} -``` - -## 4) Flat props only - -This package uses a flat prop API. Use these props directly on the component: - -- `agentId` (required in practice) -- `inline` (`true` = inline, omitted/false = floating) -- `headerEnabled` (defaults to true for floating; actual use case for inline mode) -- `width`, `height` (actual work is when inline mode is true) -- `styleTokens` -- `salesforceOrigin`, `frontdoorUrl` - -## 5) Inline mode example - -```tsx - -``` - -## 6) Theming example - -```tsx - -``` - -## 7) Do not do this - -- Do not create custom chat UIs. -- Do not use third-party chat libraries. -- Do not call `embedAgentforceClient` directly from @salesforce/agentforce-conversation-client. - -## 8) Prerequisites - -Ensure org setup is valid: - -1. Agent is active and deployed to the correct channel. -2. `localhost:` is trusted for inline frames in local dev. -3. First-party Salesforce cookie restriction is disabled when required for embedding. - -## Troubleshooting - -If the chat widget does not appear, fails to authenticate, or behaves unexpectedly, see [troubleshooting.md](docs/troubleshooting.md). diff --git a/skills/integrating-webapp-agentforce-conversation-client/docs/embed-examples.md b/skills/integrating-webapp-agentforce-conversation-client/docs/embed-examples.md deleted file mode 100644 index 2b4048a..0000000 --- a/skills/integrating-webapp-agentforce-conversation-client/docs/embed-examples.md +++ /dev/null @@ -1,116 +0,0 @@ -# Embed examples (flat-prop API) - -All examples use `AgentforceConversationClient` with flat props. - -> `agentId` is required in practice. Use this placeholder pattern in examples: `""`. - ---- - -## Floating mode (default) - -```tsx - -``` - -## Explicit floating - -```tsx - -``` - ---- - -## Inline mode - -### Fixed pixels - -```tsx - -``` - -### CSS string size - -```tsx - -``` - -### Inline sidebar - -```tsx -
-
{/* App content */}
- -
-``` - ---- - -## Theming - -```tsx - -``` - ---- - -## Inline with header enabled - -```tsx - -``` - -`headerEnabled` defaults to `true` for floating mode, and you can use it in inline mode to add/remove the header. - ---- - -## Full layout example - -```tsx -import { Outlet } from "react-router"; -import { AgentforceConversationClient } from "@salesforce/webapp-template-feature-react-agentforce-conversation-client-experimental"; - -export default function AppLayout() { - return ( - <> - - - - ); -} -``` diff --git a/skills/managing-webapp-agentforce-conversation-client/SKILL.md b/skills/managing-webapp-agentforce-conversation-client/SKILL.md new file mode 100644 index 0000000..846805d --- /dev/null +++ b/skills/managing-webapp-agentforce-conversation-client/SKILL.md @@ -0,0 +1,186 @@ +--- +name: managing-webapp-agentforce-conversation-client +description: Adds or modifies AgentforceConversationClient in React apps (.tsx or .jsx files). Use when user says "add chat widget", "embed agentforce", "add agent", "add chatbot", "integrate conversational AI", or asks to change colors, dimensions, styling, or configure agentId, width, height, inline mode, or styleTokens for travel agent, HR agent, employee agent, or any Salesforce agent chat. +metadata: + author: ACC Components + version: 1.0.0 + package: "@salesforce/webapp-template-feature-react-agentforce-conversation-client-experimental" + sdk-package: "@salesforce/agentforce-conversation-client" + last-updated: 2025-03-18 +--- + +# Managing Agentforce Conversation Client + +## Instructions + +### Step 1: Check if component already exists + +Search for existing usage across all app files (not implementation files): + +```bash +grep -r "AgentforceConversationClient" --include="*.tsx" --include="*.jsx" --exclude-dir=node_modules +``` + +**Important:** Look for React files that import and USE the component (for example, shared shells, route components, or feature pages). Do NOT open files named `AgentforceConversationClient.tsx` or `AgentforceConversationClient.jsx` - those are the component implementation. + +**If found:** Read the file and check the current `agentId` value. + +**Agent ID validation rule (deterministic):** + +- Valid only if it matches: `^0Xx[a-zA-Z0-9]{15}$` +- Meaning: starts with `0Xx` and total length is 18 characters + +**Decision:** + +- If `agentId` matches `^0Xx[a-zA-Z0-9]{15}$` and user wants to update other props → Go to Step 4 (update props) +- If `agentId` is missing, empty, or does NOT match `^0Xx[a-zA-Z0-9]{15}$` → Continue to Step 2 (need real ID) +- If not found → Continue to Step 2 (add new) + +### Step 2: Get agent ID + +If component doesn't exist or has an invalid placeholder value, ask user for their Salesforce agent ID. + +Treat these as placeholder/invalid values: + +- `"0Xx..."` +- `"Placeholder"` +- `"YOUR_AGENT_ID"` +- `""` +- Any value that does not match `^0Xx[a-zA-Z0-9]{15}$` + +Skip this step if: + +- Component exists with a real agent ID +- User only wants to update styling or dimensions + +### Step 3: Canonical import strategy + +Use this import path by default in app code: + +```tsx +import { AgentforceConversationClient } from "@salesforce/webapp-template-feature-react-agentforce-conversation-client-experimental"; +``` + +If the package is not installed, install it: + +```bash +npm install @salesforce/webapp-template-feature-react-agentforce-conversation-client-experimental +``` + +Only use a local relative import (for example, `./components/AgentforceConversationClient`) when the user explicitly asks to use a patched/local component in that app. + +Do not infer import path from file discovery alone. Prefer one consistent package import across the codebase. + +### Step 4: Add or update component + +**For new installations:** + +Add to the target React component file using the canonical package import: + +```tsx +import { Outlet } from "react-router"; +import { AgentforceConversationClient } from "@salesforce/webapp-template-feature-react-agentforce-conversation-client-experimental"; + +export default function AgentChatHost() { + return ( + <> + + + + ); +} +``` + +**Fallback note:** Use a local relative import only when the user explicitly requests patched/local component usage in that app. + +**For updates:** + +Read the file where component is used and modify only the props that need to change. Preserve all other props. Never delete and recreate. + +**Replacing placeholder values:** + +If the component has a placeholder agentId (e.g., `agentId="Placeholder"` or `agentId="0Xx..."`), replace it with the real agent ID: + +```tsx +// Before (template with placeholder) + + +// After (with real agent ID) + +``` + +### Step 5: Configure props + +**Available props (use directly on component):** + +- `agentId` (string, required) - Salesforce agent ID +- `inline` (boolean) - `true` for inline mode, omit for floating +- `width` (number | string) - e.g., `420` or `"100%"` +- `height` (number | string) - e.g., `600` or `"80vh"` +- `headerEnabled` (boolean) - Show/hide header +- `styleTokens` (object) - For all styling (colors, fonts, spacing) +- `salesforceOrigin` (string) - Auto-resolved +- `frontdoorUrl` (string) - Auto-resolved + +**Examples:** + +Floating mode (default): + +```tsx + +``` + +Inline mode with dimensions: + +```tsx + +``` + +Styling with styleTokens: + +```tsx + +``` + +**For complex patterns,** consult `references/examples.md` for: + +- Sidebar containers and responsive sizing +- Dark theme and advanced theming combinations +- Inline without header, calculated dimensions +- Complete host component examples + +**For styling:** For ANY color, font, or spacing changes, use `styleTokens` prop only. See `references/style-tokens.md` for complete token list and examples. + +**Common mistakes to avoid:** Consult `references/constraints.md` for: + +- Invalid props (containerStyle, style, className) +- Invalid styling approaches (CSS files, style tags) +- What files NOT to edit (implementation files) + +## Common Issues + +If component doesn't appear or authentication fails, see `references/troubleshooting.md` for: + +- Agent activation and deployment +- Localhost trusted domains +- Cookie restriction settings + +## Prerequisites + +Before the component will work, the following Salesforce settings must be configured by the user: + +**Cookie settings:** + +- Setup → My Domain → Disable "Require first party use of Salesforce cookies" + +**Trusted domains (required only for local development):** + +- Setup → Session Settings → Trusted Domains for Inline Frames → Add your domain + - Local development: `localhost:` (e.g., `localhost:3000`) diff --git a/skills/managing-webapp-agentforce-conversation-client/references/constraints.md b/skills/managing-webapp-agentforce-conversation-client/references/constraints.md new file mode 100644 index 0000000..55402c2 --- /dev/null +++ b/skills/managing-webapp-agentforce-conversation-client/references/constraints.md @@ -0,0 +1,134 @@ +# Constraints and Anti-Patterns + +This document lists all invalid approaches and patterns to avoid when working with AgentforceConversationClient. + +## Never Edit Implementation Files + +**CRITICAL: Only edit files where the component is USED, never the component implementation itself.** + +- ✅ **DO edit**: Any React files that import and use `` (for example, shared shells, route components, or feature pages) +- ❌ **DO NOT edit**: AgentforceConversationClient.tsx, AgentforceConversationClient.jsx, index.tsx, index.jsx, or any files inside: + - `node_modules/@salesforce/webapp-template-feature-react-agentforce-conversation-client-experimental/src/` + - `packages/template/feature/feature-react-agentforce-conversation-client/src/` + - `src/components/AgentforceConversationClient.tsx` (patched templates) + - Any path containing `/components/AgentforceConversationClient.` + +**If you're reading a file named `AgentforceConversationClient.tsx`, you're in the wrong place. Stop and search for the USAGE instead.** + +## Invalid Props + +AgentforceConversationClient uses a flat prop API and does NOT accept these props: + +- ❌ `containerStyle` - Use `width` and `height` props directly instead +- ❌ `style` - Use `styleTokens` for theming +- ❌ `className` - Not supported +- ❌ Any standard React div props - This wraps an embedded iframe, not a div + +**Why:** The component is a wrapper around an embedded iframe using Lightning Out 2.0. Standard React styling props don't apply. + +## Invalid Styling Approaches + +**CRITICAL: For ALL styling, theming, branding, or color changes - ONLY use `styleTokens` prop.** + +Never use these approaches: + +- ❌ Creating CSS files (e.g., `agent-styles.css`, `theme.css`) +- ❌ Creating ` + + +``` + +### ✅ Correct - Using styleTokens + +```tsx + +``` + +### ❌ Wrong - Editing implementation file + +Reading or editing: `node_modules/@salesforce/webapp-template-feature-react-agentforce-conversation-client-experimental/src/AgentforceConversationClient.tsx` + +### ✅ Correct - Editing usage file + +Reading and editing: usage files where the component is imported and used (for example, `src/app.tsx`, a route component, or a feature page) diff --git a/skills/managing-webapp-agentforce-conversation-client/references/examples.md b/skills/managing-webapp-agentforce-conversation-client/references/examples.md new file mode 100644 index 0000000..e583469 --- /dev/null +++ b/skills/managing-webapp-agentforce-conversation-client/references/examples.md @@ -0,0 +1,132 @@ +# Additional Examples + +Essential examples for common patterns and combinations. All use flat props API. + +--- + +## Layout Patterns + +### Sidebar Chat + +```tsx +export default function DashboardWithChat() { + return ( +
+
{/* Main content */}
+ +
+ ); +} +``` + +### Full Page Chat + +```tsx +export default function SupportPage() { + return ( +
+

Customer Support

+ +
+ ); +} +``` + +--- + +## Size Variations + +### Responsive sizing + +```tsx + +``` + +### Calculated dimensions + +```tsx + +``` + +--- + +## Theming Combinations + +### Brand theme with custom sizing + +```tsx + +``` + +### Dark theme + +```tsx + +``` + +### Inline without header + +```tsx + +``` + +--- + +## Complete Host Component Example + +```tsx +import { Outlet } from "react-router"; +import { AgentforceConversationClient } from "@salesforce/webapp-template-feature-react-agentforce-conversation-client-experimental"; + +export default function AgentChatHost() { + return ( + <> + + + + ); +} +``` + +--- + +For complete style token reference, see `references/style-tokens.md` or `node_modules/@salesforce/agentforce-conversation-client/README.md`. diff --git a/skills/managing-webapp-agentforce-conversation-client/references/style-tokens.md b/skills/managing-webapp-agentforce-conversation-client/references/style-tokens.md new file mode 100644 index 0000000..0f0f58f --- /dev/null +++ b/skills/managing-webapp-agentforce-conversation-client/references/style-tokens.md @@ -0,0 +1,101 @@ +# Style Tokens Reference + +This document explains how to use `styleTokens` for theming and styling the AgentforceConversationClient. + +## Overview + +The `styleTokens` prop is the **ONLY** way to customize the appearance of the Agentforce conversation client. It accepts an object with style token keys and CSS values. + +## Source of Truth + +For the complete and always up-to-date list of all 60+ style tokens, see: + +**[@salesforce/agentforce-conversation-client on npm](https://www.npmjs.com/package/@salesforce/agentforce-conversation-client)** + +The npm package README contains the definitive documentation with all available style tokens. + +## Token Categories + +Style tokens are organized by UI area: + +- **Header** (7 tokens): background, text color, hover, active, focus, border, font family +- **Messages** (10 tokens): colors, padding, margins, border radius, fonts, body width +- **Inbound messages** (5 tokens): background, text color, width, alignment, hover +- **Outbound messages** (5 tokens): background, text color, width, alignment, margin +- **Input** (33 tokens): colors, borders, fonts, padding, buttons, scrollbar, textarea, actions + +## Common Use Cases + +### Change header color + +```tsx + +``` + +### Change message colors + +```tsx + +``` + +### Apply brand colors + +```tsx + +``` + +### Adjust spacing and fonts + +```tsx + +``` + +## How to Find Token Names + +1. Check the [@salesforce/agentforce-conversation-client npm package](https://www.npmjs.com/package/@salesforce/agentforce-conversation-client) for the complete list of all tokens + +2. Token names follow a pattern: + - `headerBlock*` - Header area + - `messageBlock*` - Message bubbles + - `messageBlockInbound*` - Messages from customer to agent + - `messageBlockOutbound*` - Messages from agent to customer + - `messageInput*` - Input field and send button + +## Important Notes + +- You do NOT need to provide all tokens - only override the ones you want to change +- Token values are CSS strings (e.g., `"#FF0000"`, `"16px"`, `"bold"`) +- Invalid token names are silently ignored +- The component uses default values for any tokens you don't specify diff --git a/skills/integrating-webapp-agentforce-conversation-client/docs/troubleshooting.md b/skills/managing-webapp-agentforce-conversation-client/references/troubleshooting.md similarity index 63% rename from skills/integrating-webapp-agentforce-conversation-client/docs/troubleshooting.md rename to skills/managing-webapp-agentforce-conversation-client/references/troubleshooting.md index 43fb5ac..abbae03 100644 --- a/skills/integrating-webapp-agentforce-conversation-client/docs/troubleshooting.md +++ b/skills/managing-webapp-agentforce-conversation-client/references/troubleshooting.md @@ -23,7 +23,7 @@ Common issues when using the Agentforce Conversation Client. **Solution:** 1. Confirm the id is correct (18-char Salesforce id, starts with `0Xx`). -2. Ensure the agent is Active in **Setup → Agents**. +2. Ensure the agent is Active in **Setup → Agentforce Agents**. 3. Verify the agent is deployed to the target channel. --- @@ -36,25 +36,22 @@ Common issues when using the Agentforce Conversation Client. 1. Go to **Setup → Session Settings → Trusted Domains for Inline Frames**. 2. Add `localhost:` (example: `localhost:3000`). -3. Restart the dev server. + +**Important:** + +- This setting should be **temporary for local development only**. +- **Remove `localhost:` from trusted domains after development**. +- **Recommended:** Test the Agentforce conversation client in a deployed app instead of relying on localhost trusted domains for extended periods. --- ### Blank iframe / auth session issues -**Cause:** First-party Salesforce cookie restriction is enabled. +**Possible cause:** First-party Salesforce cookie restriction may block embedded auth flow in some environments. **Solution:** 1. Go to **Setup → Session Settings**. 2. Find **Require first party use of Salesforce cookies**. -3. Disable it. +3. Disable it **only if needed and approved by your security/admin team**. 4. Save and reload. - ---- - -### Multiple chat widgets appear - -**Cause:** Component rendered more than once. - -**Solution:** Render one instance in app layout only.