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

Dynamic Form Builder - Code Generation Deliverable

This document provides a comprehensive, detailed, and professional output for the "Dynamic Form Builder" workflow, focusing on generating the core code components. The goal is to deliver a robust and flexible solution for rendering forms dynamically based on a JSON schema.

1. Solution Overview

A Dynamic Form Builder empowers users to create and manage forms without writing code, simply by defining their structure and fields. This deliverable focuses on the rendering engine for such a system, providing the necessary frontend components to take a form definition (typically a JSON object) and dynamically generate the corresponding HTML form. This approach ensures high reusability, maintainability, and scalability.

We will utilize a modern web development stack, specifically React.js, for its component-based architecture, declarative UI, and efficient state management. The generated code will be clean, well-commented, and production-ready, forming the foundation for a full-fledged dynamic form solution.

2. Core Components & Features

The generated code will provide the following core components and features:

3. Data Model (JSON Schema for Form Definition)

The heart of the dynamic form builder is its data model. Here's a proposed JSON schema for defining a form:

text • 1,115 chars
**Schema Explanation:**

*   `formId`, `formTitle`, `description`: General information about the form.
*   `fields`: An array of field objects, each defining a form input.
    *   `id`: Unique identifier for the field (useful for UI elements).
    *   `name`: The name attribute for the input, used for form data submission.
    *   `label`: The visible label for the field.
    *   `type`: The type of input (e.g., `text`, `email`, `textarea`, `select`, `checkbox`, `radio`, `number`, `password`).
    *   `placeholder`: Placeholder text for text-based inputs.
    *   `required`: Boolean indicating if the field is mandatory.
    *   `options`: (For `select`, `radio`, `checkbox`) An array of objects with `value` and `label`.
    *   `validationRules`: (Optional) An array of validation rule objects. Each rule has a `type`, `value`, and `message`.

### 4. Code Implementation (React.js)

Below is the production-ready React code for the dynamic form renderer.

#### 4.1. `src/components/FormFieldRenderer.js`

This component is responsible for rendering individual form fields based on their `type` property.

Sandboxed live preview

As part of the "Dynamic Form Builder" workflow, we are pleased to present the detailed architecture plan, outlining the foundational design and strategic approach for developing a robust, scalable, and user-friendly system. This plan serves as a comprehensive guide for the initial phase of development, ensuring all core components and considerations are thoroughly addressed.


Dynamic Form Builder: Architecture Plan

Executive Summary

This document details the architectural plan for a "Dynamic Form Builder" application. The goal is to create a platform that empowers users to effortlessly design, deploy, and manage custom forms, collect responses, and analyze data. The architecture prioritizes modularity, extensibility, scalability, and an intuitive user experience. We will outline the core components, proposed technology stack, key architectural decisions, and a phased approach to implementation.

1. Architectural Goals & Non-Functional Requirements

The following objectives and non-functional requirements will guide the design and development of the Dynamic Form Builder:

  • Modularity & Extensibility:

* Objective: Allow for easy addition of new field types (e.g., signature, payment), validation rules, and integration points without significant refactoring.

* Metric: New field types can be added with minimal code changes, primarily through configuration or dedicated modules.

  • Scalability:

* Objective: Support a large number of concurrent users, forms, and submitted responses without performance degradation.

* Metric: System should handle thousands of forms and millions of submissions per month with consistent response times.

  • Performance:

* Objective: Ensure rapid form rendering, quick submission processing, and responsive form builder UI.

* Metric: Form rendering time under 500ms, API response times under 200ms for critical operations.

  • Security:

* Objective: Protect form definitions, submitted data, and user accounts from unauthorized access and vulnerabilities.

* Metric: Adherence to OWASP Top 10, secure data at rest and in transit (HTTPS, encryption), robust authentication and authorization.

  • Usability & User Experience (UX):

* Objective: Provide an intuitive drag-and-drop interface for form creation and a seamless experience for form respondents.

* Metric: High user satisfaction scores from usability testing, low learning curve for new users.

  • Reliability & Data Integrity:

