Dynamic Form Builder
Run ID: 69cc4d9c8f41b62a970c26192026-03-31Web Development
PantheraHive BOS
BOS Dashboard

This document provides a comprehensive, detailed, and professional output for the "Dynamic Form Builder" component, generated as Step 2 of 3 in your workflow. This deliverable includes a conceptual overview, a robust JSON schema for defining forms, and production-ready code examples for both the frontend (React) and a basic backend API (Node.js/Express).


Dynamic Form Builder: Professional Code Deliverable

1. Introduction

This deliverable provides the core components and architecture for a dynamic form builder. The solution is designed to allow users to define complex form structures using a simple JSON schema, which can then be rendered dynamically on the frontend. It includes basic validation, state management, and a foundational API for form definition storage and submission handling.

Key Features:

2. Core Concepts and Architecture

The Dynamic Form Builder operates on a schema-driven approach. A form's structure, fields, labels, types, options, and validation rules are all defined in a JSON object.

Architecture Overview:

* Reads a form schema (JSON).

* The DynamicForm component iterates through the schema fields.

* For each field, it renders the appropriate input component (TextInput, SelectInput, etc.).

* Manages form state (field values, validation errors).

* Handles form submission, sending data to the backend.

* Provides RESTful endpoints for:

* Retrieving available form schemas.

* Creating/Updating form schemas.

* Receiving and storing form submissions.

* (For this example, a simple in-memory data store is used; in a production environment, this would integrate with a database like MongoDB, PostgreSQL, etc.)

3. Form Definition Schema (JSON)

The heart of the dynamic form builder is its JSON schema. Each object in the array represents a single form field.

3.1. Schema Structure

text • 229 chars
### 4. Frontend Implementation (React)

This section provides the React components necessary to render forms dynamically based on the JSON schema.

#### 4.1. Project Setup (Create React App)

First, create a new React project:

Sandboxed live preview

Dynamic Form Builder - Architecture Plan

This document outlines the proposed architecture for a robust, scalable, and user-friendly Dynamic Form Builder. This plan focuses on creating a flexible system that empowers users to design and deploy custom forms efficiently, while ensuring secure data handling and easy integration.


1. Executive Summary

The Dynamic Form Builder will provide a comprehensive platform for users to visually construct forms, define their logic, and collect submissions. The architecture is designed with a microservices-oriented approach, separating concerns into dedicated frontend (builder and renderer) and backend services (form definition, submission, authentication, integration). This ensures modularity, scalability, and ease of maintenance. Data will be managed using a combination of NoSQL for flexible form definitions and relational/NoSQL for submissions, depending on specific

javascript

// src/components/fields/TextInput.js

import React from 'react';

const TextInput

gemini Output

Dynamic Form Builder: Comprehensive Solution Deliverable

Executive Summary

This document presents a comprehensive, detailed solution for a Dynamic Form Builder. This system empowers users to create, configure, and deploy custom forms with unparalleled flexibility and ease, without requiring coding knowledge. The solution is designed to enhance operational efficiency, accelerate data collection, and improve user experience across various applications and business processes. By abstracting the complexity of form development, organizations can rapidly adapt to evolving data requirements and streamline workflows.

1. Solution Overview: Dynamic Form Builder

The Dynamic Form Builder is a robust, modular system designed to provide an intuitive interface for form creation and management, coupled with a powerful backend for data handling and rendering.

1.1 Key Features

  • Drag-and-Drop Interface: Intuitive visual editor for easy form layout and element placement.
  • Diverse Field Types: Support for a wide range of input fields (text, number, date, dropdown, checkbox, radio, file upload, rich text, etc.).
  • Conditional Logic: Ability to show/hide fields, sections, or pages based on user input or predefined rules.
  • Validation Rules: Built-in and custom validation rules (required, min/max length, regex, custom functions) to ensure data integrity.
  • Form Templates: Pre-built or user-defined templates for rapid form creation.
  • Multi-Page Forms: Support for breaking down complex forms into manageable steps.
  • Theming & Styling: Customization options for form appearance to match brand guidelines.
  • Data Export & Integration: Seamless integration with existing systems and robust data export capabilities (CSV, JSON, PDF).
  • Version Control: Track changes and revert to previous form versions.
  • Access Control: Define permissions for form creation, editing, and submission.
  • Responsive Design: Forms render correctly across various devices (desktop, tablet, mobile).
  • Workflow Integration: Triggers and actions based on form submissions (e.g., send email, update CRM, create task).

