Repository: roundtableAI/roundtable-js Branch: main Commit: c752b33a7c89 Files: 33 Total size: 154.7 KB Directory structure: gitextract_qhmt1r8t/ ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── examples/ │ ├── index.html │ └── studies/ │ ├── book-a-demo.js │ ├── data-annotation.js │ ├── element-showcase.js │ ├── enterprise-market-research.js │ ├── llm-rlhf.js │ ├── nps-with-branding.js │ ├── product-market-fit.js │ └── typeform.js ├── index.js ├── library/ │ ├── core/ │ │ ├── element.js │ │ ├── plugin.js │ │ └── survey.js │ ├── elements/ │ │ ├── HTML.js │ │ ├── boundingBox.js │ │ ├── checkBox.js │ │ ├── dropdownSelect.js │ │ ├── grid.js │ │ ├── multiSelect.js │ │ ├── numberEntry.js │ │ ├── numberScale.js │ │ ├── openEnd.js │ │ ├── singleSelect.js │ │ └── textInput.js │ └── plugins/ │ ├── pageHTML.js │ └── progressBar.js ├── package.json └── webpack.config.cjs ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ /node_modules /dist ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at support@roundtable.ai. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. [homepage]: https://www.contributor-covenant.org [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html [Mozilla CoC]: https://github.com/mozilla/diversity [FAQ]: https://www.contributor-covenant.org/faq [translations]: https://www.contributor-covenant.org/translations ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing to RoundtableJS Thank you for considering contributing to **RoundtableJS**. Here are a few guidelines to help you get started. ### Code of Conduct Please read our [Code of Conduct](https://github.com/roundtableAI/roundtable-js/blob/main/CODE_OF_CONDUCT.md) before participating. We expect all contributors to adhere to it. ### How Can I Contribute? **Reporting Bugs** - Check the [issues](https://github.com/roundtableAI/roundtable-js/issues) for similar reportings. - Draft a bug report for submission. - Use a clear and descriptive title for the issue to identify the problem. - Describe the steps to reproduce the problem in as much detail as possible. Include any relevant information like operating system, browser version, and any logs or error messages. Provide screenshots or animated GIFs if possible. **Suggesting Enhancements** - Check the [issues](https://github.com/roundtableAI/roundtable-js/issues) for similar suggestions. - Draft an enhancement submission report. - Use a clear and descriptive title for the suggestion. - Provide a detailed explanation of the suggested enhancement. Explain why this enhancement would be useful to most **RoundtableJS** users. **Submitting Pull Requests** 1. Check the [issues](https://github.com/roundtableAI/roundtable-js/issues) for relevant discussions. 2. Fork the repository and create your branch from `main`. 3. If you've added code that should be tested, add tests. 4. Ensure the test suite passes and that your code lints. 5. Create a pull request using the pull request template (in progress) Thank you for your contribution! 📊 ✨ ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2024 Roundtable Technologies Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================

Roundtable Logo

RoundtableJS

Programmatic survey software
Cloud editorSlackDocumentation

GitHub Stars NPM Downloads Hacker News Cloud Editor

Twitter Follow Join Slack LinkedIn Follow

RoundtableJS is an open-source JavaScript library for building complex surveys, forms, and data annotation tasks. It's designed to be simple but completely customizable. We make it easy to add complex logic (e.g. branching, skipping, looping), modify question types, and fully customize the design. ## 🌟 Features - **Designed for the Modern Web:** We're designed in JavaScript and leverage its asynchronous functionality for managing survey logic. For example, rather than determining this logic based on callbacks that trigger when a page is submitted, our library builds the timeline in an async function which means the logic flows intuitively from top to bottom. - **Developer-Friendly:** We are open-source and API-first. The idea for RoundtableJS arose by seeing how difficult it was to integrate Roundtable's API into other survey software. We want the open-source offering to include a robust plugin ecosystem where people can introduce new question types, integrate with tools like CRMs, and control how data is stored and processed. - **AI-Native Functionality:** Our [cloud offering](https://surveys.roundtable.ai) has AI-native features such as natural language programming and automated fraud detection. We're continuously expanding our AI features. Let us know what tools you'd like to see! ## 🖼️ Examples Here are some example surveys built with RoundtableJS. All code is in the [examples/studies](examples/studies) directory. - [Element showcase](https://roundtable.ai/survey/3e76ab92512f398e366baffd772b06cf972c0c0e) - [Enterprise market research survey](https://roundtable.ai/survey/3020c264e57a0415889a7d82330af66daf30db15) - [Simple NPS with branding](https://roundtable.ai/survey/bed16082755fc02b70f582c1fe143b8e7d292a43) - [Typeform survey](https://roundtable.ai/survey/134a2317bb595d7768194de65772f97dc760b60b) - [Product market fit survey](https://roundtable.ai/survey/765c87578ccf7e24522e91c44cf41f845c4bcd0e) - [Book a demo form](https://roundtable.ai/survey/374fd1f3f1719d69b21438cbacd7013d28b7daeb) - [Data annotation task](https://roundtable.ai/survey/1518e8ae74e9075349b07ffeee8ee21166477e4d) - [RLHF data collection](https://roundtable.ai/survey/89eeb07064400b58f2d3a3d979b0cff729f1ee2b) ## 🚀 Quick Start ## Installation ### Option 1: npm 1. Install roundtable-js using npm: ```bash npm install roundtable-js ``` ### Option 2: Git 1. Clone the repository: ``` git clone https://github.com/roundtableAI/roundtable-js.git ``` 2. Navigate to the project directory: ``` cd roundtable-js ``` 3. Include the necessary files in your project. ### Option 3: CDN 1. Include the following script tag in your HTML: ```html ``` ## Usage 1. Import the necessary modules in your JavaScript file for npm or Git installations: ```javascript import Survey from 'roundtable-js/core/survey.js'; import SingleSelect from 'roundtable-js/elements/singleSelect.js'; ``` For CDN installation, ensure the script is loaded and use the global `RoundtableJS` object: ```javascript const { Survey, SingleSelect } = RoundtableJS; ``` 2. Create a survey instance and add pages with questions: ```javascript // Define an asynchronous function to run the survey async function runSurvey() { // Create a new Survey instance with a specific participant ID const survey = new Survey({ participantId: 'participant_123' }); // Define the first question as a single-select question with two options const question1 = new SingleSelect({ id: 'question1', text: 'A question', options: ['Option 1', 'Option 2'], }); // Define the second question as a single-select question with two options const question2 = new SingleSelect({ id: 'question2', text: 'A second question', options: ['Option 1', 'Option 2'], }); // Show the first page with the first question and wait for it to be answered await survey.showPage({ id: 'page1', elements: [question1] }); // This code runs only after the first page is completed console.log('Page 1 completed'); // Show the next page with the second question and wait for it to be answered await survey.showPage({ id: 'page2', elements: [question2] }); // Finish the survey once all pages are completed and display an end message survey.finishSurvey('Thank you for completing the survey!'); } // Start the survey by calling the runSurvey function runSurvey(); ``` 3. Set up your HTML: ```html Survey ``` ## 📚 Documentation Read our [full documentation](https://docs.roundtable.ai/rjs/introduction). ## 🎉 Community Join our community: - [Slack](https://join.slack.com/t/roundtablejs/shared_invite/zt-2m09n74yv-B~UeGbxSzGMTO3f0qXhRxQ) - [Twitter](https://twitter.com/roundtabledotai) - [Blog](https://roundtable.ai/blog) - [LinkedIn](https://www.linkedin.com/company/roundtable-ai) ## 🛠️ Development / Open-Source Community Please see our [Contributing Guide](CONTRIBUTING.md). ## 📜 License RoundtableJS is open source software [licensed](LICENSE). --- ================================================ FILE: examples/index.html ================================================ Survey ================================================ FILE: examples/studies/book-a-demo.js ================================================ import Survey from '../../library/core/survey.js'; import TextInput from '../../library/elements/textInput.js'; import HTML from '../../library/elements/HTML.js'; import OpenEnd from '../../library/elements/openEnd.js'; import PageHTML from '../../library/plugins/pageHTML.js'; async function runSurvey() { const survey = new Survey({ condition: 'test', participant_id: 'p123', styles: { container: { maxWidth: '650px', padding: '30px', paddingTop: '40px', paddingBottom: '50px', position: 'relative', }, button: { backgroundColor: 'black', '&:hover': { backgroundColor: '#333333', } } } }); const logo = new PageHTML({ id: 'logo', content: 'Roundtable Logo', position: 'top', styles: { root: { display: 'block', margin: '0 auto', maxWidth: '190px', marginBottom: '20px' } } }); survey.addPlugin(logo); const subtitle = new HTML({ id: 'subtitle', content: '

Please fill out this form and a member of our sales team will contact you.

' }); const email = new TextInput({ id: 'email', text: 'Email', required: true, placeholder: 'Your email', }); const name = new TextInput({ id: 'name', text: 'Name', required: true, placeholder: 'Your name', }); const company = new TextInput({ id: 'company', text: 'Company', required: true, placeholder: 'Your company name', }); const role = new TextInput({ id: 'role', text: 'Role', required: true, placeholder: 'Your role', }); const participantVolume = new TextInput({ id: 'participantVolume', text: 'What is your average participant volume per month?', required: true, placeholder: 'Average participant volume', }); const businessType = new TextInput({ id: 'businessType', text: 'What % B2B vs B2C?', required: true, placeholder: 'Your answer', }); const hearAboutUs = new TextInput({ id: 'hearAboutUs', text: 'How did you hear about us?', required: false, placeholder: 'Optional', }); const additionalComments = new OpenEnd({ id: 'additionalComments', text: 'Additional comments', required: false, placeholder: 'Optional', }); const builtWith = new PageHTML({ id: 'builtWith', content: '
Built with RoundtableJS
', position: 'bottom', styles: { root: { position: 'absolute', bottom: '49px', right: '25px', fontSize: '14px', padding: '0px', textAlign: 'right', } } }); survey.addPlugin(builtWith); await survey.showPage({ id: 'demoForm', elements: [ subtitle, email, name, company, role, participantVolume, businessType, hearAboutUs, additionalComments, ] }); survey.removePlugin(builtWith); survey.finishSurvey(`

Thank you for your interest

A member of our sales team will contact you shortly.

