# Survey Question Builder Implementation ## Overview A comprehensive, interactive survey question builder that allows users to create and manage survey templates with dynamic question forms, visual choice management, and real-time preview capabilities. ## Features Implemented ### Phase 1: Dynamic Question Management ✅ **File**: `static/surveys/js/builder.js` #### Features: - **Add/Remove Questions**: Dynamic addition and removal of survey questions - **Question Reordering**: Move questions up/down to adjust order - **Question Numbering**: Automatic question numbering - **Question Types**: Support for multiple question types: - Text (short answer) - Rating (1-5 scale) - Multiple Choice (checkboxes) - Single Choice (radio buttons) - **Required Field Toggle**: Mark questions as required or optional - **Formset Integration**: Seamlessly integrates with Django formsets - **Visual Feedback**: Highlight animations for new questions #### Key Functions: ```javascript - addQuestion() - Adds a new question form - deleteQuestion() - Removes a question with confirmation - moveQuestion() - Reorders questions - updateQuestionNumbers() - Updates question numbering - setupQuestionTypeHandlers() - Manages question type visibility ``` ### Phase 2: Visual Choices Builder ✅ **File**: `static/surveys/js/choices-builder.js` #### Features: - **Visual UI**: Intuitive interface for managing multiple choice options - **Bilingual Support**: Add choices in both English and Arabic - **Value Management**: Assign unique values to each choice - **Add/Remove Choices**: Dynamic management of choice options - **JSON Generation**: Automatically generates valid JSON for choices - **Real-time Updates**: Changes reflect immediately in JSON textarea - **Drag Handles**: Ready for future drag-and-drop functionality #### Key Functions: ```javascript - createChoicesUI() - Initializes the visual choices interface - addChoice() - Adds a new choice option - createChoiceElement() - Renders a single choice item - updateChoicesJSON() - Updates the JSON textarea - parseChoices() - Parses existing JSON from textarea ``` #### Choice Structure: ```json [ { "value": "1", "label": "Excellent", "label_ar": "ممتاز" } ] ``` ### Phase 3: Real-time Survey Preview ✅ **File**: `static/surveys/js/preview.js` #### Features: - **Live Preview**: Real-time preview as questions are added/modified - **Toggle Panel**: Show/hide preview panel - **Expandable View**: Expand preview for full-screen viewing - **Question Rendering**: Renders all question types correctly: - Text questions show input fields - Rating questions show clickable rating badges - Multiple choice shows checkboxes - Single choice shows radio buttons - **Required Indicators**: Shows asterisk for required questions - **Auto-scroll**: Automatically scrolls to newly added questions #### Key Functions: ```javascript - createPreviewPanel() - Creates the preview UI - updatePreview() - Refreshes the preview content - renderQuestionPreview() - Renders individual questions - extractQuestionData() - Extracts question data from form - togglePreview() - Shows/hides preview panel ``` ## File Structure ``` static/surveys/js/ ├── builder.js # Main question builder functionality ├── choices-builder.js # Visual choices management └── preview.js # Real-time survey preview templates/surveys/ └── template_form.html # Survey template form with builder integration ``` ## Template Integration ### JavaScript Modules All three modules are loaded in `template_form.html`: ```html {% block extra_js %} {% endblock %} ``` ### CSS Styles Enhanced styling for: - Question forms and animations - Reorder controls - Choices builder UI - Preview panel - Hover effects and transitions ## User Interface ### Survey Builder Interface 1. **Template Details Section** - Survey name (English/Arabic) - Hospital selection - Survey type - Scoring method - Negative threshold - Active status toggle 2. **Questions Section** - "Add Question" button - Question forms with: - Delete button - Reorder controls (up/down arrows) - Question text (English/Arabic) - Question type dropdown - Order number - Required checkbox - Choices field (for choice-based questions) 3. **Preview Button** - Located in page header - Toggles preview panel ### Preview Panel - **Header**: Preview title with expand/close buttons - **Content**: Real-time rendered survey preview - **Scrollable**: Limited height with scroll when expanded - **Responsive**: Adapts to different screen sizes ## Usage Examples ### Creating a Text Question 1. Click "Add Question" 2. Enter question text in English field 3. Optionally enter Arabic translation 4. Select "Text" as question type 5. Set order number 6. Check "Required" if needed ### Creating a Rating Question 1. Click "Add Question" 2. Enter question text 3. Select "Rating (1-5)" as question type 4. Preview will show 5 clickable rating badges ### Creating a Multiple Choice Question 1. Click "Add Question" 2. Enter question text 3. Select "Multiple Choice" as question type 4. Choices builder UI appears 5. Click "Add Choice" for each option 6. Enter: - Value (e.g., "1", "2", "3") - Label (English text) - Label (Arabic translation) 7. Preview shows checkboxes for each choice ### Creating a Single Choice Question Same as multiple choice, but preview shows radio buttons instead of checkboxes ## Technical Details ### Question Form Structure Each question form contains: - Hidden fields: `id`, `DELETE` - Text fields: `text`, `text_ar` - Select field: `question_type` - Number field: `order` - Checkbox: `is_required` - Textarea: `choices_json` (for choice-based questions) ### Formset Management - Uses Django formset for dynamic form management - `TOTAL_FORMS` updated when adding questions - `DELETE` checkboxes handle question removal - Form indexing automatically updated ### Event Handling - **DOM Loaded**: All modules initialize - **Form Changes**: MutationObserver watches for changes - **Input Events**: Live updates to preview - **Click Events**: Button handlers for add/delete/move - **Change Events**: Question type visibility toggles ### Data Flow ``` User Input → JavaScript Module → Form Update → Preview Update ↓ JSON Generation (choices) ↓ Form Submission (Django) ``` ## Browser Compatibility - **Modern Browsers**: Chrome, Firefox, Safari, Edge (latest versions) - **Features Used**: - ES6 Classes - MutationObserver - Template literals - Arrow functions - Array methods (map, filter, forEach) ## Accessibility - Semantic HTML elements - Keyboard navigation support - ARIA labels where appropriate - High contrast colors - Clear visual indicators for required fields ## Performance Considerations - MutationObserver efficiently watches for DOM changes - Debouncing not implemented (could be added for large forms) - Preview updates on every input change (could be debounced) - Minimal DOM manipulation for smooth performance ## Future Enhancements (Phase 4 & 5) ### Potential Improvements 1. **Question Templates** - Pre-built question templates - Quick-insert common questions - Question categories 2. **Question Validation** - Real-time validation feedback - Custom validation rules - Pattern matching for text inputs 3. **Question Grouping** - Group related questions - Section headers - Conditional logic (show/hide based on answers) 4. **Import/Export** - Import questions from JSON - Export to Word/PDF - Copy questions between templates 5. **Advanced Choice Features** - Drag-and-drop reordering - Bulk edit choices - Choice images/icons 6. **Preview Enhancements** - Mobile preview mode - Print preview - Preview with sample responses 7. **Collaboration Features** - Comment on questions - Version history - Multiple editors 8. **Analytics Integration** - Question performance metrics - Response rate predictions - Survey completion estimates ## Testing ### Manual Testing Checklist - [ ] Add question appears in list - [ ] Delete question removes from list - [ ] Reorder up moves question up - [ ] Reorder down moves question down - [ ] Question numbers update correctly - [ ] Question type changes show correct fields - [ ] Choices builder appears for choice questions - [ ] Add choice creates new choice item - [ ] Delete choice removes choice item - [ ] JSON updates correctly - [ ] Preview toggles on/off - [ ] Preview shows all question types - [ ] Preview updates in real-time - [ ] Required questions show asterisk - [ ] Form submits correctly - [ ] Validation errors display correctly ### Browser Testing Test on: - Chrome (desktop & mobile) - Firefox (desktop) - Safari (desktop & mobile) - Edge (desktop) ## Troubleshooting ### Common Issues **Issue**: Preview not updating - **Solution**: Check browser console for JavaScript errors **Issue**: Choices builder not appearing - **Solution**: Ensure question type is "multiple_choice" or "single_choice" **Issue**: Form submission fails - **Solution**: Check that all required fields are filled **Issue**: Question numbering incorrect - **Solution**: Refresh page or manually update order numbers ## Support For issues or questions: 1. Check browser console for errors 2. Review Django logs 3. Verify JavaScript files are loading 4. Check network tab for failed requests ## Version History - **v1.0** (2026-01-21): Initial implementation - Phase 1: Dynamic question management - Phase 2: Visual choices builder - Phase 3: Real-time preview - Enhanced CSS styling