* Objective: Ensure high availability of the platform and consistent, accurate storage of all form data.

* Metric: Uptime target of 99.9%, ACID compliance for critical data operations, robust error handling.

  • Maintainability:

* Objective: Develop a clean, well-documented codebase with clear separation of concerns, making future enhancements and debugging straightforward.

* Metric: High code quality metrics (e.g., cyclomatic complexity, test coverage), clear documentation.

2. High-Level System Components

The Dynamic Form Builder will consist of the following primary components, interacting to deliver the full functionality:

  • 2.1. Frontend Application (Web UI)

* Form Builder: A rich, interactive interface for users to design forms using drag-and-drop functionality, configure field properties, validation rules, and layout.

* Form Renderer: A lightweight, performant component responsible for displaying published forms to end-users for data submission.

* Dashboard & Analytics: Interface for managing created forms, viewing submitted data, and basic analytics.

* User Authentication & Management: UI for user registration, login, profile management.

  • 2.2. Backend API Service

* Form Management API: CRUD operations for form definitions (creation, retrieval, update, deletion).

* Form Submission API: Handles receiving, validating, and storing submitted form data.

* Data Retrieval API: Provides endpoints for accessing submitted data, potentially with filtering and aggregation.

* Authentication & Authorization: Manages user sessions, roles, and permissions (e.g., who can create forms, who can view specific data).

* Validation Engine: Dynamically applies validation rules defined in the form schema during submission.

* File Upload Service: Handles storage and retrieval of files submitted through file upload fields.

  • 2.3. Database Layer

* Form Definitions Storage: Stores the schema and metadata for each created form. This will need to be flexible to accommodate various field types and configurations.

* Submitted Data Storage: Stores the actual data submitted by respondents for each form.

* User Management & Configuration Storage: Stores user accounts, roles, permissions, and system configurations.

  • 2.4. Cloud Infrastructure (Deployment Environment)

* Compute: Servers to run the backend API and host the frontend application.

* Storage: Database, file storage (e.g., S3-compatible object storage).

* Networking: Load balancers, CDN (Content Delivery Network) for frontend assets.

* Monitoring & Logging: Tools for observing system health and debugging.

3. Proposed Technology Stack & Design Patterns

We propose the following technology stack, selected for its robustness, scalability, developer productivity, and community support:

  • 3.1. Frontend:

* Framework: React.js – Offers a component-based architecture, excellent for building complex, interactive UIs like a drag-and-drop form builder.

* UI Library: Material-UI (MUI) – Provides a comprehensive set of pre-built, accessible, and customizable React components, accelerating UI development.

* State Management: React Query / Redux Toolkit – For efficient data fetching, caching, and global state management.

* Styling: Styled-components / Tailwind CSS – For flexible and maintainable styling.

  • 3.2. Backend:

* Framework: NestJS (Node.js) – A progressive Node.js framework for building efficient, reliable, and scalable server-side applications. It enforces a modular structure, inspired by Angular, which is excellent for maintainability and extensibility.

* Language: TypeScript – Provides static typing for improved code quality, readability, and reduced bugs.

* Authentication: JWT (JSON Web Tokens) – For secure, stateless authentication.

* Validation: Built-in NestJS validation pipes leveraging class-validator.

  • 3.3. Database:

* Primary Database: PostgreSQL – A powerful, open-source relational database known for its reliability, feature richness, and strong support for JSONB data types.

* Rationale: JSONB allows for flexible schema storage for form definitions (e.g., an array of field objects with varying properties) and submitted data (e.g., storing all responses as a JSON document per submission), while still leveraging PostgreSQL's transactional integrity and advanced querying capabilities.

* ORM: TypeORM / Prisma – For seamless interaction with the PostgreSQL database.

  • 3.4. File Storage:

* Cloud Storage: AWS S3 / Google Cloud Storage / Azure Blob Storage – For scalable and secure storage of uploaded files.

  • 3.5. Design Patterns:

* Repository Pattern: To abstract data access logic from the business logic, making the system more testable and database-agnostic.

