# sf-featurepriority

[![npm version](https://img.shields.io/npm/v/@sensefolks/featurepriority.svg)](https://www.npmjs.com/package/@sensefolks/featurepriority)
[![npm downloads](https://img.shields.io/npm/dm/@sensefolks/featurepriority.svg)](https://www.npmjs.com/package/@sensefolks/featurepriority)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

> Identify high-impact features using a funneled Kano → MaxDiff → Pairwise methodology that progressively narrows the feature set per respondent in real time.

## Features

- 🔬 Funneled three-step prioritization: Kano classification → MaxDiff scoring → Pairwise comparison
- 🎯 Per-respondent real-time filtering — only features that matter advance to the next step
- 📊 Client-side scoring: Kano classification, MaxDiff utility scores, Bradley-Terry rankings
- 🔄 Sessionless progress — every page reload starts the survey from the beginning
- ⌨️ Keyboard-accessible throughout
- ♿ Screen reader optimized with ARIA live regions
- 🎨 Customizable via CSS Parts
- 📱 Responsive design
- 🌐 Works with any framework

## How It Works

The survey chains three research methods in a fixed sequence with automatic per-respondent filtering between steps:

```
All Features (4–7 items)
     │
     ▼
┌─────────────┐
│  Kano Step  │  Respondent rates each feature (functional + dysfunctional)
│             │  → Must-Be, One-Dimensional, Attractive features advance
│             │  → Indifferent, Reverse, Questionable features filtered out
└──────┬──────┘
       │ survivors
       ▼
┌─────────────┐
│ MaxDiff Step│  Best/Worst selections across balanced trials
│             │  → Top-N features by utility score advance
└──────┬──────┘
       │ top-N features
       ▼
┌─────────────┐
│Pairwise Step│  Head-to-head matchups → Bradley-Terry final ranking
└──────┬──────┘
       │
       ▼
  Final Ranking
```

**Adaptive step skipping:**

- If fewer than 4 features survive Kano → MaxDiff is skipped, survivors go directly to Pairwise
- If fewer than 3 features survive Kano → survey ends with Kano-only results

Required respondent fields are indicated and keep Submit disabled until valid without showing required-field errors. Email format feedback starts only after `@` is entered and the respondent pauses typing for 1.5 seconds.

## Configuration

```json
{
  "question": "Which features matter most to you?",
  "itemsPerTrial": 4,
  "topNThreshold": 3,
  "items": [
    { "title": "Dark mode", "description": "Switch to a dark color scheme", "value": "dark-mode" },
    { "title": "Offline support", "value": "offline" },
    { "title": "Collaboration", "value": "collab" },
    { "title": "API access", "value": "api" }
  ]
}
```

| Field           | Type     | Range    | Default | Description                                                                  |
| --------------- | -------- | -------- | ------- | ---------------------------------------------------------------------------- |
| `question`      | `string` | —        | —       | Survey question text (required)                                              |
| `items`         | `array`  | 4–7      | —       | Priority items, each with `title`, `value`, optional `description`           |
| `itemsPerTrial` | `number` | 3–5      | `4`     | Features shown per MaxDiff trial                                             |
| `topNThreshold` | `number` | 2..(N-1) | —       | Features advancing from MaxDiff to Pairwise (required, must be < item count) |

## Installation

### NPM

```bash
npm install @sensefolks/featurepriority
```

### CDN

```html
<!-- ES modules -->
<script type="module" src="https://unpkg.com/@sensefolks/featurepriority@5.0.2/dist/sf-featurepriority/sf-featurepriority.esm.js"></script>
```

jsDelivr:

```html
<script type="module" src="https://cdn.jsdelivr.net/npm/@sensefolks/featurepriority@5.0.2/dist/sf-featurepriority/sf-featurepriority.esm.js"></script>
```

## Usage

### HTML

```html
<sf-featurepriority survey-key="your-survey-uuid"> </sf-featurepriority>
```

### React

```jsx
import '@sensefolks/featurepriority';

function App() {
  return <sf-featurepriority survey-key="your-survey-uuid"></sf-featurepriority>;
}
```

### Vue

```vue
<template>
  <sf-featurepriority survey-key="your-survey-uuid"> </sf-featurepriority>
</template>

<script>
import '@sensefolks/featurepriority';
export default {};
</script>
```

### Angular

```typescript
// app.module.ts
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import '@sensefolks/featurepriority';

@NgModule({ schemas: [CUSTOM_ELEMENTS_SCHEMA] })
```

```html
<!-- template -->
<sf-featurepriority survey-key="your-survey-uuid"></sf-featurepriority>
```

## Framework Notes

- React + Next.js: use the React snippet above. In Next.js, render surveys inside a `'use client'` component.
- Vue + Nuxt: use the Vue snippet above. In Nuxt pages that SSR, wrap the survey with `<ClientOnly>`.
- Svelte: load the package inside `onMount` and render the same `sf-*` tag.
- Astro: keep the `sf-*` tag in markup and load the package with a client-side module import.
- Vanilla JS: use the HTML/CDN snippet or a module import in a `<script type="module">` block.

For complete copy-paste examples, see: https://sensefolks.com/docs/tutorials/embedding-a-survey/

## API Properties

| Property            | Attribute            | Type     | Default                          | Description                    |
| ------------------- | -------------------- | -------- | -------------------------------- | ------------------------------ |
| `surveyKey`         | `survey-key`         | `string` | —                                | Survey public UUID (required)  |
| `completionMessage` | `completion-message` | `string` | `'Thank you for your response!'` | Fallback message shown after submission when the survey has no saved thank-you message |
| `thankYouMessage`   | `thank-you-message`  | `string` | —                                | Overrides the saved survey thank-you message |
| `sessionData`      | —                    | `object` | `{}`                             | Every schema field is required when a schema exists; schema-less surveys accept safe flat string, finite number, and boolean values |

For schema-backed surveys, assign the complete `sessionData` object before setting `surveyKey`. Reassign a new object whenever Session Data values change; the component refetches after a meaningful reassignment.

## Events

| Event     | Detail                                       | Description                                |
| --------- | -------------------------------------------- | ------------------------------------------ |
| `sfError` | `{ surveyKey, errorType, errorMessage }`     | Load, submit, or validation error occurred |

## CSS Custom Properties

Customize the component by setting CSS custom properties on the element or a parent:

| Property              | Default      | Description                |
| --------------------- | ------------ | -------------------------- |
| `--sf-primary`        | `#005fcc`    | Primary brand color        |
| `--sf-primary-hover`  | `#0047a3`    | Primary hover color        |
| `--sf-text-primary`   | `#111827`    | Primary text color         |
| `--sf-text-secondary` | `#6b7280`    | Secondary/muted text color |
| `--sf-error-color`    | `#dc2626`    | Error state color          |
| `--sf-error-text`     | `#991b1b`    | Error message text color     |
| `--sf-error-bg`       | `#fef2f2`    | Error state background       |
| `--sf-error-border`   | `#fecaca`    | Error state border color     |
| `--sf-success-text`   | `#166534`    | Success message text color   |
| `--sf-success-bg`     | `#f0fdf4`    | Success state background     |
| `--sf-success-border` | `#bbf7d0`    | Success state border color   |
| `--sf-card-bg`        | `#ffffff`    | Card background color      |
| `--sf-card-border`    | `#d1d5db`    | Card border color          |
| `--sf-card-radius`    | `8px`        | Card border radius         |
| `--sf-button-radius`  | `6px`        | Button border radius       |
| `--sf-transition`     | `150ms ease` | Transition timing          |
| `--sf-progress-bg`    | `#e5e7eb`    | Progress track color       |
| `--sf-progress-fill`  | primary      | Progress fill color        |
| `--sf-feature-focus-bg` | `rgba(0, 95, 204, 0.1)` | Focused feature item background |
| `--sf-feature-drag-bg` | `rgba(0, 95, 204, 0.2)` | Drag-mode feature item background |

## CSS Parts

All interactive elements expose CSS parts for custom styling via `::part()`.

### Layout parts

| Part               | Description                          |
| ------------------ | ------------------------------------ |
| `survey-container` | Outer survey wrapper                 |
| `container`        | Host element wrapper                 |
| `step`             | Step container (shared by all steps) |
| `progress`         | Top progress header wrapper           |
| `progress-indicator` | Compatibility alias for the progress header |
| `progress-label`   | "Step X of Y" label                   |
| `progress-text`    | Compatibility alias for the progress label |
| `progress-track`   | Continuous progress bar track         |
| `progress-bar`     | Compatibility alias for the progress bar track |
| `progress-fill`    | Filled portion of the progress bar    |
| `heading`          | Compatibility hook for primary body text |
| `instructions`     | Step instructions (shared)           |
| `button-container` | Button row container                 |
| `button`           | All buttons (shared)                 |
| `next-button`      | Next/Continue button                 |
| `back-button`      | Back button                          |
| `submit-button`    | Submit button                        |

### Message parts

| Part              | Description               |
| ----------------- | ------------------------- |
| `message`         | General messages          |
| `error-message`   | Error messages            |
| `survey-field-error-message` | Inline email feedback shown after a 1.5-second idle delay |
| `loading-message` | Loading state message     |
| `error-container` | Error state container     |
| `announcements`   | Screen reader live region |

### Kano parts

| Part                  | Description                  |
| --------------------- | ---------------------------- |
| `kano-step`           | Kano step container          |
| `kano-heading`        | Kano item title text         |
| `kano-description`    | Kano item description        |
| `kano-question`       | Kano question block          |
| `kano-functional`     | Functional question block    |
| `kano-dysfunctional`  | Dysfunctional question block |
| `kano-question-label` | Kano question label          |
| `kano-option`         | Kano radio option wrapper    |
| `radio-group`         | Radio button group           |
| `radio-input`         | Radio input element          |
| `radio-label`         | Radio option label           |

### Transition parts

| Part                     | Description                 |
| ------------------------ | --------------------------- |
| `step-transition`        | Transition screen container |
| `transition-heading`     | Transition title text       |
| `transition-summary`     | Transition summary text     |
| `transition-description` | Transition description text |

### MaxDiff parts

| Part                       | Description                      |
| -------------------------- | -------------------------------- |
| `maxdiff-step`             | MaxDiff step container           |
| `maxdiff-heading`          | MaxDiff prompt text              |
| `maxdiff-instructions`     | MaxDiff instructions             |
| `maxdiff-trial`            | MaxDiff trial container          |
| `maxdiff-columns`          | MaxDiff column headers row       |
| `maxdiff-column-header`    | MaxDiff column header cell       |
| `maxdiff-option`           | MaxDiff option row               |
| `maxdiff-item-label`       | MaxDiff item label               |
| `maxdiff-item-description` | MaxDiff item description         |
| `best-selector`            | "Most Important" radio selector  |
| `worst-selector`           | "Least Important" radio selector |

### Pairwise parts

| Part                          | Description                |
| ----------------------------- | -------------------------- |
| `pairwise-step`               | Pairwise step container    |
| `pairwise-heading`            | Pairwise prompt text       |
| `pairwise-instructions`       | Pairwise instructions      |
| `pairwise-matchup`            | Pairwise matchup container |
| `pairwise-option`             | Base part for each pairwise option button |
| `pairwise-option-left`        | Left option button         |
| `pairwise-option-right`       | Right option button        |
| `pairwise-option-title`       | Option title text          |
| `pairwise-option-description` | Option description text    |
| `pairwise-vs`                 | "vs" divider               |

### Completion parts

| Part                      | Description                    |
| ------------------------- | ------------------------------ |
| `funnel-complete-step`    | Completion step container      |
| `funnel-complete-heading` | Completion/results text        |
| `completion-heading`      | Compatibility hook for the submitted completion message |
| `success-message`         | Green completion status message |
| `funnel-results`          | Results container              |
| `ranking-summary`         | Ranking summary block          |
| `summary-heading`         | Summary label text             |
| `summary-list`            | Summary list container         |
| `summary-item`            | Individual summary item        |
| `summary-rank`            | Rank number                    |
| `summary-title`           | Item title in summary          |
| `summary-kano-label`      | Kano category label in summary |

### Respondent details parts

| Part                         | Description                  |
| ---------------------------- | ---------------------------- |
| `survey-fields-step`         | Survey Fields container |
| `survey-fields-heading`      | Survey Fields introductory text |
| `form-container`             | Form container               |
| `form-field`                 | Form field wrapper           |
| `form-label`                 | Form field label             |
| `form-input`                 | Text/email/number input      |
| `form-select`                | Select dropdown              |
| `hcaptcha-container`          | Wrapper for the hCaptcha widget (when enabled) |
| `form-radio-group`           | Radio group in form          |
| `form-radio`                 | Radio input in form          |
| `form-radio-label`           | Radio label in form          |
| `form-checkbox-group`        | Checkbox group in form       |
| `form-checkbox`              | Checkbox input in form       |
| `form-checkbox-label`        | Checkbox label in form       |
| `field-error`                | Field validation error       |
| `required-indicator`         | Required field asterisk      |

### Branding parts

| Part            | Description        |
| --------------- | ------------------ |
| `branding`      | Branding container |
| `branding-link` | Branding link      |
| `branding-logo` | Branding logo      |

## Styling Example

```css
sf-featurepriority {
  --sf-primary: #7c3aed;
  --sf-text-primary: #1f2937;
  --sf-card-radius: 12px;
  --sf-button-radius: 8px;
}

sf-featurepriority::part(kano-step) {
  padding: 1.5rem;
  background: var(--sf-card-bg);
  border-radius: var(--sf-card-radius);
}

sf-featurepriority::part(pairwise-option-left),
sf-featurepriority::part(pairwise-option-right) {
  border: 2px solid var(--sf-card-border);
  border-radius: var(--sf-card-radius);
  padding: 1rem;
  transition: border-color var(--sf-transition);
}

sf-featurepriority::part(pairwise-option-selected) {
  border-color: var(--sf-primary);
  background-color: rgba(124, 58, 237, 0.05);
}
```

## Agent Integration

```json
{
  "component": "sf-featurepriority",
  "package": "@sensefolks/featurepriority",
  "tag": "sf-featurepriority",
  "cssParts": [
    "container",
    "survey-container",
    "step",
    "progress",
    "progress-indicator",
    "progress-label",
    "progress-text",
    "progress-track",
    "progress-bar",
    "progress-fill",
    "heading",
    "instructions",
    "button-container",
    "button",
    "next-button",
    "back-button",
    "submit-button",
    "message",
    "error-message",
    "survey-field-error-message",
    "loading-message",
    "error-container",
    "troubleshooting-link",
    "announcements",
    "kano-step",
    "kano-heading",
    "kano-description",
    "kano-question",
    "kano-functional",
    "kano-dysfunctional",
    "kano-question-label",
    "kano-option",
    "radio-group",
    "radio-input",
    "radio-label",
    "step-transition",
    "transition-heading",
    "transition-summary",
    "transition-description",
    "maxdiff-step",
    "maxdiff-heading",
    "maxdiff-instructions",
    "maxdiff-trial",
    "maxdiff-columns",
    "maxdiff-column-header",
    "maxdiff-option",
    "maxdiff-item-label",
    "maxdiff-item-description",
    "best-selector",
    "worst-selector",
    "pairwise-step",
    "pairwise-heading",
    "pairwise-instructions",
    "pairwise-matchup",
    "pairwise-option-left",
    "pairwise-option-right",
    "pairwise-option-selected",
    "pairwise-option-title",
    "pairwise-option-description",
    "pairwise-vs",
    "funnel-complete-step",
    "funnel-complete-heading",
    "completion-heading",
    "success-message",
    "funnel-results",
    "ranking-summary",
    "summary-heading",
    "summary-list",
    "summary-item",
    "summary-rank",
    "summary-title",
    "summary-kano-label",
    "survey-fields-step",
    "survey-fields-heading",
    "form-container",
    "form-field",
    "form-label",
    "form-input",
    "form-select",
    "form-radio-group",
    "form-radio",
    "form-radio-label",
    "form-checkbox-group",
    "form-checkbox",
    "form-checkbox-label",
    "field-error",
    "required-indicator",
    "branding",
    "branding-link",
    "branding-logo"
  ],
  "cssCustomProperties": [
    "--sf-primary",
    "--sf-primary-hover",
    "--sf-text-primary",
    "--sf-text-secondary",
    "--sf-error-color",
    "--sf-error-text",
    "--sf-error-bg",
    "--sf-error-border",
    "--sf-success-text",
    "--sf-success-bg",
    "--sf-success-border",
    "--sf-card-bg",
    "--sf-card-border",
    "--sf-card-radius",
    "--sf-button-radius",
    "--sf-transition",
    "--sf-progress-bg",
    "--sf-progress-fill",
    "--sf-feature-focus-bg",
    "--sf-feature-drag-bg"
  ]
}
```

## Response Data

The component submits a single `FunneledFeaturePriorityResponse` containing computed scores only (no raw trial/matchup data):

```typescript
interface FunneledFeaturePriorityResponse {
  stepsCompleted: ('kano' | 'maxdiff' | 'pairwise')[];
  stepsSkipped: ('maxdiff' | 'pairwise')[];
  kanoResults: { itemValue: string; category: KanoCategory }[];
  advancedItems: {
    afterKano: string[];
    afterMaxDiff?: string[];
  };
  maxdiffResults?: { utilityScores: Record<string, number> };
  pairwiseResults?: { bradleyTerryScores: Record<string, number> };
}
```

## Privacy And Network Requirements

sf-featurepriority loads survey configuration from the SenseFolks embed request endpoint and submits responses to the SenseFolks embed response endpoint. The `survey-key` value is validated as a UUID before requests are made and is URL encoded in request paths.

Submitted payloads can include the respondent's answers, configured survey fields, prepared session data values supplied by the host page, completion timing, and metadata including user-agent string, platform, language, cookie-enabled status, online status, screen resolution, color depth, timezone, and timestamp. Survey progress exists only in the component's in-memory state. The component does not use cookies, localStorage, sessionStorage, or IndexedDB, and every page reload starts a fresh response.

If hCaptcha is enabled by the survey config, allow hCaptcha in your CSP: `script-src https://js.hcaptcha.com`, `frame-src https://hcaptcha.com https://*.hcaptcha.com`, and a `connect-src` that includes your SenseFolks API origin plus the hCaptcha endpoints.

## Accessibility

- All interactive elements are keyboard-navigable
- ARIA live regions announce step transitions, filtering results, and selection confirmations
- Radio groups use descriptive `aria-label` attributes
- Pairwise matchups use `role="group"` with `aria-describedby`
- Step indicators include full context in `aria-label`
- Respects `prefers-reduced-motion` — all animations are disabled when set

## Browser Support

| Browser | Version        |
| ------- | -------------- |
| Chrome  | 88+            |
| Firefox | 85+            |
| Safari  | 14+            |
| Edge    | 88+            |

Internet Explorer 11 is not supported. The host browser must provide modern
Web Component APIs, `fetch`, and `AbortController`.

## License

MIT © [SenseFolks](https://sensefolks.com)