Back to our website
`); } runSurvey(); ================================================ FILE: examples/studies/data-annotation.js ================================================ import Survey from '../../library/core/survey.js'; import BoundingBox from '../../library/elements/boundingBox.js'; import ProgressBar from '../../library/plugins/progressBar.js'; // Add images and questions for each page const imageUrls = ['https://www.usnews.com/object/image/00000168-b98c-d246-a9f9-fddd8bb50000/190204-seattletunnel-editorial.jpg?update-time=1549301335348&size=responsive640', 'https://www.giviexplorer.com/imagesC/11886/576x576xGIVI-Explorer_friends4adventure_Ecuador-cover.jpg']; async function addBoundingBoxPage(survey, imageUrl, index) { const boundingBoxQ = new BoundingBox({ id: `bb-q${index}`, text: `Draw a bounding box around the vehicles in the image below`, subText: `If there are no vehicles, skip to the next page`, imageUrl: imageUrl, }); const id = `q${index}-bb`; await survey.showPage({ id, elements: [ boundingBoxQ ] }); } async function runSurvey() { const survey = new Survey({ participantId: 'test-participant', condition: 'car-labeling', }); const progressBar = new ProgressBar({ maxPages: imageUrls.length, styles: { bar: { backgroundColor: 'black' } } }); survey.addPlugin(progressBar); // Bounding box pages for (let i = 0; i < imageUrls.length; i++) { await addBoundingBoxPage(survey, imageUrls[i], i); } survey.finishSurvey('Thank you for completing the task!'); } runSurvey(); ================================================ FILE: examples/studies/element-showcase.js ================================================ import Survey from '../../library/core/survey.js'; import BoundingBox from '../../library/elements/boundingBox.js'; import CheckBox from '../../library/elements/checkBox.js'; import TextInput from '../../library/elements/textInput.js'; import DropdownSelect from '../../library/elements/dropdownSelect.js'; import Grid from '../../library/elements/grid.js'; import HTML from '../../library/elements/HTML.js'; import MultiSelect from '../../library/elements/multiSelect.js'; import NumberEntry from '../../library/elements/numberEntry.js'; import NumberScale from '../../library/elements/numberScale.js'; import OpenEnd from '../../library/elements/openEnd.js'; import SingleSelect from '../../library/elements/singleSelect.js'; import ProgressBar from '../../library/plugins/progressBar.js'; import PageHTML from '../../library/plugins/pageHTML.js'; async function runSurvey() { const survey = new Survey({ title: "Comprehensive Survey Example", description: "This survey demonstrates all question types and plugins.", styles: { body: { background: '#f9f9f7', } } }); const htmlIntro = new HTML({ id: 'intro', content: '

Welcome to our element showcase

This survey include examples of every question type and plugin. The code for the survey is available on our GitHub.

', styles: { root: { textAlign: 'center', } } }); const textInput = new TextInput({ id: 'name', text: 'Name', required: true, placeholder: 'Your name', }) const singleSelect = new SingleSelect({ id: 'favorite-color', text: 'What is your favorite color?', subText: 'Select one option', options: ['Red', 'Blue', 'Green', 'Yellow'], required: true, allowOther: true, }); const multiSelect = new MultiSelect({ id: 'hobbies', text: 'Which of the following are your hobbies? (Select all that apply)', options: ['Reading', 'Sports', 'Cooking', 'Gaming', 'Traveling'], required: true, minSelect: 1, maxSelect: 3 }); const dropdownSelect = new DropdownSelect({ id: 'country', text: 'Select your country of residence', options: ['United States', 'Canada', 'United Kingdom', 'Australia', 'Germany', 'France', 'Japan', 'Other'], required: true }); const checkBox = new CheckBox({ id: 'terms', text: 'I agree to the terms and conditions', required: true }); const numberEntry = new NumberEntry({ id: 'age', text: 'Please enter your age', min: 18, max: 100, required: true }); const numberScale = new NumberScale({ id: 'satisfaction', text: 'How satisfied are you with our service?', min: 1, max: 10, minLabel: 'Not at all satisfied', maxLabel: 'Extremely satisfied', required: true }); const openEnd = new OpenEnd({ id: 'feedback', text: 'Please provide any additional feedback you may have', required: false, maxLength: 500 }); const grid = new Grid({ id: 'feature-rating', text: 'Please rate the following features of our product', rows: ['Ease of use', 'Performance', 'Design', 'Customer support'], columns: ['Poor', 'Fair', 'Good', 'Excellent'], required: true }); const boundingBox = new BoundingBox({ id: 'image-selection', text: 'Please draw a box around the house', imageUrl: 'https://images.pexels.com/photos/106399/pexels-photo-106399.jpeg', required: true }); // Group questions into pages const page1 = { id: 'page1', elements: [htmlIntro, textInput, singleSelect, multiSelect, dropdownSelect] }; const page2 = { id: 'page2', elements: [checkBox, numberEntry, numberScale, openEnd] }; const page3 = { id: 'page3', elements: [grid, boundingBox] }; const progress = new ProgressBar({ maxPages: 3 }); const logo = new PageHTML({ id: 'logo', content: 'Company Logo', position: 'top', styles:{ root: { margin: '0 auto', width: '100%', maxWidth: '180px', marginTop: '5px', marginBottom: '10px' } } }); survey.addPlugin(logo); survey.addPlugin(progress); // Show pages sequentially await survey.showPage(page1); await survey.showPage(page2); await survey.showPage(page3); // Finish the survey survey.finishSurvey(`

Thank you for completing our comprehensive survey!

Your responses have been recorded and will help us improve our services.

`); // Log the survey data (in a real scenario, you'd probably send this to a server) console.log('Survey data:', survey.getAllSurveyData()); } // Run the survey runSurvey(); ================================================ FILE: examples/studies/enterprise-market-research.js ================================================ import Survey from '../../library/core/survey.js'; import Grid from '../../library/elements/grid.js'; import HTML from '../../library/elements/HTML.js'; import MultiSelect from '../../library/elements/multiSelect.js'; import NumberEntry from '../../library/elements/numberEntry.js'; import OpenEnd from '../../library/elements/openEnd.js'; import SingleSelect from '../../library/elements/singleSelect.js'; import ProgressBar from '../../library/plugins/progressBar.js'; async function runSurvey() { const survey = new Survey({ condition: 'test', participant_id: 'p123', styles: { body: { background: '#f0f8ff', '@media (max-width: 650px)': { background: 'white', }, }, container: { boxShadow: '0 0 10px rgba(0,0,255,0.1)', '@media (max-width: 650px)': { boxShadow: 'none', }, }, button: { backgroundColor: '#4682b4', '&:hover': { backgroundColor: '#5f9ea0', } }, question: { borderBottom: '1px solid #b0d4ff', paddingBottom: '20px', '@media (max-width: 650px)': { borderBottom: 'none', paddingBottom: '0px', }, } } }); const progressBar = new ProgressBar({ maxPages: 8, progressAsPercentage: true, styles: { bar: { background: '#4682b4', } } }); survey.addPlugin(progressBar); const welcome = new HTML({ id: 'welcome', content: `

Welcome to the Annual Travel Habits Survey

We appreciate your participation in this study.

` }); await survey.showPage({ id: 'welcome_page', elements: [welcome] }); const q1 = new SingleSelect({ id: 'travel_frequency', text: 'How often do you travel for business?', options: ['Never', 'Once a year', '2-3 times a year', '4-6 times a year', 'Monthly', 'Weekly'], required: true }); await survey.showPage({ id: 'page1', elements: [q1] }); if (survey.getResponse('travel_frequency') !== 'Never') { const q2 = new MultiSelect({ id: 'travel_destinations', text: 'Which regions do you typically travel to for business? (Select all that apply)', options: ['North America', 'South America', 'Europe', 'Asia', 'Africa', 'Australia'], required: true }); await survey.showPage({ id: 'page2', elements: [q2] }); const destinations = survey.getResponse('travel_destinations'); for (const destination of destinations) { const q_destination = new OpenEnd({ id: `travel_experience_${destination}`, text: `Please describe your typical business travel experience in ${destination}:`, minLength: 10, maxLength: 200, required: true }); await survey.showPage({ id: `page_${destination}`, elements: [q_destination] }); } const q3 = new Grid({ id: 'travel_satisfaction', text: 'Please rate your satisfaction with the following aspects of your most recent business trip:', rows: ['Flight', 'Hotel', 'Transportation', 'Food', 'Meeting facilities'], columns: ['Very Dissatisfied', 'Dissatisfied', 'Neutral', 'Satisfied', 'Very Satisfied'], required: true }); await survey.showPage({ id: 'page4', elements: [q3] }); const q4 = new NumberEntry({ id: 'travel_budget', text: 'What is your average budget per business trip (in USD)?', min: 0, max: 1000000, required: true }); await survey.showPage({ id: 'page5', elements: [q4] }); const q5 = new OpenEnd({ id: 'travel_improvement', text: 'What one thing would most improve your business travel experience?', required: true }); await survey.showPage({ id: 'page6', elements: [q5] }); } survey.finishSurvey(`

Thank you for completing our business travel survey!

Your insights will help us improve business travel experiences.

If you have any questions, please contact us at research@example.com.

`); } runSurvey(); ================================================ FILE: examples/studies/llm-rlhf.js ================================================ import Survey from '../../library/core/survey.js'; import OpenEnd from '../../library/elements/openEnd.js'; import HTML from '../../library/elements/HTML.js'; import MultiSelect from '../../library/elements/multiSelect.js'; import SingleSelect from '../../library/elements/singleSelect.js'; import NumberScale from '../../library/elements/numberScale.js'; import ProgressBar from '../../library/plugins/progressBar.js'; function generatePromptResponseHTML(prompt, response) { return `

Prompt:

${prompt}

Response:

${response}
`; } function generatePage(pageNumber, prompt, response) { const promptResponseHTML = new HTML({ id: `prompt-response-${pageNumber}`, content: generatePromptResponseHTML(prompt, response) }); const relevanceQuestion = new SingleSelect({ id: `relevance-${pageNumber}`, text: 'Is the response relevant for the prompt?', options: ['Yes', 'No', 'Partially'], required: true }); const avoidanceQuestion = new MultiSelect({ id: `avoidance-${pageNumber}`, text: 'Does the response include anything that should be avoided?', options: ['Racial slurs', 'Explicit content', 'Misinformation', 'Biased language'], required: true }); const qualityQuestion = new NumberScale({ id: `quality-${pageNumber}`, text: 'Rate the overall quality of the response', min: 1, max: 10, minLabel: 'Poor', maxLabel: 'Excellent', required: true }); const feedbackQuestion = new OpenEnd({ id: `feedback-${pageNumber}`, text: 'Any additional comments or feedback on the response?', required: false }); return { id: `evaluation-${pageNumber}`, elements: [promptResponseHTML, relevanceQuestion, avoidanceQuestion, qualityQuestion, feedbackQuestion] }; } async function runSurvey() { const survey = new Survey({ participantId: 'test-participant', condition: 'llm-evaluation', styles: { body: { background: 'white' }, container: { boxShadow: 'none', }, } }); const progressBar = new ProgressBar({ maxPages: 2, styles: { bar: { backgroundColor: 'black', } } }); survey.addPlugin(progressBar); const samplePrompt1 = "What is the population of the United States?"; const sampleResponse1 = "As of 2024, the population of the United States is estimated to be around 335 million people. This figure can fluctuate slightly due to births, deaths, and migration patterns. For the most up-to-date and precise figure, I'd recommend checking the U.S. Census Bureau website, as they provide regular population estimates and projections."; const samplePrompt2 = "Write a Python function that calculates the factorial of a number."; const sampleResponse2 = `Here is a Python function that calculates the total factorial of a number:
def factorial(n):
  if n == 0 or n == 1:
    return 1
  else:
    return n * factorial(n - 1)
