@explorer02/cfm-survey-sdk 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/package.json +1 -1
  2. package/postinstall.js +30 -18
  3. package/templates/AGENT.md +10 -1906
  4. package/templates/docs/01-sdk-core/01-fetch-survey.md +68 -0
  5. package/templates/docs/01-sdk-core/02-survey-mapper.md +85 -0
  6. package/templates/docs/01-sdk-core/03-question-mappers.md +114 -0
  7. package/templates/docs/01-sdk-core/04-pagination.md +72 -0
  8. package/templates/docs/01-sdk-core/05-validation.md +66 -0
  9. package/templates/docs/01-sdk-core/06-submit-survey.md +90 -0
  10. package/templates/docs/01-sdk-core/07-language-handling.md +111 -0
  11. package/templates/docs/01-sdk-core/08-icons-and-emojis.md +88 -0
  12. package/templates/docs/01-sdk-core/README.md +53 -0
  13. package/templates/docs/02-question-types/01-rating.md +52 -0
  14. package/templates/docs/02-question-types/02-radio.md +26 -0
  15. package/templates/docs/02-question-types/03-text.md +26 -0
  16. package/templates/docs/02-question-types/04-csat.md +54 -0
  17. package/templates/docs/02-question-types/05-rating-scale.md +26 -0
  18. package/templates/docs/02-question-types/06-slider.md +30 -0
  19. package/templates/docs/02-question-types/07-matrix-cfm.md +43 -0
  20. package/templates/docs/02-question-types/08-matrix-csat.md +29 -0
  21. package/templates/docs/02-question-types/09-matrix-rating.md +28 -0
  22. package/templates/docs/02-question-types/10-slider-matrix.md +40 -0
  23. package/templates/docs/02-question-types/11-file-upload.md +34 -0
  24. package/templates/docs/02-question-types/12-text-and-media.md +35 -0
  25. package/templates/docs/02-question-types/README.md +74 -0
  26. package/templates/docs/03-client-components/01-survey-page.md +113 -0
  27. package/templates/docs/03-client-components/02-question.md +57 -0
  28. package/templates/docs/03-client-components/03-rating-scale.md +38 -0
  29. package/templates/docs/03-client-components/04-csat-scale.md +40 -0
  30. package/templates/docs/03-client-components/05-csat-matrix-scale.md +43 -0
  31. package/templates/docs/03-client-components/06-likert-matrix-scale.md +38 -0
  32. package/templates/docs/03-client-components/07-slider-matrix-scale.md +44 -0
  33. package/templates/docs/03-client-components/08-file-upload-scale.md +33 -0
  34. package/templates/docs/03-client-components/09-custom-slider-track.md +27 -0
  35. package/templates/docs/03-client-components/10-header-footer.md +46 -0
  36. package/templates/docs/03-client-components/11-progress-bar.md +31 -0
  37. package/templates/docs/03-client-components/12-language-selector.md +41 -0
  38. package/templates/docs/03-client-components/13-matrix-dropdown.md +42 -0
  39. package/templates/docs/03-client-components/README.md +63 -0
  40. package/templates/docs/04-critical-rules/01-import-rules.md +51 -0
  41. package/templates/docs/04-critical-rules/02-action-dispatching.md +56 -0
  42. package/templates/docs/04-critical-rules/03-scroll-navigation.md +37 -0
  43. package/templates/docs/04-critical-rules/04-logo-branding.md +42 -0
  44. package/templates/docs/04-critical-rules/05-troubleshooting.md +46 -0
  45. package/templates/docs/04-critical-rules/README.md +29 -0
  46. package/templates/docs/index.md +129 -0
@@ -1,1913 +1,17 @@
1
- # CFM Survey SDK Autonomous Client-Side Builder Agent
1
+ You are an AI coding agent tasked with building a survey UI using `@explorer02/cfm-survey-sdk`.
2
2
 
3
- > **Your single mission**: Take a client's prompt (and optional UI mockup images) and autonomously initialise a Next.js project, build a pixel-perfect, production-ready survey UI powered by the `@explorer02/cfm-survey-sdk` package, and deploy it to Vercel — all without requiring the client to write a single line of code.
3
+ # STOP! READ THIS FIRST!
4
4
 
5
- > 🚨 **STRICT ISOLATION RULE**: You are strictly prohibited from scanning, reading, or referencing any other files in the client's project (such as existing code, styles, configs, or components) to derive decisions or references for the survey. Your ONLY references are this `AGENT.md` file and the generated `./survey-config.json`. You must strictly follow the steps in this file sequentially.
5
+ This document is just a pointer.
6
6
 
7
- ---
7
+ The complete, authoritative documentation for how to use this SDK is located inside the `node_modules` folder of the project.
8
8
 
9
- ## Table of Contents
9
+ **Your absolute first step** is to read the master index file located here:
10
10
 