1.2 Core Components

The Dynamic Form Builder solution comprises several interconnected components:

  1. Form Designer (Frontend):

* Visual Editor: Drag-and-drop canvas for arranging form elements.

* Field Palette: Library of available form field types.

* Property Panel: For configuring properties of selected fields (label, placeholder, validation, options, default values, conditional logic).

* Preview Mode: To visualize the form as an end-user would see it.

* Save/Publish Functionality: To persist form definitions.

  1. Form Renderer (Frontend):

* A JavaScript library or component that interprets the saved form definition (JSON/XML) and renders the interactive form for end-users.

* Handles client-side validation and conditional logic execution.

* Manages form submission.

  1. Backend API (Server-Side):

* Form Definition Management: CRUD operations for form definitions (saving, retrieving, updating, deleting forms).

* Form Submission Handling: Receives and stores submitted form data.

* Validation Engine: Server-side validation to ensure data integrity before persistence.

* Integration Services: Connectors for external systems (CRM, ERP, notification services).

* Authentication & Authorization: Secures access to form definitions and submissions.

  1. Database:

* Form Definitions Store: Stores the structure, configuration, and metadata of each created form (e.g., as JSON documents).

* Form Submissions Store: Stores all submitted data for each form instance.

1.3 How It Works (Workflow)

  1. Design Phase: A user (e.g., an administrator, business analyst) accesses the Form Designer interface. They drag and drop fields onto a canvas, configure field properties, add validation rules, and set up conditional logic.
  2. Save/Publish: Once satisfied, the user saves and publishes the form. The Backend API receives this form definition (typically a JSON structure) and stores it in the Database.
  3. Deployment/Embedding: The published form can be embedded into web pages, applications, or accessed via a unique URL.
  4. User Interaction: An end-user accesses the rendered form. The Form Renderer component interprets the stored form definition and displays the interactive form. Client-side validation and conditional logic apply dynamically.
  5. Form Submission: Upon submission, the form data is sent to the Backend API.
  6. Data Processing: The Backend API performs server-side validation, processes the data, stores it in the Database, and triggers any configured integrations or workflows (e.g., sending an email notification, updating a record in a CRM).
  7. Data Retrieval & Analysis: Authorized users can access the Backend API or an administrative interface to view, export, and analyze submitted form data.

2. Benefits & Value Proposition

Implementing the Dynamic Form Builder delivers significant strategic and operational advantages:

  • Accelerated Development: Drastically reduces the time and resources required to create and deploy new forms, enabling rapid response to business needs.
  • Increased Agility: Business users can create and modify forms independently, reducing reliance on IT departments and fostering greater organizational agility.
  • Improved Data Quality: Robust validation rules (client-side and server-side) ensure that collected data is accurate and consistent, minimizing errors.
  • Enhanced User Experience: Responsive and intuitive forms improve completion rates and user satisfaction.
  • Reduced Costs: Lowers development and maintenance costs associated with custom form coding.
  • Centralized Management: Provides a single platform for managing all organizational forms and their data.
  • Scalability: Designed to handle a growing number of forms and submissions without performance degradation.
  • Empowered Business Users: Enables non-technical staff to build sophisticated data collection tools.

3. Technical Architecture & Implementation Guidance

3.1 Recommended Technologies

  • Frontend (Form Designer & Renderer):

* Framework: React, Angular, or Vue.js for building interactive user interfaces.

* Drag-and-Drop Library: react-dnd, vue-draggable, ng2-drag-drop or similar.

* UI Component Library: Material-UI, Ant Design, Bootstrap, or Tailwind CSS for consistent styling and pre-built components.

* State Management: Redux, Vuex, or NgRx for managing complex application state.

  • Backend (API):

* Language/Framework: Node.js (Express.js/NestJS), Python (Django/Flask), Java (Spring Boot), .NET Core. These offer robust API development capabilities.

* Database:

* NoSQL (e.g., MongoDB, PostgreSQL with JSONB): Highly recommended for storing flexible form definitions (JSON documents) and heterogeneous form submission data.