# Example usage
number = 5
result = factorial(number)
print(f"The factorial of {number} is {result}")
`; await survey.showPage(generatePage(1, samplePrompt1, sampleResponse1)); await survey.showPage(generatePage(2, samplePrompt2, sampleResponse2)); survey.finishSurvey('Thank you for completing the evaluation!'); } runSurvey(); ================================================ FILE: examples/studies/nps-with-branding.js ================================================ import Survey from '../../library/core/survey.js'; import HTML from '../../library/elements/HTML.js'; import NumberScale from '../../library/elements/numberScale.js'; import SingleSelect from '../../library/elements/singleSelect.js'; import PageHTML from '../../library/plugins/pageHTML.js'; async function runSurvey() { const survey = new Survey({ condition: 'starbucks_nps', participant_id: 'p123', styles: { body: { color: '#1e3932', }, container: { color: '#1e3932', maxWidth: '600px', }, button: { backgroundColor: '#00704A', color: '#FFFFFF', transition: 'background-color 0.3s ease', '&:hover': { backgroundColor: '#004E33' } } } }); const logo = new PageHTML({ id: 'starbucks_logo', content: 'Starbucks Logo', position: 'top', styles: { root: { marginTop: '10px', marginBottom: '30px', } } }); survey.addPlugin(logo); const welcome = new HTML({ id: 'welcome_message', content: '

Starbucks Customer Feedback

We value your opinion. This short survey will take about 1-2 minutes to complete.

', styles: { root: { textAlign: 'center', marginBottom: '30px', } } }); const npsQuestion = new NumberScale({ id: 'nps_score', text: 'How likely are you to recommend Starbucks to a friend or colleague?', subText: 'Please rate on a scale from 0 (Not at all likely) to 10 (Extremely likely)', min: 1, max: 7, minLabel: 'Not at all likely', maxLabel: 'Extremely likely', required: true, styles: { subText: { fontSize: '14px', fontStyle: 'italic', marginBottom: '15px', }, } }); const experienceQuestion = new SingleSelect({ id: 'experience_rating', text: 'How would you rate your overall experience with Starbucks?', options: [ 'Excellent', 'Very Good', 'Good', 'Fair', 'Poor' ], required: true, styles: { text:{ marginBottom: '15px', }, label: { fontWeight: 'bold', color: '#00704A' }, } }); const thankYou = new PageHTML({ id: 'thank_you_message', content: '

Thank you for your feedback!

We appreciate your time and input. Your responses will help us improve our services.

', styles: { root: { textAlign: 'center', marginTop: '30px' } } }); await survey.showPage({ id: 'page1', elements: [welcome, npsQuestion] }); await survey.showPage({ id: 'page2', elements: [experienceQuestion] }); survey.finishSurvey(thankYou.content); } runSurvey(); ================================================ FILE: examples/studies/product-market-fit.js ================================================ import Survey from '../../library/core/survey.js'; import MultiSelect from '../../library/elements/multiSelect.js'; import NumberScale from '../../library/elements/numberScale.js'; import OpenEnd from '../../library/elements/openEnd.js'; import SingleSelect from '../../library/elements/singleSelect.js'; import PageHTML from '../../library/plugins/pageHTML.js'; async function runSurvey() { const survey = new Survey(); const logo = new PageHTML({ id: 'logo', content: 'RoundtableJS Logo', position: 'top', styles: { root: { maxWidth: '190px', margin: '10px auto 30px', } } }); survey.addPlugin(logo); const q1 = new SingleSelect({ id: 'role', text: 'What best describes your role?', options: ['Developer', 'Designer', 'Product Manager', 'Researcher'], required: true, allowOther: true, }); await survey.showPage({ id: 'page1', elements: [q1] }); const q2 = new NumberScale({ id: 'satisfaction', text: 'How satisfied are you with RoundtableJS?', min: 1, max: 10, minLabel: 'Very Dissatisfied', maxLabel: 'Very Satisfied', required: true, }); await survey.showPage({ id: 'page2', elements: [q2] }); const q3 = new MultiSelect({ id: 'features', text: 'Which features of RoundtableJS do you find most valuable?', options: ['Easy to use', 'Customizable', 'Fast performance', 'Good documentation', 'Responsive design'], minSelected: 1, maxSelected: 3, required: true, }); await survey.showPage({ id: 'page3', elements: [q3] }); const q4 = new OpenEnd({ id: 'improvement', text: 'What one thing would you improve about RoundtableJS?', required: true, }); await survey.showPage({ id: 'page4', elements: [q4] }); const q5 = new SingleSelect({ id: 'recommend', text: 'How likely are you to recommend RoundtableJS to a colleague?', options: ['Very likely', 'Likely', 'Neutral', 'Unikely', 'Very unlikely'], required: true, }); await survey.showPage({ id: 'page5', elements: [q5] }); survey.finishSurvey("

Thank you for your feedback!

Your responses will help us improve RoundtableJS.

"); } runSurvey(); ================================================ FILE: examples/studies/typeform.js ================================================ import Survey from '../../library/core/survey.js'; import OpenEnd from '../../library/elements/openEnd.js'; import HTML from '../../library/elements/HTML.js'; import NumberScale from '../../library/elements/numberScale.js'; async function runSurvey() { const survey = new Survey({ condition: 'test', participant_id: 'p123', styles: { body: { fontWeight: '300 !important', display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh', background: '#ebf2f5', padding: '0px', }, container: { maxWidth: '800px', width: '100%', padding: '40px', boxShadow: 'none', background: 'none', }, button: { background: '#404040', borderRadius: '12px', transition: 'all 0.15s ease', display: 'block', margin: '0 auto', '&:hover': { transform: 'scale(1.1)', }, }, Element: { text: { fontSize: '32px', marginBottom: '30px', }, subText: { fontSize: '18px', marginBottom: '30px', textAlign: 'center', }, }, } }); const initialPage = new HTML({ id: 'initial-page', content: `

How was our product?

We'd love to hear about your experience.
` }); const npsQuestion = new NumberScale({ id: 'nps', text: 'How likely are you to recommend our product to a friend or colleague?', min: 0, max: 10, minLabel: 'Not at all likely', maxLabel: 'Extremely likely', required: true, styles: { scaleContainer: { marginTop: '20px', }, scaleCircle: { transition: 'all 0.15s ease', background: 'transparent', border: '1px solid black', '&:hover': { transform: 'scale(1.1)', boxShadow: '0 5px 15px rgba(0,0,0,0.1)', }, }, } }); const feedbackQuestion = new OpenEnd({ id: 'feedback', text: 'What is the primary reason for your score?', required: true, styles: { textarea: { width: '100%', padding: '16px', fontSize: '20px', border: '1px solid black', borderRadius: '10px', resize: 'vertical', minHeight: '150px', transition: 'border-color 0.3s ease', '&:focus': { borderColor: 'black', outline: 'none', }, } } }); const enterHint = new PageHTML({ id: 'enter-hint', content: '
Or press Enter ↵
', position: 'bottom', targetId: 'navigation', styles: { root: { fontSize: '12px', color: '#888', marginTop: '5px', textAlign: 'center', } } }); survey.addPlugin(enterHint); document.addEventListener('keydown', function(event) { if (event.key === 'Enter') { const nextButton = document.getElementById('next-button'); if (nextButton) { nextButton.click(); } else { const startButton = document.getElementById('start-survey'); if (startButton) { startButton.click(); } } } }); await survey.showPage({ id: 'initial', elements: [initialPage] }); await survey.showPage({ id: 'page1', elements: [npsQuestion] }); await survey.showPage({ id: 'page2', elements: [feedbackQuestion] }); survey.removePlugin(enterHint); survey.finishSurvey(`

Thank you for your feedback!

Your responses have been recorded and will help us improve our product.