* Strategy Pattern: For implementing various field validation rules, allowing new rules to be added easily without modifying existing code.

* Observer Pattern: Potentially for triggering actions based on form submission events (e.g., sending notifications, integrating with webhooks).

* Modular Monolith (Initial): Start with a well-structured monolithic application, allowing for clear separation of concerns (modules for forms, submissions, users) with the option to refactor into microservices if scaling demands it in the future.

4. Key Architectural Decisions & Milestones

This section outlines critical decisions to be made and key milestones to be achieved during the architecture and initial development phase.

  • 4.1. Key Architectural Decisions:

* Form Schema Representation: How will form definitions be stored in the database? (e.g., JSONB document, normalized tables for fields).

* Proposed: JSONB column in PostgreSQL for the main form definition, allowing for flexible field properties and easy extension.

* Submitted Data Storage: How will submitted responses be stored? (e.g., single JSONB document per submission, separate table per form, or a flexible key-value store).

* Proposed: A single JSONB column per submission, referencing the form ID, providing flexibility and easy retrieval.

* Extensibility Mechanism: How will custom field types and validation rules be integrated? (e.g., plugin architecture, configuration-driven).

* Proposed: Configuration-driven for standard fields, with a clear API for developing custom field components (frontend) and validation logic (backend).

* Authentication & Authorization Strategy: Role-Based Access Control (RBAC) for managing permissions (e.g., form creator, data viewer, admin).

* Deployment Strategy: Initial choice of cloud provider (AWS, GCP, Azure) and CI/CD pipeline setup.

  • 4.2. Milestones for Architecture Phase:

* Milestone 1 (End of Week 1): Initial Technology Stack & Core Data Model Proof-of-Concept (PoC)

* Deliverable: Documented tech stack choice, basic database schema for form definitions, and a working PoC of saving/retrieving a simple form schema.

* Milestone 2 (End of Week 2): API Design & Authentication Flows Defined

* Deliverable: Detailed API endpoint specifications (OpenAPI/Swagger documentation) for form management and submission, clear authentication (JWT) and authorization (RBAC) flow diagrams.

* Milestone 3 (End of Week 3): Frontend Component Strategy & Builder Mockup

* Deliverable: Strategy for reusable React components, initial wireframes/mockups for the drag-and-drop form builder, and a plan for form rendering.

* Milestone 4 (End of Week 4): Deployment & Monitoring Strategy Outline

* Deliverable: High-level cloud infrastructure diagram, initial thoughts on CI/CD pipeline, logging, and monitoring tools.

* Milestone 5 (End of Week 4): Architecture Review & Sign-off

* Deliverable: Finalized Architecture Document, presentation to stakeholders, and formal approval to proceed to the development phase.

5. Architecture Review & Validation Strategy

To ensure the proposed architecture is sound, meets requirements, and aligns with best practices, we will employ the following validation strategies:

  • 5.1. Peer Reviews:

* Description: Internal team

jsx

// src/components/DynamicForm.js

import React, { useState, useEffect } from 'react';

import FormFieldRenderer from './FormFieldRenderer';

import './DynamicForm.css'; // Basic styling for the form container

/**

* Renders a dynamic form based on a JSON form definition.

* Manages form state, handles input changes, performs basic validation, and triggers submission.

*

* @param {object} props - The component props.

* @param {object} props.formDefinition - The JSON object defining the form structure and fields.

* @param {function} props.onSubmit - Callback function to be executed when the form is successfully submitted.

*/