* Relational (e.g., PostgreSQL, MySQL): Can be used, but requires more schema management for diverse form structures or JSON/TEXT fields to store definitions/submissions.

* Caching: Redis or Memcached for improving performance of frequently accessed form definitions.

* Message Queue (Optional): RabbitMQ, Kafka, or AWS SQS for asynchronous processing of form submissions or integrations.

  • Infrastructure:

* Cloud Provider: AWS, Azure, GCP for scalable hosting, database services, and other managed services.

* Containerization: Docker for consistent development and deployment environments.

* Orchestration (Optional): Kubernetes for managing containerized applications at scale.

3.2 Data Model Considerations

Form Definition Schema (Example - JSON Document in NoSQL or JSONB field in PostgreSQL):


{
  "formId": "uuid-v4",
  "name": "Customer Feedback Form",
  "description": "Collects feedback on recent service interactions.",
  "version": 1,
  "status": "published", // draft, published, archived
  "createdAt": "timestamp",
  "updatedAt": "timestamp",
  "config": {
    "theme": "default",
    "submitButtonText": "Send Feedback",
    "redirectUrl": "/thank-you",
    "emailNotifications": ["admin@example.com"]
  },
  "fields": [
    {
      "id": "field-1",
      "type": "text",
      "label": "Your Name",
      "name": "customerName",
      "placeholder": "Enter your full name",
      "validations": [{ "rule": "required" }],
      "conditionalLogic": []
    },
    {
      "id": "field-2",
      "type": "radio",
      "label": "Service Rating",
      "name": "serviceRating",
      "options": [
        {"value": "excellent", "label": "Excellent"},
        {"value": "good", "label": "Good"},
        {"value": "poor", "label": "Poor"}
      ],
      "validations": [{ "rule": "required" }]
    },
    // ... more fields with their respective configurations
    {
      "id": "field-3",
      "type": "textarea",
      "label": "Comments",
      "name": "comments",
      "placeholder": "Any additional comments?",
      "validations": [{ "rule": "maxLength", "value": 500 }],
      "conditionalLogic": [
        {
          "targetFieldId": "field-3",
          "action": "show",
          "condition": {
            "field": "serviceRating",
            "operator": "equals",
            "value": "poor"
          }
        }
      ]
    }
  ]
}

Form Submission Schema (Example - JSON Document in NoSQL or JSONB field in PostgreSQL):


{
  "submissionId": "uuid-v4",
  "formId": "uuid-v4-of-form-definition",
  "submittedAt": "timestamp",
  "submittedBy": "user-id-or-ip-address",
  "data": {
    "customerName": "John Doe",
    "serviceRating": "excellent",
    "comments": "Great service!"
  }
}

3.3 API Endpoints (Conceptual)

  • Form Definition API:

* POST /forms: Create a new form definition.

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

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

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

* GET /forms: List all form definitions (with pagination/filters).

* POST /forms/{id}/publish: Publish a form.

* POST /forms/{id}/unpublish: Unpublish a form.

  • Form Submission API:

* POST /forms/{formId}/submit: Submit data for a specific form.

* GET /forms/{formId}/submissions: Retrieve all submissions for a specific form (with pagination/filters).

* GET /submissions/{submissionId}: Retrieve a specific submission.

* GET /forms/{formId}/submissions/export: Export submissions (CSV, JSON).

  • Authentication & Authorization API:

* Standard endpoints for user login, registration, role management.

3.4 Frontend Integration

The Form Renderer component should be designed to be easily embeddable into any web application or CMS. This can be achieved via:

  • JavaScript SDK/Widget: A lightweight JS library that can be included in any webpage, initialized with a formId, and it will render the form.
  • iFrame: Less flexible, but a simple way to embed a standalone form page.
  • Component Library: If using a specific frontend framework (React, Angular, Vue), provide a reusable component that consumes the form definition and renders the form.