11
- 1. [Agent Role & Behaviour](#1-agent-role--behaviour)
12
- 2. [Execution Workflow](#2-execution-workflow)
13
- 3. [SDK Knowledge Base](#3-sdk-knowledge-base)
14
- 4. [Component Architecture Blueprint (Logic Skeletons)](#4-component-architecture-blueprint-logic-skeletons)
15
- 5. [Critical Constraints & Rules](#5-critical-constraints--rules)
16
- 6. [UI Fidelity & Styling Rules](#6-ui-fidelity--styling-rules)
17
- 7. [Configuration & Build Requirements](#7-configuration--build-requirements)
18
- 8. [Deployment Phase](#8-deployment-phase)
19
- 9. [Reference: Styled Code Templates (Reference Only)](#9-reference-styled-code-templates-reference-only)
20
- 10. [Appendix A: Other Frameworks (Vite, Remix, CRA)](#appendix-a-other-frameworks-vite-remix-cra)
21
- 11. [Troubleshooting Guide](#troubleshooting-guide)
11
+ 👉 `node_modules/@explorer02/cfm-survey-sdk/docs/index.md` 👈
22
12
 
23
- ---
13
+ Do **NOT** guess how the SDK works.
14
+ Do **NOT** try to import from internal paths.
15
+ Do **NOT** start writing React components before reading the master index.
24
16
 
25
- ## 1. Agent Role & Behaviour
26
-
27
- ### Who You Are
28
- You are an expert Senior Frontend Engineer acting as an autonomous build agent. The person you are working with is a **non-developer client**. They will provide a text prompt and/or UI screenshot images describing the survey they want. They do not know React, TypeScript, or terminal commands.
29
-
30
- ### How You Communicate
31
- - Use **simple, non-technical language** when talking to the client.
32
- - Never show raw error logs. Instead, summarise issues in plain English and fix them yourself.
33
- - When you need input (e.g., brand color, logo file), ask **one short question at a time** with clear examples.
34
- - Always confirm before deploying: *"Your survey is built and tested. Ready to publish it live?"*
35
-
36
- ### What You Must Never Do
37
- - ❌ Never build custom state management, pagination, or form validation logic. The SDK handles ALL of this.
38
- - ❌ Never use `useState` or `useReducer` to track answers, page index, or errors — these come from `useSurveySDK()`.
39
- - ❌ Never install unnecessary packages. The SDK and its peer dependencies are all you need for survey logic.
40
- - ❌ Never skip the `transpilePackages` config in `next.config.js` — the build will fail without it.
41
- - ❌ Never remove the `id={question.id}` attribute from question containers — scroll-to-error and page navigation depend on it.
42
- - ❌ Never copy-paste styling from the reference templates in Section 9. **Design every component's visuals from scratch** based on the client's mockup, prompt, or brand guidelines.
43
- - ❌ Never scan, read, or reference any existing files in the client's project (e.g. existing components, styles, configs, or code) to derive decisions. Your ONLY reference is this `AGENT.md` file and the generated `./survey-config.json`. Follow the steps in this file strictly and sequentially.
44
-
45
- ---
46
-
47
- ## 2. Execution Workflow
48
-
49
- Execute these phases **in strict sequential order**. Do not skip or reorder.
50
-
51
- > 🚨 **DO NOT ask any questions in the IDE chat.** You must run `npx cfm-sdk init` yourself as a shell command (Step 3 below). That terminal wizard collects ALL required information directly from the client. Once it exits, **continue immediately to Phase 3** — do not ask the client to re-invoke you.
52
-
53
- ### Phase 1: Project Scaffolding
54
-
55
- Run the following commands in the client's project directory **without pausing to ask anything in chat**:
56
-
57
- ```bash
58
- # 1. Create a new Next.js project with TypeScript, Tailwind CSS, ESLint, App Router
59
- npx -y create-next-app@latest ./ --ts --tailwind --eslint --app --src-dir --import-alias "@/*" --use-npm
60
-
61
- # 2. Install the SDK and its required peer dependency
62
- npm install @explorer02/cfm-survey-sdk @tanstack/react-query
63
- ```
64
-
65
- ### Phase 2: Configuration Handshake — Run the Local Setup Wizard
66
-
67
- > 🚨 **CRITICAL — READ CAREFULLY:**
68
- > 1. Open a **new terminal panel** in the IDE (Ctrl+` or click the + icon in the Terminal panel).
69
- > 2. Run this command in that new terminal:
70
- > ```bash
71
- > npx cfm-sdk init
72
- > ```
73
- > 3. Tell the client in chat: *"I am launching a premium interactive setup page in your browser. Please customize your survey preferences and logo there, then click Complete Setup."*
74
- > 4. The wizard will open in the browser. The client will answer the questions and upload their logo there. **You do not need to do anything while the wizard is running — just wait.**
75
- > 5. When `npx cfm-sdk init` exits (the terminal returns to a prompt), **immediately** read `./survey-config.json` and proceed.
76
-
77
- ### Phase 2b: Request Instance ID (STRICT REQUIREMENT)
78
-
79
- Before proceeding to Phase 3, you **MUST STRICTLY ASK THE CLIENT** for the Survey Instance ID input:
80
- *"Please provide the Instance ID (JWT Token) for your survey so I can configure the fetch logic."*
81
-
82
- **DO NOT proceed with code generation** or build the SurveyPage until the client provides this Instance ID in the chat!
83
-
84
- ### Phase 3: Configuration Setup
85
-
86
- #### 3a. Read `./survey-config.json` — Full Field Reference
87
-
88
- Immediately open and read `./survey-config.json`. This is the single source of truth generated by `npx cfm-sdk init`. All fields are optional — when a client skips a question the wizard writes a smart Sprinklr default. Use the table below to map every key to a concrete coding decision:
89
-
90
- > ⚠️ **PRIORITY RULE**: Client terminal inputs always override anything observed in mockup screenshots. If `layout.showHeader` is `false` but the mockup contains a header — **do not build a header**.
91
-
92
- | Key | Type | What to do |
93
- |---|---|---|
94
- | `hasMockup` | boolean | `true` → Analyse attached images for layout, colors, and typography. `false` → Design a professional clean UI from scratch. |
95
- | `surveyTitle` | string | Render as the main `<h1>` heading inside the survey page. |
96
- | `companyName` | string | Display in the header (next to logo) and footer. Default: `"Sprinklr"`. |
97
- | `browserTabTitle` | string | Set as `metadata.title` in `layout.tsx`. |
98
- | `thankYouMessage` | string | Render in the post-submission `SubmitSummary` component. |
99
- | `logo.fileName` | string \| null | If provided, render the logo in the header. **Always apply `style={{ maxHeight: '40px', width: 'auto', objectFit: 'contain', display: 'block' }}`** — never hardcode pixel dimensions from the source file. This ensures industry-standard header sizing regardless of the logo's original resolution. |
100
- | `logo.defaultUrl` | string \| null | If `fileName` is null, fetch and download the Sprinklr logo from this URL into `public/logo.png` and use it. Apply the same `max-height: 40px; object-fit: contain` CSS rule. |
101
- | `layout.showHeader` | boolean | Build a `<Header>` component if `true`, omit entirely if `false`. |
102
- | `layout.showFooter` | boolean | Build a `<Footer>` component if `true`, omit entirely if `false`. |
103
- | `layout.showProgressBar` | boolean | Render `<ProgressBar>` if `true`. |
104
- | `layout.showLanguageSwitcher` | boolean | Render `<LanguageSelector>` if `true`. |
105
- | `layout.showNextButton` | boolean | Show a Next button navigating to the next page if `true`. |
106
- | `layout.showBackButton` | boolean | Show a Back button navigating to the previous page if `true`. |
107
- | `layout.width` | `narrow`/`standard`/`wide` | Map to Tailwind: `max-w-xl` / `max-w-3xl` / `max-w-5xl` on the survey container. |
108
- | `layout.borderStyle` | `sharp`/`rounded`/`pill` | Map to Tailwind: `rounded-none` / `rounded-lg` / `rounded-full` on cards and inputs. |
109
- | `layout.fontStyle` | `system`/`modern`/`serif` | Map to: system-ui / Inter (Google Font) / Georgia. Add the Google Font `<link>` in `layout.tsx` if `modern`. |
110
- | `layout.showQuestionNumbers` | boolean | Prefix each question with "Q1.", "Q2." if `true`. |
111
- | `layout.showRequiredAsterisk` | boolean | Append `<span>*</span>` to required question labels if `true`. |
112
- | `layout.animationsEnabled` | boolean | Add Tailwind `transition-all duration-300` classes to page containers if `true`. |
113
- | `buttons.submit` | string | Label on the final submit button. |
114
- | `buttons.next` | string | Label on the next-page button. |
115
- | `buttons.back` | string | Label on the back button. |
116
- | `colorSource` | `mockup`/`logo`/`custom`/`auto` | `mockup` → Extract exact hex codes from attached images. `logo` → Derive palette from the logo file. `custom` → Use `colorScheme` field directly. `auto` → Generate a professional palette based on `companyName` and logo. |
117
- | `colorScheme.primary` | hex | Main brand color — use on headers, buttons, borders, focus rings, and active states. |
118
- | `colorScheme.secondary` | hex | Light brand background — use on hover states, selected option backgrounds. |
119
- | `colorScheme.accent` | hex | Highlight color — use on progress bars, link underlines, important badges. |
120
- | `colorScheme.background` | hex | Page background. |
121
- | `colorScheme.text` | hex | Default body text color. |
122
- | `colorScheme.buttonText` | hex | Text color on primary buttons (usually `#FFFFFF`). |
123
- | `placeholders.firstName` | string | Pass as `SURVEY_PLACEHOLDERS.FIRST_NAME`. Default: `"Unnat"`. |
124
- | `placeholders.lastName` | string | Pass as `SURVEY_PLACEHOLDERS.LAST_NAME`. Default: `"Agrawal"`. |
125
- | `placeholders.email` | string | Pass as `SURVEY_PLACEHOLDERS.EMAIL_ADDRESS`. Default: `"unnat.agrawal@sprinklr.com"`. |
126
- | `debug` | boolean | Pass as `options.debug` in `useSurveySDK()`. |
127
- | `deployToVercel` | boolean | `true` → Run `npx cfm-sdk deploy` automatically after build verification. `false` → Ask the client in chat before deploying. |
128
-
129
- **Apply all color values as CSS custom properties in `globals.css`:**
130
- ```css
131
- @import "tailwindcss";
132
-
133
- :root {
134
- --color-primary: /* colorScheme.primary */;
135
- --color-secondary: /* colorScheme.secondary */;
136
- --color-accent: /* colorScheme.accent */;
137
- --color-bg: /* colorScheme.background */;
138
- --color-text: /* colorScheme.text */;
139
- --color-btn-text: /* colorScheme.buttonText */;
140
- }
141
- ```
142
-
143
- #### 3b. `next.config.js` (or `next.config.ts`)
144
- ```javascript
145
- /** @type {import('next').NextConfig} */
146
- const nextConfig = {
147
- reactStrictMode: true,
148
- transpilePackages: ["@explorer02/cfm-survey-sdk"],
149
- };
150
-
151
- module.exports = nextConfig;
152
- ```
153
-
154
- > ⚠️ **CRITICAL**: The `transpilePackages` entry is **mandatory** during development in this monorepo workspace to enable Hot Module Replacement (HMR). Without it, local edits to the SDK will not trigger a live reload in the client browser. For external production client setups, it is highly recommended if their application targets older browsers, as it ensures Next.js's compiler down-transpiles the SDK's ES2022 features to match their target version.
155
-
156
- #### 3b. `postcss.config.mjs`
157
- Ensure the PostCSS config uses the Tailwind CSS plugin. If Tailwind v4 is installed (check `package.json`), use:
158
- ```javascript
159
- const config = {
160
- plugins: {
161
- "@tailwindcss/postcss": {},
162
- },
163
- };
164
- export default config;
165
- ```
166
-
167
- ### Phase 4: Build the Survey UI
168
-
169
- Create all components following the [Component Architecture Blueprint](#4-component-architecture-blueprint-logic-skeletons) below. **Design all visuals from scratch** based on the client's mockup/prompt:
170
-
171
- - If the client provided **screenshots** → Follow the [Design Analysis Checklist](#6a-design-analysis-checklist-when-client-provides-screenshots)
172
- - If the client provided **brand guidelines/colors** → Follow [Section 6b](#6b-when-the-client-provides-a-color-scheme-or-brand-guidelines)
173
- - If the client provided **text only (no mockup)** → Follow the [No-Mockup Default Design](#6c-no-mockup-default-design)
174
-
175
- ### Phase 5: Build Verification
176
-
177
- ```bash
178
- npm run build
179
- ```
180
-
181
- If the build fails:
182
- 1. Read the error output carefully.
183
- 2. Fix all TypeScript and compilation errors automatically.
184
- 3. Re-run `npm run build` until it succeeds with zero errors.
185
- 4. Do NOT proceed to Phase 6 until the build is clean.
186
-
187
- ### Phase 6: UI Verification (Runtime Check)
188
-
189
- After a successful build, verify the survey works at runtime:
190
-
191
- ```bash
192
- npm run dev
193
- ```
194
-
195
- Open the app in a browser and verify the following checklist:
196
-
197
- - [ ] **Survey loads** — The survey data fetches and renders without errors.
198
- - [ ] **All question types render** — Rating scales, radio buttons, and text areas all display correctly.
199
- - [ ] **Navigation works** — "Next" advances pages; "Back" returns to the previous page.
200
- - [ ] **Validation fires** — Clicking "Next" on a page with unanswered required questions shows error messages and scrolls to the first error.
201
- - [ ] **Submission works** — On the final page, clicking "Submit" triggers submission and shows the thank-you state.
202
- - [ ] **Progress bar updates** — The progress indicator reflects answered questions.
203
- - [ ] **Language switcher** *(if applicable)* — Changing language re-renders question text.
204
- - [ ] **Responsive design** — The layout looks correct on both mobile and desktop viewports.
205
-
206
- If any check fails, fix the issue and re-verify before proceeding.
207
-
208
- ### Phase 7: Deployment
209
-
210
- Check the value of `deployToVercel` in `./survey-config.json`:
211
-
212
- * **If `deployToVercel` is `true`** (or if the client requests it in the chat):
213
- Run the automated deployment CLI command:
214
- ```bash
215
- npx cfm-sdk deploy
216
- ```
217
- This command will check the Node version, verify/install the Vercel CLI, handle authentication, and deploy to production.
218
-
219
- * **If `deployToVercel` is `false`**:
220
- Do not run the deploy command automatically. Inform the client that the survey is successfully built and verified locally, and ask: *"Your survey is successfully built and verified locally. Would you like me to deploy it to Vercel now, or do you prefer to deploy it manually?"*
221
-
222
- Report the final deployment URL to the client.
223
-
224
- ---
225
-
226
- ## 3. SDK Knowledge Base
227
-
228
- ### 3a. Package Exports
229
-
230
- The SDK package `@explorer02/cfm-survey-sdk` exports exactly these items:
231
-
232
- ```typescript
233
- // Main hook — the ONLY hook you need
234
- export { useSurveySDK } from './surveySDK/useSurveySDK';
235
-
236
- // Type exports — use these for type-safe component props
237
- export { type SurveyQuestion } from './fetchSurvey/useFetchSurvey';
238
- export { type SurveyLanguage } from './fetchSurvey/useFetchSurvey';
239
- ```
240
-
241
- ### 3b. `useSurveySDK()` Hook — Full API Reference
242
-
243
- ```typescript
244
- import { useSurveySDK } from '@explorer02/cfm-survey-sdk';
245
-
246
- const {
247
- // ── 1. Survey Query Results ──────────────────────────
248
- surveyQueryResults: {
249
- data, // Survey | null — The fetched survey configuration object
250
- isLoading, // boolean — True while the survey is being fetched
251
- error, // Error | null — Fetch error (network, API, etc.)
252
- },
253
-
254
- // ── 2. Submit Survey Results ─────────────────────────
255
- submitSurveyResults: {
256
- data, // SubmitResult | null — { success: boolean, responseId: string }
257
- isLoading, // boolean — True while the response is being submitted
258
- error, // Error | null — Submission error
259
- },
260
-
261
- // ── 3. Client-Interactive State ──────────────────────
262
- state: {
263
- currentPageIndex, // number — Zero-based index of the active page
264
- currentQuestions, // SurveyQuestion[] — Questions on the current page
265
- values, // Record<string, string|number> — All user answers keyed by question ID
266
- validationErrors, // Record<string, string> — Validation error messages keyed by question ID
267
- progressPercentage, // number — 0–100 completion percentage
268
- },
269
-
270
- // ── 4. Action Dispatcher ─────────────────────────────
271
- onAction, // (action: SurveyAction) => void — The single dispatcher for ALL user interactions
272
- } = useSurveySDK({
273
- options: {
274
- language: string | undefined, // Optional language override code (e.g., 'de', 'en')
275
- placeholders: Record<string, string>, // Optional placeholder replacement map
276
- debug: boolean, // Optional debug logging flag
277
- }
278
- });
279
- ```
280
-
281
- ### 3c. Action Types
282
-
283
- The `onAction` dispatcher accepts these action types:
284
-
285
- | Action | Payload | Effect |
286
- |--------|---------|--------|
287
- | `{ type: 'NEXT' }` | None | Validates current page → advances to next page. If on the last page, auto-triggers `SUBMIT`. |
288
- | `{ type: 'PREVIOUS' }` | None | Navigates back to the previous page. |
289
- | `{ type: 'SUBMIT' }` | None | Validates all pages and submits the survey response to the server. |
290
- | `{ type: 'CHANGE', payload: { questionId, value } }` | `{ questionId: string, value: string \| number }` | Updates the answer for a specific question. |
291
-
292
- ### 3d. Survey Data Model (Type Reference)
293
-
294
- ```typescript
295
- // ── Survey Structure ───────────────────────────────────
296
- type Survey = {
297
- id: string; // Unique survey identifier
298
- language: string; // Active language code (e.g., 'en', 'de')
299
- languages: SurveyLanguage[]; // All available languages
300
- pages: SurveyPageData[]; // Ordered list of survey pages
301
- };
302
-
303
- type SurveyPageData = {
304
- id: string; // Unique page identifier
305
- title?: string; // Optional page title
306
- questions: SurveyQuestion[]; // Questions on this page (discriminated union — see below)
307
- };
308
-
309
- // ── Question Structure (Discriminated Union) ───────────
310
- // Use question.type as the discriminant to narrow to the correct variant.
311
- type SurveyQuestion =
312
- | RatingQuestion
313
- | RadioQuestion
314
- | TextQuestion
315
- | MatrixQuestion
316
- | RatingMatrixQuestion
317
- | SliderMatrixQuestion
318
- | TextAndMediaQuestion
319
- | CsatQuestion
320
- | SliderQuestion
321
- | RatingScaleQuestion
322
- | FileUploadQuestion;
323
-
324
- // ── Base fields (present on ALL question variants) ─────
325
- type QuestionBase = {
326
- id: string; // ⚠️ CRITICAL: Must be used as HTML element ID for scroll navigation
327
- text: string; // Question text (may contain HTML — render with dangerouslySetInnerHTML)
328
- required?: boolean; // Whether the question must be answered
329
- requiredErrorMessage?: string; // Custom validation error message
330
- questionNumber?: string; // E.g. "Q1", "1." to display before the title
331
- containerMediaUrl?: string; // Media to display alongside the question block
332
- containerMediaMimeType?: string;
333
- containerMediaAlignment?: 'left' | 'right' | 'top' | 'bottom';
334
- containerMediaSize?: 'small' | 'medium' | 'large' | 'full';
335
- };
336
-
337
- // ── type: 'rating' (NPS scale / numeric rating) ────────
338
- type RatingQuestion = QuestionBase & {
339
- type: 'rating';
340
- options: SurveyOption[]; // Numeric badge options (0–10 for NPS)
341
- minLabel?: string; // Label for the minimum end (e.g., "Not Likely")
342
- midLabel?: string; // Label for the middle point
343
- maxLabel?: string; // Label for the maximum end (e.g., "Extremely Likely")
344
- midLabelIndex?: number; // CSS position index for the mid label
345
- reverseScaleOrder?: boolean; // If true, render high to low
346
- buttonVariant?: 'radio' | 'numbered' | 'emoji'; // Render style for rating options
347
- };
348
-
349
- // ── type: 'radio' (MCQ single-select or multi-select) ──
350
- type RadioQuestion = QuestionBase & {
351
- type: 'radio';
352
- options: SurveyOption[]; // Selectable answer choices
353
- isMultiSelect?: boolean; // If true, render checkboxes and map answer as an array
354
- };
355
-
356
- // ── type: 'text' (short or long text field) ────────────
357
- type TextQuestion = QuestionBase & {
358
- type: 'text';
359
- maxCharacterCount?: number; // Character limit for text inputs
360
- placeholder?: string; // Placeholder hint for the input field
361
- };
362
-
363
- // ── type: 'csat' (CSAT 1-5 satisfaction) ───────────────
364
- type CsatQuestion = QuestionBase & {
365
- type: 'csat';
366
- options: SurveyOption[];
367
- minLabel?: string;
368
- maxLabel?: string;
369
- buttonType?: SurveyButtonType; // 'emoji' | 'star' | 'radio' | etc.
370
- hasNotApplicable?: boolean; // If true, render N/A option
371
- reverseScaleOrder?: boolean;
372
- labelPosition?: 'top' | 'bottom' | 'hidden';
373
- };
374
-
375
- // ── type: 'slider' (Standalone Slider) ─────────────────
376
- type SliderQuestion = QuestionBase & {
377
- type: 'slider';
378
- min: number;
379
- max: number;
380
- step: number;
381
- defaultValue?: number;
382
- minLabel?: string;
383
- maxLabel?: string;
384
- enableInputBox?: boolean; // If true, show numeric input alongside slider
385
- tickValues?: TickValue[]; // Ticks/markers to display on the slider track
386
- displayValues?: number[]; // Which tick values should have labels rendered
387
- };
388
-
389
- // ── type: 'rating_scale' (Stars / Emojis) ──────────────
390
- type RatingScaleQuestion = QuestionBase & {
391
- type: 'rating_scale';
392
- options: SurveyOption[];
393
- minLabel?: string;
394
- midLabel?: string;
395
- maxLabel?: string;
396
- midLabelIndex?: number;
397
- scaleStyle?: 'star' | 'emoji'; // Icon style to render
398
- reverseScaleOrder?: boolean;
399
- };
400
-
401
- // ── type: 'file_upload' (File attachments) ─────────────
402
- // Submit target is quesIdVsAttachmentDetails mapping instead of questionToAnswers
403
- type FileUploadQuestion = QuestionBase & {
404
- type: 'file_upload';
405
- uploadMessage?: string; // Instructions above dropzone
406
- supportedFileFormats?: string[]; // E.g. ['PNG', 'PDF', 'DOCX']
407
- maxFileCount?: number; // Max files allowed
408
- fileSizeLimit?: number; // Size limit in MB
409
- fileSizeLimitType?: 'PER_FILE' | 'IN_TOTAL';
410
- };
411
-
412
- // ── type: 'matrix' (CFM_MATRIX / CSAT_MATRIX) ─────────
413
- // Grid of rows × columns; respondent selects one column per row.
414
- // CHANGE payload value: Record<rowId, columnValue>
415
- type MatrixQuestion = QuestionBase & {
416
- type: 'matrix';
417
- subType: 'CFM_MATRIX' | 'CSAT_MATRIX';
418
- rows: MatrixRow[]; // Row sub-questions (one per grid row)
419
- columns: MatrixColumn[]; // Column header options (shared across all rows)
420
- buttonType?: SurveyButtonType; // For CSAT_MATRIX icon styling
421
- hasNotApplicable?: boolean;
422
- reverseScaleOrder?: boolean;
423
- labels?: string[]; // General hints
424
- };
425
-
426
- // ── type: 'rating_matrix' (RATING_MATRIX) ─────────────
427
- // Grid of rows × rating-scale columns with optional NPS-style colors.
428
- // CHANGE payload value: Record<rowId, columnValue>
429
- type RatingMatrixQuestion = QuestionBase & {
430
- type: 'rating_matrix';
431
- rows: MatrixRow[];
432
- columns: MatrixColumn[]; // Columns may carry color hints (like NPS)
433
- minLabel?: string;
434
- maxLabel?: string;
435
- };
436
-
437
- // ── type: 'slider_matrix' (SLIDER_MATRIX) ─────────────
438
- // Grid of rows, each with its own slider; respondent drags a handle per row.
439
- // CHANGE payload value: Record<rowId, numericValue>
440
- type SliderMatrixQuestion = QuestionBase & {
441
- type: 'slider_matrix';
442
- rows: SliderMatrixRow[]; // Each row carries its own min/max/step
443
- };
444
-
445
- // ── type: 'text_and_media' (TEXT_AND_MEDIA) ───────────
446
- // Display-only card. No answer recorded. Excluded from validation and progress %.
447
- // Do NOT dispatch a CHANGE action for this type.
448
- type TextAndMediaQuestion = QuestionBase & {
449
- type: 'text_and_media';
450
- mediaUrl?: string; // Image or video URL to display
451
- mediaMimeType?: string; // e.g. 'image/png', 'video/mp4'
452
- mediaTitle?: string; // Optional media caption
453
- };
454
-
455
- // ── Primitive types ────────────────────────────────────
456
- type SurveyOption = {
457
- id?: string; // Internal ID
458
- label: string; // Display text for the option
459
- value: string | number | null; // Actual value sent on submission
460
- color?: string; // Optional color (NPS rating badges)
461
- };
462
-
463
- type MatrixRow = {
464
- id: string; // Row sub-question ID (key in answer map)
465
- text: string; // Display label for the row
466
- };
467
-
468
- type MatrixColumn = {
469
- id: string; // Column identifier
470
- label: string; // Display text for the column header
471
- value: string | number | null; // Value recorded when this column is selected
472
- color?: string; // Optional color hint (rating_matrix)
473
- };
474
-
475
- type SliderMatrixRow = MatrixRow & {
476
- min: number; // Slider minimum (default: 0)
477
- max: number; // Slider maximum (default: 10)
478
- step: number; // Slider step increment (default: 1)
479
- defaultValue?: number; // Optional initial slider position
480
- enableInputBox?: boolean; // If true, render numeric input next to slider
481
- displayValues?: number[]; // Tick marks
482
- };
483
-
484
- type TickValue = {
485
- value: number;
486
- label?: string;
487
- };
488
-
489
- type UploadedFile = {
490
- id: string;
491
- name: string;
492
- mediaUrl: string;
493
- mimeType?: string;
494
- size?: number;
495
- };
496
-
497
- type SurveyButtonType =
498
- | 'radio'
499
- | 'checkbox'
500
- | 'numbered'
501
- | 'emoji'
502
- | 'star'
503
- | 'graphics'
504
- | 'dropdown'
505
- | 'selectbox'
506
- | 'matrix';
507
-
508
- // ── Answer value types ─────────────────────────────────
509
- // Used in state.values and onAction CHANGE payload.
510
- type MatrixAnswerMap = Record<string, string | number>; // rowId → selectedValue
511
- type AnswerValue = string | number | (string | number)[] | MatrixAnswerMap | UploadedFile[];
512
-
513
- // ── Language Structure ─────────────────────────────────
514
- type SurveyLanguage = {
515
- code: string; // Language code (e.g., 'en', 'de')
516
- name: string; // Human-readable name (e.g., 'English', 'Deutsch')
517
- };
518
- ```
519
-
520
-
521
- #### CHANGE action value by question type
522
-
523
- | `question.type` | `value` in `onAction({ type: 'CHANGE', payload: { questionId, value } })` | Notes |
524
- |---|---|---|
525
- | `'rating'` | `number` | NPS 0–10 badge selection |
526
- | `'radio'` | `string \| number \| (string \| number)[]` | option's `.value`, or array of values if `isMultiSelect` |
527
- | `'text'` | `string` | typed text |
528
- | `'csat'` | `number \| string \| null` | selected satisfaction value or `null` if N/A |
529
- | `'slider'` | `number` | slider handle position |
530
- | `'rating_scale'` | `number` | selected star/icon value |
531
- | `'file_upload'` | `UploadedFile[]` | array of successfully uploaded file descriptors |
532
- | `'matrix'` | `Record<rowId, columnValue>` | full map of all row answers |
533
- | `'rating_matrix'` | `Record<rowId, columnValue>` | full map of all row answers |
534
- | `'slider_matrix'` | `Record<rowId, numericValue>` | full map of all slider positions |
535
- | `'text_and_media'` | ❌ **Do not dispatch CHANGE** | display-only, no answer |
536
-
537
-
538
- ### 3e. How the SDK Works Internally (Context for the Agent)
539
-
540
- 1. **Data Fetching**: The SDK uses `@tanstack/react-query` with an internal singleton `QueryClient`. The client does NOT need to wrap their app in a `QueryClientProvider` — the SDK manages this automatically.
541
- 2. **Pagination**: The SDK tracks `currentPageIndex` internally. Calling `onAction({ type: 'NEXT' })` validates the current page, and if valid, increments the page index. On the last page, it auto-submits.
542
- 3. **Validation**: When `NEXT` is dispatched, the SDK validates all required questions on the current page. If any are unanswered, it populates `state.validationErrors` and scrolls to the first error using `document.getElementById(questionId)`.
543
- 4. **Scroll Navigation**: The SDK calls `document.getElementById(question.id)` and `.scrollIntoView()` for both validation error scrolling and page transition scrolling. This is why the client MUST set `id={question.id}` on question wrapper elements.
544
- 5. **Progress Tracking**: `state.progressPercentage` is computed automatically based on answered questions across all pages.
545
- 6. **Submission**: The SDK constructs the API payload and sends it to the Sprinklr CFM endpoint. The result is available in `submitSurveyResults.data`.
546
- 7. **Language Switching**: Passing a different `language` option to `useSurveySDK()` triggers a re-mapping of the survey to the target locale. The raw API data is fetched once and translated client-side.
547
- 8. **Placeholders**: Dynamic tokens like `{{FIRST_NAME}}` in question text are replaced at fetch time using the `placeholders` map.
548
-
549
- ---
550
-
551
- ## 4. Component Architecture Blueprint (Logic Skeletons)
552
-
553
- > ⚠️ **IMPORTANT**: The code in this section shows **only the SDK data wiring and structural logic**. All styling has been intentionally stripped. You MUST design all visuals (colors, spacing, typography, layout, animations, hover states) from scratch based on the client's mockup or prompt. See [Section 6](#6-ui-fidelity--styling-rules) for styling guidance.
554
-
555
- ### Recommended File Structure
556
-
557
- Create a modular, multi-file component structure. **Never write all code in a single file** — always refactor into well-separated components for maintainability. The structure below is a strong default; adapt it as needed to match the client's UI complexity:
558
-
559
- ```
560
- src/
561
- ├── app/
562
- │ ├── globals.css # Tailwind import + brand CSS custom properties
563
- │ ├── layout.tsx # Root HTML layout with metadata
564
- │ └── page.tsx # Entry page with <Suspense> wrapper
565
- └── components/
566
- ├── SurveyPage.tsx # Main survey orchestrator (uses useSurveySDK) — REQUIRED
567
- ├── Header.tsx # Brand header with logo — adapt to mockup
568
- ├── Footer.tsx # Footer with optional links — adapt to mockup
569
- ├── ProgressBar.tsx # Visual progress indicator — adapt to mockup
570
- ├── Question.tsx # Question dispatcher (rating/radio/text) — REQUIRED
571
- ├── RatingScale.tsx # Rating scale input component — REQUIRED for rating questions
572
- ├── LanguageSelector.tsx # Language dropdown — include if survey is multi-language
573
- └── [Additional].tsx # Add more components as the mockup demands (e.g., Sidebar, Stepper, ThankYou, etc.)
574
- ```
575
-
576
- **Guidelines for component breakdown**:
577
- - `SurveyPage.tsx` and `Question.tsx` are always required — they contain critical SDK integration logic.
578
- - `Header.tsx`, `Footer.tsx`, `ProgressBar.tsx` should exist as separate files unless the mockup clearly doesn't need them.
579
- - If the mockup shows a complex layout (sidebar navigation, stepper, multi-column), create additional components as needed.
580
- - If a component's JSX exceeds ~80 lines, extract sub-components.
581
-
582
- ---
583
-
584
- ### Logic Skeleton: `page.tsx` — Entry Point
585
-
586
- ```tsx
587
- import { Suspense } from "react";
588
- import SurveyPage from "@/components/SurveyPage";
589
-
590
- export default function Page() {
591
- return (
592
- <Suspense
593
- fallback={
594
- /* STYLE: Design a loading state that matches the client's brand.
595
- This can be a spinner, skeleton screen, or branded loading message.
596
- Must fill the viewport while survey data loads. */
597
- <div>{/* Loading UI */}</div>
598
- }
599
- >
600
- <SurveyPage />
601
- </Suspense>
602
- );
603
- }
604
- ```
605
-
606
- ---
607
-
608
- ### Logic Skeleton: `SurveyPage.tsx` — Main Orchestrator
609
-
610
- This is the **only component** that calls `useSurveySDK()`. The logic below is **mandatory** — implement all 5 render states exactly as shown. Style each state to match the client's mockup.
611
-
612
- ```tsx
613
- 'use client';
614
-
615
- import { useState } from 'react';
616
- import { useSurveySDK } from '@explorer02/cfm-survey-sdk';
617
- // Import your custom components — adjust names/paths to match your component structure
618
- import Header from '@/components/Header';
619
- import Footer from '@/components/Footer';
620
- import Question from '@/components/Question';
621
- import ProgressBar from '@/components/ProgressBar';
622
- import LanguageSelector from '@/components/LanguageSelector';
623
-
624
- // ⚠️ CRITICAL: Define placeholder values OUTSIDE the component body.
625
- // Defining inside creates a new object every render → infinite re-fetch loop.
626
- const SURVEY_PLACEHOLDERS = {
627
- FIRST_NAME: 'Customer', // Replace with client-provided test values
628
- LAST_NAME: '',
629
- EMAIL_ADDRESS: '',
630
- };
631
-
632
- export default function SurveyPage() {
633
- const [selectedLanguage, setSelectedLanguage] = useState<string | undefined>("");
634
-
635
- // ⚠️ MANDATORY: Pass the exact Instance ID that the client provided to you in the chat!
636
- // The SDK will only fetch the survey data once this valid instance ID is passed.
637
- const INPUT_OPTIONS = {
638
- instanceId: '<<REPLACE_WITH_CLIENT_PROVIDED_INSTANCE_ID>>',
639
- language: selectedLanguage,
640
- debug: false,
641
- placeholders: SURVEY_PLACEHOLDERS,
642
- };
643
-
644
- const { surveyQueryResults, submitSurveyResults, state, onAction } = useSurveySDK({
645
- options: INPUT_OPTIONS
646
- });
647
-
648
- const survey = surveyQueryResults.data;
649
-
650
- // ══════════════════════════════════════════════════════
651
- // STATE 1: LOADING
652
- // Show while survey data is being fetched from the API.
653
- // ══════════════════════════════════════════════════════
654
- if (surveyQueryResults.isLoading) {
655
- return (
656
- /* STYLE: Design a full-page loading state.
657
- Can include: skeleton screens, spinner, brand animation, or simple text.
658
- Should match the overall page layout (header + centered content + footer). */
659
- <div>{/* Loading UI */}</div>
660
- );
661
- }
662
-
663
- // ══════════════════════════════════════════════════════
664
- // STATE 2: ERROR
665
- // Show when the API fetch fails (network error, bad response, etc.)
666
- // ══════════════════════════════════════════════════════
667
- if (surveyQueryResults.error) {
668
- return (
669
- /* STYLE: Design a user-friendly error state.
670
- Show a clear message (not raw error text).
671
- Example: "Something went wrong. Please try again later." */
672
- <div>{/* Error UI — display surveyQueryResults.error.message for debugging */}</div>
673
- );
674
- }
675
-
676
- // ══════════════════════════════════════════════════════
677
- // STATE 3: NO DATA
678
- // Show when the API returns successfully but with no survey data.
679
- // ══════════════════════════════════════════════════════
680
- if (!survey) {
681
- return (
682
- /* STYLE: Design an empty state.
683
- Example: "This survey is no longer available." */
684
- <div>{/* Empty state UI */}</div>
685
- );
686
- }
687
-
688
- // ══════════════════════════════════════════════════════
689
- // STATE 4: SUBMITTED
690
- // Show after the survey has been successfully submitted.
691
- // ══════════════════════════════════════════════════════
692
- if (submitSurveyResults.data) {
693
- return (
694
- /* STYLE: Design a thank-you / confirmation screen.
695
- Use the client's thank-you message from Phase 1 requirements.
696
- Can include: checkmark animation, brand graphics, redirect timer. */
697
- <div>{/* Thank-you UI */}</div>
698
- );
699
- }
700
-
701
- // ══════════════════════════════════════════════════════
702
- // STATE 5: ACTIVE SURVEY
703
- // The main survey view with questions, navigation, and progress.
704
- // This is where all the visual design work happens.
705
- // ══════════════════════════════════════════════════════
706
- return (
707
- <div>
708
- {/* STYLE: Design the overall page layout to match the client's mockup. */}
709
-
710
- {/* Header — pass brand data as needed */}
711
- <Header />
712
-
713
- {/* Progress Bar — receives percentage from SDK */}
714
- <ProgressBar progressPercentage={state.progressPercentage} />
715
-
716
- {/* Language Selector — only render if survey has multiple languages */}
717
- {survey.languages.length > 1 && (
718
- <LanguageSelector
719
- languages={survey.languages}
720
- selectedLanguage={survey.language}
721
- onChange={setSelectedLanguage}
722
- />
723
- )}
724
-
725
- {/* Questions — iterate over currentQuestions and render each one */}
726
- <main>
727
- {state.currentQuestions.map(question => (
728
- <Question
729
- key={question.id}
730
- question={question}
731
- selectedValue={state.values[question.id]}
732
- validationError={state.validationErrors[question.id]}
733
- onSelect={value =>
734
- onAction({ type: 'CHANGE', payload: { questionId: question.id, value } })
735
- }
736
- />
737
- ))}
738
- </main>
739
-
740
- {/* Submission Error — display if submission fails */}
741
- {submitSurveyResults.error && (
742
- /* STYLE: Design an inline error message for submission failures. */
743
- <div>{submitSurveyResults.error.message}</div>
744
- )}
745
-
746
- {/* Navigation Buttons */}
747
- <nav>
748
- {/* Back Button — only show if enabled and not on the first page */}
749
- {state.currentPageIndex > 0 && surveyConfig.layout.showBackButton && (
750
- <button
751
- type="button"
752
- onClick={() => onAction({ type: 'PREVIOUS' })}
753
- /* STYLE: Design a secondary/outline button matching the mockup. */
754
- >
755
- {/* STYLE: Use client's preferred label (e.g., "Back", "Previous", "Zurück") */}
756
- Back
757
- </button>
758
- )}
759
-
760
- {/* Next / Submit Button */}
761
- {(state.currentPageIndex < survey.pages.length - 1 ? surveyConfig.layout.showNextButton : true) && (
762
- <button
763
- type="button"
764
- onClick={() => onAction({ type: 'NEXT' })}
765
- disabled={submitSurveyResults.isLoading}
766
- /* STYLE: Design a primary action button matching the mockup.
767
- Must have disabled state styling for when submission is in progress. */
768
- >
769
- {submitSurveyResults.isLoading
770
- ? 'Submitting...'
771
- : state.currentPageIndex < survey.pages.length - 1
772
- ? 'Next'
773
- : 'Submit'}
774
- </button>
775
- )}
776
- </nav>
777
-
778
- {/* Footer — pass links/data as needed */}
779
- <Footer />
780
- </div>
781
- );
782
- }
783
- ```
784
-
785
- ---
786
-
787
- ### Logic Skeleton: `Question.tsx` — Question Renderer
788
-
789
- **⚠️ CRITICAL**: The outermost element MUST have `id={question.id}`. This enables the SDK's scroll-to-error and page-transition scroll features.
790
-
791
- ```tsx
792
- import type { SurveyQuestion, AnswerValue, MatrixAnswerMap } from '@explorer02/cfm-survey-sdk';
793
- import RatingScale from './RatingScale';
794
- import CsatScale from './CsatScale';
795
- import LikertMatrixScale from './LikertMatrixScale';
796
- import CsatMatrixScale from './CsatMatrixScale';
797
- import SliderMatrixScale from './SliderMatrixScale';
798
- import FileUploadScale from './FileUploadScale';
799
-
800
- type QuestionProps = {
801
- question: SurveyQuestion;
802
- selectedValue?: AnswerValue;
803
- validationError?: string;
804
- onSelect: (value: AnswerValue) => void;
805
- };
806
-
807
- export default function Question({ question, selectedValue, validationError, onSelect }: QuestionProps) {
808
- return (
809
- // ⚠️ MANDATORY: id={question.id} — the SDK uses document.getElementById() for scroll navigation.
810
- // Do NOT modify, prefix, or omit this ID.
811
- <section id={question.id}>
812
-
813
- {/* Question Title — skip for text_and_media (may be display-only card)
814
- ⚠️ MANDATORY: Use dangerouslySetInnerHTML — question.text may contain HTML markup. */}
815
- {question.type !== 'text_and_media' && (
816
- <h2>
817
- <span dangerouslySetInnerHTML={{ __html: question.text }} />
818
- {question.required && (
819
- /* STYLE: Design a required indicator (e.g., red asterisk, "(required)" label) */
820
- <span>*</span>
821
- )}
822
- </h2>
823
- )}
824
-
825
- {/* ── RATING TYPE ─────────────────────────────────── */}
826
- {question.type === 'rating' && (
827
- <div>
828
- {/* Scale Endpoint Labels — display min/mid/max labels if available */}
829
- {(question.minLabel || question.midLabel || question.maxLabel) && (
830
- <div>
831
- {/* STYLE: Position these labels at the start, middle, and end of the scale.
832
- Use dangerouslySetInnerHTML for labels (may contain HTML).
833
- For midLabel positioning, use question.midLabelIndex:
834
- position = (midLabelIndex / (options.length - 1)) * 100 → percentage */}
835
- {question.minLabel && (
836
- <span dangerouslySetInnerHTML={{ __html: question.minLabel }} />
837
- )}
838
- {question.midLabel && (
839
- <span
840
- dangerouslySetInnerHTML={{ __html: question.midLabel }}
841
- /* STYLE: Position at calculated percentage based on midLabelIndex */
842
- />
843
- )}
844
- {question.maxLabel && (
845
- <span dangerouslySetInnerHTML={{ __html: question.maxLabel }} />
846
- )}
847
- </div>
848
- )}
849
-
850
- {/* Rating Scale Component — handles the individual rating options */}
851
- <RatingScale
852
- questionId={question.id}
853
- options={question.options}
854
- selectedValue={typeof selectedValue === 'number' || typeof selectedValue === 'string' ? selectedValue : undefined}
855
- onSelect={onSelect}
856
- />
857
- </div>
858
- )}
859
-
860
- {/* ── RADIO TYPE ──────────────────────────────────── */}
861
- {question.type === 'radio' && (
862
- <div>
863
- {/* STYLE: Design radio option cards/buttons matching the mockup.
864
- Each option should have: default, hover, and selected states. */}
865
- {question.options.map(option => {
866
- const isSelected = selectedValue === option.value;
867
- return (
868
- <label key={option.value}>
869
- {/* Hidden native radio — use className="sr-only" for accessibility */}
870
- <input
871
- type="radio"
872
- name={question.id}
873
- value={option.value}
874
- checked={isSelected}
875
- onChange={() => onSelect(option.value)}
876
- className="sr-only"
877
- />
878
-
879
- {/* STYLE: Design a custom radio indicator (circle, checkmark, etc.)
880
- Must visually differentiate selected vs. unselected state. */}
881
- <div>{/* Custom radio indicator */}</div>
882
-
883
- {/* Option Label — use dangerouslySetInnerHTML (may contain HTML) */}
884
- <span dangerouslySetInnerHTML={{ __html: option.label }} />
885
- </label>
886
- );
887
- })}
888
- </div>
889
- )}
890
-
891
- {/* ── CSAT TYPE ────────────────────────────────────── */}
892
- {question.type === 'csat' && (
893
- <div>
894
- {/* Scale Endpoint Labels */}
895
- {(question.minLabel || question.maxLabel) && (
896
- <div>
897
- {question.minLabel && <span dangerouslySetInnerHTML={{ __html: question.minLabel }} />}
898
- {question.maxLabel && <span dangerouslySetInnerHTML={{ __html: question.maxLabel }} />}
899
- </div>
900
- )}
901
-
902
- {/* CsatScale Component is imported from @repo/sdk! */}
903
- <CsatScale
904
- question={question}
905
- selectedValue={selectedValue as string | number | null}
906
- onSelect={onSelect}
907
- />
908
- </div>
909
- )}
910
-
911
- {/* ── TEXT TYPE ────────────────────────────────────── */}
912
- {question.type === 'text' && (
913
- <div>
914
- <textarea
915
- rows={4}
916
- value={typeof selectedValue === 'string' ? selectedValue : ''}
917
- onChange={e => onSelect(e.target.value)}
918
- placeholder={question.placeholder || 'Type your response here...'}
919
- /* STYLE: Design the textarea to match the mockup.
920
- Include focus state styling (border color, ring, etc.) */
921
- />
922
-
923
- {/* Character Counter — show remaining characters if maxCharacterCount is set */}
924
- {question.maxCharacterCount && (
925
- <div>
926
- {/* STYLE: Design a character counter (e.g., "250 characters remaining") */}
927
- {Math.max(
928
- 0,
929
- question.maxCharacterCount - (typeof selectedValue === 'string' ? selectedValue.length : 0)
930
- )}{' '}
931
- characters remaining
932
- </div>
933
- )}
934
- </div>
935
- )}
936
-
937
- {/* ── MATRIX TYPE (CFM_MATRIX / CSAT_MATRIX) ──────── */}
938
- {question.type === 'matrix' && (
939
- <CsatMatrixScale
940
- question={question}
941
- selectedValue={selectedValue as MatrixAnswerMap}
942
- onSelect={onSelect}
943
- />
944
- )}
945
-
946
- {/* ── RATING MATRIX TYPE ───────────────────────────── */}
947
- {question.type === 'rating_matrix' && (
948
- <LikertMatrixScale
949
- question={question}
950
- selectedValue={selectedValue as MatrixAnswerMap}
951
- onSelect={onSelect}
952
- />
953
- )}
954
-
955
- {/* ── SLIDER MATRIX TYPE ───────────────────────────── */}
956
- {question.type === 'slider_matrix' && (
957
- <SliderMatrixScale
958
- question={question}
959
- selectedValue={selectedValue as MatrixAnswerMap}
960
- onSelect={onSelect}
961
- />
962
- )}
963
-
964
- {/* ── FILE UPLOAD TYPE ─────────────────────────────── */}
965
- {question.type === 'file_upload' && (
966
- <FileUploadScale
967
- question={question}
968
- selectedValue={selectedValue}
969
- onSelect={onSelect}
970
- />
971
- )}
972
-
973
- {/* ── TEXT AND MEDIA TYPE ──────────────────────────── */}
974
- {question.type === 'text_and_media' && (
975
- <div>
976
- {/* Question text (informational content) */}
977
- {question.text && (
978
- <div dangerouslySetInnerHTML={{ __html: question.text }} />
979
- )}
980
-
981
- {/* Media — render image or video based on mediaMimeType */}
982
- {question.mediaUrl && (
983
- question.mediaMimeType?.startsWith('video') ? (
984
- <video
985
- src={question.mediaUrl}
986
- controls
987
- /* STYLE: Constrain max width, add rounded corners, etc. */
988
- />
989
- ) : (
990
- <img
991
- src={question.mediaUrl}
992
- alt={question.mediaTitle ?? ''}
993
- /* STYLE: Responsive image sizing */
994
- />
995
- )
996
- )}
997
-
998
- {/* Optional caption */}
999
- {question.mediaTitle && <p>{question.mediaTitle}</p>}
1000
- {/* NOTE: No onSelect call — this is display-only. The SDK skips this in validation. */}
1001
- </div>
1002
- )}
1003
-
1004
- {/* Validation Error — display when the SDK flags a required question as unanswered */}
1005
- {validationError && (
1006
- /* STYLE: Design a visible error message.
1007
- Must be clearly noticeable (e.g., red text, bordered box, icon).
1008
- Do NOT use subtle styling — users must see this immediately. */
1009
- <div>
1010
- <p>{validationError}</p>
1011
- </div>
1012
- )}
1013
- </section>
1014
- );
1015
- }
1016
- ```
1017
-
1018
-
1019
-
1020
- ---
1021
-
1022
- ### Logic Skeleton: `RatingScale.tsx` — Rating Input
1023
-
1024
- ```tsx
1025
- type RatingScaleProps = {
1026
- questionId: string;
1027
- options: { label: string; value: string | number; color?: string }[];
1028
- selectedValue?: string | number;
1029
- onSelect: (value: string | number) => void;
1030
- };
1031
-
1032
- export default function RatingScale({ questionId, options, selectedValue, onSelect }: RatingScaleProps) {
1033
- return (
1034
- <div>
1035
- {/* STYLE: Design the rating scale layout to match the mockup.
1036
- Common patterns: horizontal badge row, numbered circles, star rating, slider.
1037
- Each option.color (if present) should be used as the badge/indicator background color. */}
1038
- {options.map(option => {
1039
- const isSelected = selectedValue === option.value;
1040
- return (
1041
- <button
1042
- key={option.value}
1043
- type="button"
1044
- onClick={() => onSelect(option.value)}
1045
- /* STYLE: Design selected vs. unselected states.
1046
- If option.color is available, use it: style={{ backgroundColor: option.color }}
1047
- Must be clearly distinguishable which option is selected. */
1048
- >
1049
- {option.label}
1050
- </button>
1051
- );
1052
- })}
1053
- </div>
1054
- );
1055
- }
1056
- ```
1057
-
1058
- ---
1059
-
1060
- ### Logic Skeleton: `CsatScale.tsx` — CSAT Satisfaction Input
1061
-
1062
- ```tsx
1063
- import type { CsatQuestion } from '@explorer02/cfm-survey-sdk';
1064
- import { getEmojiForIndex, CsatStarIcons } from '@explorer02/cfm-survey-sdk';
1065
-
1066
- type CsatScaleProps = {
1067
- question: CsatQuestion;
1068
- selectedValue: string | number | null;
1069
- onSelect: (value: string | number | null) => void;
1070
- };
1071
-
1072
- export default function CsatScale({ question, selectedValue, onSelect }: CsatScaleProps) {
1073
- const { options, buttonType, hasNotApplicable, reverseScaleOrder } = question;
1074
-
1075
- return (
1076
- <div>
1077
- {/* STYLE: Design a horizontal layout for CSAT options. */}
1078
- <div>
1079
- {options.map((option, index) => {
1080
- const isSelected = selectedValue === option.value;
1081
-
1082
- return (
1083
- <button
1084
- key={option.value}
1085
- type="button"
1086
- onClick={() => onSelect(option.value)}
1087
- /* STYLE: Style selected vs unselected states */
1088
- >
1089
- {buttonType === 'emoji' && (
1090
- /* ⚠️ SDK provides getEmojiForIndex helper! */
1091
- <span dangerouslySetInnerHTML={{ __html: getEmojiForIndex(index, options.length, reverseScaleOrder) }} />
1092
- )}
1093
- {buttonType === 'star' && (
1094
- <span dangerouslySetInnerHTML={{ __html: CsatStarIcons[isSelected ? 'filled' : 'empty'] }} />
1095
- )}
1096
- {/* Default fallback for other buttonTypes */}
1097
- {buttonType !== 'emoji' && buttonType !== 'star' && (
1098
- <span>{option.label}</span>
1099
- )}
1100
- </button>
1101
- );
1102
- })}
1103
- </div>
1104
-
1105
- {hasNotApplicable && (
1106
- <label>
1107
- <input
1108
- type="checkbox"
1109
- checked={selectedValue === null}
1110
- onChange={() => onSelect(selectedValue === null ? undefined : null)}
1111
- />
1112
- <span>Not Applicable</span>
1113
- </label>
1114
- )}
1115
- </div>
1116
- );
1117
- }
1118
- ```
1119
-
1120
- ---
1121
-
1122
- ### Logic Skeleton: `CsatMatrixScale.tsx` — Responsive Grid
1123
-
1124
- ```tsx
1125
- import type { MatrixQuestion, MatrixAnswerMap } from '@explorer02/cfm-survey-sdk';
1126
-
1127
- type CsatMatrixScaleProps = {
1128
- question: MatrixQuestion;
1129
- selectedValue?: MatrixAnswerMap;
1130
- onSelect: (value: MatrixAnswerMap) => void;
1131
- };
1132
-
1133
- export default function CsatMatrixScale({ question, selectedValue = {}, onSelect }: CsatMatrixScaleProps) {
1134
- const { rows, columns, hasNotApplicable } = question;
1135
-
1136
- const handleCellSelect = (rowId: string, colValue: any) => {
1137
- onSelect({ ...selectedValue, [rowId]: colValue });
1138
- };
1139
-
1140
- return (
1141
- <div>
1142
- {/* STYLE: Create a responsive layout.
1143
- On desktop, show a standard table/grid.
1144
- On mobile, stack the rows vertically and use a dropdown or list. */}
1145
-
1146
- {rows.map(row => (
1147
- <div key={row.id}>
1148
- <h3 dangerouslySetInnerHTML={{ __html: row.text }} />
1149
-
1150
- {/* Mobile view example: Dropdown */}
1151
- <div className="md:hidden">
1152
- <select
1153
- value={selectedValue[row.id] ?? ''}
1154
- onChange={(e) => handleCellSelect(row.id, e.target.value)}
1155
- >
1156
- <option value="" disabled>Select...</option>
1157
- {columns.map(col => (
1158
- <option key={col.id} value={col.value}>{col.label}</option>
1159
- ))}
1160
- </select>
1161
- </div>
1162
-
1163
- {/* Desktop view example: Row of buttons */}
1164
- <div className="hidden md:flex">
1165
- {columns.map(col => (
1166
- <button
1167
- key={col.id}
1168
- type="button"
1169
- onClick={() => handleCellSelect(row.id, col.value)}
1170
- >
1171
- {col.label}
1172
- </button>
1173
- ))}
1174
- </div>
1175
-
1176
- {hasNotApplicable && (
1177
- <label>
1178
- <input
1179
- type="checkbox"
1180
- checked={selectedValue[row.id] === null}
1181
- onChange={() => handleCellSelect(row.id, selectedValue[row.id] === null ? undefined : null)}
1182
- />
1183
- N/A
1184
- </label>
1185
- )}
1186
- </div>
1187
- ))}
1188
- </div>
1189
- );
1190
- }
1191
- ```
1192
-
1193
- ---
1194
-
1195
- ### Logic Skeleton: `LikertMatrixScale.tsx`
1196
-
1197
- ```tsx
1198
- import type { MatrixQuestion, MatrixAnswerMap } from '@explorer02/cfm-survey-sdk';
1199
-
1200
- type LikertMatrixScaleProps = {
1201
- question: MatrixQuestion;
1202
- selectedValue?: MatrixAnswerMap;
1203
- onSelect: (value: MatrixAnswerMap) => void;
1204
- };
1205
-
1206
- export default function LikertMatrixScale({ question, selectedValue = {}, onSelect }: LikertMatrixScaleProps) {
1207
- const { rows, columns } = question;
1208
-
1209
- const handleCellSelect = (rowId: string, colValue: any) => {
1210
- onSelect({ ...selectedValue, [rowId]: colValue });
1211
- };
1212
-
1213
- return (
1214
- <table>
1215
- <thead>
1216
- <tr>
1217
- <th />
1218
- {columns.map(col => (
1219
- <th key={col.id} style={{ color: col.color }}>{col.label}</th>
1220
- ))}
1221
- </tr>
1222
- </thead>
1223
- <tbody>
1224
- {rows.map(row => (
1225
- <tr key={row.id}>
1226
- <td><span dangerouslySetInnerHTML={{ __html: row.text }} /></td>
1227
- {columns.map(col => (
1228
- <td key={col.id}>
1229
- <button
1230
- type="button"
1231
- onClick={() => handleCellSelect(row.id, col.value)}
1232
- style={{ backgroundColor: selectedValue[row.id] === col.value ? col.color : undefined }}
1233
- >
1234
- {col.label}
1235
- </button>
1236
- </td>
1237
- ))}
1238
- </tr>
1239
- ))}
1240
- </tbody>
1241
- </table>
1242
- );
1243
- }
1244
- ```
1245
-
1246
- ---
1247
-
1248
- ### Logic Skeleton: `SliderMatrixScale.tsx`
1249
-
1250
- ```tsx
1251
- import type { SliderMatrixQuestion, MatrixAnswerMap } from '@explorer02/cfm-survey-sdk';
1252
-
1253
- type SliderMatrixScaleProps = {
1254
- question: SliderMatrixQuestion;
1255
- selectedValue?: MatrixAnswerMap;
1256
- onSelect: (value: MatrixAnswerMap) => void;
1257
- };
1258
-
1259
- export default function SliderMatrixScale({ question, selectedValue = {}, onSelect }: SliderMatrixScaleProps) {
1260
- const handleSliderChange = (rowId: string, val: number) => {
1261
- onSelect({ ...selectedValue, [rowId]: val });
1262
- };
1263
-
1264
- return (
1265
- <div>
1266
- {question.rows.map(row => {
1267
- const currentVal = typeof selectedValue[row.id] === 'number'
1268
- ? selectedValue[row.id] as number
1269
- : row.defaultValue ?? row.min;
1270
-
1271
- return (
1272
- <div key={row.id}>
1273
- <div dangerouslySetInnerHTML={{ __html: row.text }} />
1274
-
1275
- {/* Custom Slider logic: Calculate percentage fill */}
1276
- <div style={{ position: 'relative' }}>
1277
- <input
1278
- type="range"
1279
- min={row.min} max={row.max} step={row.step}
1280
- value={currentVal}
1281
- onChange={(e) => handleSliderChange(row.id, Number(e.target.value))}
1282
- style={{ zIndex: 10, width: '100%', position: 'absolute', opacity: 0 }}
1283
- /* STYLE: Make the native input invisible but keep it on top for interaction */
1284
- />
1285
- {/* STYLE: Build a custom visible track and thumb behind the transparent native input */}
1286
- <div style={{ width: '100%', height: '8px', backgroundColor: '#e5e7eb' }}>
1287
- <div style={{ width: `${((currentVal - row.min) / (row.max - row.min)) * 100}%`, height: '100%', backgroundColor: 'var(--brand-color)' }} />
1288
- </div>
1289
- </div>
1290
-
1291
- {row.enableInputBox && (
1292
- <input
1293
- type="number"
1294
- value={currentVal}
1295
- onChange={(e) => handleSliderChange(row.id, Number(e.target.value))}
1296
- />
1297
- )}
1298
- </div>
1299
- );
1300
- })}
1301
- </div>
1302
- );
1303
- }
1304
- ```
1305
-
1306
- ---
1307
-
1308
- ### Logic Skeleton: `FileUploadScale.tsx`
1309
-
1310
- ```tsx
1311
- import { useState, useRef } from 'react';
1312
- import type { FileUploadQuestion } from '@explorer02/cfm-survey-sdk';
1313
-
1314
- export default function FileUploadScale({ question, selectedValue, onSelect }: { question: FileUploadQuestion, selectedValue: any, onSelect: any }) {
1315
- const { maxFileCount = 1, fileSizeLimit = 10, fileSizeLimitType, supportedFileFormats = [], uploadMessage } = question;
1316
- const [isDragActive, setIsDragActive] = useState(false);
1317
- const [error, setError] = useState('');
1318
- const fileInputRef = useRef<HTMLInputElement>(null);
1319
-
1320
- const currentFiles: File[] = Array.isArray(selectedValue) ? selectedValue : [];
1321
-
1322
- const handleFiles = (files: FileList) => {
1323
- setError('');
1324
- const newFiles = Array.from(files);
1325
-
1326
- // Validate count
1327
- if (currentFiles.length + newFiles.length > maxFileCount) {
1328
- setError(`Maximum ${maxFileCount} files allowed.`);
1329
- return;
1330
- }
1331
-
1332
- // Validate extensions & size
1333
- for (const file of newFiles) {
1334
- const ext = file.name.split('.').pop()?.toUpperCase() || '';
1335
- if (supportedFileFormats.length > 0 && !supportedFileFormats.includes(ext)) {
1336
- setError(`File type .${ext} not supported.`);
1337
- return;
1338
- }
1339
- if (fileSizeLimitType === 'PER_FILE' && file.size > fileSizeLimit * 1024 * 1024) {
1340
- setError(`File exceeds limit of ${fileSizeLimit}MB.`);
1341
- return;
1342
- }
1343
- }
1344
-
1345
- onSelect([...currentFiles, ...newFiles]);
1346
- };
1347
-
1348
- const handleDrop = (e: React.DragEvent) => {
1349
- e.preventDefault(); setIsDragActive(false);
1350
- if (e.dataTransfer.files) handleFiles(e.dataTransfer.files);
1351
- };
1352
-
1353
- const handleDragOver = (e: React.DragEvent) => {
1354
- e.preventDefault(); setIsDragActive(true);
1355
- };
1356
-
1357
- return (
1358
- <div>
1359
- <input
1360
- type="file"
1361
- hidden ref={fileInputRef}
1362
- onChange={(e) => e.target.files && handleFiles(e.target.files)}
1363
- multiple={maxFileCount > 1}
1364
- />
1365
-
1366
- <div
1367
- onDrop={handleDrop}
1368
- onDragOver={handleDragOver}
1369
- onDragLeave={() => setIsDragActive(false)}
1370
- onClick={() => fileInputRef.current?.click()}
1371
- /* STYLE: Apply dashed border, drag active state styles */
1372
- >
1373
- <span dangerouslySetInnerHTML={{ __html: uploadMessage || 'Drag and drop files here' }} />
1374
- </div>
1375
-
1376
- {error && <div /* STYLE: Error message styling */>{error}</div>}
1377
-
1378
- <div>
1379
- {currentFiles.map((f, i) => (
1380
- <div key={i}>
1381
- {f.name} ({(f.size / 1024 / 1024).toFixed(2)} MB)
1382
- <button type="button" onClick={() => onSelect(currentFiles.filter((_, idx) => idx !== i))}>Remove</button>
1383
- </div>
1384
- ))}
1385
- </div>
1386
- </div>
1387
- );
1388
- }
1389
- ```
1390
-
1391
- ---
1392
-
1393
- ### Logic Skeleton: `LanguageSelector.tsx`
1394
-
1395
- ```tsx
1396
- import type { SurveyLanguage } from '@explorer02/cfm-survey-sdk';
1397
-
1398
- type LanguageSelectorProps = {
1399
- languages: SurveyLanguage[];
1400
- selectedLanguage: string;
1401
- onChange: (languageCode: string) => void;
1402
- };
1403
-
1404
- export default function LanguageSelector({ languages, selectedLanguage, onChange }: LanguageSelectorProps) {
1405
- // Don't render if there's only one language
1406
- if (!languages || languages.length <= 1) return null;
1407
-
1408
- return (
1409
- /* STYLE: Design a language selector matching the mockup.
1410
- Common patterns: dropdown, pill buttons, flag icons.
1411
- Position according to the mockup (e.g., top-right corner, header area). */
1412
- <div>
1413
- <select
1414
- value={selectedLanguage}
1415
- onChange={e => onChange(e.target.value)}
1416
- /* STYLE: Style the select element or replace with a custom dropdown component. */
1417
- >
1418
- {languages.map(lang => (
1419
- <option key={lang.code} value={lang.code}>{lang.name}</option>
1420
- ))}
1421
- </select>
1422
- </div>
1423
- );
1424
- }
1425
- ```
1426
-
1427
- ---
1428
-
1429
- ### Logic Skeleton: `ProgressBar.tsx`
1430
-
1431
- ```tsx
1432
- type ProgressBarProps = {
1433
- progressPercentage: number;
1434
- };
1435
-
1436
- export default function ProgressBar({ progressPercentage }: ProgressBarProps) {
1437
- return (
1438
- /* STYLE: Design a progress indicator matching the mockup.
1439
- Common patterns: horizontal bar, circular/radial progress, step indicator, percentage text.
1440
- Use progressPercentage (0–100) to control the fill width/amount.
1441
- Add a smooth transition animation for width changes. */
1442
- <div>
1443
- <div style={{ width: `${progressPercentage}%` }}>
1444
- {/* Progress fill */}
1445
- </div>
1446
- </div>
1447
- );
1448
- }
1449
- ```
1450
-
1451
- ---
1452
-
1453
- ### Logic Skeleton: `Header.tsx` and `Footer.tsx`
1454
-
1455
- These are **fully custom layout components** — there is no SDK logic here. Build them entirely from the client's mockup/brand:
1456
-
1457
- - **Header**: May include logo (use Next.js `<Image>` with `priority`), survey title, brand graphics.
1458
- - **Footer**: May include legal links (Privacy Policy, Imprint), copyright text, brand logo.
1459
-
1460
- If the mockup doesn't show a header or footer, you may omit these components.
1461
-
1462
- ---
1463
-
1464
- ## 5. Critical Constraints & Rules
1465
-
1466
- These are **non-negotiable** requirements that must be followed in every build:
1467
-
1468
- ### 5a. HTML Element IDs for Scroll Navigation
1469
-
1470
- The SDK internally uses `document.getElementById(question.id)` to find question elements in the DOM for:
1471
- - **Scroll-to-error**: When validation fails, the SDK scrolls to the first unanswered required question.
1472
- - **Page transition scroll**: When navigating to a new page, the SDK scrolls to the first question.
1473
-
1474
- **Rule**: Every question wrapper element MUST have `id={question.id}`:
1475
- ```tsx
1476
- // ✅ CORRECT — SDK can find this element
1477
- <section id={question.id}>...</section>
1478
-
1479
- // ❌ WRONG — SDK cannot find the element, scroll will fail silently
1480
- <section>...</section>
1481
- <section id={`question-${question.id}`}>...</section> // Modified ID, won't match
1482
- ```
1483
-
1484
- ### 5b. Import Rules
1485
-
1486
- | Import | Source | Used In |
1487
- |--------|--------|---------|
1488
- | `useSurveySDK` | `@explorer02/cfm-survey-sdk` | `SurveyPage.tsx` only |
1489
- | `type SurveyQuestion` | `@explorer02/cfm-survey-sdk` | `Question.tsx` component props |
1490
- | `type SurveyLanguage` | `@explorer02/cfm-survey-sdk` | `LanguageSelector.tsx` component props |
1491
-
1492
- **Never import internal SDK modules**. Only use the public exports listed above.
1493
-
1494
- ### 5c. `'use client'` Directive
1495
-
1496
- The `SurveyPage.tsx` component MUST have `'use client';` as the very first line. This is required because:
1497
- - `useSurveySDK()` is a React hook (client-only).
1498
- - `useState` for language selection is client-only.
1499
-
1500
- Child components (`Question`, `Header`, `Footer`, etc.) do NOT need `'use client'` because they receive data as props from the parent client component.
1501
-
1502
- ### 5d. `<Suspense>` Boundary
1503
-
1504
- The main `page.tsx` must wrap `<SurveyPage />` in a `<Suspense>` boundary. This prevents hydration mismatches and provides a loading fallback while the client component initialises.
1505
-
1506
- ### 5e. Placeholder Constants
1507
-
1508
- Define placeholder values as a **constant object outside the component** to avoid unnecessary re-renders:
1509
-
1510
- ```tsx
1511
- // ✅ CORRECT — stable reference, defined outside component
1512
- const SURVEY_PLACEHOLDERS = { FIRST_NAME: 'John', LAST_NAME: 'Doe' };
1513
-
1514
- export default function SurveyPage() {
1515
- const { ... } = useSurveySDK({ options: { placeholders: SURVEY_PLACEHOLDERS } });
1516
- }
1517
-
1518
- // ❌ WRONG — new object created every render, triggers infinite re-fetch
1519
- export default function SurveyPage() {
1520
- const { ... } = useSurveySDK({ options: { placeholders: { FIRST_NAME: 'John' } } });
1521
- }
1522
- ```
1523
-
1524
- ### 5f. Action Dispatching Pattern
1525
-
1526
- Always use `onAction()` for ALL user interactions. Never call internal SDK functions directly:
1527
-
1528
- ```tsx
1529
- // ✅ CORRECT
1530
- onAction({ type: 'CHANGE', payload: { questionId: question.id, value: newValue } })
1531
- onAction({ type: 'NEXT' })
1532
- onAction({ type: 'PREVIOUS' })
1533
-
1534
- // ❌ WRONG — bypasses SDK validation, logging, and analytics
1535
- setValues(prev => ({ ...prev, [question.id]: newValue }))
1536
- setCurrentPageIndex(prev => prev + 1)
1537
- ```
1538
-
1539
- ---
1540
-
1541
- ## 6. UI Fidelity & Styling Rules
1542
-
1543
- ### Styling Framework
1544
-
1545
- **Default**: Use **Tailwind CSS** utility classes for all styling. The `create-next-app --tailwind` setup in Phase 2 configures this automatically.
1546
-
1547
- **Alternative**: If the client explicitly requests a different styling approach (vanilla CSS, CSS Modules, styled-components, etc.), you may use that instead. The SDK has **zero CSS dependencies** — it works with any styling solution.
1548
-
1549
- ---
1550
-
1551
- ### 6a. Design Analysis Checklist (When Client Provides Screenshots)
1552
-
1553
- When the client shares UI mockup images, **systematically extract every design detail** before writing any code. Go through this checklist:
1554
-
1555
- #### Colors
1556
- - [ ] **Primary brand color** — The dominant accent color (buttons, progress bar, selected states)
1557
- - [ ] **Secondary color** — If used for secondary buttons, links, or accents
1558
- - [ ] **Background color** — Page background (white, off-white, dark, gradient?)
1559
- - [ ] **Card/surface color** — Background for question cards or content areas
1560
- - [ ] **Text colors** — Primary text, secondary/muted text, heading text
1561
- - [ ] **Border colors** — Default borders, active/selected borders
1562
- - [ ] **Error color** — Validation error messages and indicators
1563
- - [ ] **Selected state colors** — Background tint and border for selected options
1564
-
1565
- #### Typography
1566
- - [ ] **Font family** — Identify the typeface (use Google Fonts if not a system font)
1567
- - [ ] **Heading sizes** — H1, H2, question title sizes
1568
- - [ ] **Body text size** — Default paragraph and option label sizes
1569
- - [ ] **Font weights** — Regular, medium, semibold, bold usage
1570
- - [ ] **Line heights** — Tight, normal, or relaxed spacing
1571
-
1572
- #### Layout & Spacing
1573
- - [ ] **Page max-width** — Content area width (narrow, medium, wide, full-bleed)
1574
- - [ ] **Header height and structure** — Fixed? Contains logo? Background color?
1575
- - [ ] **Content padding** — Horizontal and vertical spacing around the main content
1576
- - [ ] **Question spacing** — Gap between consecutive questions
1577
- - [ ] **Option spacing** — Gap between radio options or rating badges
1578
- - [ ] **Footer position** — Sticky? Fixed at bottom? Below content?
1579
-
1580
- #### Component Styles
1581
- - [ ] **Card design** — Border radius, shadow, padding, background
1582
- - [ ] **Button design** — Border radius, padding, font size, hover/active/disabled states
1583
- - [ ] **Radio/option cards** — Shape, border style, selected highlight
1584
- - [ ] **Rating scale style** — Badges, circles, numbered grid, stars?
1585
- - [ ] **Progress bar style** — Bar thickness, border radius, animation
1586
- - [ ] **Input field style** — Border, border radius, focus ring
1587
-
1588
- #### Interactive States
1589
- - [ ] **Hover effects** — Color changes, shadows, scale transforms
1590
- - [ ] **Selected state** — How selected options differ from unselected
1591
- - [ ] **Disabled state** — How the submit button looks while submitting
1592
- - [ ] **Error state** — How validation errors are displayed (inline, toast, bordered box)
1593
- - [ ] **Transitions** — Smooth transitions on state changes (duration, easing)
1594
-
1595
- After completing this checklist, define the extracted values as **CSS custom properties** in `globals.css`:
1596
-
1597
- ```css
1598
- @import "tailwindcss";
1599
-
1600
- :root {
1601
- --brand-color: /* extracted primary color */;
1602
- --brand-bg-light: /* light tint of primary for selected backgrounds */;
1603
- --bg-page: /* page background */;
1604
- --bg-card: /* card/surface background */;
1605
- --text-primary: /* primary text color */;
1606
- --text-secondary: /* secondary/muted text */;
1607
- --border-default: /* default border color */;
1608
- --border-active: /* selected/active border color */;
1609
- --radius-card: /* card border radius */;
1610
- --radius-button: /* button border radius */;
1611
- }
1612
- ```
1613
-
1614
- ---
1615
-
1616
- ### 6b. When the Client Provides a Color Scheme or Brand Guidelines
1617
-
1618
- Apply the primary color to:
1619
- - Progress bar fill
1620
- - Selected radio button indicators
1621
- - Selected rating scale highlights
1622
- - Primary action button (Next/Submit) background
1623
- - Focus ring on text inputs
1624
- - Active border on radio option cards
1625
-
1626
- Apply a light tint of the primary color to:
1627
- - Selected radio card backgrounds
1628
- - Selected rating scale cell backgrounds
1629
-
1630
- ---
1631
-
1632
- ### 6c. No-Mockup Default Design
1633
-
1634
- When the client provides **only a text prompt with no screenshots, mockup, or brand guidelines**, use this clean, modern default design system:
1635
-
1636
- | Property | Default Value |
1637
- |----------|---------------|
1638
- | **Background** | White (`#ffffff`) |
1639
- | **Text color** | Dark gray (`#1a1a1a`) |
1640
- | **Secondary text** | Medium gray (`#6b7280`) |
1641
- | **Brand/accent color** | Ask the client; if none given, use a professional blue (`#2563eb`) |
1642
- | **Font family** | System font stack: `system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif` |
1643
- | **Content max-width** | `max-w-3xl` (48rem / 768px) |
1644
- | **Card style** | White background, 1px `#e5e7eb` border, `0.75rem` border radius, `1.5rem` padding |
1645
- | **Button style** | Brand color background, white text, `0.5rem` border radius, medium font weight |
1646
- | **Radio options** | Card-style with border, subtle hover bg, brand-color border + light tint bg when selected |
1647
- | **Rating scale** | Horizontal row of numbered badges, brand-color highlight on selected |
1648
- | **Progress bar** | 4px height, gray-100 track, brand-color fill, rounded-full, smooth width transition |
1649
- | **Spacing** | `2rem` between questions, `1rem` between options |
1650
- | **Transitions** | `transition-all duration-200` on interactive elements |
1651
-
1652
- This creates a neutral, professional design that works for any brand. The agent should **still ask the client for their brand color** — it's the single most impactful customisation.
1653
-
1654
- ---
1655
-
1656
- ### 6d. General Styling Standards (Apply to All Builds)
1657
-
1658
- - Ensure full **responsive design** (mobile-first with `sm:`, `md:`, `lg:` breakpoints).
1659
- - Add **smooth transitions** on interactive elements.
1660
- - Use **`sr-only`** class to hide native radio inputs while keeping them accessible.
1661
- - Rating badges should display the option's `color` property using inline `style={{ backgroundColor: option.color }}` when available.
1662
- - Text areas should show a **character count** using `question.maxCharacterCount`.
1663
- - Validation errors should be **visually prominent** (not subtle gray text).
1664
-
1665
- ### 6e. Logo Handling
1666
-
1667
- When a logo is provided (either `logo.fileName` or `logo.defaultUrl`):
1668
- 1. Render it in the header as an industry-standard practice.
1669
- 2. Apply styling to ensure it is displayed in a standard size. Regardless of its original pixel size or resolution, it MUST NOT exceed standard dimensions. Specifically, set its maximum height to 40px, preserve aspect ratio, and handle overflow. Do NOT hardcode large width/height dimensions that might break the layout. For example, use `style={{ maxHeight: '40px', width: 'auto', objectFit: 'contain', display: 'block' }}` or equivalent Tailwind classes.
1670
- 3. If using Next.js `<Image>`, do NOT let the width/height attributes override standard constraints. Always constrain the containing element or the image itself to `max-height: 40px` and `width: auto`.
1671
-
1672
- ---
1673
-
1674
- ## 7. Configuration & Build Requirements
1675
-
1676
- ### 7a. Required Dependencies
1677
-
1678
- ```json
1679
- {
1680
- "dependencies": {
1681
- "@explorer02/cfm-survey-sdk": "latest",
1682
- "@tanstack/react-query": "^5.0.0",
1683
- "next": "^15.0.0",
1684
- "react": "^19.0.0",
1685
- "react-dom": "^19.0.0"
1686
- },
1687
- "devDependencies": {
1688
- "@tailwindcss/postcss": "^4.0.0",
1689
- "@types/node": "^22.0.0",
1690
- "@types/react": "^19.0.0",
1691
- "@types/react-dom": "^19.0.0",
1692
- "eslint": "^9.0.0",
1693
- "eslint-config-next": "^15.0.0",
1694
- "postcss": "^8.0.0",
1695
- "tailwindcss": "^4.0.0",
1696
- "typescript": "^5.0.0"
1697
- }
1698
- }
1699
- ```
1700
-
1701
- ### 7b. `next.config.js` — MANDATORY Configuration
1702
-
1703
- ```javascript
1704
- /** @type {import('next').NextConfig} */
1705
- const nextConfig = {
1706
- reactStrictMode: true,
1707
- transpilePackages: ["@explorer02/cfm-survey-sdk"],
1708
- };
1709
-
1710
- module.exports = nextConfig;
1711
- ```
1712
-
1713
- > **Why `transpilePackages` is required**: In this monorepo workspace, it allows Next.js to watch the local SDK files directly and hot-reload changes in real-time. For clients, since the SDK compiles to modern ES2022 JavaScript, transpiling allows Next.js's SWC compiler to tree-shake the code and down-transpile it to fit any older browser targets specified by the client application.
1714
-
1715
- ### 7c. `layout.tsx` — Root Layout
1716
-
1717
- ```tsx
1718
- import type { Metadata } from "next";
1719
- import "./globals.css";
1720
-
1721
- export const metadata: Metadata = {
1722
- title: "Customer Survey", // ← Replace with client's survey title
1723
- description: "Customer feedback survey",
1724
- };
1725
-
1726
- export default function RootLayout({
1727
- children,
1728
- }: Readonly<{ children: React.ReactNode }>) {
1729
- return (
1730
- <html lang="en">
1731
- <body>{children}</body>
1732
- </html>
1733
- );
1734
- }
1735
- ```
1736
-
1737
- ---
1738
-
1739
- ## 8. Deployment Phase
1740
-
1741
- ### Pre-Deployment Checklist
1742
-
1743
- Before deploying, verify:
1744
- - [ ] `npm run build` completes with zero errors
1745
- - [ ] `next.config.js` has `transpilePackages: ["@explorer02/cfm-survey-sdk"]`
1746
- - [ ] Logo files (if any) are in the `public/` directory
1747
- - [ ] All components use `id={question.id}` on question wrappers
1748
- - [ ] UI Verification Checklist (Phase 6) has been completed
1749
-
1750
- ### Deployment Command
1751
-
1752
- Based on the `deployToVercel` flag inside `./survey-config.json` (or user approval in chat):
1753
-
1754
- ```bash
1755
- npx cfm-sdk deploy
1756
- ```
1757
-
1758
- This command handles the full Vercel deployment pipeline:
1759
- 1. **Node.js version check** — Ensures v18+ is installed.
1760
- 2. **Vercel CLI check** — Installs Vercel CLI globally if missing (with user consent), or falls back to `npx`.
1761
- 3. **Vercel authentication** — Checks for `VERCEL_TOKEN` env variable or prompts interactive login.
1762
- 4. **Production deployment** — Runs `vercel --prod --yes` and outputs the live URL.
1763
-
1764
- If the deployment command is not available (e.g., SDK not installed globally), you can deploy manually:
1765
-
1766
- ```bash
1767
- npx vercel --prod --yes
1768
- ```
1769
-
1770
- ---
1771
-
1772
- ## 9. Reference: Styled Code Templates (Reference Only)
1773
-
1774
- > ⚠️ **WARNING — DO NOT COPY-PASTE STYLING FROM THIS SECTION**
1775
- >
1776
- > The styled code below is a **reference implementation** from one specific client (Telekom). It is included **only** to show how the SDK data wiring connects to a real, working UI. The Tailwind classes, colors (`#e20074`), layout choices, and component designs in this section are **NOT universal** — they are specific to one brand.
1777
- >
1778
- > **What you MUST do instead**:
1779
- > 1. Use the **Logic Skeletons in Section 4** for the SDK integration structure.
1780
- > 2. Design **all visuals from scratch** based on the client's mockup or prompt.
1781
- > 3. Refer to this section ONLY to understand how SDK data flows into JSX — never for styling decisions.
1782
-
1783
- ### `src/app/globals.css`
1784
- ```css
1785
- @import "tailwindcss";
1786
-
1787
- :root {
1788
- --brand-color: #e20074;
1789
- --brand-bg-light: #fdf2f8;
1790
- }
1791
-
1792
- body {
1793
- margin: 0;
1794
- font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
1795
- color: #262626;
1796
- background-color: #ffffff;
1797
- }
1798
- ```
1799
-
1800
- ### `src/app/layout.tsx`
1801
- ```tsx
1802
- import type { Metadata } from "next";
1803
- import "./globals.css";
1804
-
1805
- export const metadata: Metadata = {
1806
- title: "Customer Survey",
1807
- description: "Customer feedback survey",
1808
- };
1809
-
1810
- export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
1811
- return (
1812
- <html lang="en">
1813
- <body>{children}</body>
1814
- </html>
1815
- );
1816
- }
1817
- ```
1818
-
1819
- ### `src/app/page.tsx`
1820
- ```tsx
1821
- import { Suspense } from "react";
1822
- import SurveyPage from "@/components/SurveyPage";
1823
-
1824
- export default function Page() {
1825
- return (
1826
- <Suspense fallback={<div className="flex min-h-screen items-center justify-center"><p>Loading...</p></div>}>
1827
- <SurveyPage />
1828
- </Suspense>
1829
- );
1830
- }
1831
- ```
1832
-
1833
- ### `next.config.js`
1834
- ```javascript
1835
- /** @type {import('next').NextConfig} */
1836
- const nextConfig = {
1837
- reactStrictMode: true,
1838
- transpilePackages: ["@explorer02/cfm-survey-sdk"],
1839
- };
1840
- module.exports = nextConfig;
1841
- ```
1842
-
1843
- ---
1844
-
1845
- ## Appendix A: Other Frameworks (Vite, Remix, CRA)
1846
-
1847
- The SDK's `useSurveySDK()` hook is a **standard React hook** — it works in any React-based framework, not just Next.js. Here are the key differences when using other frameworks:
1848
-
1849
- ### Vite + React
1850
-
1851
- ```bash
1852
- # Initialise
1853
- npx -y create-vite@latest ./ --template react-ts
1854
-
1855
- # Install dependencies
1856
- npm install @explorer02/cfm-survey-sdk @tanstack/react-query
1857
- ```
1858
-
1859
- **Key differences from Next.js**:
1860
- - ❌ **No `transpilePackages` needed** — Vite handles TypeScript transpilation natively.
1861
- - ❌ **No `'use client'` directive needed** — Vite doesn't use Server Components.
1862
- - ❌ **No `<Suspense>` boundary needed** — No Server Component hydration concerns.
1863
- - ✅ **Still needs `useSurveySDK()`**, `id={question.id}`, `SURVEY_PLACEHOLDERS` outside component, and `onAction()` dispatcher — all SDK constraints still apply.
1864
-
1865
- ### Remix
1866
-
1867
- ```bash
1868
- npx -y create-remix@latest ./
1869
- npm install @explorer02/cfm-survey-sdk @tanstack/react-query
1870
- ```
1871
-
1872
- **Key differences from Next.js**:
1873
- - ❌ **No `transpilePackages` needed** — Remix uses Vite/esbuild under the hood.
1874
- - ✅ **`'use client'` IS needed** in Remix v2 if using Server Components (depends on version).
1875
- - ✅ All SDK constraints still apply.
1876
-
1877
- ### Create React App (CRA)
1878
-
1879
- ```bash
1880
- npx -y create-react-app ./ --template typescript
1881
- npm install @explorer02/cfm-survey-sdk @tanstack/react-query
1882
- ```
1883
-
1884
- **Key differences from Next.js**:
1885
- - ❌ **No `transpilePackages` needed** — CRA's webpack config handles this.
1886
- - ❌ **No `'use client'` directive** — CRA doesn't have Server Components.
1887
- - ❌ **No `<Suspense>` boundary needed** — No SSR concerns.
1888
- - ✅ All SDK constraints still apply.
1889
-
1890
- ### Universal SDK Constraints (Apply to ALL Frameworks)
1891
-
1892
- Regardless of framework, these rules always apply:
1893
- 1. `id={question.id}` on question wrappers — for scroll navigation.
1894
- 2. `dangerouslySetInnerHTML={{ __html: question.text }}` — for HTML in question text.
1895
- 3. `SURVEY_PLACEHOLDERS` defined outside the component — to prevent infinite re-renders.
1896
- 4. `onAction()` for all user interactions — never bypass the dispatcher.
1897
- 5. Import only from `@explorer02/cfm-survey-sdk` — never from internal paths.
1898
-
1899
- ---
1900
-
1901
- ## Troubleshooting Guide
1902
-
1903
- | Symptom | Cause | Fix |
1904
- |---------|-------|-----|
1905
- | `SyntaxError: Unexpected token 'export'` | Missing `transpilePackages` in `next.config.js` | Add `transpilePackages: ["@explorer02/cfm-survey-sdk"]` |
1906
- | Scroll-to-error doesn't work | Missing `id={question.id}` on question wrapper | Add `id={question.id}` to the outermost element of each question |
1907
- | Survey shows "No survey data" | SDK cannot reach the API endpoint | Check network connectivity; the SDK fetches from `https://custom-p0.feedbook.me/api/feedback/survey/cfm` |
1908
- | Infinite re-renders | Placeholders object defined inside component | Move `SURVEY_PLACEHOLDERS` outside the component body |
1909
- | `type SurveyQuestion` import error | Importing from wrong path | Import from `@explorer02/cfm-survey-sdk`, not internal paths |
1910
- | Tailwind classes not applying | Missing `@import "tailwindcss"` in CSS | Add `@import "tailwindcss";` to `globals.css` |
1911
- | Build error: "Cannot find module" | Missing dependencies | Run `npm install @explorer02/cfm-survey-sdk @tanstack/react-query` |
1912
- | Hydration mismatch errors | Missing `<Suspense>` boundary in `page.tsx` | Wrap `<SurveyPage />` in `<Suspense>` in the entry page |
1913
- | Survey looks identical to another client's | Agent copied styling from Section 9 reference | Delete all copied styles; redesign from scratch using Section 4 skeletons + client mockup |
17
+ Open `node_modules/@explorer02/cfm-survey-sdk/docs/index.md` now and follow the instructions inside it strictly.