const DynamicForm = ({ formDefinition, onSubmit }) => {

// State to hold the current values of all form fields

const [formData, setFormData] = useState({});

// State to hold validation error messages for each field

const [formErrors, setFormErrors] = useState({});

// Initialize formData when the component mounts or formDefinition changes

useEffect(() => {

const initialData = {};

formDefinition.fields.forEach(field => {

// Set initial value based on field type or default to empty

if (field.type === 'checkbox') {

initialData[field.name] = false; // Checkboxes are false by default

} else if (field.type === 'select' && field.options && field.options.length > 0) {

// Set first non-disabled option as default for select, or empty string

const defaultOption = field.options.

gemini Output

Dynamic Form Builder: Comprehensive Solution Overview

This document provides a comprehensive overview of the proposed Dynamic Form Builder solution, designed to empower your organization with unparalleled flexibility, efficiency, and control over your data collection processes. This solution enables rapid creation, deployment, and management of various forms without requiring extensive technical expertise, significantly reducing development cycles and operational overhead.


1. Executive Summary

The Dynamic Form Builder is a powerful, intuitive platform that allows users to design, publish, and manage custom forms for a multitude of purposes, from customer feedback and lead generation to internal data collection and surveys. By abstracting the complexity of form development into a user-friendly interface, it democratizes form creation, accelerates data acquisition, and ensures data integrity through robust validation and conditional logic. This solution is engineered to be scalable, secure, and seamlessly integratable into your existing digital ecosystem.


2. Key Features and Capabilities

Our Dynamic Form Builder offers a rich set of features designed to cater to diverse organizational needs:

  • Intuitive Drag-and-Drop Interface:

* Visual Editor: A user-friendly, WYSIWYG (What You See Is What You Get) interface for designing forms without writing a single line of code.

* Pre-built Templates: A library of customizable templates for common use cases (e.g., contact forms, registration forms, feedback surveys) to kickstart form creation.

  • Extensive Field Type Library:

* Standard Fields: Text input (single line, multi-line), numbers, email, phone, date, time, checkboxes, radio buttons, dropdowns.

* Advanced Fields: File uploads, signature fields, rating scales, sliders, hidden fields, rich text editors, address lookups.

* Structured Data Fields: Repeatable sections, grid/table inputs for collecting complex, multi-row data.

  • Advanced Logic and Validation:

* Conditional Logic: Dynamically show or hide fields, sections, or entire pages based on user input, creating intelligent and personalized form experiences.

* Validation Rules: Enforce data integrity with built-in and custom validation rules (e.g., required fields, specific formats, min/max values, regex patterns).

* Calculated Fields: Automatically compute values based on other form inputs, useful for quotes, scores, or summaries.

  • Customization and Branding:

* Theming Options: Apply your brand's colors, fonts, and logos to forms to maintain a consistent brand identity.

* Custom CSS/JavaScript: For advanced users, inject custom code to achieve highly specific styling or interactive behaviors.

  • Data Management and Analytics:

* Secure Submission Storage: All form submissions are securely stored and accessible through a centralized dashboard.

* Export Options: Export submission data in various formats (CSV, Excel, JSON) for further analysis or integration.

* Basic Analytics: View submission rates, completion rates, and other key metrics to optimize form performance.

  • Integration and API Access:

* RESTful API: Programmatic access to form creation, submission data, and configuration for seamless integration with existing systems (CRMs, ERPs, marketing automation platforms).

* Webhooks: Real-time notifications to external systems upon form submission, enabling immediate workflow triggers.

* Embeddable Forms: Easily embed forms into any website or application using simple code snippets (iframe, JavaScript).

  • Security and Compliance:

* Role-Based Access Control (RBAC): Define granular permissions for users, controlling who can create, edit, publish, or view form data.

* Data Encryption: Encrypt data at rest and in transit to protect sensitive information.

* Compliance Ready: Designed with best practices to support compliance with regulations such as GDPR, HIPAA, CCPA (specific compliance features may vary and require configuration).


3. Benefits to Your Organization

Implementing the Dynamic Form Builder will deliver significant strategic and operational advantages:

  • Accelerated Development Cycles: Drastically reduce the time and resources required to build and deploy new forms, enabling faster response to business needs and market changes.
  • Reduced IT Dependency: Empower business users and marketing teams to create and manage forms independently, freeing up valuable IT resources for more complex projects.
  • Improved Data Quality and Accuracy: Robust validation rules and conditional logic minimize errors and ensure that collected data is clean, consistent, and actionable.
  • Enhanced User Experience: Create dynamic, responsive, and intuitive forms that adapt to user input, leading to higher completion rates and better engagement.
  • Streamlined Workflows: Automate data flow from form submissions directly into your existing systems, eliminating manual data entry and reducing processing times.
  • Cost Efficiency: Lower development costs, reduce maintenance overhead, and optimize operational efficiency across various departments.
  • Scalability and Flexibility: Easily scale your form creation capabilities to meet growing demands and adapt to evolving business requirements without re-platforming.

4. Technical Architecture (High-Level)

The Dynamic Form Builder is built on a modern, modular, and scalable architecture, ensuring high performance, reliability, and security:

  • Frontend: Responsive web application built with modern JavaScript frameworks (e.g., React, Angular, Vue.js) for an intuitive user interface.
  • Backend: Robust, API-first architecture using a scalable programming language (e.g., Node.js, Python, Java) to handle form logic, data processing, and integrations.
  • Database: Secure and performant database solution (e.g., PostgreSQL, MongoDB) optimized for storing form configurations and submission data.
  • Cloud-Native Design: Leverages cloud infrastructure (e.g., AWS, Azure, Google Cloud) for elasticity, high availability, and global reach.
  • Microservices (Optional): For large-scale deployments, a microservices approach can be adopted to ensure independent scalability and resilience of different components (e.g., form rendering, submission processing, integration services).

5. Implementation & Integration Strategy

Our approach ensures a smooth and effective deployment of the Dynamic Form Builder:

  • Deployment Options:

* SaaS (Software-as-a-Service): Fully managed cloud solution, offering immediate access and minimal operational overhead.

* On-Premise/Private Cloud: For organizations with stringent data residency or security requirements, deployment within your own infrastructure is available.

* Hybrid: A blend of SaaS with on-premise components for specific integrations or data processing needs.

  • API-First Integration: We provide comprehensive API documentation and support to facilitate seamless integration with your existing CRMs, marketing platforms, data warehouses, and custom applications.
  • Webhooks Configuration: Guide and assist in setting up webhooks to trigger real-time actions and workflows in your connected systems upon form submission.
  • Embedding & Hosting: Clear instructions and support for embedding forms into your websites, portals, or applications, ensuring a consistent user experience.
  • Data Migration (if applicable): Assistance with migrating existing form data or configurations from legacy systems into the new platform.
  • Training & Documentation: Comprehensive user guides, tutorials, and training sessions for administrators and end-users to ensure rapid adoption and proficiency.

6. Next Steps & Call to Action

To move forward with the Dynamic Form Builder solution, we recommend the following next steps:

  1. Personalized Demonstration: Schedule a live demonstration tailored to your specific use cases and requirements, showcasing how the Dynamic Form Builder can address your unique challenges.
  2. Requirements Deep Dive: Engage in a detailed session with our solution architects to gather specific functional and non-functional requirements, ensuring the solution aligns perfectly with your strategic objectives.
  3. Pilot Program / Proof of Concept: Consider a pilot program or proof of concept (POC) to experience the builder's capabilities firsthand with a specific project or department.
  4. Integration Planning Workshop: Conduct a workshop to outline the integration points and data flow between the Dynamic Form Builder and your existing enterprise systems.

7. Support & Maintenance

We are committed to providing exceptional support and ensuring the long-term success of your Dynamic Form Builder implementation:

  • Dedicated Support Channels: Access to our support team via email, phone, and a dedicated ticketing system.
  • Comprehensive Documentation: A knowledge base with user manuals, API documentation, FAQs, and troubleshooting guides.
  • Regular Updates & Upgrades: Continuous feature enhancements, performance optimizations, and security updates to keep your platform cutting-edge.
  • Service Level Agreements (SLAs): Customizable SLAs to guarantee uptime, response times, and resolution times based on your operational needs.

We are confident that the Dynamic Form Builder will be a transformative asset for your organization, driving efficiency, improving data quality, and empowering your teams. We look forward to partnering with you on this journey.

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);}});}