3.5 Security Considerations

  • Authentication & Authorization: Implement robust user authentication (e.g., OAuth2, JWT) and role-based access control (RBAC) for managing forms and viewing submissions.
  • Input Validation: Strict client-side and server-side validation to prevent injection attacks (XSS, SQL Injection), malformed data, and buffer overflows.
  • Data Encryption: Encrypt sensitive data both in transit (HTTPS/TLS) and at rest (database encryption).
  • Rate Limiting: Protect against brute-force attacks and excessive form submissions.
  • Audit Trails: Log all significant actions (form creation, modification, publication, submission) for accountability and compliance.
  • OWASP Top 10: Ensure the solution adheres to best practices outlined in the OWASP Top 10 security risks.
  • GDPR/CCPA Compliance: Design data handling practices to comply with relevant data privacy regulations, including data minimization, consent management, and data deletion capabilities.

4. Scalability & Maintainability

  • Microservices Architecture (Optional): For very large-scale deployments, break down the backend into smaller, independent services (e.g., Form Definition Service, Submission Service, Integration Service).
  • Stateless Services: Design backend services to be stateless to facilitate horizontal scaling.
  • Database Scaling: Utilize database sharding, replication, or managed cloud database services (e.g., AWS RDS, Azure Cosmos DB) for high availability and performance.
  • Containerization: Docker and Kubernetes simplify deployment, scaling, and management of application components.
  • Code Quality: Adhere to clean code principles, use linters, conduct regular code reviews, and maintain comprehensive test suites (unit, integration, end-to-end tests).
  • Documentation: Maintain clear and up-to-date documentation for API endpoints, data models, deployment procedures, and developer guides.
  • Monitoring & Alerting: Implement robust monitoring for application performance, errors, and infrastructure health. Set up alerts for critical issues.

5. Next Steps & Call to Action

We recommend the following immediate next steps to move forward with the Dynamic Form Builder implementation:

  1. Solution Review & Feedback Session: Schedule a dedicated session to walk through this detailed proposal, address any questions, and gather your initial feedback.
  2. Requirements Refinement Workshop: Conduct a workshop with key stakeholders to finalize specific feature priorities, integration points, and user roles.
  3. Technology Stack Confirmation: Confirm the preferred technology stack and hosting environment based on your existing infrastructure and strategic direction.
  4. Proof of Concept (POC) / Pilot Project: Consider a small-scale POC focusing on a critical form use case to validate the core functionality and technical approach.
  5. Project Planning & Resource Allocation: Develop a detailed project plan, including timelines, milestones, and resource requirements for the full implementation.

Please contact your dedicated PantheraHive Project Manager at your earliest convenience to schedule the Solution Review & Feedback Session.

6. Support & Documentation

PantheraHive is committed to ensuring your success with the Dynamic Form Builder. Our support and documentation offerings include:

  • Comprehensive API Documentation: Detailed guides for integrating with the Form Builder's backend.
  • User Manuals: Step-by-step instructions for using the Form Designer and managing forms.
  • Developer Guides: Best practices and examples for extending the platform or building custom field types.
  • Dedicated Support Channel: Access to our expert support team for technical assistance and troubleshooting.
  • Regular Updates & Maintenance: Continuous improvements, security patches, and new features will be rolled out.

We look forward to partnering with you to bring this powerful Dynamic Form Builder to life, transforming your data collection capabilities and streamlining your operations.

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"); var hasSrcMain=Object.keys(extracted).some(function(k){return k.indexOf("src/main")>=0;}); if(!hasSrcMain) zip.file(folder+"src/main."+ext,"import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App'\nimport './index.css'\n\nReactDOM.createRoot(document.getElementById('root')!).render(\n \n \n \n)\n"); var hasSrcApp=Object.keys(extracted).some(function(k){return k==="src/App."+ext||k==="App."+ext;}); if(!hasSrcApp) zip.file(folder+"src/App."+ext,"import React from 'react'\nimport './App.css'\n\nfunction App(){\n return(\n
\n
\n

"+slugTitle(pn)+"

\n

Built with PantheraHive BOS

