react-minimal-survey-builder 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +435 -0
- package/dist/builder/index.d.mts +31 -0
- package/dist/builder/index.d.ts +31 -0
- package/dist/builder/index.js +1 -0
- package/dist/builder/index.mjs +1 -0
- package/dist/chunk-5CMRPHVX.mjs +1 -0
- package/dist/chunk-JWOXQRNV.js +1 -0
- package/dist/chunk-M6YT7KIF.js +1 -0
- package/dist/chunk-Q5PYPUG5.js +1 -0
- package/dist/chunk-RZFNCNBO.mjs +1 -0
- package/dist/chunk-YTSJTAP2.mjs +1 -0
- package/dist/core/index.d.mts +111 -0
- package/dist/core/index.d.ts +111 -0
- package/dist/core/index.js +1 -0
- package/dist/core/index.mjs +1 -0
- package/dist/index-Q8KHOfHv.d.mts +192 -0
- package/dist/index-Q8KHOfHv.d.ts +192 -0
- package/dist/index.d.mts +124 -0
- package/dist/index.d.ts +124 -0
- package/dist/index.js +1 -0
- package/dist/index.mjs +1 -0
- package/package.json +62 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
# react-minimal-survey-builder
|
|
2
|
+
|
|
3
|
+
> **The Headless Survey Engine for Modern React Apps.**
|
|
4
|
+
|
|
5
|
+
A lightweight, customizable, JSON-schema driven survey builder for React. Zero heavy dependencies. Headless-first. TypeScript-first.
|
|
6
|
+
|
|
7
|
+
[](.) [](.) [](./LICENSE)
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Why another survey library?
|
|
12
|
+
|
|
13
|
+
| Feature | SurveyJS | react-minimal-survey-builder |
|
|
14
|
+
| ------------ | ---------------- | ---------------------------- |
|
|
15
|
+
| Bundle Size | Heavy (~200kb+) | **~11kb gzipped** |
|
|
16
|
+
| Headless | Limited | **Fully headless** |
|
|
17
|
+
| Custom UI | Hard to override | **Easy, plug-and-play** |
|
|
18
|
+
| TypeScript | Partial | **First-class** |
|
|
19
|
+
| Dependencies | Many | **Zero heavy deps** |
|
|
20
|
+
| SSR | Tricky | **Full support** |
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
## Installation
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
npm install react-minimal-survey-builder
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
**Peer dependencies:** `react >= 17`, `react-dom >= 17`
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
## Quick Start
|
|
35
|
+
|
|
36
|
+
### 1. Define a schema
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
import type { SurveySchema } from "react-minimal-survey-builder";
|
|
40
|
+
|
|
41
|
+
const schema: SurveySchema = {
|
|
42
|
+
id: "survey-1",
|
|
43
|
+
title: "Customer Feedback",
|
|
44
|
+
pages: [
|
|
45
|
+
{
|
|
46
|
+
id: "page-1",
|
|
47
|
+
title: "About You",
|
|
48
|
+
questions: [
|
|
49
|
+
{
|
|
50
|
+
id: "name",
|
|
51
|
+
type: "text",
|
|
52
|
+
label: "What is your name?",
|
|
53
|
+
required: true,
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
id: "role",
|
|
57
|
+
type: "select",
|
|
58
|
+
label: "Your role?",
|
|
59
|
+
options: [
|
|
60
|
+
{ label: "Developer", value: "dev" },
|
|
61
|
+
{ label: "Designer", value: "design" },
|
|
62
|
+
{ label: "PM", value: "pm" },
|
|
63
|
+
],
|
|
64
|
+
},
|
|
65
|
+
],
|
|
66
|
+
},
|
|
67
|
+
],
|
|
68
|
+
};
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### 2. Render with zero config
|
|
72
|
+
|
|
73
|
+
```tsx
|
|
74
|
+
import { SurveyRenderer } from "react-minimal-survey-builder";
|
|
75
|
+
|
|
76
|
+
function App() {
|
|
77
|
+
return (
|
|
78
|
+
<SurveyRenderer
|
|
79
|
+
schema={schema}
|
|
80
|
+
options={{
|
|
81
|
+
onSubmit: (answers) => console.log(answers),
|
|
82
|
+
}}
|
|
83
|
+
/>
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
That's it! You get validation, navigation, progress tracking, and conditional logic out of the box.
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## Architecture
|
|
93
|
+
|
|
94
|
+
The library has 3 layers — use only what you need:
|
|
95
|
+
|
|
96
|
+
```
|
|
97
|
+
┌─────────────────────────────────┐
|
|
98
|
+
│ Builder (Drag & Drop UI) │ ← Optional
|
|
99
|
+
├─────────────────────────────────┤
|
|
100
|
+
│ React Layer (Hook + Components)│ ← Optional UI
|
|
101
|
+
├─────────────────────────────────┤
|
|
102
|
+
│ Core Engine (Framework Agnostic)│ ← Always available
|
|
103
|
+
└─────────────────────────────────┘
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### Import paths
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
// Everything
|
|
110
|
+
import {
|
|
111
|
+
useSurvey,
|
|
112
|
+
SurveyRenderer,
|
|
113
|
+
SurveyBuilder,
|
|
114
|
+
} from "react-minimal-survey-builder";
|
|
115
|
+
|
|
116
|
+
// Core only (framework agnostic, ~3kb)
|
|
117
|
+
import {
|
|
118
|
+
createSurveyManager,
|
|
119
|
+
validateSurvey,
|
|
120
|
+
} from "react-minimal-survey-builder/core";
|
|
121
|
+
|
|
122
|
+
// Builder only
|
|
123
|
+
import { SurveyBuilder } from "react-minimal-survey-builder/builder";
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## API Reference
|
|
129
|
+
|
|
130
|
+
### `useSurvey(schema, options?)`
|
|
131
|
+
|
|
132
|
+
The main React hook. Fully headless — bring your own UI.
|
|
133
|
+
|
|
134
|
+
```tsx
|
|
135
|
+
const {
|
|
136
|
+
survey, // Parsed schema
|
|
137
|
+
answers, // Current answers: Record<string, AnswerValue>
|
|
138
|
+
setAnswer, // (questionId, value) => void
|
|
139
|
+
errors, // ValidationError[]
|
|
140
|
+
getError, // (questionId) => string | undefined
|
|
141
|
+
isValid, // boolean
|
|
142
|
+
validate, // () => ValidationError[]
|
|
143
|
+
getVisibleQuestions, // () => Question[]
|
|
144
|
+
getPageQuestions, // (pageIndex) => Question[]
|
|
145
|
+
visiblePages, // Page[]
|
|
146
|
+
currentPageIndex,
|
|
147
|
+
totalPages,
|
|
148
|
+
hasNextPage,
|
|
149
|
+
hasPrevPage,
|
|
150
|
+
nextPage, // () => boolean
|
|
151
|
+
prevPage, // () => boolean
|
|
152
|
+
goToPage, // (index) => boolean
|
|
153
|
+
submit, // () => Promise<{ success, errors }>
|
|
154
|
+
isSubmitted, // boolean
|
|
155
|
+
reset, // () => void
|
|
156
|
+
progress, // 0-100
|
|
157
|
+
} = useSurvey(schema, {
|
|
158
|
+
initialAnswers: { name: "John" },
|
|
159
|
+
onChange: (answers, questionId) => {},
|
|
160
|
+
onSubmit: async (answers) => {},
|
|
161
|
+
onValidate: (errors) => {},
|
|
162
|
+
onPageChange: (pageIndex) => {},
|
|
163
|
+
});
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
### `<SurveyRenderer />`
|
|
167
|
+
|
|
168
|
+
Pre-built survey UI with full override capabilities.
|
|
169
|
+
|
|
170
|
+
```tsx
|
|
171
|
+
<SurveyRenderer
|
|
172
|
+
schema={schema}
|
|
173
|
+
options={{ onSubmit: handleSubmit }}
|
|
174
|
+
components={{
|
|
175
|
+
text: MyCustomTextInput,
|
|
176
|
+
radio: MyCustomRadioGroup,
|
|
177
|
+
}}
|
|
178
|
+
renderHeader={({ title, progress }) => (
|
|
179
|
+
<MyHeader title={title} progress={progress} />
|
|
180
|
+
)}
|
|
181
|
+
renderFooter={({ nextPage, submit, isLastPage }) => <MyFooter />}
|
|
182
|
+
renderComplete={() => <ThankYou />}
|
|
183
|
+
/>
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
**Render prop mode** for complete control:
|
|
187
|
+
|
|
188
|
+
```tsx
|
|
189
|
+
<SurveyRenderer schema={schema}>
|
|
190
|
+
{(survey) => (
|
|
191
|
+
<div>
|
|
192
|
+
{survey.getPageQuestions(survey.currentPageIndex).map((q) => (
|
|
193
|
+
<MyQuestion key={q.id} question={q} value={survey.answers[q.id]} />
|
|
194
|
+
))}
|
|
195
|
+
</div>
|
|
196
|
+
)}
|
|
197
|
+
</SurveyRenderer>
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
### `<SurveyBuilder />`
|
|
201
|
+
|
|
202
|
+
Drag-and-drop visual builder with live preview.
|
|
203
|
+
|
|
204
|
+
```tsx
|
|
205
|
+
import { SurveyBuilder } from "react-minimal-survey-builder";
|
|
206
|
+
|
|
207
|
+
function BuilderPage() {
|
|
208
|
+
const [schema, setSchema] = useState(initialSchema);
|
|
209
|
+
|
|
210
|
+
return (
|
|
211
|
+
<SurveyBuilder
|
|
212
|
+
value={schema}
|
|
213
|
+
onChange={setSchema}
|
|
214
|
+
showPreview // Side-by-side live preview
|
|
215
|
+
showJson // JSON editor tab
|
|
216
|
+
layout="horizontal" // or "vertical"
|
|
217
|
+
/>
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
---
|
|
223
|
+
|
|
224
|
+
## Schema Reference
|
|
225
|
+
|
|
226
|
+
### SurveySchema
|
|
227
|
+
|
|
228
|
+
```ts
|
|
229
|
+
type SurveySchema = {
|
|
230
|
+
id: string;
|
|
231
|
+
title?: string;
|
|
232
|
+
description?: string;
|
|
233
|
+
pages: Page[];
|
|
234
|
+
settings?: {
|
|
235
|
+
showProgress?: boolean; // default: true
|
|
236
|
+
allowBack?: boolean; // default: true
|
|
237
|
+
validateOnPageChange?: boolean; // default: true
|
|
238
|
+
showQuestionNumbers?: boolean; // default: true
|
|
239
|
+
submitText?: string; // default: "Submit"
|
|
240
|
+
nextText?: string; // default: "Next"
|
|
241
|
+
prevText?: string; // default: "Previous"
|
|
242
|
+
};
|
|
243
|
+
};
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
### Question
|
|
247
|
+
|
|
248
|
+
```ts
|
|
249
|
+
type Question = {
|
|
250
|
+
id: string;
|
|
251
|
+
type:
|
|
252
|
+
| "text"
|
|
253
|
+
| "textarea"
|
|
254
|
+
| "radio"
|
|
255
|
+
| "checkbox"
|
|
256
|
+
| "select"
|
|
257
|
+
| "number"
|
|
258
|
+
| "email"
|
|
259
|
+
| "date"
|
|
260
|
+
| "rating";
|
|
261
|
+
label: string;
|
|
262
|
+
description?: string;
|
|
263
|
+
placeholder?: string;
|
|
264
|
+
required?: boolean;
|
|
265
|
+
defaultValue?: AnswerValue;
|
|
266
|
+
options?: { label: string; value: string }[];
|
|
267
|
+
visibleIf?: string; // Conditional logic expression
|
|
268
|
+
validation?: ValidationRule[];
|
|
269
|
+
meta?: Record<string, unknown>; // Custom metadata
|
|
270
|
+
};
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
### Conditional Logic
|
|
274
|
+
|
|
275
|
+
Use `visibleIf` to show/hide questions dynamically:
|
|
276
|
+
|
|
277
|
+
```ts
|
|
278
|
+
// Simple comparison
|
|
279
|
+
{
|
|
280
|
+
visibleIf: "{role} === 'other'";
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// Multiple conditions
|
|
284
|
+
{
|
|
285
|
+
visibleIf: "{age} >= 18 && {country} === 'US'";
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// OR logic
|
|
289
|
+
{
|
|
290
|
+
visibleIf: "{plan} === 'pro' || {plan} === 'enterprise'";
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// Truthy check
|
|
294
|
+
{
|
|
295
|
+
visibleIf: "{newsletter}";
|
|
296
|
+
}
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
### Validation Rules
|
|
300
|
+
|
|
301
|
+
```ts
|
|
302
|
+
{
|
|
303
|
+
validation: [
|
|
304
|
+
{ type: "required" },
|
|
305
|
+
{ type: "email", message: "Please enter a valid email" },
|
|
306
|
+
{ type: "minLength", value: 3 },
|
|
307
|
+
{ type: "maxLength", value: 100 },
|
|
308
|
+
{ type: "min", value: 0 },
|
|
309
|
+
{ type: "max", value: 10 },
|
|
310
|
+
{ type: "pattern", value: "^[A-Z]", message: "Must start with uppercase" },
|
|
311
|
+
{
|
|
312
|
+
type: "custom",
|
|
313
|
+
validator: (value, allAnswers) => {
|
|
314
|
+
if (value === "admin") return "Reserved username";
|
|
315
|
+
return true;
|
|
316
|
+
},
|
|
317
|
+
},
|
|
318
|
+
];
|
|
319
|
+
}
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
---
|
|
323
|
+
|
|
324
|
+
## Custom Question Types
|
|
325
|
+
|
|
326
|
+
Override built-in components or register entirely new types:
|
|
327
|
+
|
|
328
|
+
```tsx
|
|
329
|
+
import type { QuestionComponentProps } from "react-minimal-survey-builder";
|
|
330
|
+
|
|
331
|
+
// Custom star rating component
|
|
332
|
+
const StarRating: React.FC<QuestionComponentProps<number>> = ({
|
|
333
|
+
question,
|
|
334
|
+
value,
|
|
335
|
+
onChange,
|
|
336
|
+
}) => (
|
|
337
|
+
<div className="star-rating">
|
|
338
|
+
{[1, 2, 3, 4, 5].map((n) => (
|
|
339
|
+
<span
|
|
340
|
+
key={n}
|
|
341
|
+
onClick={() => onChange(n)}
|
|
342
|
+
className={value >= n ? "star active" : "star"}
|
|
343
|
+
>
|
|
344
|
+
★
|
|
345
|
+
</span>
|
|
346
|
+
))}
|
|
347
|
+
</div>
|
|
348
|
+
);
|
|
349
|
+
|
|
350
|
+
// Use it
|
|
351
|
+
<SurveyRenderer schema={schema} components={{ rating: StarRating }} />;
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
---
|
|
355
|
+
|
|
356
|
+
## Core Engine (Framework Agnostic)
|
|
357
|
+
|
|
358
|
+
Use the core engine without React:
|
|
359
|
+
|
|
360
|
+
```ts
|
|
361
|
+
import { createSurveyManager } from "react-minimal-survey-builder/core";
|
|
362
|
+
|
|
363
|
+
const manager = createSurveyManager(schema, {
|
|
364
|
+
onSubmit: (answers) => saveToServer(answers),
|
|
365
|
+
});
|
|
366
|
+
|
|
367
|
+
manager.setAnswer("name", "John");
|
|
368
|
+
manager.nextPage();
|
|
369
|
+
|
|
370
|
+
const errors = manager.validate();
|
|
371
|
+
const state = manager.getState();
|
|
372
|
+
|
|
373
|
+
// Event system
|
|
374
|
+
const unsub = manager.on("answerChanged", (event) => {
|
|
375
|
+
console.log(event.payload);
|
|
376
|
+
});
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
---
|
|
380
|
+
|
|
381
|
+
## Running the Example
|
|
382
|
+
|
|
383
|
+
```bash
|
|
384
|
+
# From the project root
|
|
385
|
+
cd example
|
|
386
|
+
npm install
|
|
387
|
+
npm run dev
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
The example app demonstrates all three modes:
|
|
391
|
+
|
|
392
|
+
- **Survey Renderer** — pre-built UI with conditional logic
|
|
393
|
+
- **Headless Hook** — custom UI powered by `useSurvey()`
|
|
394
|
+
- **Drag & Drop Builder** — visual schema editor with live preview
|
|
395
|
+
|
|
396
|
+
---
|
|
397
|
+
|
|
398
|
+
## Project Structure
|
|
399
|
+
|
|
400
|
+
```
|
|
401
|
+
src/
|
|
402
|
+
├── core/ # Framework-agnostic engine
|
|
403
|
+
│ ├── schema-parser.ts # Schema parsing & validation
|
|
404
|
+
│ ├── validation-engine.ts # Question validation
|
|
405
|
+
│ ├── condition-evaluator.ts # Conditional logic
|
|
406
|
+
│ └── state-manager.ts # State management class
|
|
407
|
+
├── react/ # React layer
|
|
408
|
+
│ ├── useSurvey.ts # Main React hook
|
|
409
|
+
│ ├── SurveyRenderer.tsx # Pre-built survey UI
|
|
410
|
+
│ └── QuestionRenderer.tsx # Question component system
|
|
411
|
+
├── builder/ # Visual builder
|
|
412
|
+
│ ├── SurveyBuilder.tsx # Drag & drop builder
|
|
413
|
+
│ ├── QuestionEditor.tsx # Question property editor
|
|
414
|
+
│ └── builder-reducer.ts # Builder state management
|
|
415
|
+
├── types/ # TypeScript types
|
|
416
|
+
│ └── index.ts
|
|
417
|
+
└── index.ts # Main entry point
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
---
|
|
421
|
+
|
|
422
|
+
## Design Principles
|
|
423
|
+
|
|
424
|
+
- **No UI lock-in** — Use headless hooks or swap every component
|
|
425
|
+
- **Zero heavy dependencies** — Only React as a peer dep
|
|
426
|
+
- **Tree-shakable** — Import only what you use
|
|
427
|
+
- **SSR safe** — No browser-only APIs
|
|
428
|
+
- **Memoization friendly** — Minimal re-renders, `memo` throughout
|
|
429
|
+
- **Clean error messages** — Descriptive errors with library prefix
|
|
430
|
+
|
|
431
|
+
---
|
|
432
|
+
|
|
433
|
+
## License
|
|
434
|
+
|
|
435
|
+
MIT © 2026
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
import { S as SurveySchema, Q as Question, e as BuilderState, B as BuilderAction } from '../index-Q8KHOfHv.mjs';
|
|
3
|
+
|
|
4
|
+
interface SurveyBuilderProps {
|
|
5
|
+
/** Current schema value (controlled) */
|
|
6
|
+
value?: SurveySchema;
|
|
7
|
+
/** Called when the schema changes */
|
|
8
|
+
onChange?: (schema: SurveySchema) => void;
|
|
9
|
+
/** Custom class name */
|
|
10
|
+
className?: string;
|
|
11
|
+
/** Show the live preview panel */
|
|
12
|
+
showPreview?: boolean;
|
|
13
|
+
/** Show the JSON editor panel */
|
|
14
|
+
showJson?: boolean;
|
|
15
|
+
/** Customize builder layout */
|
|
16
|
+
layout?: "horizontal" | "vertical";
|
|
17
|
+
}
|
|
18
|
+
declare const SurveyBuilder: React.FC<SurveyBuilderProps>;
|
|
19
|
+
|
|
20
|
+
interface QuestionEditorProps {
|
|
21
|
+
question: Question;
|
|
22
|
+
pageId: string;
|
|
23
|
+
onUpdate: (questionId: string, pageId: string, updates: Partial<Question>) => void;
|
|
24
|
+
onDelete: (questionId: string, pageId: string) => void;
|
|
25
|
+
}
|
|
26
|
+
declare const QuestionEditor: React.FC<QuestionEditorProps>;
|
|
27
|
+
|
|
28
|
+
declare function createInitialBuilderState(schema?: SurveySchema): BuilderState;
|
|
29
|
+
declare function builderReducer(state: BuilderState, action: BuilderAction): BuilderState;
|
|
30
|
+
|
|
31
|
+
export { QuestionEditor, type QuestionEditorProps, SurveyBuilder, type SurveyBuilderProps, builderReducer, createInitialBuilderState };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
import { S as SurveySchema, Q as Question, e as BuilderState, B as BuilderAction } from '../index-Q8KHOfHv.js';
|
|
3
|
+
|
|
4
|
+
interface SurveyBuilderProps {
|
|
5
|
+
/** Current schema value (controlled) */
|
|
6
|
+
value?: SurveySchema;
|
|
7
|
+
/** Called when the schema changes */
|
|
8
|
+
onChange?: (schema: SurveySchema) => void;
|
|
9
|
+
/** Custom class name */
|
|
10
|
+
className?: string;
|
|
11
|
+
/** Show the live preview panel */
|
|
12
|
+
showPreview?: boolean;
|
|
13
|
+
/** Show the JSON editor panel */
|
|
14
|
+
showJson?: boolean;
|
|
15
|
+
/** Customize builder layout */
|
|
16
|
+
layout?: "horizontal" | "vertical";
|
|
17
|
+
}
|
|
18
|
+
declare const SurveyBuilder: React.FC<SurveyBuilderProps>;
|
|
19
|
+
|
|
20
|
+
interface QuestionEditorProps {
|
|
21
|
+
question: Question;
|
|
22
|
+
pageId: string;
|
|
23
|
+
onUpdate: (questionId: string, pageId: string, updates: Partial<Question>) => void;
|
|
24
|
+
onDelete: (questionId: string, pageId: string) => void;
|
|
25
|
+
}
|
|
26
|
+
declare const QuestionEditor: React.FC<QuestionEditorProps>;
|
|
27
|
+
|
|
28
|
+
declare function createInitialBuilderState(schema?: SurveySchema): BuilderState;
|
|
29
|
+
declare function builderReducer(state: BuilderState, action: BuilderAction): BuilderState;
|
|
30
|
+
|
|
31
|
+
export { QuestionEditor, type QuestionEditorProps, SurveyBuilder, type SurveyBuilderProps, builderReducer, createInitialBuilderState };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkQ5PYPUG5_js=require('../chunk-Q5PYPUG5.js');require('../chunk-JWOXQRNV.js');Object.defineProperty(exports,"QuestionEditor",{enumerable:true,get:function(){return chunkQ5PYPUG5_js.g}});Object.defineProperty(exports,"SurveyBuilder",{enumerable:true,get:function(){return chunkQ5PYPUG5_js.h}});Object.defineProperty(exports,"builderReducer",{enumerable:true,get:function(){return chunkQ5PYPUG5_js.f}});Object.defineProperty(exports,"createInitialBuilderState",{enumerable:true,get:function(){return chunkQ5PYPUG5_js.e}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{g as QuestionEditor,h as SurveyBuilder,f as builderReducer,e as createInitialBuilderState}from'../chunk-5CMRPHVX.mjs';import'../chunk-YTSJTAP2.mjs';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a,b,j,k,h,g,l,d}from'./chunk-YTSJTAP2.mjs';import {memo,useMemo,useCallback,useState,useReducer,useRef,useEffect}from'react';import {jsxs,jsx,Fragment}from'react/jsx-runtime';function ce(e,r={}){let o=useRef(r);o.current=r;let t=useMemo(()=>a(e),[e]),d=useMemo(()=>{let s={};for(let x of b(t))x.defaultValue!==void 0&&(s[x.id]=x.defaultValue);return {...s,...r.initialAnswers}},[t]),[i,a$1]=useState(d),[l$1,u]=useState([]),[m,g$1]=useState(0),[p,b$1]=useState(false),c=useMemo(()=>j(t,i),[t,i]),P=useMemo(()=>k(t,i),[t,i]),Q=useCallback((s,x)=>{a$1(I=>{let A={...I,[s]:x};return o.current.onChange?.(A,s),A}),u(I=>I.filter(A=>A.questionId!==s));},[]),D=useCallback(s=>{a$1(x=>({...x,...s}));},[]),$=useCallback(()=>{let s=h(t,i,c);return u(s),o.current.onValidate?.(s),s},[t,i,c]),G=useCallback(()=>{let s=g(t,m,i,c);return u(s),s},[t,m,i,c]),M=useCallback(s=>l$1.find(x=>x.questionId===s)?.message,[l$1]),w=t.pages.length,V=m<w-1,L=m>0,H=useCallback(()=>{if(m>=w-1)return false;if(t.settings?.validateOnPageChange){let x=g(t,m,i,c);if(x.length>0)return u(x),false}let s=m+1;return g$1(s),u([]),o.current.onPageChange?.(s),true},[m,w,t,i,c]),B=useCallback(()=>{if(m<=0||!t.settings?.allowBack)return false;let s=m-1;return g$1(s),u([]),o.current.onPageChange?.(s),true},[m,t.settings?.allowBack]),W=useCallback(s=>s<0||s>=w?false:(g$1(s),u([]),o.current.onPageChange?.(s),true),[w]),T=useCallback(()=>b(t).filter(s=>c.has(s.id)),[t,c]),n=useCallback(s=>{let x=t.pages[s];return x?l(x,i):[]},[t,i]),y=useCallback(async()=>{let s=h(t,i,c);if(s.length>0)return u(s),{success:false,errors:s};try{return await o.current.onSubmit?.(i),b$1(!0),{success:!0,errors:[]}}catch(x){let I={questionId:"__submit__",message:x instanceof Error?x.message:"Submission failed",rule:"custom"};return u([I]),{success:false,errors:[I]}}},[t,i,c]),C=useCallback(()=>{a$1(d),u([]),g$1(0),b$1(false);},[d]),Y=useMemo(()=>{let s=b(t).filter(I=>c.has(I.id));if(s.length===0)return 100;let x=s.filter(I=>{let A=i[I.id];return A!=null&&A!==""&&!(Array.isArray(A)&&A.length===0)}).length;return Math.round(x/s.length*100)},[t,i,c]),K=l$1.length===0;return {survey:t,answers:i,setAnswer:Q,setAnswers:D,errors:l$1,getError:M,isValid:K,validate:$,validateCurrentPage:G,getVisibleQuestions:T,getPageQuestions:n,visiblePages:P,currentPageIndex:m,totalPages:w,hasNextPage:V,hasPrevPage:L,nextPage:H,prevPage:B,goToPage:W,submit:y,isSubmitted:p,reset:C,progress:Y}}var ae=({question:e,value:r,onChange:o,error:t,disabled:d})=>jsx("input",{type:e.type==="email"?"email":e.type==="number"?"number":"text",id:e.id,value:r??"",onChange:i=>o(i.target.value),placeholder:e.placeholder,disabled:d,"aria-invalid":!!t,"aria-describedby":t?`${e.id}-error`:void 0,style:q}),Ce=({question:e,value:r,onChange:o,error:t,disabled:d})=>jsx("textarea",{id:e.id,value:r??"",onChange:i=>o(i.target.value),placeholder:e.placeholder,disabled:d,rows:4,"aria-invalid":!!t,"aria-describedby":t?`${e.id}-error`:void 0,style:{...q,resize:"vertical"}}),Ie=({question:e,value:r,onChange:o,disabled:t})=>jsx("div",{role:"radiogroup","aria-labelledby":`${e.id}-label`,style:{display:"flex",flexDirection:"column",gap:"8px"},children:e.options?.map(d=>jsxs("label",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:t?"default":"pointer"},children:[jsx("input",{type:"radio",name:e.id,value:d.value,checked:r===d.value,onChange:()=>o(d.value),disabled:t}),jsx("span",{children:d.label})]},d.value))}),Re=({question:e,value:r,onChange:o,disabled:t})=>{let d=Array.isArray(r)?r:[],i=a=>{let l=d.includes(a)?d.filter(u=>u!==a):[...d,a];o(l);};return jsx("div",{role:"group","aria-labelledby":`${e.id}-label`,style:{display:"flex",flexDirection:"column",gap:"8px"},children:e.options?.map(a=>jsxs("label",{style:{display:"flex",alignItems:"center",gap:"8px",cursor:t?"default":"pointer"},children:[jsx("input",{type:"checkbox",value:a.value,checked:d.includes(a.value),onChange:()=>i(a.value),disabled:t}),jsx("span",{children:a.label})]},a.value))})},Ee=({question:e,value:r,onChange:o,error:t,disabled:d})=>jsxs("select",{id:e.id,value:r??"",onChange:i=>o(i.target.value),disabled:d,"aria-invalid":!!t,"aria-describedby":t?`${e.id}-error`:void 0,style:q,children:[jsx("option",{value:"",children:e.placeholder??"Select..."}),e.options?.map(i=>jsx("option",{value:i.value,children:i.label},i.value))]}),Qe=({question:e,value:r,onChange:o,error:t,disabled:d})=>jsx("input",{type:"date",id:e.id,value:r??"",onChange:i=>o(i.target.value),disabled:d,"aria-invalid":!!t,"aria-describedby":t?`${e.id}-error`:void 0,style:q}),we=({question:e,value:r,onChange:o,disabled:t})=>{let d=e.meta?.max??5;return jsx("div",{style:{display:"flex",gap:"4px"},children:Array.from({length:d},(i,a)=>a+1).map(i=>jsx("button",{type:"button",onClick:()=>o(i),disabled:t,"aria-label":`Rate ${i} of ${d}`,style:{background:(r??0)>=i?"#fbbf24":"#e5e7eb",border:"none",borderRadius:"4px",padding:"6px 12px",cursor:t?"default":"pointer",fontSize:"16px"},children:"\u2605"},i))})},Te={text:ae,email:ae,number:ae,textarea:Ce,radio:Ie,checkbox:Re,select:Ee,date:Qe,rating:we},ie=memo(({question:e,value:r,onChange:o,error:t,disabled:d=false,components:i={},className:a,hideLabel:l=false,questionNumber:u})=>{let m=i[e.type]??Te[e.type];return m?jsxs("div",{className:a,style:{marginBottom:"20px"},"data-question-id":e.id,"data-question-type":e.type,children:[!l&&jsxs("label",{id:`${e.id}-label`,htmlFor:e.id,style:{display:"block",marginBottom:"6px",fontWeight:500,fontSize:"14px"},children:[u!==void 0&&jsxs("span",{style:{marginRight:"4px",color:"#6b7280"},children:[u,"."]}),e.label,e.required&&jsx("span",{style:{color:"#ef4444",marginLeft:"4px"},"aria-label":"required",children:"*"})]}),e.description&&jsx("p",{style:{margin:"0 0 8px",fontSize:"13px",color:"#6b7280"},children:e.description}),jsx(m,{question:e,value:r,onChange:o,error:t,disabled:d}),t&&jsx("p",{id:`${e.id}-error`,role:"alert",style:{margin:"4px 0 0",fontSize:"13px",color:"#ef4444"},children:t})]}):jsxs("div",{style:{color:"#ef4444",padding:"8px",border:"1px solid #ef4444",borderRadius:"4px"},children:['Unknown question type: "',e.type,'"']})});ie.displayName="QuestionRenderer";var q={width:"100%",padding:"8px 12px",fontSize:"14px",border:"1px solid #d1d5db",borderRadius:"6px",outline:"none",boxSizing:"border-box",fontFamily:"inherit"};var ee=memo(({schema:e,options:r,components:o,className:t,children:d,disabled:i=false,renderHeader:a,renderFooter:l,renderComplete:u})=>{let m=ce(e,r),{survey:g,answers:p,setAnswer:b,errors:c,getError:P,currentPageIndex:Q,totalPages:D,hasNextPage:$,hasPrevPage:G,nextPage:M,prevPage:w,submit:V,isSubmitted:L,isValid:H,progress:B,getPageQuestions:W}=m,T=g.pages[Q],n=useMemo(()=>W(Q),[W,Q]),y=Q===D-1,C=useCallback(s=>{s?.preventDefault(),V();},[V]);if(d)return jsx(Fragment,{children:d(m)});if(L)return u?jsx(Fragment,{children:u()}):jsxs("div",{style:{textAlign:"center",padding:"40px 20px"},children:[jsx("div",{style:{fontSize:"48px",marginBottom:"16px"},children:"\u2713"}),jsx("h2",{style:{margin:"0 0 8px",fontSize:"20px",fontWeight:600},children:"Thank you!"}),jsx("p",{style:{margin:0,color:"#6b7280"},children:"Your response has been submitted."})]});let Y=g.settings?.showQuestionNumbers??true,K=0;if(Y)for(let s=0;s<Q;s++)K+=g.pages[s].questions.length;return jsxs("form",{className:t,onSubmit:C,noValidate:true,style:{maxWidth:"640px",margin:"0 auto",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'},children:[a?a({title:g.title,description:g.description,progress:B,currentPage:Q+1,totalPages:D}):jsxs("div",{style:{marginBottom:"24px"},children:[g.title&&jsx("h1",{style:{margin:"0 0 4px",fontSize:"24px",fontWeight:700},children:g.title}),g.description&&jsx("p",{style:{margin:"0 0 12px",color:"#6b7280",fontSize:"14px"},children:g.description}),g.settings?.showProgress&&D>1&&jsxs("div",{style:{marginBottom:"16px"},children:[jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:"12px",color:"#6b7280",marginBottom:"4px"},children:[jsxs("span",{children:["Page ",Q+1," of ",D]}),jsxs("span",{children:[B,"% complete"]})]}),jsx("div",{style:{width:"100%",height:"4px",backgroundColor:"#e5e7eb",borderRadius:"2px",overflow:"hidden"},children:jsx("div",{style:{width:`${B}%`,height:"100%",backgroundColor:"#3b82f6",borderRadius:"2px",transition:"width 0.3s ease"}})})]}),T?.title&&jsx("h2",{style:{margin:"0 0 4px",fontSize:"18px",fontWeight:600},children:T.title}),T?.description&&jsx("p",{style:{margin:"0 0 8px",color:"#6b7280",fontSize:"13px"},children:T.description})]}),n.map((s,x)=>jsx(ie,{question:s,value:p[s.id],onChange:I=>b(s.id,I),error:P(s.id),disabled:i,components:o,questionNumber:Y?K+x+1:void 0},s.id)),l?l({hasPrevPage:G,hasNextPage:$,isLastPage:y,prevPage:w,nextPage:()=>M(),submit:()=>V(),isValid:H}):jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginTop:"24px",gap:"12px"},children:[G&&g.settings?.allowBack?jsx("button",{type:"button",onClick:w,style:Oe,children:g.settings?.prevText??"Previous"}):jsx("div",{}),y?jsx("button",{type:"submit",style:ge,children:g.settings?.submitText??"Submit"}):jsx("button",{type:"button",onClick:()=>M(),style:ge,children:g.settings?.nextText??"Next"})]}),c.some(s=>s.questionId==="__submit__")&&jsx("p",{role:"alert",style:{color:"#ef4444",fontSize:"14px",marginTop:"12px"},children:c.find(s=>s.questionId==="__submit__")?.message})]})});ee.displayName="SurveyRenderer";var ge={padding:"10px 24px",fontSize:"14px",fontWeight:600,color:"#fff",backgroundColor:"#3b82f6",border:"none",borderRadius:"6px",cursor:"pointer",fontFamily:"inherit"},Oe={padding:"10px 24px",fontSize:"14px",fontWeight:600,color:"#374151",backgroundColor:"#f3f4f6",border:"1px solid #d1d5db",borderRadius:"6px",cursor:"pointer",fontFamily:"inherit"};function me(e){let r=e??{id:d("survey"),title:"Untitled Survey",pages:[{id:d("page"),title:"Page 1",questions:[]}]};return {schema:r,selectedQuestionId:null,selectedPageId:r.pages[0]?.id??null,isDragging:false}}function be(e,r){switch(r.type){case "SET_SCHEMA":return {...e,schema:r.payload};case "ADD_PAGE":{let o={id:d("page"),title:`Page ${e.schema.pages.length+1}`,questions:[],...r.payload};return {...e,schema:{...e.schema,pages:[...e.schema.pages,o]},selectedPageId:o.id}}case "REMOVE_PAGE":{let o=e.schema.pages.filter(t=>t.id!==r.payload.pageId);return o.length===0?e:{...e,schema:{...e.schema,pages:o},selectedPageId:o[0].id,selectedQuestionId:null}}case "UPDATE_PAGE":return {...e,schema:{...e.schema,pages:e.schema.pages.map(o=>o.id===r.payload.pageId?{...o,...r.payload.updates}:o)}};case "ADD_QUESTION":{let o={id:d("q"),type:"text",label:"New Question",required:false,options:[],validation:[],...r.payload.question};return {...e,schema:{...e.schema,pages:e.schema.pages.map(t=>t.id===r.payload.pageId?{...t,questions:[...t.questions,o]}:t)},selectedQuestionId:o.id}}case "REMOVE_QUESTION":return {...e,schema:{...e.schema,pages:e.schema.pages.map(o=>o.id===r.payload.pageId?{...o,questions:o.questions.filter(t=>t.id!==r.payload.questionId)}:o)},selectedQuestionId:e.selectedQuestionId===r.payload.questionId?null:e.selectedQuestionId};case "UPDATE_QUESTION":return {...e,schema:{...e.schema,pages:e.schema.pages.map(o=>o.id===r.payload.pageId?{...o,questions:o.questions.map(t=>t.id===r.payload.questionId?{...t,...r.payload.updates}:t)}:o)}};case "REORDER_QUESTIONS":return {...e,schema:{...e.schema,pages:e.schema.pages.map(o=>{if(o.id!==r.payload.pageId)return o;let t=[...o.questions],[d]=t.splice(r.payload.fromIndex,1);return t.splice(r.payload.toIndex,0,d),{...o,questions:t}})}};case "REORDER_PAGES":{let o=[...e.schema.pages],[t]=o.splice(r.payload.fromIndex,1);return o.splice(r.payload.toIndex,0,t),{...e,schema:{...e.schema,pages:o}}}case "MOVE_QUESTION":{let o=null,t=e.schema.pages.map(i=>{if(i.id!==r.payload.fromPageId)return i;let a=[...i.questions];return [o]=a.splice(r.payload.fromIndex,1),{...i,questions:a}});if(!o)return e;let d=t.map(i=>{if(i.id!==r.payload.toPageId)return i;let a=[...i.questions];return a.splice(r.payload.toIndex,0,o),{...i,questions:a}});return {...e,schema:{...e.schema,pages:d}}}case "SELECT_QUESTION":return {...e,selectedQuestionId:r.payload.questionId};case "SELECT_PAGE":return {...e,selectedPageId:r.payload.pageId,selectedQuestionId:null};case "SET_DRAGGING":return {...e,isDragging:r.payload};default:return e}}var Ne=[{value:"text",label:"Text Input"},{value:"textarea",label:"Textarea"},{value:"number",label:"Number"},{value:"email",label:"Email"},{value:"radio",label:"Radio Group"},{value:"checkbox",label:"Checkbox Group"},{value:"select",label:"Dropdown"},{value:"date",label:"Date"},{value:"rating",label:"Rating"}],fe=["radio","checkbox","select"],se=memo(({question:e,pageId:r,onUpdate:o,onDelete:t})=>{let[d,i]=useState(false),a=fe.includes(e.type),l=useCallback(p=>{o(e.id,r,p);},[o,e.id,r]),u=useCallback(()=>{let p=[...e.options??[]],b=p.length+1;p.push({label:`Option ${b}`,value:`option_${b}`}),l({options:p});},[e.options,l]),m=useCallback((p,b,c)=>{let P=[...e.options??[]];P[p]={...P[p],[b]:c},l({options:P});},[e.options,l]),g=useCallback(p=>{let b=[...e.options??[]];b.splice(p,1),l({options:b});},[e.options,l]);return jsxs("div",{style:Ve,children:[jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"12px"},children:[jsx("span",{style:{fontSize:"12px",color:"#9ca3af",fontFamily:"monospace"},children:e.id}),jsx("button",{type:"button",onClick:()=>t(e.id,r),style:xe,title:"Delete question",children:"\u2715"})]}),jsxs("div",{style:_,children:[jsx("label",{style:U,children:"Question Label"}),jsx("input",{type:"text",value:e.label,onChange:p=>l({label:p.target.value}),style:z,placeholder:"Enter question label"})]}),jsxs("div",{style:_,children:[jsx("label",{style:U,children:"Type"}),jsx("select",{value:e.type,onChange:p=>{let b=p.target.value,c={type:b};fe.includes(b)&&(!e.options||e.options.length===0)&&(c.options=[{label:"Option 1",value:"option_1"},{label:"Option 2",value:"option_2"}]),l(c);},style:z,children:Ne.map(p=>jsx("option",{value:p.value,children:p.label},p.value))})]}),jsxs("div",{style:{..._,flexDirection:"row",alignItems:"center",gap:"8px"},children:[jsx("input",{type:"checkbox",id:`${e.id}-required`,checked:e.required??false,onChange:p=>l({required:p.target.checked})}),jsx("label",{htmlFor:`${e.id}-required`,style:{fontSize:"13px",cursor:"pointer"},children:"Required"})]}),a&&jsxs("div",{style:_,children:[jsx("label",{style:U,children:"Options"}),e.options?.map((p,b)=>jsxs("div",{style:{display:"flex",gap:"6px",marginBottom:"6px",alignItems:"center"},children:[jsx("input",{type:"text",value:p.label,onChange:c=>m(b,"label",c.target.value),placeholder:"Label",style:{...z,flex:1}}),jsx("input",{type:"text",value:p.value,onChange:c=>m(b,"value",c.target.value),placeholder:"Value",style:{...z,flex:1}}),jsx("button",{type:"button",onClick:()=>g(b),style:{...xe,fontSize:"14px"},title:"Remove option",children:"\u2715"})]},b)),jsx("button",{type:"button",onClick:u,style:Be,children:"+ Add Option"})]}),jsx("button",{type:"button",onClick:()=>i(!d),style:{background:"none",border:"none",color:"#3b82f6",fontSize:"13px",cursor:"pointer",padding:"4px 0",fontFamily:"inherit"},children:d?"\u25BE Hide Advanced":"\u25B8 Show Advanced"}),d&&jsxs("div",{style:{marginTop:"8px"},children:[jsxs("div",{style:_,children:[jsx("label",{style:U,children:"Description"}),jsx("input",{type:"text",value:e.description??"",onChange:p=>l({description:p.target.value||void 0}),style:z,placeholder:"Optional helper text"})]}),jsxs("div",{style:_,children:[jsx("label",{style:U,children:"Placeholder"}),jsx("input",{type:"text",value:e.placeholder??"",onChange:p=>l({placeholder:p.target.value||void 0}),style:z,placeholder:"Input placeholder"})]}),jsxs("div",{style:_,children:[jsx("label",{style:U,children:"Visible If (condition)"}),jsx("input",{type:"text",value:e.visibleIf??"",onChange:p=>l({visibleIf:p.target.value||void 0}),style:{...z,fontFamily:"monospace",fontSize:"12px"},placeholder:"{q1} === 'yes'"}),jsxs("span",{style:{fontSize:"11px",color:"#9ca3af"},children:["Use ","{questionId}"," to reference other answers"]})]}),jsxs("div",{style:_,children:[jsx("label",{style:U,children:"Default Value"}),jsx("input",{type:"text",value:String(e.defaultValue??""),onChange:p=>l({defaultValue:p.target.value||void 0}),style:z,placeholder:"Default answer"})]})]})]})});se.displayName="QuestionEditor";var Ve={padding:"16px",border:"1px solid #e5e7eb",borderRadius:"8px",backgroundColor:"#fff"},_={display:"flex",flexDirection:"column",marginBottom:"12px"},U={fontSize:"12px",fontWeight:600,color:"#374151",marginBottom:"4px",textTransform:"uppercase",letterSpacing:"0.5px"},z={padding:"6px 10px",fontSize:"13px",border:"1px solid #d1d5db",borderRadius:"4px",outline:"none",fontFamily:"inherit",boxSizing:"border-box"},xe={background:"none",border:"none",color:"#ef4444",cursor:"pointer",fontSize:"16px",padding:"2px 6px",borderRadius:"4px",lineHeight:1},Be={background:"none",border:"1px dashed #d1d5db",borderRadius:"4px",padding:"6px 12px",fontSize:"13px",color:"#6b7280",cursor:"pointer",width:"100%",fontFamily:"inherit"};var Me=memo(({value:e,onChange:r,className:o,showPreview:t=true,showJson:d=false,layout:i="horizontal"})=>{let[a,l]=useReducer(be,e,n=>me(n)),[u,m]=useState("editor"),g=useRef(null),p=useRef(null),b=useRef(e);useEffect(()=>{e&&e!==b.current&&(l({type:"SET_SCHEMA",payload:e}),b.current=e);},[e]);let c=useRef(a.schema);useEffect(()=>{a.schema!==c.current&&(r?.(a.schema),c.current=a.schema);},[a.schema,r]);let P=useMemo(()=>a.schema.pages.find(n=>n.id===a.selectedPageId)??a.schema.pages[0],[a.schema.pages,a.selectedPageId]),Q=useCallback(n=>{l({type:"ADD_QUESTION",payload:{pageId:n}});},[]),D=useCallback((n,y,C)=>{l({type:"UPDATE_QUESTION",payload:{pageId:y,questionId:n,updates:C}});},[]),$=useCallback((n,y)=>{l({type:"REMOVE_QUESTION",payload:{pageId:y,questionId:n}});},[]),G=useCallback(n=>{l({type:"SELECT_QUESTION",payload:{questionId:n}});},[]),M=useCallback((n,y)=>{g.current={pageId:n,index:y},l({type:"SET_DRAGGING",payload:true});},[]),w=useCallback((n,y,C)=>{n.preventDefault(),p.current={pageId:y,index:C};},[]),V=useCallback(n=>{n.preventDefault();let y=g.current,C=p.current;y&&C&&(y.pageId===C.pageId?l({type:"REORDER_QUESTIONS",payload:{pageId:y.pageId,fromIndex:y.index,toIndex:C.index}}):l({type:"MOVE_QUESTION",payload:{fromPageId:y.pageId,toPageId:C.pageId,fromIndex:y.index,toIndex:C.index}})),g.current=null,p.current=null,l({type:"SET_DRAGGING",payload:false});},[]),L=useCallback(()=>{g.current=null,p.current=null,l({type:"SET_DRAGGING",payload:false});},[]),H=useCallback(n=>{l({type:"SET_SCHEMA",payload:{...a.schema,title:n.target.value}});},[a.schema]),B=useMemo(()=>JSON.stringify(a.schema,null,2),[a.schema]),W=useCallback(n=>{try{let y=JSON.parse(n.target.value);l({type:"SET_SCHEMA",payload:y});}catch{}},[]),T=i==="horizontal";return jsxs("div",{className:o,style:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',display:"flex",flexDirection:T?"row":"column",gap:"16px",minHeight:"500px"},children:[jsxs("div",{style:{flex:T?"1 1 50%":"auto",minWidth:0,display:"flex",flexDirection:"column"},children:[jsx("div",{style:{display:"flex",gap:"0",borderBottom:"1px solid #e5e7eb",marginBottom:"16px"},children:["editor","preview","json"].filter(n=>!(n==="preview"&&!t||n==="json"&&!d)).map(n=>jsx("button",{type:"button",onClick:()=>m(n),style:{padding:"8px 16px",fontSize:"13px",fontWeight:u===n?600:400,color:u===n?"#3b82f6":"#6b7280",background:"none",border:"none",borderBottom:u===n?"2px solid #3b82f6":"2px solid transparent",cursor:"pointer",fontFamily:"inherit",textTransform:"capitalize"},children:n},n))}),u==="editor"&&jsxs("div",{style:{flex:1,overflow:"auto"},children:[jsx("div",{style:{marginBottom:"16px"},children:jsx("input",{type:"text",value:a.schema.title??"",onChange:H,placeholder:"Survey Title",style:{width:"100%",padding:"10px 12px",fontSize:"18px",fontWeight:700,border:"1px solid #e5e7eb",borderRadius:"6px",outline:"none",boxSizing:"border-box",fontFamily:"inherit"}})}),jsxs("div",{style:{display:"flex",gap:"8px",marginBottom:"16px",flexWrap:"wrap",alignItems:"center"},children:[a.schema.pages.map((n,y)=>jsx("button",{type:"button",onClick:()=>l({type:"SELECT_PAGE",payload:{pageId:n.id}}),style:{padding:"6px 14px",fontSize:"13px",fontWeight:a.selectedPageId===n.id?600:400,backgroundColor:a.selectedPageId===n.id?"#3b82f6":"#f3f4f6",color:a.selectedPageId===n.id?"#fff":"#374151",border:"none",borderRadius:"16px",cursor:"pointer",fontFamily:"inherit"},children:n.title||`Page ${y+1}`},n.id)),jsx("button",{type:"button",onClick:()=>l({type:"ADD_PAGE"}),style:{padding:"6px 14px",fontSize:"13px",backgroundColor:"transparent",color:"#3b82f6",border:"1px dashed #3b82f6",borderRadius:"16px",cursor:"pointer",fontFamily:"inherit"},children:"+ Page"}),a.schema.pages.length>1&&a.selectedPageId&&jsx("button",{type:"button",onClick:()=>l({type:"REMOVE_PAGE",payload:{pageId:a.selectedPageId}}),style:{padding:"4px 8px",fontSize:"12px",backgroundColor:"transparent",color:"#ef4444",border:"none",cursor:"pointer",fontFamily:"inherit"},title:"Remove current page",children:"Remove Page"})]}),P&&jsx("div",{style:{marginBottom:"12px"},children:jsx("input",{type:"text",value:P.title??"",onChange:n=>l({type:"UPDATE_PAGE",payload:{pageId:P.id,updates:{title:n.target.value}}}),placeholder:"Page Title",style:{width:"100%",padding:"6px 10px",fontSize:"14px",border:"1px solid #e5e7eb",borderRadius:"4px",outline:"none",boxSizing:"border-box",fontFamily:"inherit"}})}),jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[P?.questions.map((n,y)=>jsxs("div",{draggable:true,onDragStart:()=>M(P.id,y),onDragOver:C=>w(C,P.id,y),onDrop:V,onDragEnd:L,onClick:()=>G(n.id),style:{cursor:"grab",opacity:a.isDragging?.8:1,border:a.selectedQuestionId===n.id?"2px solid #3b82f6":"1px solid transparent",borderRadius:"10px",transition:"border-color 0.15s ease"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 12px",backgroundColor:"#f9fafb",borderRadius:a.selectedQuestionId===n.id?"8px 8px 0 0":"8px",borderBottom:a.selectedQuestionId===n.id?"1px solid #e5e7eb":"none"},children:[jsx("span",{style:{color:"#9ca3af",cursor:"grab",userSelect:"none"},children:"\u283F"}),jsx("span",{style:{flex:1,fontSize:"14px",fontWeight:500},children:n.label||"Untitled"}),jsx("span",{style:{fontSize:"11px",padding:"2px 8px",backgroundColor:"#e5e7eb",borderRadius:"10px",color:"#6b7280"},children:n.type})]}),a.selectedQuestionId===n.id&&jsx(se,{question:n,pageId:P.id,onUpdate:D,onDelete:$})]},n.id)),jsx("button",{type:"button",onClick:()=>Q(P?.id??a.schema.pages[0].id),style:{padding:"12px",fontSize:"14px",fontWeight:500,color:"#6b7280",backgroundColor:"#fff",border:"2px dashed #d1d5db",borderRadius:"8px",cursor:"pointer",fontFamily:"inherit",transition:"border-color 0.15s ease, color 0.15s ease"},onMouseEnter:n=>{n.currentTarget.style.borderColor="#3b82f6",n.currentTarget.style.color="#3b82f6";},onMouseLeave:n=>{n.currentTarget.style.borderColor="#d1d5db",n.currentTarget.style.color="#6b7280";},children:"+ Add Question"})]})]}),u==="preview"&&t&&jsx("div",{style:{flex:1,overflow:"auto",padding:"16px",backgroundColor:"#f9fafb",borderRadius:"8px"},children:jsx(ee,{schema:a.schema,options:{onSubmit:n=>console.log("Preview submit:",n)}})}),u==="json"&&jsx("div",{style:{flex:1},children:jsx("textarea",{value:B,onChange:W,style:{width:"100%",height:"100%",minHeight:"400px",padding:"12px",fontSize:"12px",fontFamily:'"SF Mono", "Fira Code", monospace',border:"1px solid #e5e7eb",borderRadius:"6px",resize:"vertical",outline:"none",boxSizing:"border-box",backgroundColor:"#fafafa",lineHeight:1.5}})})]}),T&&t&&u==="editor"&&jsxs("div",{style:{flex:"1 1 50%",minWidth:0,padding:"20px",backgroundColor:"#f9fafb",borderRadius:"8px",border:"1px solid #e5e7eb",overflow:"auto"},children:[jsx("div",{style:{fontSize:"12px",color:"#9ca3af",marginBottom:"12px",textTransform:"uppercase",letterSpacing:"0.5px",fontWeight:600},children:"Live Preview"}),jsx(ee,{schema:a.schema,options:{onSubmit:n=>console.log("Preview submit:",n)}})]})]})});Me.displayName="SurveyBuilder";export{ce as a,Te as b,ie as c,ee as d,me as e,be as f,se as g,Me as h};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';function A(e){if(!e||typeof e!="object")throw new u("Schema must be a valid object");if(!e.id||typeof e.id!="string")throw new u('Schema must have a string "id"');if(!Array.isArray(e.pages)||e.pages.length===0)throw new u("Schema must have at least one page");return {...e,title:e.title??"",description:e.description??"",pages:e.pages.map(h),settings:{showProgress:true,allowBack:true,validateOnPageChange:true,showQuestionNumbers:true,submitText:"Submit",nextText:"Next",prevText:"Previous",...e.settings}}}function h(e,t){if(!e.id)throw new u(`Page at index ${t} must have an "id"`);if(!Array.isArray(e.questions))throw new u(`Page "${e.id}" must have a "questions" array`);return {...e,title:e.title??"",description:e.description??"",questions:e.questions.map((r,i)=>v(r,i,e.id))}}function v(e,t,r){if(!e.id)throw new u(`Question at index ${t} in page "${r}" must have an "id"`);if(!e.type)throw new u(`Question "${e.id}" in page "${r}" must have a "type"`);if(!e.label)throw new u(`Question "${e.id}" in page "${r}" must have a "label"`);return {required:false,...e,options:e.options??[],validation:e.validation??[],meta:e.meta??{}}}function g(e){return e.pages.flatMap(t=>t.questions)}function $(e,t){for(let r=0;r<e.pages.length;r++){let i=e.pages[r],s=i.questions.findIndex(n=>n.id===t);if(s!==-1)return {question:i.questions[s],page:i,pageIndex:r,questionIndex:s}}return null}function P(e="item"){return `${e}_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}var u=class extends Error{constructor(t){super(`[react-minimal-survey-builder] ${t}`),this.name="SurveySchemaError";}};function p(e,t,r){let i=[];if(e.required&&m(t))return i.push({questionId:e.id,message:`"${e.label}" is required`,rule:"required"}),i;if(m(t))return i;let s=e.validation??[];for(let n of s){let a=S(n,t,e,r);a&&i.push(a);}return i}function N(e,t,r,i){let s=e.pages[t];return s?s.questions.filter(n=>i.has(n.id)).flatMap(n=>p(n,r[n.id],r)):[]}function E(e,t,r){return g(e).filter(i=>r.has(i.id)).flatMap(i=>p(i,t[i.id],t))}function S(e,t,r,i){let s=String(t??"");switch(e.type){case "required":if(m(t))return o(r.id,e,`"${r.label}" is required`);break;case "minLength":if(typeof e.value=="number"&&s.length<e.value)return o(r.id,e,`"${r.label}" must be at least ${e.value} characters`);break;case "maxLength":if(typeof e.value=="number"&&s.length>e.value)return o(r.id,e,`"${r.label}" must be at most ${e.value} characters`);break;case "min":if(typeof e.value=="number"&&Number(t)<e.value)return o(r.id,e,`"${r.label}" must be at least ${e.value}`);break;case "max":if(typeof e.value=="number"&&Number(t)>e.value)return o(r.id,e,`"${r.label}" must be at most ${e.value}`);break;case "pattern":{if(!(e.value instanceof RegExp?e.value:new RegExp(String(e.value))).test(s))return o(r.id,e,`"${r.label}" does not match the required pattern`);break}case "email":{if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s))return o(r.id,e,`"${r.label}" must be a valid email`);break}case "custom":if(e.validator){let n=e.validator(t,i);if(n!==true&&typeof n=="string")return o(r.id,e,n);if(n===false)return o(r.id,e,e.message??`"${r.label}" is invalid`)}break}return null}function m(e){return !!(e==null||e===""||Array.isArray(e)&&e.length===0)}function o(e,t,r){return {questionId:e,message:t.message??r,rule:t.type}}function c(e,t){if(!e||e.trim()==="")return true;try{let r=e.replace(/\{([^}]+)\}/g,(i,s)=>{let n=t[s.trim()];return n==null?"undefined":typeof n=="string"||Array.isArray(n)?JSON.stringify(n):String(n)});return f(r)}catch{return console.warn(`[react-minimal-survey-builder] Failed to evaluate condition: "${e}"`),true}}function k(e,t){let r=new Set;for(let i of e.pages)if(c(i.visibleIf,t))for(let s of i.questions)c(s.visibleIf,t)&&r.add(s.id);return r}function W(e,t){return e.pages.filter(r=>c(r.visibleIf,t))}function R(e,t){return c(e.visibleIf,t)?e.questions.filter(r=>c(r.visibleIf,t)):[]}function f(e){let t=e.trim(),r=b(t,"||");if(r.length>1)return r.some(n=>f(n));let i=b(t,"&&");if(i.length>1)return i.every(n=>f(n));if(t.startsWith("!"))return !f(t.slice(1));if(t.startsWith("(")&&t.endsWith(")"))return f(t.slice(1,-1));for(let n of ["===","!==",">=","<=",">","<","==","!="]){let a=t.indexOf(n);if(a!==-1){let d=l(t.slice(0,a).trim()),y=l(t.slice(a+n.length).trim());return w(d,y,n)}}if(t.includes(".includes(")){let n=t.match(/^(.+)\.includes\((.+)\)$/);if(n){let a=l(n[1].trim()),d=l(n[2].trim());if(Array.isArray(a))return a.includes(d);if(typeof a=="string")return a.includes(String(d))}}let s=l(t);return x(s)}function b(e,t){let r=[],i=0,s="";for(let n=0;n<e.length;n++)e[n]==="("&&i++,e[n]===")"&&i--,i===0&&e.startsWith(t,n)?(r.push(s),s="",n+=t.length-1):s+=e[n];return r.push(s),r.map(n=>n.trim()).filter(Boolean)}function l(e){let t=e.trim();if(t==="undefined")return;if(t==="null")return null;if(t==="true")return true;if(t==="false")return false;if(t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))return t.slice(1,-1);if(t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return t}let r=Number(t);return !isNaN(r)&&t!==""?r:t}function w(e,t,r){switch(r){case "===":case "==":return e===t;case "!==":case "!=":return e!==t;case ">":return Number(e)>Number(t);case "<":return Number(e)<Number(t);case ">=":return Number(e)>=Number(t);case "<=":return Number(e)<=Number(t);default:return false}}function x(e){return !(e==null||e===""||e===false||e===0||Array.isArray(e)&&e.length===0)}exports.a=A;exports.b=g;exports.c=$;exports.d=P;exports.e=u;exports.f=p;exports.g=N;exports.h=E;exports.i=c;exports.j=k;exports.k=W;exports.l=R;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkJWOXQRNV_js=require('./chunk-JWOXQRNV.js');var n=class{constructor(e,t={}){this.schema=chunkJWOXQRNV_js.a(e),this.options=t,this.listeners=new Map,this.stateChangeCallbacks=new Set;let s=this.buildInitialAnswers(t.initialAnswers),r=chunkJWOXQRNV_js.j(this.schema,s);this.state={answers:s,currentPageIndex:0,errors:[],isValid:true,isSubmitted:false,visibleQuestionIds:r};}getState(){return {...this.state}}getSchema(){return this.schema}getAnswers(){return {...this.state.answers}}getCurrentPage(){return this.schema.pages[this.state.currentPageIndex]??null}getCurrentPageIndex(){return this.state.currentPageIndex}getTotalPages(){return this.schema.pages.length}getErrors(){return [...this.state.errors]}isValid(){return this.state.isValid}isSubmitted(){return this.state.isSubmitted}getVisibleQuestionIds(){return new Set(this.state.visibleQuestionIds)}setAnswer(e,t){let s={...this.state.answers,[e]:t},r=chunkJWOXQRNV_js.j(this.schema,s);this.updateState({answers:s,visibleQuestionIds:r,errors:this.state.errors.filter(d=>d.questionId!==e)}),this.emit("answerChanged",{questionId:e,value:t,answers:s}),this.options.onChange?.(s,e);}nextPage(){let{currentPageIndex:e}=this.state,t=e+1;if(t>=this.schema.pages.length)return false;if(this.schema.settings?.validateOnPageChange){let s=chunkJWOXQRNV_js.g(this.schema,e,this.state.answers,this.state.visibleQuestionIds);if(s.length>0)return this.updateState({errors:s,isValid:false}),this.emit("validated",{errors:s,isValid:false}),false}return this.updateState({currentPageIndex:t,errors:[]}),this.emit("pageChanged",{pageIndex:t}),this.options.onPageChange?.(t),true}prevPage(){let{currentPageIndex:e}=this.state;if(e<=0||!this.schema.settings?.allowBack)return false;let t=e-1;return this.updateState({currentPageIndex:t,errors:[]}),this.emit("pageChanged",{pageIndex:t}),this.options.onPageChange?.(t),true}goToPage(e){return e<0||e>=this.schema.pages.length?false:(this.updateState({currentPageIndex:e,errors:[]}),this.emit("pageChanged",{pageIndex:e}),this.options.onPageChange?.(e),true)}validate(){let e=chunkJWOXQRNV_js.h(this.schema,this.state.answers,this.state.visibleQuestionIds),t=e.length===0;return this.updateState({errors:e,isValid:t}),this.emit("validated",{errors:e,isValid:t}),this.options.onValidate?.(e),e}validateCurrentPage(){let e=chunkJWOXQRNV_js.g(this.schema,this.state.currentPageIndex,this.state.answers,this.state.visibleQuestionIds),t=e.length===0;return this.updateState({errors:e,isValid:t}),this.emit("validated",{errors:e,isValid:t}),e}async submit(){let e=this.validate();if(e.length>0)return {success:false,errors:e};try{return await this.options.onSubmit?.(this.state.answers),this.updateState({isSubmitted:!0}),this.emit("submitted",{answers:this.state.answers}),{success:!0,errors:[]}}catch(t){return {success:false,errors:[{questionId:"__submit__",message:t instanceof Error?t.message:"Submission failed",rule:"custom"}]}}}reset(e){let t=this.buildInitialAnswers(e??this.options.initialAnswers),s=chunkJWOXQRNV_js.j(this.schema,t);this.updateState({answers:t,currentPageIndex:0,errors:[],isValid:true,isSubmitted:false,visibleQuestionIds:s});}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.listeners.get(e)?.delete(t)}onStateChange(e){return this.stateChangeCallbacks.add(e),()=>this.stateChangeCallbacks.delete(e)}updateState(e){this.state={...this.state,...e},this.stateChangeCallbacks.forEach(t=>t(this.getState()));}emit(e,t){let s={type:e,payload:t,timestamp:Date.now()};this.listeners.get(e)?.forEach(r=>r(s));}buildInitialAnswers(e){let t={};for(let s of chunkJWOXQRNV_js.b(this.schema))s.defaultValue!==void 0&&(t[s.id]=s.defaultValue);return e&&Object.assign(t,e),t}};function S(o,e){return new n(o,e)}exports.a=n;exports.b=S;
|