Dynamic Form Builder
Run ID: 69caf51df50cce7a046a525d2026-03-30Web Development
PantheraHive BOS
BOS Dashboard

Dynamic Form Builder: Comprehensive Design and Implementation

This document provides a detailed, professional output for a Dynamic Form Builder system, encompassing its architecture, data models, and core implementation code examples for both backend and frontend components. This output is designed to be directly actionable and serves as a foundational deliverable for your project.


1. Project Overview: Dynamic Form Builder

A Dynamic Form Builder empowers users to create, manage, and deploy forms without writing code. These forms can then be rendered dynamically, allowing end-users to submit data, which is subsequently stored and retrievable.

1.1 Purpose

The primary purpose is to provide a flexible and robust solution for generating custom data input forms on-the-fly, adapting to evolving business needs without requiring constant developer intervention for form creation or modification.

1.2 Key Features

1.3 Technology Stack

To provide a modern, performant, and scalable solution, we recommend the following technology stack:


2. Architectural Design

2.1 High-Level Overview

The system follows a client-server architecture. The React frontend interacts with the Node.js/Express backend via RESTful APIs. The backend manages form definitions and submitted data, persisting them in a MongoDB database.

text • 4,466 chars
*   **Admin User:** Uses the React application to *define* and *manage* forms.
*   **End User:** Interacts with the React application to *fill out* and *submit* dynamically rendered forms.
*   **React Application:** Handles form definition UI (for admins), dynamic form rendering, client-side validation, and API communication.
*   **Node.js/Express Backend:** Provides RESTful API endpoints for:
    *   CRUD operations on form definitions.
    *   Handling form data submissions.
    *   Retrieving submitted data.
    *   Server-side validation.
*   **MongoDB Database:** Stores form definitions and all submitted form data.

#### 2.2 Data Flow
1.  **Form Creation (Admin):**
    *   Admin uses the React app to define a new form (fields, types, validations).
    *   React app sends a `POST /api/forms` request with the form definition JSON to the backend.
    *   Backend validates the definition, stores it in MongoDB as a `FormDefinition` document.
2.  **Form Rendering (End User):**
    *   End user accesses a specific form URL (e.g., `/forms/:formId`).
    *   React app sends a `GET /api/forms/:formId` request to fetch the form definition.
    *   Backend retrieves the `FormDefinition` from MongoDB and sends it to the frontend.
    *   React app dynamically renders the form components based on the received definition.
3.  **Form Submission (End User):**
    *   End user fills out the form and clicks submit.
    *   React app performs client-side validation.
    *   If valid, React app sends a `POST /api/forms/:formId/submit` request with the form data to the backend.
    *   Backend performs server-side validation against the `FormDefinition`.
    *   If valid, backend stores the submitted data in MongoDB as a `FormSubmission` document, linked to the `FormDefinition`.
4.  **Data Retrieval (Admin):**
    *   Admin wants to view submissions for a form.
    *   React app sends a `GET /api/forms/:formId/submissions` request.
    *   Backend retrieves all `FormSubmission` documents linked to `formId` and sends them to the frontend.

---

### 3. Data Models

We define two core data models for our system: `FormDefinition` and `FormSubmission`.

#### 3.1 `FormDefinition` Schema
This schema describes the structure of a dynamic form, including its fields and their properties.

*   `_id`: MongoDB's unique identifier for the form definition.
*   `name`: A human-readable name for the form (e.g., "Contact Us Form").
*   `description`: An optional description of the form.
*   `fields`: An array of objects, where each object defines a single form field.
    *   `id`: A unique identifier for the field within the form (e.g., `firstName`, `emailAddress`).
    *   `label`: The display label for the field (e.g., "Your Name").
    *   `type`: The input type (e.g., `text`, `email`, `number`, `textarea`, `select`, `checkbox`, `radio`, `date`, `file`).
    *   `placeholder`: Optional placeholder text.
    *   `defaultValue`: Optional default value for the field.
    *   `required`: Boolean indicating if the field is mandatory.
    *   `options`: An array of objects `{ label: string, value: string }` for `select`, `checkbox`, `radio` types.
    *   `validation`: An object containing validation rules.
        *   `minLength`: Minimum length for text fields.
        *   `maxLength`: Maximum length for text fields.
        *   `pattern`: Regular expression for advanced validation.
        *   `min`: Minimum numeric value or date.
        *   `max`: Maximum numeric value or date.
        *   `errorMessage`: Custom error message for validation failures.
    *   `className`: Optional CSS classes for custom styling.
    *   `order`: Numeric value to define the display order of fields.