\n
\n
\n )\n}\nexport default App\n"); zip.file(folder+"src/index.css","*{margin:0;padding:0;box-sizing:border-box}\nbody{font-family:system-ui,-apple-system,sans-serif;background:#f0f2f5;color:#1a1a2e}\n.app{min-height:100vh;display:flex;flex-direction:column}\n.app-header{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:40px}\nh1{font-size:2.5rem;font-weight:700}\n"); zip.file(folder+"src/App.css",""); zip.file(folder+"src/components/.gitkeep",""); zip.file(folder+"src/pages/.gitkeep",""); zip.file(folder+"src/hooks/.gitkeep",""); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\nnpm run dev\n\`\`\`\n\n## Build\n\`\`\`bash\nnpm run build\n\`\`\`\n\n## Open in IDE\nOpen the project folder in VS Code or WebStorm.\n"); zip.file(folder+".gitignore","node_modules/\ndist/\n.env\n.DS_Store\n*.local\n"); } /* --- Vue (Vite + Composition API + TypeScript) --- */ function buildVue(zip,folder,app,code,panelTxt){ var pn=pkgName(app); var C=cc(pn); var extracted=extractCode(panelTxt); zip.file(folder+"package.json",'{\n "name": "'+pn+'",\n "version": "0.0.0",\n "type": "module",\n "scripts": {\n "dev": "vite",\n "build": "vue-tsc -b && vite build",\n "preview": "vite preview"\n },\n "dependencies": {\n "vue": "^3.5.13",\n "vue-router": "^4.4.5",\n "pinia": "^2.3.0",\n "axios": "^1.7.9"\n },\n "devDependencies": {\n "@vitejs/plugin-vue": "^5.2.1",\n "typescript": "~5.7.3",\n "vite": "^6.0.5",\n "vue-tsc": "^2.2.0"\n }\n}\n'); zip.file(folder+"vite.config.ts","import { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport { resolve } from 'path'\n\nexport default defineConfig({\n plugins: [vue()],\n resolve: { alias: { '@': resolve(__dirname,'src') } }\n})\n"); zip.file(folder+"tsconfig.json",'{"files":[],"references":[{"path":"./tsconfig.app.json"},{"path":"./tsconfig.node.json"}]}\n'); zip.file(folder+"tsconfig.app.json",'{\n "compilerOptions":{\n "target":"ES2020","useDefineForClassFields":true,"module":"ESNext","lib":["ES2020","DOM","DOM.Iterable"],\n "skipLibCheck":true,"moduleResolution":"bundler","allowImportingTsExtensions":true,\n "isolatedModules":true,"moduleDetection":"force","noEmit":true,"jsxImportSource":"vue",\n "strict":true,"paths":{"@/*":["./src/*"]}\n },\n "include":["src/**/*.ts","src/**/*.d.ts","src/**/*.tsx","src/**/*.vue"]\n}\n'); zip.file(folder+"env.d.ts","/// \n"); zip.file(folder+"index.html","\n\n\n \n \n "+slugTitle(pn)+"\n\n\n
\n \n\n\n"); var hasMain=Object.keys(extracted).some(function(k){return k==="src/main.ts"||k==="main.ts";}); if(!hasMain) zip.file(folder+"src/main.ts","import { createApp } from 'vue'\nimport { createPinia } from 'pinia'\nimport App from './App.vue'\nimport './assets/main.css'\n\nconst app = createApp(App)\napp.use(createPinia())\napp.mount('#app')\n"); var hasApp=Object.keys(extracted).some(function(k){return k.indexOf("App.vue")>=0;}); if(!hasApp) zip.file(folder+"src/App.vue","\n\n\n\n\n"); zip.file(folder+"src/assets/main.css","*{margin:0;padding:0;box-sizing:border-box}body{font-family:system-ui,sans-serif;background:#fff;color:#213547}\n"); zip.file(folder+"src/components/.gitkeep",""); zip.file(folder+"src/views/.gitkeep",""); zip.file(folder+"src/stores/.gitkeep",""); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\nnpm run dev\n\`\`\`\n\n## Build\n\`\`\`bash\nnpm run build\n\`\`\`\n\nOpen in VS Code or WebStorm.\n"); zip.file(folder+".gitignore","node_modules/\ndist/\n.env\n.DS_Store\n*.local\n"); } /* --- Angular (v19 standalone) --- */ function buildAngular(zip,folder,app,code,panelTxt){ var pn=pkgName(app); var C=cc(pn); var sel=pn.replace(/_/g,"-"); var extracted=extractCode(panelTxt); zip.file(folder+"package.json",'{\n "name": "'+pn+'",\n "version": "0.0.0",\n "scripts": {\n "ng": "ng",\n "start": "ng serve",\n "build": "ng build",\n "test": "ng test"\n },\n "dependencies": {\n "@angular/animations": "^19.0.0",\n "@angular/common": "^19.0.0",\n "@angular/compiler": "^19.0.0",\n "@angular/core": "^19.0.0",\n "@angular/forms": "^19.0.0",\n "@angular/platform-browser": "^19.0.0",\n "@angular/platform-browser-dynamic": "^19.0.0",\n "@angular/router": "^19.0.0",\n "rxjs": "~7.8.0",\n "tslib": "^2.3.0",\n "zone.js": "~0.15.0"\n },\n "devDependencies": {\n "@angular-devkit/build-angular": "^19.0.0",\n "@angular/cli": "^19.0.0",\n "@angular/compiler-cli": "^19.0.0",\n "typescript": "~5.6.0"\n }\n}\n'); zip.file(folder+"angular.json",'{\n "$schema": "./node_modules/@angular/cli/lib/config/schema.json",\n "version": 1,\n "newProjectRoot": "projects",\n "projects": {\n "'+pn+'": {\n "projectType": "application",\n "root": "",\n "sourceRoot": "src",\n "prefix": "app",\n "architect": {\n "build": {\n "builder": "@angular-devkit/build-angular:application",\n "options": {\n "outputPath": "dist/'+pn+'",\n "index": "src/index.html",\n "browser": "src/main.ts",\n "tsConfig": "tsconfig.app.json",\n "styles": ["src/styles.css"],\n "scripts": []\n }\n },\n "serve": {"builder":"@angular-devkit/build-angular:dev-server","configurations":{"production":{"buildTarget":"'+pn+':build:production"},"development":{"buildTarget":"'+pn+':build:development"}},"defaultConfiguration":"development"}\n }\n }\n }\n}\n'); zip.file(folder+"tsconfig.json",'{\n "compileOnSave": false,\n "compilerOptions": {"baseUrl":"./","outDir":"./dist/out-tsc","forceConsistentCasingInFileNames":true,"strict":true,"noImplicitOverride":true,"noPropertyAccessFromIndexSignature":true,"noImplicitReturns":true,"noFallthroughCasesInSwitch":true,"paths":{"@/*":["src/*"]},"skipLibCheck":true,"esModuleInterop":true,"sourceMap":true,"declaration":false,"experimentalDecorators":true,"moduleResolution":"bundler","importHelpers":true,"target":"ES2022","module":"ES2022","useDefineForClassFields":false,"lib":["ES2022","dom"]},\n "references":[{"path":"./tsconfig.app.json"}]\n}\n'); zip.file(folder+"tsconfig.app.json",'{\n "extends":"./tsconfig.json",\n "compilerOptions":{"outDir":"./dist/out-tsc","types":[]},\n "files":["src/main.ts"],\n "include":["src/**/*.d.ts"]\n}\n'); zip.file(folder+"src/index.html","\n\n\n \n "+slugTitle(pn)+"\n \n \n \n\n\n \n\n\n"); zip.file(folder+"src/main.ts","import { bootstrapApplication } from '@angular/platform-browser';\nimport { appConfig } from './app/app.config';\nimport { AppComponent } from './app/app.component';\n\nbootstrapApplication(AppComponent, appConfig)\n .catch(err => console.error(err));\n"); zip.file(folder+"src/styles.css","* { margin: 0; padding: 0; box-sizing: border-box; }\nbody { font-family: system-ui, -apple-system, sans-serif; background: #f9fafb; color: #111827; }\n"); var hasComp=Object.keys(extracted).some(function(k){return k.indexOf("app.component")>=0;}); if(!hasComp){ zip.file(folder+"src/app/app.component.ts","import { Component } from '@angular/core';\nimport { RouterOutlet } from '@angular/router';\n\n@Component({\n selector: 'app-root',\n standalone: true,\n imports: [RouterOutlet],\n templateUrl: './app.component.html',\n styleUrl: './app.component.css'\n})\nexport class AppComponent {\n title = '"+pn+"';\n}\n"); zip.file(folder+"src/app/app.component.html","
\n
\n

"+slugTitle(pn)+"

\n

Built with PantheraHive BOS

\n
\n \n
\n"); zip.file(folder+"src/app/app.component.css",".app-header{display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:60vh;gap:16px}h1{font-size:2.5rem;font-weight:700;color:#6366f1}\n"); } zip.file(folder+"src/app/app.config.ts","import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';\nimport { provideRouter } from '@angular/router';\nimport { routes } from './app.routes';\n\nexport const appConfig: ApplicationConfig = {\n providers: [\n provideZoneChangeDetection({ eventCoalescing: true }),\n provideRouter(routes)\n ]\n};\n"); zip.file(folder+"src/app/app.routes.ts","import { Routes } from '@angular/router';\n\nexport const routes: Routes = [];\n"); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\nng serve\n# or: npm start\n\`\`\`\n\n## Build\n\`\`\`bash\nng build\n\`\`\`\n\nOpen in VS Code with Angular Language Service extension.\n"); zip.file(folder+".gitignore","node_modules/\ndist/\n.env\n.DS_Store\n*.local\n.angular/\n"); } /* --- Python --- */ function buildPython(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^\`\`\`[\w]*\n?/m,"").replace(/\n?\`\`\`$/m,"").trim(); var reqMap={"numpy":"numpy","pandas":"pandas","sklearn":"scikit-learn","tensorflow":"tensorflow","torch":"torch","flask":"flask","fastapi":"fastapi","uvicorn":"uvicorn","requests":"requests","sqlalchemy":"sqlalchemy","pydantic":"pydantic","dotenv":"python-dotenv","PIL":"Pillow","cv2":"opencv-python","matplotlib":"matplotlib","seaborn":"seaborn","scipy":"scipy"}; var reqs=[]; Object.keys(reqMap).forEach(function(k){if(src.indexOf("import "+k)>=0||src.indexOf("from "+k)>=0)reqs.push(reqMap[k]);}); var reqsTxt=reqs.length?reqs.join("\n"):"# add dependencies here\n"; zip.file(folder+"main.py",src||"# "+title+"\n# Generated by PantheraHive BOS\n\nprint(title+\" loaded\")\n"); zip.file(folder+"requirements.txt",reqsTxt); zip.file(folder+".env.example","# Environment variables\n"); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\npython3 -m venv .venv\nsource .venv/bin/activate\npip install -r requirements.txt\n\`\`\`\n\n## Run\n\`\`\`bash\npython main.py\n\`\`\`\n"); zip.file(folder+".gitignore",".venv/\n__pycache__/\n*.pyc\n.env\n.DS_Store\n"); } /* --- Node.js --- */ function buildNode(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^\`\`\`[\w]*\n?/m,"").replace(/\n?\`\`\`$/m,"").trim(); var depMap={"mongoose":"^8.0.0","dotenv":"^16.4.5","axios":"^1.7.9","cors":"^2.8.5","bcryptjs":"^2.4.3","jsonwebtoken":"^9.0.2","socket.io":"^4.7.4","uuid":"^9.0.1","zod":"^3.22.4","express":"^4.18.2"}; var deps={}; Object.keys(depMap).forEach(function(k){if(src.indexOf(k)>=0)deps[k]=depMap[k];}); if(!deps["express"])deps["express"]="^4.18.2"; var pkgJson=JSON.stringify({"name":pn,"version":"1.0.0","main":"src/index.js","scripts":{"start":"node src/index.js","dev":"nodemon src/index.js"},"dependencies":deps,"devDependencies":{"nodemon":"^3.0.3"}},null,2)+"\n"; zip.file(folder+"package.json",pkgJson); var fallback="const express=require(\"express\");\nconst app=express();\napp.use(express.json());\n\napp.get(\"/\",(req,res)=>{\n res.json({message:\""+title+" API\"});\n});\n\nconst PORT=process.env.PORT||3000;\napp.listen(PORT,()=>console.log(\"Server on port \"+PORT));\n"; zip.file(folder+"src/index.js",src||fallback); zip.file(folder+".env.example","PORT=3000\n"); zip.file(folder+".gitignore","node_modules/\n.env\n.DS_Store\n"); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\n\`\`\`\n\n## Run\n\`\`\`bash\nnpm run dev\n\`\`\`\n"); } /* --- Vanilla HTML --- */ function buildVanillaHtml(zip,folder,app,code){ var title=slugTitle(app); var isFullDoc=code.trim().toLowerCase().indexOf("=0||code.trim().toLowerCase().indexOf("=0; var indexHtml=isFullDoc?code:"\n\n\n\n\n"+title+"\n\n\n\n"+code+"\n\n\n\n"; zip.file(folder+"index.html",indexHtml); zip.file(folder+"style.css","/* "+title+" — styles */\n*{margin:0;padding:0;box-sizing:border-box}\nbody{font-family:system-ui,-apple-system,sans-serif;background:#fff;color:#1a1a2e}\n"); zip.file(folder+"script.js","/* "+title+" — scripts */\n"); zip.file(folder+"assets/.gitkeep",""); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\n## Open\nDouble-click \`index.html\` in your browser.\n\nOr serve locally:\n\`\`\`bash\nnpx serve .\n# or\npython3 -m http.server 3000\n\`\`\`\n"); zip.file(folder+".gitignore",".DS_Store\nnode_modules/\n.env\n"); } /* ===== MAIN ===== */ var sc=document.createElement("script"); sc.src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"; sc.onerror=function(){ if(lbl)lbl.textContent="Download ZIP"; alert("JSZip load failed — check connection."); }; sc.onload=function(){ var zip=new JSZip(); var base=(_phFname||"output").replace(/\.[^.]+$/,""); var app=base.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"my_app"; var folder=app+"/"; var vc=document.getElementById("panel-content"); var panelTxt=vc?(vc.innerText||vc.textContent||""):""; var lang=detectLang(_phCode,panelTxt); if(_phIsHtml){ buildVanillaHtml(zip,folder,app,_phCode); } else if(lang==="flutter"){ buildFlutter(zip,folder,app,_phCode,panelTxt); } else if(lang==="react-native"){ buildReactNative(zip,folder,app,_phCode,panelTxt); } else if(lang==="swift"){ buildSwift(zip,folder,app,_phCode,panelTxt); } else if(lang==="kotlin"){ buildKotlin(zip,folder,app,_phCode,panelTxt); } else if(lang==="react"){ buildReact(zip,folder,app,_phCode,panelTxt); } else if(lang==="vue"){ buildVue(zip,folder,app,_phCode,panelTxt); } else if(lang==="angular"){ buildAngular(zip,folder,app,_phCode,panelTxt); } else if(lang==="python"){ buildPython(zip,folder,app,_phCode); } else if(lang==="node"){ buildNode(zip,folder,app,_phCode); } else { /* Document/content workflow */ var title=app.replace(/_/g," "); var md=_phAll||_phCode||panelTxt||"No content"; zip.file(folder+app+".md",md); var h=""+title+""; h+="

"+title+"

"; var hc=md.replace(/&/g,"&").replace(//g,">"); hc=hc.replace(/^### (.+)$/gm,"

$1

"); hc=hc.replace(/^## (.+)$/gm,"

$1

"); hc=hc.replace(/^# (.+)$/gm,"

$1

"); hc=hc.replace(/\*\*(.+?)\*\*/g,"$1"); hc=hc.replace(/\n{2,}/g,"

"); h+="

"+hc+"

Generated by PantheraHive BOS
"; zip.file(folder+app+".html",h); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\nFiles:\n- "+app+".md (Markdown)\n- "+app+".html (styled HTML)\n"); } zip.generateAsync({type:"blob"}).then(function(blob){ var a=document.createElement("a"); a.href=URL.createObjectURL(blob); a.download=app+".zip"; a.click(); URL.revokeObjectURL(a.href); if(lbl)lbl.textContent="Download ZIP"; }); }; document.head.appendChild(sc); } function phShare(){navigator.clipboard.writeText(window.location.href).then(function(){var el=document.getElementById("ph-share-lbl");if(el){el.textContent="Link copied!";setTimeout(function(){el.textContent="Copy share link";},2500);}});}function phEmbed(){var runId=window.location.pathname.split("/").pop().replace(".html","");var embedUrl="https://pantherahive.com/embed/"+runId;var code='';navigator.clipboard.writeText(code).then(function(){var el=document.getElementById("ph-embed-lbl");if(el){el.textContent="Embed code copied!";setTimeout(function(){el.textContent="Get Embed Code";},2500);}});}