`); } runSurvey(); ================================================ FILE: index.js ================================================ // src/index.js import Survey from './library/core/survey.js'; import BoundingBox from './library/elements/boundingBox.js'; import CheckBox from './library/elements/checkBox.js'; import DropdownSelect from './library/elements/dropdownSelect.js'; import Grid from './library/elements/grid.js'; import HTML from './library/elements/HTML.js'; import MultiSelect from './library/elements/multiSelect.js'; import NumberEntry from './library/elements/numberEntry.js'; import NumberScale from './library/elements/numberScale.js'; import OpenEnd from './library/elements/openEnd.js'; import SingleSelect from './library/elements/singleSelect.js'; import TextInput from './library/elements/textInput.js'; import ProgressBar from './library/plugins/progressBar.js'; import PageHTML from './library/plugins/pageHTML.js'; export { Survey, BoundingBox, CheckBox, DropdownSelect, Grid, HTML, MultiSelect, NumberEntry, NumberScale, OpenEnd, SingleSelect, PageHTML, ProgressBar, TextInput }; ================================================ FILE: library/core/element.js ================================================ class Element { static dataStructure = { id: null, type: null, response: null, responseTimestamp: null }; static styleKeys = ['root', 'innerContainer', 'textContainer', 'text', 'subText', 'errorMessage']; static selectorMap = { root: '', innerContainer: '.inner-container', textContainer: '.text-container', text: '.question-text', subText: '.question-subtext', errorMessage: '.error-message' }; constructor({ id, type, store_data = false, required = false, customValidation = null, styles = {} }) { if (!id || typeof id !== 'string') { throw new Error('Invalid id: must be a non-empty string'); } if (!type || typeof type !== 'string') { throw new Error('Invalid type: must be a non-empty string'); } this.id = id; this.type = type; this.store_data = Boolean(store_data); this.required = Boolean(required); this.data = { id, type, response: null, responded: false }; this.initialResponse = null; this.styles = styles; this.eventListeners = []; this.elementStyleKeys = [...this.constructor.styleKeys]; this.selectorMap = { ...this.constructor.selectorMap }; this.customValidation = customValidation; } mergeStyles(surveyElementStyles, elementStyles) { const mergedStyles = {}; this.elementStyleKeys.forEach(key => { mergedStyles[key] = { ...(surveyElementStyles[key] || {}), ...(this.constructor.defaultStyles?.[key] || {}), ...(this.styles[key] || {}), ...(elementStyles[key] || {}) }; }); return mergedStyles; } generateStylesheet(surveyElementStyles) { const mergedStyles = this.mergeStyles(surveyElementStyles, this.styles); return this.elementStyleKeys.map(key => { return this.generateStyleForSelector(this.getSelectorForKey(key), mergedStyles[key]) } ).join('\n'); } getSelectorForKey(key) { return this.selectorMap[key] || ''; } generateStyleForSelector(selector, rules) { if (!rules || typeof rules !== 'object') { console.warn(`Invalid rules for selector ${selector}`); return ''; } const baseSelector = `#${this.id}-container`; const fullSelector = selector ? `${baseSelector} ${selector}` : baseSelector; const baseStyles = this.rulesToString(rules); let styleString = `${fullSelector} { ${baseStyles} }`; Object.entries(rules) .filter(([key, value]) => typeof value === 'object') .forEach(([key, value]) => { if (key.startsWith('@media')) { styleString += `\n${key} { ${fullSelector} { ${this.rulesToString(value)} } }`; } else if (key.startsWith('&')) { styleString += `\n${fullSelector}${key.slice(1)} { ${this.rulesToString(value)} }`; } }); return styleString; } rulesToString(rules) { return Object.entries(rules) .filter(([key, value]) => typeof value !== 'object') .map(([key, value]) => `${this.camelToKebab(key)}: ${value};`) .join(' '); } camelToKebab(string) { return string.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$1-$2').toLowerCase(); } setInitialResponse(value) { this.initialResponse = value; } render(surveyElementStyles) { const questionContainer = document.getElementById('question-container'); if (questionContainer) { const elementHtml = this.generateHTML(); const tempContainer = document.createElement('div'); tempContainer.innerHTML = elementHtml; const elementContainer = tempContainer.firstElementChild; // Apply styles const styleElement = document.createElement('style'); styleElement.textContent = this.generateStylesheet(surveyElementStyles); elementContainer.prepend(styleElement); questionContainer.appendChild(elementContainer); this.attachEventListeners(); // Set the initial response after rendering this.data.response = this.initialResponse; } else { console.error('Question container not found'); } } generateHTML() { throw new Error('generateHTML method must be implemented by subclasses'); } attachEventListeners() { // This method should be overridden by subclasses if they need to attach event listeners } addEventListenerWithTracking(element, eventType, handler) { const wrappedHandler = (event) => { handler(event); }; element.addEventListener(eventType, wrappedHandler); this.eventListeners.push({ element, eventType, handler: wrappedHandler }); } collectData() { return this.store_data ? { ...this.data } : null; } setResponse(value) { if (this.store_data) { this.data.response = value; this.data.responseTimestamp = new Date().toISOString(); this.data.responded = true; } this.showValidationError(null); } addData(key, value) { if (this.store_data) { this.data[key] = value; } } validate() { let isValid = true; let errorMessage = ''; // Check if the question is required and answered if (this.required && !this.data.responded) { isValid = false; errorMessage = 'Please provide a response.'; } // If basic validation passed and custom validation is provided, run it if (isValid && typeof this.customValidation === 'function') { const customValidationResult = this.customValidation(this.data.response); if (customValidationResult !== true) { isValid = false; errorMessage = customValidationResult || 'Invalid input.'; } } return { isValid, errorMessage }; } showValidationError(message) { const errorElement = document.getElementById(`${this.id}-error`); if (errorElement) { errorElement.textContent = message || ''; errorElement.style.display = message ? 'block' : 'none'; } else { console.warn(`Error element not found for ${this.id}`); } } destroy() { // Remove all event listeners if they exist if (this.eventListeners) { this.eventListeners.forEach(({ element, eventType, handler }) => { element.removeEventListener(eventType, handler); }); this.eventListeners = []; } // Remove the element from the DOM const container = document.getElementById(`${this.id}-container`); if (container) { container.remove(); } // Clear any data this.data = null; // Remove any custom properties Object.keys(this).forEach(key => { if (this.hasOwnProperty(key)) { this[key] = null; } }); } } export default Element; ================================================ FILE: library/core/plugin.js ================================================ class Plugin { constructor({ targetId = 'survey-container', position = 'top', styles = {} }) { this.targetId = targetId; this.position = position; this.styles = styles; this.pluginId = `plugin-${Math.random().toString(36).substr(2, 9)}`; } initialize(survey) { this.survey = survey; this.injectPlugin(); } injectPlugin() { const targetContainer = document.getElementById(this.targetId); if (!targetContainer) { console.warn(`Target container with id "${this.targetId}" not found`); return; } let pluginContainer = this.getOrCreatePluginContainer(targetContainer); const pluginElement = this.createPluginElement(); pluginContainer.appendChild(pluginElement); } getOrCreatePluginContainer(targetContainer) { const containerId = `${this.targetId}-${this.position}-plugins`; let pluginContainer = document.getElementById(containerId); if (!pluginContainer) { pluginContainer = document.createElement('div'); pluginContainer.id = containerId; if (this.position === 'top') { targetContainer.insertBefore(pluginContainer, targetContainer.firstChild); } else { targetContainer.appendChild(pluginContainer); } } return pluginContainer; } createPluginElement() { const element = document.createElement('div'); element.id = this.pluginId; element.innerHTML = this.generateContent(); this.applyStyles(element); return element; } generateContent() { // To be implemented by subclasses throw new Error('generateContent method must be implemented by subclasses'); } applyStyles(element) { Object.assign(element.style, this.styles.root || {}); } beforePageRender() { // This method is intentionally left empty } afterPageRender() { // This method is intentionally left empty } beforeSurveyFinish() { // This method is intentionally left empty } destroy() { const element = document.getElementById(this.pluginId); if (element) { element.remove(); } } } export default Plugin; ================================================ FILE: library/core/survey.js ================================================ class Survey { static styleKeys = ['body', 'container', 'navigation', 'button', 'errorMessage', 'nextButtonError', 'finishMessage']; static defaultStyles = { body: { fontFamily: 'Helvetica, Arial, sans-serif', lineHeight: '1.4', color: 'black', backgroundColor: '#f7f7f7', padding: '25px', '@media (max-width: 650px)': { background: 'white', padding: '0px', }, }, container: { width: '100%', maxWidth: '680px', boxSizing: 'border-box', margin: '0 auto', padding: '25px', backgroundColor: '#ffffff', boxShadow: '0 0 10px rgba(0,0,0,0.1)', borderRadius: '12px', '@media (max-width: 650px)': { boxShadow: 'none', padding: '20px', }, }, navigation: { marginTop: '45px', }, button: { backgroundColor: '#333', maxWidth: '100%', color: '#ffffff', padding: '12px 34px', border: 'none', fontSize: '1em', borderRadius: '8px', cursor: 'pointer', '&:hover': { backgroundColor: '#444', } }, errorMessage: { color: '#fa5252', marginTop: '5px', fontSize: '0.9em', }, nextButtonError: { color: '#fa5252', marginLeft: '10px', display: 'inline-block', fontSize: '0.9em', }, finishMessage: { display: 'none', fontSize: '1.1em', textAlign: 'center', }, }; static defaultElementStyles = { root: { marginBottom: '40px', }, innerContainer: { marginTop: '5px', }, textContainer: { marginBottom: '10px', }, text: { display: 'block', }, subText: { display: 'block', color: '#888', fontSize: '1em', }, errorMessage: { color: '#fa5252', fontSize: '0.9em', marginTop: '5px' } }; constructor(customSurveyDetails = {}) { this.responses = []; this.currentPage = null; this.nextButtonListener = null; this.plugins = []; this.currentPageElements = []; this.surveyDetails = { startTime: new Date().toISOString(), ...customSurveyDetails }; this.globalStyles = this.mergeStyles(Survey.defaultStyles, this.surveyDetails.styles || {}); this.elementStyles = this.mergeStyles(Survey.defaultElementStyles, this.surveyDetails.styles?.Element || {}); if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => this.initialize()); } else { this.initialize(); } } initialize() { try { this.validateStyles(); this.applyGlobalStyles(); this.revealContent(); } catch (error) { console.error('Error during survey initialization:', error); } } mergeStyles(defaultStyles, customStyles) { const keys = Object.keys(defaultStyles); return Object.fromEntries( keys.map(key => [key, this.deepMerge(defaultStyles[key], customStyles[key])]) ); } deepMerge(target, source) { if (!source || typeof source !== 'object') return target; if (!target || typeof target !== 'object') return source; const merged = { ...target }; Object.entries(source).forEach(([key, value]) => { if (key.startsWith('&') || key.startsWith('@media')) { if(target[key]){ Object.entries(target[key]).forEach(([k,v]) => { if(k in source) target[key][k] = source[k]; }) } merged[key] = this.deepMerge(target[key] || {}, value); } else { merged[key] = value; Object.entries(merged).forEach(([k, v]) => { if (k.startsWith('&') || k.startsWith('@media')) { merged[k] = { ...v, [key]: value, }; } }); } }); return merged; } applyGlobalStyles() { const styleElement = document.createElement('style'); styleElement.textContent = this.generateStylesheet(); document.head.appendChild(styleElement); } generateStylesheet() { return Survey.styleKeys.map(key => this.generateStyleForSelector(this.getSelectorForKey(key), this.globalStyles[key]) ).join('\n'); } getSelectorForKey(key) { const selectorMap = { body: 'body', container: '#survey-container', button: '#next-button', errorMessage: '.error-message', nextButtonError: '#next-button-error', navigation: '#navigation', finishMessage: '#finish', }; return selectorMap[key] || ''; } generateStyleForSelector(selector, rules) { if (!rules || typeof rules !== 'object') return ''; const baseStyles = this.rulesToString(rules); let styleString = `${selector} { ${baseStyles} }`; Object.entries(rules) .filter(([key, value]) => typeof value === 'object') .forEach(([key, value]) => { if (key.startsWith('@media')) { styleString += `\n${key} { ${selector} { ${this.rulesToString(value)} } }`; } else if (key.startsWith('&')) { styleString += `\n${selector}${key.slice(1)} { ${this.rulesToString(value)} }`; } }); return styleString; } rulesToString(rules) { return Object.entries(rules) .filter(([key, value]) => typeof value !== 'object') .map(([key, value]) => `${this.camelToKebab(key)}: ${value};`) .join(' '); } camelToKebab(string) { return string.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$1-$2').toLowerCase(); } validateStyles() { Object.keys(this.globalStyles).forEach(key => { if (!Survey.styleKeys.includes(key)) { console.warn(`Invalid style key '${key}' for Survey. Valid keys are: ${Survey.styleKeys.join(', ')}`); } }); } revealContent() { const surveyContainer = document.getElementById('survey-container'); if (surveyContainer) { surveyContainer.classList.remove('hidden'); } else { console.warn('Survey container not found'); } } addPlugin(plugin) { if (typeof plugin.initialize === 'function') { this.plugins.push(plugin); plugin.initialize(this); } else { console.warn('Invalid plugin: missing initialize method'); } } removePlugin(plugin) { const index = this.plugins.indexOf(plugin); if (index > -1) { plugin.destroy(); this.plugins.splice(index, 1); return true; } return false; } setSurveyDetail(key, value) { this.surveyDetails[key] = value; } getSurveyDetail(key) { return this.surveyDetails[key]; } async showPage(page) { try { this.cleanupCurrentPage(); this.currentPage = page; for (const plugin of this.plugins) { await plugin.beforePageRender(page); } const pageContainer = document.getElementById('page-container'); if (!pageContainer) throw new Error('Page container not found'); pageContainer.innerHTML = ''; const questionContainer = document.createElement('div'); questionContainer.id = 'question-container'; pageContainer.appendChild(questionContainer); this.currentPageElements = []; for (const element of page.elements) { element.render(this.elementStyles); this.currentPageElements.push(element); } await this.setupNextButton(); for (const plugin of this.plugins) { await plugin.afterPageRender(page); } } catch (error) { console.error('Error showing page:', error); } } cleanupCurrentPage() { if (this.currentPageElements && this.currentPageElements.length > 0) { for (const element of this.currentPageElements) { if (typeof element.destroy === 'function') { element.destroy(); } else { console.warn(`Element ${element.id} does not have a destroy method`); } } this.currentPageElements = []; } const nextButton = document.getElementById('next-button'); if (nextButton && this.nextButtonListener) { nextButton.removeEventListener('click', this.nextButtonListener); this.nextButtonListener = null; } } async setupNextButton() { const nextButton = document.getElementById('next-button'); if (!nextButton) throw new Error('Next button not found'); const nextButtonError = document.createElement('span'); nextButtonError.id = 'next-button-error'; nextButtonError.className = 'next-button-error'; nextButtonError.style.display = 'none'; nextButton.parentNode.insertBefore(nextButtonError, nextButton.nextSibling); if (this.nextButtonListener) { nextButton.removeEventListener('click', this.nextButtonListener); } return new Promise(resolve => { this.nextButtonListener = async () => { try { if (await this.validateCurrentPage()) { this.collectPageData(this.currentPage); nextButtonError.style.display = 'none'; nextButtonError.textContent = ''; resolve(); } else { nextButtonError.style.display = 'inline-block'; nextButtonError.textContent = 'Please check your answers.'; } } catch (error) { console.error('Error in next button handler:', error); } }; nextButton.addEventListener('click', this.nextButtonListener); }); } async validateCurrentPage() { let isValid = true; for (const element of this.currentPage.elements) { if (typeof element.validate === 'function') { const { isValid: elementValid, errorMessage } = await element.validate(); if (!elementValid) { isValid = false; element.showValidationError(errorMessage); } else { element.showValidationError(null); // Clear any previous error } } } return isValid; } collectPageData(page) { page.elements.forEach(element => { const elementData = element.collectData(); if (elementData !== null) { this.updateData(elementData); } }); } updateData(elementData) { this.responses.push({ ...elementData, responseTimestamp: new Date().toISOString() }); } getResponse(questionId) { const responses = this.responses.filter(r => r.id === questionId); return responses.length > 0 ? responses[responses.length - 1].response : null; } responded(questionId) { const responses = this.responses.filter(r => r.id === questionId); return responses.length > 0 ? responses[responses.length - 1].responded : false; } getAllResponses() { return this.responses; } getAllSurveyData() { return { surveyDetails: this.surveyDetails, responses: this.responses }; } finishSurvey(message) { try { this.cleanupCurrentPage(); const navigation = document.getElementById('navigation'); if (navigation) navigation.remove(); for (const plugin of this.plugins) { plugin.beforeSurveyFinish(); } const pageContainer = document.getElementById('page-container'); if (pageContainer) { pageContainer.innerHTML = ''; } const finishElement = document.getElementById('finish') || document.createElement('div'); finishElement.id = 'finish'; finishElement.innerHTML = message; finishElement.style.display = 'block'; if (!document.getElementById('finish')) { const surveyContainer = document.getElementById('survey-container'); if (surveyContainer) { surveyContainer.appendChild(finishElement); } else { console.error('Survey container not found'); } } this.surveyDetails.endTime = new Date().toISOString(); } catch (error) { console.error('Error finishing survey:', error); } } } export default Survey; ================================================ FILE: library/elements/HTML.js ================================================ import Element from '../core/element.js'; class HTML extends Element { static styleKeys = [...Element.styleKeys]; static selectorMap = { ...Element.selectorMap }; static defaultStyles = { }; constructor({ id, content, styles = {} }) { super({ id, type: 'html', store_data: false, required: false, styles }); if (typeof content !== 'string' || content.trim() === '') { throw new Error('Content must be a non-empty string'); } this.content = content; this.rendered = false; this.required = false; this.elementStyleKeys = [...HTML.styleKeys]; this.selectorMap = { ...HTML.selectorMap }; } getSelectorForKey(key) { return this.selectorMap[key] || ''; } generateHTML() { return `
${this.content}
`; } render(surveyElementStyles) { if (this.rendered) { // If already rendered, update the content instead of recreating const container = document.getElementById(`${this.id}-container`); if (container) { container.innerHTML = this.content; return; } } // If not rendered or container not found, render as usual super.render(surveyElementStyles); this.rendered = true; } destroy() { // Only remove from DOM, don't clear all data const container = document.getElementById(`${this.id}-container`); if (container) { container.remove(); } this.rendered = false; } attachEventListeners() { // No event listeners needed for HTML content } setResponse() { // HTML elements don't have a response to set } validate() { return {isValid: true, errorMessage: ''}; } showValidationError() { // Do nothing, HTML elements don't show validation errors } } export default HTML; ================================================ FILE: library/elements/boundingBox.js ================================================ import Element from '../core/element.js'; class BoundingBox extends Element { static styleKeys = [...Element.styleKeys, 'canvas', 'controls', 'controlPoint', 'button']; static selectorMap = { ...Element.selectorMap, canvas: 'canvas', controls: '.controls', controlPoint: '.control-point', button: 'button' }; static defaultStyles = { canvas: { cursor: 'crosshair', display: 'block', marginBottom: '10px', width: '100%', height: 'auto', }, controls: { position: 'absolute', backgroundColor: 'rgba(255, 255, 255, 0.5)', }, controlPoint: { position: 'absolute', width: '10px', height: '10px', backgroundColor: 'white', border: '1px solid #333', }, button: { backgroundColor: '#333', color: '#ffffff', padding: '8px 24px', border: 'none', borderRadius: '5px', cursor: 'pointer', marginRight: '10px', '&:hover': { backgroundColor: '#444', }, '&:disabled': { backgroundColor: '#888', cursor: 'not-allowed', } }, }; constructor({ id, text, subText = '', imageUrl, boxColor = '#FF0000', boxOpacity = 0.3, maxBoxes = Infinity, required = true, customValidation = null, styles = {} }) { super({ id, type: 'bounding-box', store_data: true, required, customValidation, styles }); if (!imageUrl) { throw new Error('Image URL is required'); } this.text = text; this.subText = subText; this.imageUrl = imageUrl; this.boxColor = boxColor; this.boxOpacity = boxOpacity; this.maxBoxes = maxBoxes; this.addData('text', text); this.addData('subText', subText); this.addData('imageUrl', imageUrl); this.addData('boxColor', boxColor); this.addData('boxOpacity', boxOpacity); this.addData('maxBoxes', maxBoxes); this.initializeState(); this.bindEventHandlers(); this.initialResponse = []; this.elementStyleKeys = [...BoundingBox.styleKeys]; this.selectorMap = { ...BoundingBox.selectorMap }; } generateHTML() { return `
${this.subText ? `${this.subText}` : ''}
`; } initializeState() { this.boxes = []; this.history = [[]]; this.canvas = null; this.ctx = null; this.image = null; this.activeBox = null; this.isDrawing = false; this.isMoving = false; this.isResizing = false; this.resizeHandle = null; this.dragStartX = 0; this.dragStartY = 0; this.scaleFactor = 1; this.potentialBox = null; } bindEventHandlers() { this.handleMouseDown = this.handleMouseDown.bind(this); this.handleMouseMove = this.handleMouseMove.bind(this); this.handleMouseUp = this.handleMouseUp.bind(this); this.handleTouchStart = this.handleTouchStart.bind(this); this.handleTouchMove = this.handleTouchMove.bind(this); this.handleTouchEnd = this.handleTouchEnd.bind(this); this.handleCursorUpdate = this.handleCursorUpdate.bind(this); this.handleKeyDown = this.handleKeyDown.bind(this); this.handleResize = this.handleResize.bind(this); } attachEventListeners() { this.canvas = document.getElementById(`${this.id}-canvas`); this.ctx = this.canvas.getContext('2d'); this.image = new Image(); this.image.onload = () => { this.resizeCanvas(); this.draw(); }; this.image.src = this.imageUrl; this.addEventListenerWithTracking(this.canvas, 'mousedown', this.handleMouseDown); this.addEventListenerWithTracking(document.getElementById(`${this.id}-clear`), 'click', this.clearBoxes.bind(this)); this.addEventListenerWithTracking(document.getElementById(`${this.id}-undo`), 'click', this.undoAction.bind(this)); this.addEventListenerWithTracking(document.getElementById(`${this.id}-remove`), 'click', this.removeActiveBox.bind(this)); this.addEventListenerWithTracking(window, 'resize', this.handleResize); this.addEventListenerWithTracking(this.canvas, 'touchstart', this.handleTouchStart, { passive: false }); this.addEventListenerWithTracking(this.canvas, 'touchmove', this.handleTouchMove, { passive: false }); this.addEventListenerWithTracking(this.canvas, 'touchend', this.handleTouchEnd); this.addEventListenerWithTracking(this.canvas, 'mousemove', this.handleCursorUpdate); this.addEventListenerWithTracking(document, 'keydown', this.handleKeyDown); } handleResize() { this.resizeCanvas(); this.draw(); } resizeCanvas() { const containerWidth = this.canvas.parentElement.clientWidth; this.scaleFactor = containerWidth / this.image.width; this.canvas.width = containerWidth; this.canvas.height = this.image.height * this.scaleFactor; } handleMouseDown(e) { const { x, y } = this.getScaledPosition(e); this.startInteraction(x, y); this.addEventListenerWithTracking(document, 'mousemove', this.handleMouseMove); this.addEventListenerWithTracking(document, 'mouseup', this.handleMouseUp); } handleMouseMove(e) { const { x, y } = this.getScaledPosition(e); this.updateInteraction(x, y); } handleMouseUp() { this.endInteraction(); document.removeEventListener('mousemove', this.handleMouseMove); document.removeEventListener('mouseup', this.handleMouseUp); } handleTouchStart(e) { e.preventDefault(); const touch = e.touches[0]; const { x, y } = this.getScaledPosition(touch); this.startInteraction(x, y); } handleTouchMove(e) { e.preventDefault(); const touch = e.touches[0]; const { x, y } = this.getScaledPosition(touch); this.updateInteraction(x, y); } handleTouchEnd() { this.endInteraction(); } handleCursorUpdate(e) { const { x, y } = this.getScaledPosition(e); this.updateCursor(x, y); } handleKeyDown(e) { if ((e.key === 'Delete' || e.key === 'Backspace') && this.activeBox) { e.preventDefault(); this.removeActiveBox(); this.updateHistory(); } } startInteraction(x, y) { const clickedBox = this.getClickedBox(x, y); if (clickedBox) { this.activeBox = clickedBox; this.dragStartX = x - clickedBox.x; this.dragStartY = y - clickedBox.y; this.resizeHandle = this.getResizeHandle(clickedBox, x, y); this.isResizing = !!this.resizeHandle; this.isMoving = !this.isResizing; } else { this.activeBox = null; if (this.boxes.length < this.maxBoxes) { this.potentialBox = { startX: x, startY: y }; } } this.updateRemoveButtonState(); this.draw(); } updateInteraction(x, y) { if (this.isDrawing) { this.updateDrawing(x, y); } else if (this.isMoving) { this.updateMoving(x, y); } else if (this.isResizing) { this.updateResizing(x, y); } else if (this.potentialBox) { this.checkStartDrawing(x, y); } else { this.updateCursor(x, y); } this.draw(); } endInteraction() { if (this.isDrawing && this.activeBox.width === 0 && this.activeBox.height === 0) { this.boxes.pop(); this.activeBox = null; } this.isDrawing = false; this.isMoving = false; this.isResizing = false; this.resizeHandle = null; this.potentialBox = null; this.setResponse(this.getScaledBoxes()); this.updateRemoveButtonState(); this.draw(); this.updateHistory(); } updateDrawing(x, y) { const width = x - this.activeBox.startX; const height = y - this.activeBox.startY; this.activeBox.x = width < 0 ? x : this.activeBox.startX; this.activeBox.y = height < 0 ? y : this.activeBox.startY; this.activeBox.width = Math.abs(width); this.activeBox.height = Math.abs(height); this.constrainBoxToImage(this.activeBox); } updateMoving(x, y) { const newX = x - this.dragStartX; const newY = y - this.dragStartY; this.moveBox(this.activeBox, newX, newY); } updateResizing(x, y) { this.resizeBox(x, y); } checkStartDrawing(x, y) { const dx = x - this.potentialBox.startX; const dy = y - this.potentialBox.startY; if (Math.sqrt(dx * dx + dy * dy) > 5) { this.isDrawing = true; this.activeBox = { startX: this.potentialBox.startX, startY: this.potentialBox.startY, x: this.potentialBox.startX, y: this.potentialBox.startY, width: 0, height: 0 }; this.boxes.push(this.activeBox); this.potentialBox = null; this.updateRemoveButtonState(); } } getScaledPosition(e) { const rect = this.canvas.getBoundingClientRect(); const clientX = e.clientX || (e.touches && e.touches[0].clientX); const clientY = e.clientY || (e.touches && e.touches[0].clientY); return { x: (clientX - rect.left) / this.scaleFactor, y: (clientY - rect.top) / this.scaleFactor }; } clearBoxes() { this.boxes = []; this.activeBox = null; this.draw(); this.setResponse([]); this.updateRemoveButtonState(); this.updateHistory(); } removeActiveBox() { if (this.activeBox) { this.boxes = this.boxes.filter(box => box !== this.activeBox); this.activeBox = null; this.draw(); this.setResponse(this.getScaledBoxes()); this.updateRemoveButtonState(); this.updateHistory(); } } updateRemoveButtonState() { const removeButton = document.getElementById(`${this.id}-remove`); removeButton.disabled = !this.activeBox; } getClickedBox(x, y) { return this.boxes.find(box => x >= box.x && x <= box.x + box.width && y >= box.y && y <= box.y + box.height ); } getResizeHandle(box, x, y) { const handles = [ { x: box.x, y: box.y, cursor: 'nw-resize' }, { x: box.x + box.width / 2, y: box.y, cursor: 'n-resize' }, { x: box.x + box.width, y: box.y, cursor: 'ne-resize' }, { x: box.x + box.width, y: box.y + box.height / 2, cursor: 'e-resize' }, { x: box.x + box.width, y: box.y + box.height, cursor: 'se-resize' }, { x: box.x + box.width / 2, y: box.y + box.height, cursor: 's-resize' }, { x: box.x, y: box.y + box.height, cursor: 'sw-resize' }, { x: box.x, y: box.y + box.height / 2, cursor: 'w-resize' }, ]; return handles.find(h => Math.abs(x - h.x) < 15 && Math.abs(y - h.y) < 15); } updateCursor(x, y) { const clickedBox = this.getClickedBox(x, y); if (clickedBox) { const resizeHandle = this.getResizeHandle(clickedBox, x, y); this.canvas.style.cursor = resizeHandle ? resizeHandle.cursor : 'move'; } else { this.canvas.style.cursor = this.boxes.length < this.maxBoxes ? 'crosshair' : 'default'; } } resizeBox(x, y) { const box = this.activeBox; let newX = box.x; let newY = box.y; let newWidth = box.width; let newHeight = box.height; switch (this.resizeHandle.cursor) { case 'nw-resize': newWidth = box.width + (box.x - x); newHeight = box.height + (box.y - y); newX = x; newY = y; break; case 'n-resize': newHeight = box.height + (box.y - y); newY = y; break; case 'ne-resize': newWidth = x - box.x; newHeight = box.height + (box.y - y); newY = y; break; case 'e-resize': newWidth = x - box.x; break; case 'se-resize': newWidth = x - box.x; newHeight = y - box.y; break; case 's-resize': newHeight = y - box.y; break; case 'sw-resize': newWidth = box.width + (box.x - x); newHeight = y - box.y; newX = x; break; case 'w-resize': newWidth = box.width + (box.x - x); newX = x; break; } // Flip the box if necessary if (newWidth < 0) { newX += newWidth; newWidth = Math.abs(newWidth); this.flipResizeHandle('horizontal'); } if (newHeight < 0) { newY += newHeight; newHeight = Math.abs(newHeight); this.flipResizeHandle('vertical'); } // Update the box properties box.x = newX; box.y = newY; box.width = newWidth; box.height = newHeight; this.constrainBoxToImage(box); } flipResizeHandle(direction) { const flipMap = { 'horizontal': { 'nw-resize': 'ne-resize', 'ne-resize': 'nw-resize', 'sw-resize': 'se-resize', 'se-resize': 'sw-resize', 'w-resize': 'e-resize', 'e-resize': 'w-resize' }, 'vertical': { 'nw-resize': 'sw-resize', 'ne-resize': 'se-resize', 'sw-resize': 'nw-resize', 'se-resize': 'ne-resize', 'n-resize': 's-resize', 's-resize': 'n-resize' } }; if (this.resizeHandle && flipMap[direction][this.resizeHandle.cursor]) { this.resizeHandle.cursor = flipMap[direction][this.resizeHandle.cursor]; } } moveBox(box, newX, newY) { box.x = Math.max(0, Math.min(newX, this.image.width - box.width)); box.y = Math.max(0, Math.min(newY, this.image.height - box.height)); } constrainBoxToImage(box) { box.x = Math.max(0, Math.min(box.x, this.image.width - 1)); box.y = Math.max(0, Math.min(box.y, this.image.height - 1)); box.width = Math.max(1, Math.min(box.width, this.image.width - box.x)); box.height = Math.max(1, Math.min(box.height, this.image.height - box.y)); } draw() { this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); this.ctx.drawImage(this.image, 0, 0, this.canvas.width, this.canvas.height); this.boxes.forEach(box => { this.ctx.fillStyle = this.getRGBAColor(this.boxColor, this.boxOpacity); this.ctx.fillRect( box.x * this.scaleFactor, box.y * this.scaleFactor, box.width * this.scaleFactor, box.height * this.scaleFactor ); if (box === this.activeBox) { this.drawResizeHandles(box); } }); } drawResizeHandles(box) { const handles = [ { x: box.x, y: box.y }, { x: box.x + box.width / 2, y: box.y }, { x: box.x + box.width, y: box.y }, { x: box.x + box.width, y: box.y + box.height / 2 }, { x: box.x + box.width, y: box.y + box.height }, { x: box.x + box.width / 2, y: box.y + box.height }, { x: box.x, y: box.y + box.height }, { x: box.x, y: box.y + box.height / 2 }, ]; handles.forEach(handle => { this.ctx.fillStyle = 'white'; this.ctx.fillRect( handle.x * this.scaleFactor - 5, handle.y * this.scaleFactor - 5, 10, 10 ); }); } getRGBAColor(color, opacity) { if (color.startsWith('#')) { const r = parseInt(color.slice(1, 3), 16); const g = parseInt(color.slice(3, 5), 16); const b = parseInt(color.slice(5, 7), 16); return `rgba(${r}, ${g}, ${b}, ${opacity})`; } else { return color; } } getScaledBoxes() { return this.boxes.map(box => ({ x: box.x / this.image.width, y: box.y / this.image.height, width: box.width / this.image.width, height: box.height / this.image.height })); } updateHistory() { if (this.boxes.length > 0) { if (this.history.length === 1 || JSON.stringify(this.history[this.history.length - 1]) !== JSON.stringify(this.boxes)) { this.history.push(JSON.parse(JSON.stringify(this.boxes))); document.getElementById(`${this.id}-undo`).disabled = false; } } else if (this.history.length > 1) { this.history = [[]]; document.getElementById(`${this.id}-undo`).disabled = true; } } undoAction() { if (this.history.length > 1) { this.history.pop(); this.boxes = JSON.parse(JSON.stringify(this.history[this.history.length - 1])); this.activeBox = null; this.draw(); this.setResponse(this.getScaledBoxes()); this.updateRemoveButtonState(); if (this.history.length === 1) { document.getElementById(`${this.id}-undo`).disabled = true; } } } setResponse(value) { super.setResponse(value, value.length > 0); this.showValidationError(null); } validate() { // BoundingBox-specific validation if (this.required && this.boxes.length === 0) { return { isValid: false, errorMessage: 'Please draw at least one bounding box.' }; } // If BoundingBox-specific validation passed, call parent's validate method return super.validate(); } destroy() { // Remove all event listeners this.eventListeners.forEach(({ element, eventType, handler }) => { element.removeEventListener(eventType, handler); }); this.eventListeners = []; // Clear the canvas if (this.ctx) { this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); } // Reset all state this.initializeState(); // Call the parent destroy method super.destroy(); } } export default BoundingBox; ================================================ FILE: library/elements/checkBox.js ================================================ import Element from '../core/element.js'; class CheckBox extends Element { static styleKeys = [...Element.styleKeys, 'checkboxFlexContainer', 'checkbox', 'checkboxLabel'] static selectorMap = { ...Element.selectorMap, checkboxFlexContainer: '.checkbox-flex-container', checkbox: 'input[type="checkbox"]', checkboxLabel: '.checkbox-label', }; static defaultStyles = { checkboxFlexContainer: { display: 'flex', alignItems: 'center', justifyContent: 'flex-start', gap: '5px', background: 'white', }, checkbox: { width: '20px', height: '20px', accentColor: 'black', borderColor: 'black', backgroundColor: 'transparent', marginRight: '5px', '@media (max-width: 650px)': { width: '16px', height: '16px' } }, checkboxLabel: { } }; constructor({ id, text, required = true, customValidation = null, styles = {} }) { super({ id, type: 'checkbox', store_data: true, required, customValidation, styles }); this.text = text; this.addData('text', text); this.initialResponse = false; this.elementStyleKeys = [...CheckBox.styleKeys]; this.selectorMap = { ...CheckBox.selectorMap }; } generateHTML() { return `
`; } attachEventListeners() { const checkbox = document.getElementById(this.id); this.addEventListenerWithTracking(checkbox, 'change', (e) => { this.setResponse(e.target.checked); }); } setResponse(value) { super.setResponse(Boolean(value)); this.showValidationError(null); } validate() { // CheckBox-specific validation if (this.required && this.data.response !== true) { return { isValid: false, errorMessage: 'This checkbox is required.' }; } // If CheckBox-specific validation passed, call parent's validate method return super.validate(); } } export default CheckBox; ================================================ FILE: library/elements/dropdownSelect.js ================================================ import Element from '../core/element.js'; class DropdownSelect extends Element { static styleKeys = [...Element.styleKeys, 'select', 'option']; static selectorMap = { ...Element.selectorMap, select: 'select', option: 'option' }; static defaultStyles = { select: { width: '100%', cursor: 'pointer', padding: '12px', border: '1px solid #ccc', borderRadius: '8px', fontSize: '1em', marginBottom: '0px', display: 'block', appearance: 'none', backgroundImage: 'url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'12\' height=\'12\' fill=\'%23333\' viewBox=\'0 0 16 16\'%3E%3Cpath d=\'M7.247 11.14L2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z\'/%3E%3C/svg%3E")', backgroundRepeat: 'no-repeat', backgroundPosition: 'right 12px center', backgroundSize: '12px', '&:focus': { borderColor: 'black', outline: 'none', }, }, option: { padding: '8px', } }; constructor({ id, text, subText = '', options, required = true, placeholder = 'Select an option', customValidation = null, styles = {}, }) { super({ id, type: 'dropdown-select', store_data: true, required, customValidation, styles }); if (!Array.isArray(options) || options.length === 0) { throw new Error('Options must be a non-empty array'); } this.text = text; this.subText = subText; this.options = options; this.placeholder = placeholder; this.addData('text', text); this.addData('subText', subText); this.addData('options', options); this.initialResponse = ''; this.elementStyleKeys = [...DropdownSelect.styleKeys]; this.selectorMap = { ...DropdownSelect.selectorMap }; } generateHTML() { const optionsHTML = this.options.map(option => `` ).join(''); return ` `; } attachEventListeners() { const select = document.getElementById(this.id); this.addEventListenerWithTracking(select, 'change', this.handleChange.bind(this)); } handleChange(e) { const value = e.target.value; this.setResponse(value); } validate() { const value = this.data.response; if (!value && this.required) { return { isValid: false, errorMessage: 'Please select an option.' }; } if (value && !this.options.includes(value)) { return { isValid: false, errorMessage: 'Selected option is not valid.' }; } return super.validate(); } } export default DropdownSelect; ================================================ FILE: library/elements/grid.js ================================================ import Element from '../core/element.js'; class Grid extends Element { static styleKeys = [...Element.styleKeys, 'table', 'headerRow', 'headerCell', 'rowWrapper', 'row', 'rowLabel', 'cell', 'radio']; static selectorMap = { ...Element.selectorMap, table: 'table', headerRow: 'thead tr', headerCell: 'thead th', rowWrapper: '.row-wrapper', row: 'tbody tr', rowLabel: 'tbody td.row-label', cell: 'tbody td', radio: 'input[type="radio"]' }; static defaultStyles = { table: { width: '100%', borderCollapse: 'separate', borderSpacing: '0 10px', lineHeight: '1', '@media (max-width: 650px)': { fontSize: '0.9em' } }, headerRow: {}, headerCell: { padding: '0px 16px', textAlign: 'center', fontWeight: 'normal', '@media (max-width: 650px)': { padding: '0px 12px' } }, row: { backgroundColor: '#f0f0f0', borderRadius: '12px', }, rowLabel: { padding: '12px 16px', textAlign: 'left', borderTopLeftRadius: '8px', borderBottomLeftRadius: '8px', '@media (max-width: 650px)': { padding: '12px' } }, cell: { textAlign: 'center', verticalAlign: 'middle', }, radio: { appearance: 'none', width: '20px', height: '20px', borderRadius: '50%', border: '1px solid black', border: '1px solid #767676', outline: 'none', margin: '0 auto', background: 'white', cursor: 'pointer', verticalAlign: 'middle', '&:checked': { backgroundColor: 'black', boxShadow: 'inset 0 0 0 3px #ffffff' }, '@media (max-width: 650px)': { width: '16px', height: '16px' } } }; constructor({ id, text, subText = '', rows, columns, required = true, randomizeRows = false, randomizeColumns = false, customValidation = null, styles = {} }) { super({ id, type: 'grid', store_data: true, required, customValidation, styles }); if (!Array.isArray(rows) || rows.length === 0 || !Array.isArray(columns) || columns.length === 0) { throw new Error('Rows and columns must be non-empty arrays'); } this.text = text; this.subText = subText; this.rows = rows; this.columns = columns; this.randomizeRows = Boolean(randomizeRows); this.randomizeColumns = Boolean(randomizeColumns); this.addData('text', text); this.addData('subText', subText); this.addData('rows', rows); this.addData('columns', columns); this.addData('randomizeRows', this.randomizeRows); this.addData('randomizeColumns', this.randomizeColumns); this.initialResponse = {}; this.elementStyleKeys = [...Grid.styleKeys]; this.selectorMap = { ...Grid.selectorMap }; } generateHTML() { const rowsHTML = this.randomizeRows ? this.shuffleArray([...this.rows]) : this.rows; const columnsHTML = this.randomizeColumns ? this.shuffleArray([...this.columns]) : this.columns; const headerRow = ` ${columnsHTML.map(column => `${column}`).join('')} `; const bodyRows = rowsHTML.map((row, rowIndex) => ` ${row} ${columnsHTML.map((column, colIndex) => ` `).join('')} `).join(''); return `
${this.subText ? `${this.subText}` : ''}
${headerRow}${bodyRows}
`; } generateStylesheet(surveyElementStyles) { const stylesheet = super.generateStylesheet(surveyElementStyles); // Add styles for the last cell in each row const lastCellStyles = this.generateStyleForSelector(`${this.getSelectorForKey('cell')}:last-child`, { borderTopRightRadius: '8px', borderBottomRightRadius: '8px', }); return stylesheet + '\n' + lastCellStyles; } shuffleArray(array) { return array.sort(() => Math.random() - 0.5); } attachEventListeners() { const container = document.getElementById(`${this.id}-container`); this.addEventListenerWithTracking(container, 'change', this.handleChange.bind(this)); } handleChange(e) { if (e.target.type === 'radio') { this.updateResponse(); } } updateResponse() { const container = document.getElementById(`${this.id}-container`); const responses = Object.fromEntries( this.rows.map((row, index) => { const selectedRadio = container.querySelector(`input[name="${this.id}-${index}"]:checked`); return [row, selectedRadio ? selectedRadio.value : null]; }) ); this.setResponse(responses); } setResponse(value) { super.setResponse(value); this.showValidationError(null); } validate() { // Grid-specific validation const unansweredRows = this.rows.filter(row => !this.data.response[row]); if (unansweredRows.length > 0) { return { isValid: false, errorMessage: `Please provide a response for all rows. Missing: ${unansweredRows.join(', ')}` }; } // If Grid-specific validation passed, call parent's validate method return super.validate(); } } export default Grid; ================================================ FILE: library/elements/multiSelect.js ================================================ import Element from '../core/element.js'; class MultiSelect extends Element { static styleKeys = [...Element.styleKeys, 'optionsContainer', 'option', 'checkbox', 'label']; static selectorMap = { ...Element.selectorMap, optionsContainer: '.options-container', option: '.option', checkbox: 'input[type="checkbox"]', label: 'label' }; static defaultStyles = { optionsContainer: { display: 'flex', flexDirection: 'column', gap: '10px', lineHeight: '1', }, option: { backgroundColor: '#f0f0f0', borderRadius: '8px', padding: '12px 16px', display: 'flex', alignItems: 'center', cursor: 'pointer', '&:hover': { backgroundColor: '#e0e0e0', '@media (max-width: 650px)': { backgroundColor: '#f0f0f0' } }, '@media (max-width: 650px)': { padding: '12px' } }, checkbox: { width: '20px', height: '20px', accentColor: 'black', borderColor: 'black', backgroundColor: 'transparent', margin: '0', marginRight: '10px', '@media (max-width: 650px)': { width: '16px', height: '16px' } }, label: { cursor: 'pointer', flexGrow: 1 } }; constructor({ id, text, subText = '', options, required = true, randomize = false, minSelected = 0, maxSelected = null, customValidation = null, styles = {} }) { super({ id, type: 'multi-select', store_data: true, required, customValidation, styles }); if (!Array.isArray(options) || options.length === 0) { throw new Error('Options must be a non-empty array'); } if (minSelected < 0 || (maxSelected !== null && minSelected > maxSelected)) { throw new Error('Invalid minSelected or maxSelected values'); } this.text = text; this.subText = subText; this.options = options; this.randomize = Boolean(randomize); this.minSelected = minSelected; this.maxSelected = maxSelected; this.addData('text', text); this.addData('subText', subText); this.addData('options', options); this.addData('randomize', this.randomize); this.addData('minSelected', minSelected); this.addData('maxSelected', maxSelected); this.initialResponse = []; this.elementStyleKeys = [...MultiSelect.styleKeys]; this.selectorMap = { ...MultiSelect.selectorMap }; } generateHTML() { let optionsHTML = this.randomize ? this.shuffleArray([...this.options]) : this.options; const optionsString = optionsHTML.map((option, index) => `
`).join(''); return `
${this.subText ? `${this.subText}` : ''}
${optionsString}
`; } attachEventListeners() { const container = document.getElementById(`${this.id}-container`); this.addEventListenerWithTracking(container, 'click', this.handleClick.bind(this)); } handleClick(e) { const optionDiv = e.target.closest('.option'); if (optionDiv) { const checkbox = optionDiv.querySelector('input[type="checkbox"]'); checkbox.checked = !checkbox.checked; this.updateResponse(); } } updateResponse() { const container = document.getElementById(`${this.id}-container`); const checkedBoxes = container.querySelectorAll(`input[name="${this.id}"]:checked`); const selectedOptions = Array.from(checkedBoxes).map(cb => cb.value); this.setResponse(selectedOptions); } setResponse(value) { super.setResponse(value); this.showValidationError(null); } validate() { const selectedCount = this.data.response ? this.data.response.length : 0; if (this.minSelected > 0 && selectedCount < this.minSelected) { return { isValid: false, errorMessage: `Please select at least ${this.minSelected} option(s).` }; } if (this.maxSelected !== null && selectedCount > this.maxSelected) { return { isValid: false, errorMessage: `Please select no more than ${this.maxSelected} option(s).` }; } return super.validate(); } shuffleArray(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } return array; } } export default MultiSelect; ================================================ FILE: library/elements/numberEntry.js ================================================ import Element from '../core/element.js'; class NumberEntry extends Element { static styleKeys = [...Element.styleKeys, 'input', 'unit']; static selectorMap = { ...Element.selectorMap, input: 'input[type="number"]', unit: '.unit-label' }; static defaultStyles = { input: { width: '80px', padding: '8px', border: '1px solid #ccc', borderRadius: '4px', fontSize: '1em', }, unit: { marginLeft: '5px', fontSize: '0.9em', } }; constructor({ id, text, subText = '', min = null, max = null, step = 1, unit = '', required = true, customValidation = null, styles = {} }) { super({ id, type: 'number-entry', store_data: true, required, customValidation, styles }); this.text = text; this.subText = subText; this.min = min; this.max = max; this.step = step; this.unit = unit; this.addData('text', text); this.addData('subText', subText); this.addData('min', min); this.addData('max', max); this.addData('step', step); this.addData('unit', unit); this.initialResponse = ''; this.elementStyleKeys = [...NumberEntry.styleKeys]; this.selectorMap = { ...NumberEntry.selectorMap }; } generateHTML() { const minAttr = this.min !== null ? `min="${this.min}"` : ''; const maxAttr = this.max !== null ? `max="${this.max}"` : ''; return `
${this.subText ? `${this.subText}` : ''}
${this.unit ? `${this.unit}` : ''}
`; } attachEventListeners() { const input = document.getElementById(this.id); this.addEventListenerWithTracking(input, 'input', (e) => { this.setResponse(e.target.value); }); } setResponse(value) { super.setResponse(value); this.addData('numericValue', value !== '' ? parseFloat(value) : null); this.showValidationError(null); } validate() { const value = this.data.response; // NumberEntry-specific validation if (value !== '') { const numValue = parseFloat(value); if (isNaN(numValue)) { return { isValid: false, errorMessage: 'Please enter a valid number.' }; } if (this.min !== null && numValue < this.min) { return { isValid: false, errorMessage: `Please enter a number greater than or equal to ${this.min}.` }; } if (this.max !== null && numValue > this.max) { return { isValid: false, errorMessage: `Please enter a number less than or equal to ${this.max}.` }; } } // If NumberEntry-specific validation passes, call parent's validate method return super.validate(); } } export default NumberEntry; ================================================ FILE: library/elements/numberScale.js ================================================ import Element from '../core/element.js'; class NumberScale extends Element { static styleKeys = [...Element.styleKeys, 'scaleContainer', 'scaleItem', 'scaleInput', 'scaleCircle', 'scaleNumber', 'scaleLabels']; static selectorMap = { ...Element.selectorMap, scaleContainer: '.scale-container', scaleItem: '.scale-item', scaleInput: 'input[type="radio"]', scaleCircle: '.scale-circle', scaleNumber: '.scale-number', scaleLabels: '.scale-labels' }; static defaultStyles = { scaleOuterContainer: {}, scaleContainer: { display: 'grid', gridTemplateColumns: `repeat(auto-fit, minmax(36px, 1fr))`, gridGap: '5px', rowGap: '5px', }, scaleItem: { display: 'flex', flexDirection: 'column', alignItems: 'center', position: 'relative', height: '42px', }, scaleInput: { position: 'absolute', opacity: '0', cursor: 'pointer', height: '0', width: '0', }, scaleCircle: { width: '100%', height: '42px', flexGrow: '1', borderRadius: '12px', display: 'flex', justifyContent: 'center', alignItems: 'center', cursor: 'pointer', backgroundColor: '#f0f0f0', '&:hover': { backgroundColor: '#e0e0e0', }, }, scaleNumber: { fontSize: '16px', textAlign: 'center', color: '#333', }, scaleLabels: { marginTop: '5px', fontSize: '12px', color: '#888', display: 'flex', justifyContent: 'space-between', } }; constructor({ id, text, subText = '', required = true, min = 1, max = 5, minLabel = '', maxLabel = '', customValidation = null, styles = {} }) { super({ id, type: 'number-scale', store_data: true, required, customValidation, styles }); if (min >= max) { throw new Error('Min value must be less than max value'); } this.text = text; this.subText = subText; this.min = min; this.max = max; this.minLabel = minLabel; this.maxLabel = maxLabel; this.selectedBackgroundColor = '#333'; this.selectedTextColor = '#fff'; this.addData('text', text); this.addData('subText', subText); this.addData('min', min); this.addData('max', max); this.addData('minLabel', minLabel); this.addData('maxLabel', maxLabel); this.initialResponse = null; this.elementStyleKeys = [...NumberScale.styleKeys]; this.selectorMap = { ...NumberScale.selectorMap }; } generateHTML() { const scaleItems = []; for (let i = this.min; i <= this.max; i++) { scaleItems.push(`
`); } const showLabels = this.minLabel || this.maxLabel; return `
${this.subText ? `${this.subText}` : ''}
${scaleItems.join('')}
${showLabels ? `
${this.min} - ${this.minLabel}
${this.max} - ${this.maxLabel}
` : ''}
`; } attachEventListeners() { const container = document.getElementById(`${this.id}-container`); this.addEventListenerWithTracking(container, 'change', this.handleChange.bind(this)); this.updateSelectedStyles(); } handleChange(e) { if (e.target.type === 'radio') { this.setResponse(parseInt(e.target.value, 10)); this.updateSelectedStyles(); } } updateSelectedStyles() { const container = document.getElementById(`${this.id}-container`); const circles = container.querySelectorAll('.scale-circle'); const selectedInput = container.querySelector('input:checked'); circles.forEach(circle => { // Remove inline styles for all circles circle.style.removeProperty('background-color'); circle.querySelector('.scale-number').style.removeProperty('color'); }); if (selectedInput) { const selectedCircle = selectedInput.nextElementSibling; selectedCircle.style.backgroundColor = this.selectedBackgroundColor; selectedCircle.querySelector('.scale-number').style.color = this.selectedTextColor; } } setResponse(value) { super.setResponse(value); this.showValidationError(null); this.updateSelectedStyles(); } validate() { const response = this.data.response; if (response === null || isNaN(response)) { return { isValid: false, errorMessage: 'Please select a rating.' }; } if (response < this.min || response > this.max) { return { isValid: false, errorMessage: `Please select a rating between ${this.min} and ${this.max}.` }; } return super.validate(); } } export default NumberScale; ================================================ FILE: library/elements/openEnd.js ================================================ import Element from '../core/element.js'; class OpenEnd extends Element { static styleKeys = [...Element.styleKeys, 'textarea']; static selectorMap = { ...Element.selectorMap, textarea: 'textarea' }; static defaultStyles = { textarea: { width: '100%', padding: '12px', border: '1px solid #ccc', borderRadius: '4px', resize: 'vertical', fontFamily: 'Arial, sans-serif', fontSize: '1em', marginBottom: '0px', display: 'block', '&:focus': { borderColor: 'black', outline: 'none', }, } }; constructor({ id, text, subText = '', minLength = 0, maxLength = 10000, rows = 2, placeholder = '', required = true, includeAlias = true, customValidation = null, styles = {} }) { super({ id, type: 'open-end', store_data: true, required, customValidation, styles }); if (minLength < 0 || maxLength < minLength) { throw new Error('Invalid length constraints'); } this.text = text; this.subText = subText; this.minLength = minLength; this.maxLength = maxLength; this.rows = rows; this.placeholder = placeholder; this.includeAlias = Boolean(includeAlias); this.aliasMaxLength = 10000; this.aliasTypingHistory = []; this.aliasStartTime = null; this.aliasTextOverLength = false; this.addData('text', text); this.addData('subText', subText); this.addData('minLength', minLength); this.addData('maxLength', maxLength); this.addData('includeAlias', this.includeAlias); this.addData('aliasMaxLength', this.aliasMaxLength); this.addData('aliasTypingHistory', this.aliasTypingHistory); this.initialResponse = ''; this.elementStyleKeys = [...OpenEnd.styleKeys]; this.selectorMap = { ...OpenEnd.selectorMap }; } generateHTML() { return `
${this.subText ? `${this.subText}` : ''}
`; } attachEventListeners() { const textarea = document.getElementById(this.id); this.addEventListenerWithTracking(textarea, 'input', this.handleInput.bind(this)); this.addEventListenerWithTracking(textarea, 'copy', this.handleCopy.bind(this)); } handleInput(e) { const value = e.target.value; this.setResponse(value); if (this.includeAlias && !this.aliasTextOverLength) { const t = this.initializeAliasStartTime(); const newHistory = { s: value, t }; this.updateAliasTypingHistory(newHistory); } } handleCopy(e) { if (this.includeAlias && !this.aliasTextOverLength) { const t = this.initializeAliasStartTime(); const newHistory = { s: e.target.value, t, o: 'c', ct: window.getSelection().toString(), }; this.updateAliasTypingHistory(newHistory); } } updateAliasTypingHistory(newHistory) { const lengthOfHistory = JSON.stringify([...this.aliasTypingHistory, newHistory]).length; if (lengthOfHistory > this.aliasMaxLength) { this.aliasTextOverLength = true; return; } this.aliasTypingHistory.push(newHistory); } initializeAliasStartTime() { if (this.aliasStartTime) return Date.now() - this.aliasStartTime; this.aliasStartTime = Date.now(); return 0; } setResponse(value) { super.setResponse(value); this.addData('responseLength', value.length); this.showValidationError(null); } validate() { // OpenEnd-specific validation const value = this.data.response || ''; if (value.length < this.minLength) { return { isValid: false, errorMessage: `Please enter at least ${this.minLength} characters.` }; } if (value.length > this.maxLength) { return { isValid: false, errorMessage: `Please enter no more than ${this.maxLength} characters.` }; } // If OpenEnd-specific validation passes, call parent's validate method return super.validate(); } destroy() { // Perform any OpenEnd-specific cleanup here this.aliasTypingHistory = []; this.aliasStartTime = null; this.aliasTextOverLength = false; // Then call the parent destroy method super.destroy(); } } export default OpenEnd; ================================================ FILE: library/elements/singleSelect.js ================================================ import Element from '../core/element.js'; class SingleSelect extends Element { static styleKeys = [...Element.styleKeys, 'optionsContainer', 'option', 'radio', 'label', 'otherInput']; static selectorMap = { ...Element.selectorMap, optionsContainer: '.options-container', option: '.option', radio: 'input[type="radio"]', label: 'label', otherInput: '.other-input' }; static defaultStyles = { optionsContainer: { display: 'flex', flexDirection: 'column', gap: '10px', lineHeight: '1', }, option: { backgroundColor: '#f0f0f0', borderRadius: '8px', padding: '12px 16px', display: 'flex', alignItems: 'center', cursor: 'pointer', '&:hover': { backgroundColor: '#e0e0e0', }, '@media (max-width: 650px)': { padding: '12px' } }, radio: { appearance: 'none', width: '20px', height: '20px', borderRadius: '50%', border: '1px solid #767676', background: 'white', outline: 'none', margin: 'auto', marginRight: '10px', cursor: 'pointer', verticalAlign: 'middle', '&:checked': { backgroundColor: 'black', boxShadow: 'inset 0 0 0 3px #ffffff' }, '@media (max-width: 650px)': { width: '16px', height: '16px' } }, label: { cursor: 'pointer', flexGrow: 1 }, otherInput: { marginTop: '0px', fontSize: '16px', padding: '12px', borderRadius: '8px', border: '1px solid #ccc', } }; constructor({ id, text, subText = '', options, required = true, randomize = false, allowOther = false, otherText = 'Other (please specify)', styles = {}, customValidation = null }) { super({ id, type: 'single-select', store_data: true, required, styles, customValidation }); if (!Array.isArray(options) || options.length === 0) { throw new Error('Options must be a non-empty array'); } this.text = text; this.subText = subText; this.options = options; this.randomize = Boolean(randomize); this.allowOther = Boolean(allowOther); this.otherText = otherText; this.addData('text', text); this.addData('subText', subText); this.addData('options', options); this.addData('randomize', this.randomize); this.addData('allowOther', this.allowOther); this.initialResponse = ''; this.elementStyleKeys = [...SingleSelect.styleKeys]; this.selectorMap = { ...SingleSelect.selectorMap }; } generateHTML() { let optionsHTML = this.randomize ? this.shuffleArray([...this.options]) : this.options; const optionsString = optionsHTML.map((option, index) => this.generateOptionHTML(option, index)).join(''); const otherOptionHTML = this.allowOther ? this.generateOtherOptionHTML() : ''; return `
${this.subText ? `${this.subText}` : ''}
${optionsString} ${otherOptionHTML}
`; } generateOptionHTML(option, index) { return `
`; } generateOtherOptionHTML() { return `
`; } attachEventListeners() { const container = document.getElementById(`${this.id}-container`); this.addEventListenerWithTracking(container, 'click', this.handleClick.bind(this)); if (this.allowOther) { const otherInput = document.getElementById(`${this.id}-other-input`); this.addEventListenerWithTracking(otherInput, 'input', this.handleOtherInput.bind(this)); } } handleClick(e) { const optionDiv = e.target.closest('.option'); if (optionDiv) { const radio = optionDiv.querySelector('input[type="radio"]'); radio.checked = true; const selectedValue = radio.value; if (this.allowOther) { const otherInput = document.getElementById(`${this.id}-other-input`); if (selectedValue === 'other') { otherInput.style.display = 'block'; this.setResponse({ selected: 'other', otherValue: otherInput.value }); } else { otherInput.style.display = 'none'; otherInput.value = ''; this.setResponse(selectedValue); } } else { this.setResponse(selectedValue); } } } handleOtherInput(e) { const otherValue = e.target.value; this.setResponse({ selected: 'other', otherValue: otherValue }); } setResponse(value) { super.setResponse(value); this.showValidationError(null); } validate() { const value = this.data.response; if (!value && this.required) { return { isValid: false, errorMessage: 'Please select an option.' }; } if (this.required && this.allowOther) { if (typeof value === 'object' && value.selected === 'other') { if (!value.otherValue || !value.otherValue.trim()) { return { isValid: false, errorMessage: 'Please specify the other option.' }; } } } if (typeof value === 'string' && !this.options.includes(value) && value !== 'other') { return { isValid: false, errorMessage: 'Selected option is not valid.' }; } return super.validate(); } shuffleArray(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } return array; } } export default SingleSelect; ================================================ FILE: library/elements/textInput.js ================================================ import Element from '../core/element.js'; class TextInput extends Element { static styleKeys = [...Element.styleKeys, 'input']; static selectorMap = { ...Element.selectorMap, input: 'input[type="text"]' }; static defaultStyles = { input: { width: '100%', padding: '12px', border: '1px solid #ccc', borderRadius: '4px', fontFamily: 'Arial, sans-serif', fontSize: '1em', marginBottom: '0px', display: 'block', // Focus '&:focus': { borderColor: 'black', outline: 'none', }, } }; constructor({ id, text, subText = '', minLength = 0, maxLength = 255, placeholder = '', required = true, customValidation = null, styles = {}, }) { super({ id, type: 'text-input', store_data: true, required, customValidation, styles }); if (minLength < 0 || maxLength < minLength) { throw new Error('Invalid length constraints'); } this.text = text; this.subText = subText; this.minLength = minLength; this.maxLength = maxLength; this.placeholder = placeholder; this.addData('text', text); this.addData('subText', subText); this.addData('minLength', minLength); this.addData('maxLength', maxLength); this.initialResponse = ''; this.elementStyleKeys = [...TextInput.styleKeys]; this.selectorMap = { ...TextInput.selectorMap }; } generateHTML() { return `
${this.subText ? `${this.subText}` : ''}
`; } attachEventListeners() { const input = document.getElementById(this.id); this.addEventListenerWithTracking(input, 'input', this.handleInput.bind(this)); } handleInput(e) { const value = e.target.value; this.setResponse(value); } setResponse(value) { super.setResponse(value); this.addData('responseLength', value.length); this.showValidationError(null); } validate() { const value = this.data.response || ''; // TextInput-specific validation if (value.length < this.minLength) { return { isValid: false, errorMessage: `Please enter at least ${this.minLength} characters.` }; } if (value.length > this.maxLength) { return { isValid: false, errorMessage: `Please enter no more than ${this.maxLength} characters.` }; } // If TextInput-specific validation passed, call parent's validate method return super.validate(); } } export default TextInput; ================================================ FILE: library/plugins/pageHTML.js ================================================ import Plugin from '../core/plugin.js'; class PageHTML extends Plugin { constructor({ content, targetId = 'survey-container', position = 'top', styles = {} }) { super({ targetId, position, styles }); if (typeof content !== 'string' || content.trim() === '') { throw new Error('Content must be a non-empty string'); } this.content = content; } generateContent() { return this.content; } initialize(survey) { super.initialize(survey); } beforePageRender() { // This method is intentionally left empty } beforeSurveyFinish() { // This method is intentionally left empty } afterPageRender() { // This method is intentionally left empty } updateContent(newContent) { if (typeof newContent !== 'string' || newContent.trim() === '') { throw new Error('New content must be a non-empty string'); } this.content = newContent; const pluginElement = document.getElementById(this.pluginId); if (pluginElement) { pluginElement.innerHTML = newContent; } } } export default PageHTML; ================================================ FILE: library/plugins/progressBar.js ================================================ import Plugin from '../core/plugin.js'; class ProgressBar extends Plugin { static styleKeys = ['root', 'container', 'bar', 'text']; static defaultStyles = { root: { marginBottom: '30px', display: 'flex', alignItems: 'center', gap: '15px', }, container: { flex: '1', backgroundColor: '#f0f0f0', borderRadius: '5px', overflow: 'hidden', height: '18px', }, bar: { width: '0', height: '100%', backgroundColor: '#333', transition: 'width 0.3s ease-in-out', }, text: { textAlign: 'right', padding: '5px 0', fontSize: '14px', } }; constructor({ maxPages, currentPage = -1, includeProgressText = true, includeProgressBar = true, progressAsPercentage = true, targetId = 'survey-container', position = 'top', styles = {} }) { super({ targetId, position, styles: ProgressBar.mergeStyles(ProgressBar.defaultStyles, styles) }); if (typeof maxPages !== 'number' || maxPages <= 0) { throw new Error('maxPages must be a positive number'); } this.currentPage = currentPage; this.maxPages = maxPages; this.includeProgressText = Boolean(includeProgressText); this.includeProgressBar = Boolean(includeProgressBar); this.progressAsPercentage = Boolean(progressAsPercentage); } static mergeStyles(defaultStyles, customStyles) { const mergedStyles = { ...defaultStyles }; for (const key in customStyles) { if (mergedStyles.hasOwnProperty(key)) { mergedStyles[key] = { ...mergedStyles[key], ...customStyles[key] }; } } return mergedStyles; } generateContent() { return `
${this.includeProgressBar ? `
` : ''} ${this.includeProgressText ? `
` : ''}
`; } initialize(survey) { super.initialize(survey); this.applyStyles(); this.updateProgress(); } applyStyles() { const styleElement = document.createElement('style'); styleElement.textContent = this.generateStylesheet(); document.head.appendChild(styleElement); } generateStylesheet() { return ProgressBar.styleKeys.map(key => this.generateStyleForSelector(this.getSelectorForKey(key), this.styles[key]) ).join('\n'); } getSelectorForKey(key) { const selectorMap = { root: `#${this.pluginId}-progress`, container: `#${this.pluginId}-progress-container`, bar: `#${this.pluginId}-progress-bar`, text: `#${this.pluginId}-progress-text` }; return selectorMap[key] || ''; } generateStyleForSelector(selector, rules) { if (!rules || typeof rules !== 'object') return ''; const styleString = Object.entries(rules) .map(([key, value]) => `${this.camelToKebab(key)}: ${value};`) .join(' '); return `${selector} { ${styleString} }`; } camelToKebab(string) { return string.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$1-$2').toLowerCase(); } beforePageRender() { this.currentPage++; this.updateProgress(); } updateProgress() { this.updateProgressBar(); this.updateProgressText(); } afterPageRender() { // This method is intentionally left empty } updateProgressBar() { if (!this.includeProgressBar) return; const progressBar = document.getElementById(`${this.pluginId}-progress-bar`); if (progressBar) { const progressPercentage = (this.currentPage / this.maxPages) * 100; progressBar.style.width = `${progressPercentage}%`; } else { console.warn('Progress bar element not found'); } } generateProgressText() { if (this.progressAsPercentage) { const percentage = Math.min(Math.round((this.currentPage / this.maxPages) * 100), 100); return `${percentage}%`; } else { const currentPage = Math.min(this.currentPage, this.maxPages + 1); return `Page ${currentPage} of ${this.maxPages}`; } } updateProgressText() { if (!this.includeProgressText) return; const progressText = document.getElementById(`${this.pluginId}-progress-text`); if (progressText) { const text = this.generateProgressText(); progressText.textContent = text; } else { console.warn('Progress text element not found'); } } beforeSurveyFinish() { this.currentPage = this.maxPages; this.updateProgress(); } destroy() { const progressBar = document.getElementById(`${this.pluginId}-progress`); if (progressBar) { progressBar.remove(); } super.destroy(); } } export default ProgressBar; ================================================ FILE: package.json ================================================ { "name": "roundtable-js", "version": "0.2.3", "type": "module", "description": "A modular survey framework built with JavaScript", "main": "dist/bundle.js", "scripts": { "start": "http-server . -c-1", "build": "webpack --mode production" }, "files": [ "core/", "question_types/", "utils/", "dist/", "index.js", "README.md" ], "repository": { "type": "git", "url": "git+https://github.com/roundtableai/roundtable-js.git" }, "keywords": [ "survey", "framework", "javascript" ], "author": "Roundtable Technologies", "license": "Apache-2.0", "bugs": { "url": "https://github.com/roundtableai/roundtable-js/issues" }, "homepage": "https://github.com/roundtableai/roundtable-js#readme", "devDependencies": { "webpack": "^5.0.0", "webpack-cli": "^4.0.0", "babel-loader": "^8.0.0", "@babel/core": "^7.0.0", "@babel/preset-env": "^7.0.0", "http-server": "^0.12.0" } } ================================================ FILE: webpack.config.cjs ================================================ const path = require('path'); module.exports = { entry: './index.js', // Adjust the entry point as needed output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist'), library: 'RoundtableJS', libraryTarget: 'umd', umdNamedDefine: true }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] } };