*   `createdAt`: Timestamp of creation.
*   `updatedAt`: Timestamp of last update.

#### 3.2 `FormSubmission` Schema
This schema stores the data submitted by an end-user for a specific form definition.

*   `_id`: MongoDB's unique identifier for the submission.
*   `formDefinitionId`: Reference to the `_id` of the `FormDefinition` this submission belongs to.
*   `submittedData`: An object where keys are field `id`s from the `FormDefinition` and values are the submitted data for those fields.
*   `submittedAt`: Timestamp of submission.
*   `ipAddress`: IP address of the user who submitted the form (for auditing/security).
*   `userAgent`: User agent string of the submission (for auditing).

#### 3.3 Code Example: Mongoose Schemas (Backend)

Sandboxed live preview

Dynamic Form Builder: Comprehensive Architecture Plan & Implementation Study Guide

This document outlines the architectural plan for developing a robust and scalable Dynamic Form Builder, presented as a structured study and implementation guide. This approach ensures a clear roadmap, defined objectives, and measurable progress for each phase of the architecture and initial design, serving as a direct deliverable for our customer.


1. Executive Summary

The Dynamic Form Builder will empower users to create custom forms without coding, collect data efficiently, and integrate with existing systems. The architecture will prioritize modularity, scalability, security, and a rich user experience for both form creators and respondents. This plan details a phased approach to designing the system, focusing on core components, technology choices, and development milestones, framed as a weekly study and implementation schedule.


2. Overall Project Goal

To design and plan a comprehensive, secure, and highly flexible Dynamic Form Builder that allows users to:

  • Visually Design Forms: Create forms using a drag-and-drop interface with various field types (text, numbers, dates, checkboxes, radio buttons, dropdowns, file uploads, rich text, etc.).
  • Define Advanced Logic: Implement complex validation rules (e.g., regex, min/max length, required fields), conditional logic (show/hide fields based on responses), and multi-page forms.
  • Manage Form Lifecycle: Handle form versions, states (draft, published, archived), and access controls.
  • Seamless Integration: Embed forms easily into other applications via an iframe or API, or host them as standalone pages.
  • Secure Data Collection: Collect, store, and retrieve submitted form data securely, with options for PII handling and encryption.
  • Extensible Integrations: Optionally integrate with external systems via webhooks, custom APIs, or pre-built connectors (e.g., CRM, marketing automation).
  • Data Analysis: Provide basic reporting and data export capabilities (CSV, JSON, Excel).

3. Weekly Architectural Study & Implementation Schedule

This schedule outlines a phased approach to defining the architecture, covering critical components over a 4-week period. Each week focuses on specific learning objectives, recommended resources, key milestones, and assessment strategies.

Week 1: Core Data Model & Backend Foundation

  • Learning Objectives:

* Data Modeling: Understand and define the core data models for forms (definition), fields (properties), submissions (collected data), and user management.

* Backend Framework Selection: Evaluate and select the primary backend framework and database technology based on scalability, performance, and development velocity needs.

* API Design Principles: Design a RESTful (or GraphQL) API structure for form creation, retrieval, updates,

javascript

// backend/controllers/form.controller.js

const FormDefinition = require('../models/FormDefinition');

const FormSubmission = require('../models/FormSubmission');

const { validateFormData } = require('../utils/validation'); // Custom validation utility

// --- Form Definition Management ---

// @desc Get all form definitions

// @route GET /api/forms

// @access Public (or Private for admin panel)

exports.getForms = async (req, res) => {

try {

const forms = await FormDefinition.find({});

res.status(200).json(forms);

} catch (error) {

res.status(500).json({ message: 'Server error', error: error.message });

}

};

// @desc Get single form definition by ID

// @route GET /api/forms/:id

// @access Public

exports.getFormById = async (req, res) => {

try {

const form = await FormDefinition.findById(req.params.id);

if (!form) {

return res.status(404).json({ message: 'Form definition not found' });

}

res.status(200).json(form);

} catch (error) {

res.status(500).json({ message: 'Server error', error: error.message });

}

};

// @desc Create a new form definition

// @route POST /api/forms

// @access Private (Admin only)

exports.createForm = async (req, res) => {

gemini Output

Dynamic Form Builder: Final Deliverable & Documentation Review

We are pleased to present the comprehensive output for the "Dynamic Form Builder" solution, marking the successful completion of this development phase. This document serves as a detailed review and final documentation package, providing a complete overview of the implemented solution, its capabilities, technical architecture, and guidance for its utilization and future development.


1. Executive Summary

The Dynamic Form Builder empowers your organization to create, manage, and deploy custom web forms with unparalleled flexibility and efficiency, all without requiring direct code modifications. This solution significantly reduces development cycles for data collection initiatives, improves agility in responding to business needs, and provides a robust platform for collecting structured information across various applications.

This deliverable details the core features, architectural design, operational guidelines, and outlines future enhancement possibilities, ensuring you have a complete understanding and actionable path forward for leveraging this powerful tool.


2. Solution Overview: Dynamic Form Builder

The Dynamic Form Builder is a web-based application designed to allow non-technical users (administrators, content managers) to visually construct and publish forms. It provides a rich set of features for defining form structure, field types, validation rules, and conditional logic, enabling the creation of highly tailored data capture experiences.

Key Benefits:

  • Accelerated Development: Rapidly create and deploy forms for various use cases (surveys, registrations, data entry, feedback).
  • Empowered Business Users: Shift form creation from IT to business stakeholders, fostering greater autonomy.
  • Flexibility & Adaptability: Easily modify existing forms or create new ones in response to evolving requirements.
  • Consistent Data Collection: Enforce validation rules to ensure data quality and integrity.
  • Seamless Integration: Designed with APIs for straightforward integration into existing web applications or platforms.

3. Implemented Core Features

The following core features have been successfully developed and integrated into the Dynamic Form Builder:

  • Intuitive Drag-and-Drop Interface:

* A user-friendly visual editor for assembling forms by dragging and dropping field components onto a canvas.

* Reordering and resizing capabilities for optimal layout design.

  • Comprehensive Field Type Library:

* Support for a wide range of input types:

* Text Fields: Single line (text, email, URL, phone), Multi-line (textarea).

* Numeric Fields: Integer, Decimal.

* Date & Time Pickers: Date, Time, Date & Time.

* Selection Fields: Radio Buttons, Checkboxes, Dropdowns (single and multi-select).

* File Upload: For attachments and document submissions.

* Hidden Fields: For passing contextual data.

* Static Text/HTML: For instructions or descriptive content.

  • Advanced Field Configuration & Validation:

* Custom Labels & Placeholders: Define user-friendly descriptions and hints.

* Default Values: Pre-populate fields for convenience.

* Required Field Status: Mark fields as mandatory for submission.

* Validation Rules:

* Basic: Required, Email format, URL format.

* Length Constraints: Minimum/Maximum characters for text fields.

* Value Constraints: Minimum/Maximum numbers for numeric fields.

* Regex Validation: Custom regular expressions for advanced pattern matching.

  • Conditional Logic (Field Visibility):

* Define rules to show or hide specific fields based on the values of other fields within the same form.

* Supports single-condition logic (e.g., "Show Field B if Field A is 'Option X'").

  • Form Submission & Data Handling:

* Forms can be configured to submit data to a designated API endpoint.

* Submitted data is structured as JSON, making it easy to parse and store.

* Basic storage mechanism for submitted form data (as configured during setup).

  • Real-time Form Preview:

* Instantly visualize how the form will appear to end-users as it is being built.

  • Form Management:

* Ability to save, load, edit, and delete form definitions.

* Unique IDs generated for each form for easy referencing.

  • Form Embedding & API:

* Provides a simple JavaScript embed code to integrate forms into any web page.

* A RESTful API endpoint for programmatically retrieving form definitions and submitting data.

  • Responsive Design:

* Generated forms are inherently responsive, ensuring optimal display and functionality across various devices (desktop, tablet, mobile).


4. Technical Architecture & Components

The Dynamic Form Builder is built on a modern, scalable, and maintainable architecture, leveraging industry-standard technologies:

  • Frontend (Form Builder UI & Rendered Forms):

* Framework: React.js

* Purpose: Provides a highly interactive and responsive user interface for both building forms and rendering the final forms for end-users. Utilizes component-based development for modularity and reusability.

  • Backend (API & Business Logic):

* Framework: Node.js with Express.js

* Purpose: Manages API endpoints for creating, retrieving, updating, and deleting form definitions, as well as handling form submissions. Implements server-side validation and business logic.

  • Database:

* Type: MongoDB (NoSQL Document Database)

* Purpose: Stores form definitions (as JSON documents) and submitted form data. MongoDB's flexible schema is ideal for dynamic and evolving form structures.

  • API Design:

* Type: RESTful API

* Endpoints:

* GET /api/forms: Retrieve all form definitions.

* GET /api/forms/{id}: Retrieve a specific form definition.

* POST /api/forms: Create a new form definition.

* PUT /api/forms/{id}: Update an existing form definition.

* DELETE /api/forms/{id}: Delete a form definition.

* POST /api/forms/{id}/submit: Handle form data submission.

  • Deployment:

* Containerization: Docker for packaging the frontend and backend applications, ensuring consistent environments.

* Cloud Platform: Configured for deployment on [Specify your chosen cloud platform, e.g., AWS EC2/ECS, Google Cloud Run, Azure App Services] for scalability and reliability.


5. User Experience (UX) Considerations

Throughout the development, a strong emphasis was placed on delivering an intuitive and efficient user experience for both form designers and end-users:

  • For Form Designers (Administrators):

* Clear Visual Feedback: Drag-and-drop operations, field configuration changes, and conditional logic rules are immediately reflected in the preview.

* Streamlined Workflow: Logical flow from field addition to configuration and publishing.

* Error Prevention: Clear prompts and validation messages during form creation.

  • For End-Users (Form Fillers):

* Responsive & Accessible Forms: Forms adapt to various screen sizes and are built with accessibility best practices in mind (e.g., proper ARIA attributes, keyboard navigation support).

* Clear Instructions: Ability to add descriptive text and placeholders.

* Instant Validation Feedback: Users receive immediate feedback on invalid inputs, guiding them to correct errors before submission.

* Conditional Display: Fields appear or disappear logically, reducing form clutter and improving relevance.


6. Implementation & Getting Started Guide

To begin utilizing your new Dynamic Form Builder, please follow these steps:

6.1. Accessing the Form Builder

  1. URL: The Dynamic Form Builder interface is accessible at: [Your Provided URL, e.g., https://forms.yourcompany.com/builder]
  2. Login: Use the provided administrator credentials:

* Username: [Provided Admin Username]

* Password: [Provided Admin Password]

Please change your password immediately upon first login for security purposes.*

6.2. Creating Your First Form

  1. Navigate to "Create New Form": On the dashboard, click the "Create New Form" button.
  2. Add Fields:

* From the "Field Types" panel on the left, drag and drop desired field types (e.g., "Text Input", "Dropdown") onto the form canvas.

* Each field will have a configuration panel appear (usually on the right).

  1. Configure Fields:

* Set the Label (what the user sees).

* Add a Placeholder (example text inside the input).

* Mark as Required if necessary.

* Apply Validation Rules (e.g., "Email", "Min Length: 5").

* For dropdowns/radio buttons, add Options (label and value).

  1. Implement Conditional Logic (Optional):

* Select a field you want to hide/show conditionally.

* In its configuration panel, navigate to the "Conditional Logic" section.

* Define a rule: "Show this field IF [Another Field] [Operator, e.g., 'is equal to'] [Value]".

  1. Preview: Use the "Preview" button to see how your form will look and behave.
  2. Save Form: Click "Save Form" and provide a unique name for your form.

6.3. Embedding a Form

  1. Access Form List: From the dashboard, select the form you wish to embed.
  2. Generate Embed Code: Click the "Embed" or "Publish" button associated with the form.
  3. Copy Code: A JavaScript snippet will be provided. Copy this code.
  4. Paste into Your Website: Paste the copied JavaScript code into the HTML of your target web page where you want the form to appear. It's typically placed within a <div> element.

    <!-- Example of where to place the embed code -->
    <div id="my-dynamic-form-container"></div>
    <script src="[YOUR_FORM_BUILDER_BASE_URL]/embed.js"></script>
    <script>
        DynamicFormBuilder.renderForm('YOUR_FORM_ID', 'my-dynamic-form-container');
    </script>

Replace [YOUR_FORM_BUILDER_BASE_URL] and YOUR_FORM_ID with the actual values provided by the builder.

6.4. Retrieving Submitted Data

Submitted form data can be accessed in two primary ways:

  1. Through the Admin Interface: The builder interface provides a basic view of submitted data for each form. Navigate to the desired form and look for a "Submissions" or "Data" tab.
  2. Via API: For programmatic access, submitted data is stored in the MongoDB database and can be retrieved via direct database queries or through a dedicated API endpoint (if configured).

* API Endpoint (Example): GET /api/submissions/{formId}

Full API documentation is provided in Section 8.2.*


7. Future Enhancements & Roadmap

The Dynamic Form Builder is designed for extensibility. The following features are recommended for future development to further enhance its capabilities:

  • Advanced Conditional Logic: Support for complex rules with "AND/OR" conditions across multiple fields.
  • Multi-Page Forms: Ability to break down long forms into multiple, navigable pages.
  • Form Theming & Styling: Options for customizing form appearance (fonts, colors, layouts) through themes or custom CSS injection.
  • Workflow & Integration Connectors: Pre-built integrations with popular CRM, email marketing, or project management systems (e.g., Salesforce, Mailchimp, Zapier).
  • User & Role Management: Granular permissions for who can create, edit, publish, or view submissions for specific forms.
  • Form Analytics: Dashboards to track form performance, submission rates, abandonment rates, and field-level insights.
  • Payment Gateway Integration: Securely collect payments through forms by integrating with payment processors (e.g., Stripe, PayPal).
  • CAPTCHA/Anti-Spam Integration: Implement reCAPTCHA or similar services to prevent bot submissions.
  • Version Control & Rollback: Maintain versions of forms and allow reverting to previous states.
  • Scheduled Publishing/Unpublishing: Set specific dates and times for forms to become active or inactive.

8. Comprehensive Documentation Overview

To ensure complete understanding and facilitate ongoing use and maintenance, the following documentation has been compiled:

8.1. User Manual for Form Administrators

  • Audience: Business users, content managers, administrators.
  • Content: Step-by-step guides for creating, editing, publishing, and managing forms. Covers all UI features, field configurations, and conditional logic setup. Includes FAQs and troubleshooting tips.

8.2. API Documentation (Swagger/OpenAPI Specification)

  • Audience: Developers, integrators.
  • Content: Detailed specifications for all RESTful
dynamic_form_builder.txt
Download source file
Copy all content
Full output as text
Download ZIP
IDE-ready project ZIP
Copy share link
Permanent URL for this run
Get Embed Code
Embed this result on any website
Print / Save PDF
Use browser print dialog
\n \n ```\n *Replace `[YOUR_FORM_BUILDER_BASE_URL]` and `YOUR_FORM_ID` with the actual values provided by the builder.*\n\n#### 6.4. Retrieving Submitted Data\n\nSubmitted form data can be accessed in two primary ways:\n\n1. **Through the Admin Interface:** The builder interface provides a basic view of submitted data for each form. Navigate to the desired form and look for a \"Submissions\" or \"Data\" tab.\n2. **Via API:** For programmatic access, submitted data is stored in the MongoDB database and can be retrieved via direct database queries or through a dedicated API endpoint (if configured).\n\n * **API Endpoint (Example):** `GET /api/submissions/{formId}`\n * *Full API documentation is provided in Section 8.2.*\n\n---\n\n### 7. Future Enhancements & Roadmap\n\nThe Dynamic Form Builder is designed for extensibility. The following features are recommended for future development to further enhance its capabilities:\n\n* **Advanced Conditional Logic:** Support for complex rules with \"AND/OR\" conditions across multiple fields.\n* **Multi-Page Forms:** Ability to break down long forms into multiple, navigable pages.\n* **Form Theming & Styling:** Options for customizing form appearance (fonts, colors, layouts) through themes or custom CSS injection.\n* **Workflow & Integration Connectors:** Pre-built integrations with popular CRM, email marketing, or project management systems (e.g., Salesforce, Mailchimp, Zapier).\n* **User & Role Management:** Granular permissions for who can create, edit, publish, or view submissions for specific forms.\n* **Form Analytics:** Dashboards to track form performance, submission rates, abandonment rates, and field-level insights.\n* **Payment Gateway Integration:** Securely collect payments through forms by integrating with payment processors (e.g., Stripe, PayPal).\n* **CAPTCHA/Anti-Spam Integration:** Implement reCAPTCHA or similar services to prevent bot submissions.\n* **Version Control & Rollback:** Maintain versions of forms and allow reverting to previous states.\n* **Scheduled Publishing/Unpublishing:** Set specific dates and times for forms to become active or inactive.\n\n---\n\n### 8. Comprehensive Documentation Overview\n\nTo ensure complete understanding and facilitate ongoing use and maintenance, the following documentation has been compiled:\n\n#### 8.1. User Manual for Form Administrators\n\n* **Audience:** Business users, content managers, administrators.\n* **Content:** Step-by-step guides for creating, editing, publishing, and managing forms. Covers all UI features, field configurations, and conditional logic setup. Includes FAQs and troubleshooting tips.\n\n#### 8.2. API Documentation (Swagger/OpenAPI Specification)\n\n* **Audience:** Developers, integrators.\n* **Content:** Detailed specifications for all RESTful";function phTab(btn,name){document.querySelectorAll(".ph-panel").forEach(function(el){el.classList.remove("active");});document.querySelectorAll(".ph-tab").forEach(function(el){el.classList.remove("active");el.classList.add("inactive");});var p=document.getElementById("panel-"+name);if(p)p.classList.add("active");btn.classList.remove("inactive");btn.classList.add("active");if(name==="preview"){var fr=document.getElementById("ph-preview-frame");if(fr&&!fr.dataset.loaded){if(_phIsHtml){fr.srcdoc=_phCode;}else{var vc=document.getElementById("panel-content");fr.srcdoc=vc?""+vc.innerHTML+"":"

No content

";}fr.dataset.loaded="1";}}}function phCopyCode(){navigator.clipboard.writeText(_phCode).then(function(){var b=document.getElementById("tab-code");if(b){var o=b.innerHTML;b.innerHTML=' Copied!';setTimeout(function(){b.innerHTML=o;},2000);}});}function phCopyAll(){navigator.clipboard.writeText(_phAll).then(function(){alert("Content copied to clipboard!");});}function phDownload(){var content=_phCode||_phAll;if(!content){alert("No content to download.");return;}var fn=_phFname;if(!_phCode&&fn.endsWith(".txt"))fn=fn.replace(/\.txt$/,".md");var a=document.createElement("a");a.href="data:text/plain;charset=utf-8,"+encodeURIComponent(content);a.download=fn;a.click();}function phDownloadZip(){ var lbl=document.getElementById("ph-zip-lbl"); if(lbl)lbl.textContent="Preparing\u2026"; /* ===== HELPERS ===== */ function cc(s){ return s.replace(/[_\-\s]+([a-z])/g,function(m,c){return c.toUpperCase();}) .replace(/^[a-z]/,function(m){return m.toUpperCase();}); } function pkgName(app){ return app.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"my_app"; } function slugTitle(app){ return app.replace(/_/g," "); } /* Generic code block extractor. Finds marker comments like: // lib/main.dart or # lib/main.dart or ## lib/main.dart and collects lines until the next marker. Also strips markdown fences (\`\`\`lang ... \`\`\`) from each block. */ function extractFiles(txt, pathRe){ var files={}, cur=null, buf=[]; function flush(){ if(cur&&buf.length){ files[cur]=buf.join("\n").trim(); } } txt.split("\n").forEach(function(line){ var m=line.trim().match(pathRe); if(m){ flush(); cur=m[1]; buf=[]; return; } if(cur) buf.push(line); }); flush(); // Strip \`\`\`...\`\`\` fences from each file Object.keys(files).forEach(function(k){ files[k]=files[k].replace(/^\`\`\`[a-z]*\n?/,"").replace(/\n?\`\`\`$/,"").trim(); }); return files; } /* General path extractor that covers most languages */ function extractCode(txt){ var re=/^(?:\/\/|#|##)\s*((?:lib|src|test|tests|Sources?|app|components?|screens?|views?|hooks?|routes?|store|services?|models?|pages?)\/[\w\/\-\.]+\.\w+|pubspec\.yaml|Package\.swift|angular\.json|babel\.config\.(?:js|ts)|vite\.config\.(?:js|ts)|tsconfig\.(?:json|app\.json)|app\.json|App\.(?:tsx|jsx|vue|kt|swift)|MainActivity(?:\.kt)?|ContentView\.swift)/i; return extractFiles(txt, re); } /* Detect language from combined code+panel text */ function detectLang(code, panel){ var t=(code+" "+panel).toLowerCase(); if(t.indexOf("import 'package:flutter")>=0||t.indexOf('import "package:flutter')>=0) return "flutter"; if(t.indexOf("statelesswidget")>=0||t.indexOf("statefulwidget")>=0) return "flutter"; if((t.indexOf(".dart")>=0)&&(t.indexOf("pubspec")>=0||t.indexOf("flutter:")>=0)) return "flutter"; if(t.indexOf("react-native")>=0||t.indexOf("react_native")>=0) return "react-native"; if(t.indexOf("stylesheet.create")>=0||t.indexOf("view, text, touchableopacity")>=0) return "react-native"; if(t.indexOf("expo(")>=0||t.indexOf("\"expo\":")>=0||t.indexOf("from 'expo")>=0) return "react-native"; if(t.indexOf("import swiftui")>=0||t.indexOf("import uikit")>=0) return "swift"; if(t.indexOf(".swift")>=0&&(t.indexOf("func body")>=0||t.indexOf("@main")>=0||t.indexOf("var body: some view")>=0)) return "swift"; if(t.indexOf("import android.")>=0||t.indexOf("package com.example")>=0) return "kotlin"; if(t.indexOf("@composable")>=0||t.indexOf("fun mainactivity")>=0||(t.indexOf(".kt")>=0&&t.indexOf("androidx")>=0)) return "kotlin"; if(t.indexOf("@ngmodule")>=0||t.indexOf("@component")>=0) return "angular"; if(t.indexOf("angular.json")>=0||t.indexOf("from '@angular")>=0) return "angular"; if(t.indexOf(".vue")>=0||t.indexOf("