Repository: mdbootstrap/TW-Elements Branch: master Commit: 6616b67d7e1c Files: 50 Total size: 266.1 KB Directory structure: gitextract_jks9prp9/ ├── .clabot ├── .github/ │ └── ISSUE_TEMPLATE/ │ └── bug_report.md ├── .gitignore ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── README.txt ├── index.html ├── package.json ├── plugin.cjs ├── src/ │ ├── css/ │ │ └── tailwind.scss │ └── js/ │ ├── autoinit/ │ │ ├── Register.js │ │ ├── callbacks/ │ │ │ └── free.js │ │ ├── index.free.js │ │ ├── index.js │ │ ├── initSelectors/ │ │ │ └── free.js │ │ └── jqueryInit.js │ ├── base-component.js │ ├── dom/ │ │ ├── data.js │ │ ├── event-handler.js │ │ ├── manipulator.js │ │ └── selector-engine.js │ ├── free/ │ │ ├── components/ │ │ │ ├── button.js │ │ │ ├── carousel.js │ │ │ ├── collapse.js │ │ │ ├── dropdown.js │ │ │ ├── modal.js │ │ │ ├── offcanvas.js │ │ │ ├── popover.js │ │ │ └── tooltip.js │ │ ├── forms/ │ │ │ └── input.js │ │ ├── methods/ │ │ │ └── ripple.js │ │ └── navigation/ │ │ ├── scrollspy.js │ │ └── tab.js │ ├── tw-elements.free.es.js │ ├── tw-elements.free.umd.js │ └── util/ │ ├── add-perfect-scrollbar-styles.js │ ├── backdrop.js │ ├── component-functions.js │ ├── focusTrap.js │ ├── getStyle.js │ ├── index.js │ ├── keycodes.js │ ├── sanitizer.js │ ├── scrollbar.js │ ├── stack.js │ └── touch/ │ ├── index.js │ ├── swipe.js │ └── touchUtil.js └── types/ └── tw-elements.d.ts ================================================ FILE CONTENTS ================================================ ================================================ FILE: .clabot ================================================ { "contributors": "https://cla.tailwind-elements.com/users", "message": "Thank you for your pull request and welcome to our community! We require contributors to sign a [Contributor License Agreement](https://cla.tailwind-elements.com/) and we don't seem to have CLAs on file for these contributors to the Pull Request: ({{usersWithoutCLA}}). In order for your PR to be reviewed and merged, please sign our CLA first.\n\nIf there are any questions, please don't hesitate to [get in touch with our team](https://github.com/mdbootstrap/Tailwind-Elements/discussions)." } ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.md ================================================ --- name: Bug report about: Create a report to help us improve title: "[Component name] [description of the issue]" labels: "" assignees: "" --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** A clear and concise description of what you expected to happen. **Actual behavior** A clear and concise description of what is happening instead. **Show your code** It will be easier for us to help you if you [create a snippet using TE playground](https://tailwind-elements.com/snippets/) and include a link to it in your issue. **Desktop (please complete the following information):** - OS: [e.g. iOS] - Browser [e.g. chrome, safari] - Version [e.g. 22] **Smartphone (please complete the following information):** - Device: [e.g. iPhone6] - OS: [e.g. iOS8.1] - Browser [e.g. stock browser, safari] - Version [e.g. 22] **Additional context** Add any other context about the problem here. **Make sure it is indeed an issue/bug report** - If it's a general support question (you just can't figure out how something works), but not an issue with the UI Kit or documentation itself it's better to ask here: https://github.com/mdbootstrap/Tailwind-Elements/discussions/categories/support-from-community - If it's an idea for a new feature, but you cannot write the code for it yourself, it's better to ask here: https://github.com/mdbootstrap/Tailwind-Elements/discussions/categories/share-ideas-request-features - If it's general feedback, it's better to post it here: https://github.com/mdbootstrap/Tailwind-Elements/discussions/categories/kind-words-general-feedback ================================================ FILE: .gitignore ================================================ node_modules ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: - Using welcoming and inclusive language - Being respectful of differing viewpoints and experiences - Gracefully accepting constructive criticism - Focusing on what is best for the community - Showing empathy towards other community members Examples of unacceptable behavior by participants include: - The use of sexualized language or imagery and unwelcome sexual attention or advances - Trolling, insulting/derogatory comments, and personal or political attacks - Public or private harassment - Publishing others' private information, such as a physical or electronic address, without explicit permission - Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers 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, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at contact@mdbootstrap.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2024 MDBootstrap Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # TW Elements [tw-elements](https://tw-elements.com/)Total Downloads Latest Release TW Elements is a huge collection of free, interactive components for Tailwind CSS.
  • 500+ UI components
  • 117+ design blocks
  • Dark mode support
  • Easy theming & customization
  • Simple, 1 minute install
  • Free for personal & commercial use

Get started with TW Elements now!

--- ## Table of Contents - [Table of Contents](#table-of-contents) - [Community](#community) - [Coming soon](#coming-soon) - [Components](#components) - [Design blocks](#design-blocks) - [Installation](#installation) --- ## Community - Motivate us with some [words of encouragament ❤️](https://github.com/mdbootstrap/TW-Elements/discussions/categories/kind-words-general-feedback) - Share your [ideas & feature requests 💡](https://github.com/mdbootstrap/TW-Elements/discussions/categories/share-ideas-request-features) - Aks for help & help others in our [community support 🙏](https://github.com/mdbootstrap/TW-Elements/discussions/categories/support-from-community) - **Engage, discuss & have fun in our [community 💬](https://github.com/mdbootstrap/TW-Elements/discussions)** **If you want to help the project grow, start by simply sharing it with your peers!** - [Share via Dev.to]() - [Share via Twitter](https://twitter.com/intent/tweet?text=500%2B%20open-source%20components%20for%20%23TailwindCSS%20%F0%9F%A4%A9%0Ahttps%3A//tw-elements.com/%0A%0ACongrats%20%40MDBootstrap%20%40ascensus_mdb%20%40dawidadach%20for%20this%20awesome%20design%20collection!%0A%0AI%20will%20keep%20using%20it%20in%20my%20projects%20for%20sure!%0A%0A%23uiux%20%23webdevelopment%20%23HTML%20%23CSS%20%23design%20%23Webdesign%20%23programming%20) - [Share via Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A//tw-elements.com) - [Share via LinkedIn](http://www.linkedin.com/shareArticle?url=https%3A%2F%2Ftw-elements.com%2F&title=500%2B%20open-source%20components%20for%20TailwindCSS) - [Share via Pinterest](https://www.pinterest.com/pin/create/button?url=https://tw-elements.com/&media=https://tw-elements.com/img/components-big.jpg&description=TailwindElements) - [Share via Reddit](https://reddit.com/submit?url=https://tw-elements.com/&title=500+%20open-source%20components%20for%20TailwindCSS) - [Share via StumbleUpon](https://www.stumbleupon.com/submit?url=https://tw-elements.com/&title=500+%20open-source%20components%20for%20TailwindCSS) - [Share via Vkontakte](https://vk.com/share.php?url=https://tw-elements.com/) - [Share via Weibo](https://service.weibo.com/share/share.php?url=https://tw-elements.com/&title=500+%20open-source%20components%20for%20TailwindCSS) - [Share via Hackernews](https://news.ycombinator.com/submitlink?u=https://tw-elements.com/&t=500+%20open-source%20components%20for%20TailwindCSS) - [Share via Gmail](https://mail.google.com/mail/?view=cm&to=%7Bemail_address%7D&su=Check%20out%20this%20project&body=Hello,%0AI%27m%20reaching%20out%20to%20recommend%20my%20latest%20discovery.%0A%0AIt%27s%20over%20500+%20open-source%20components%20for%20TailwindCSS%20with%20excellent%20support%20and%20an%20awesome%20community:%0Ahttps://tw-elements.com/%0A%0AI%20hope%20you%20will%20find%20it%20useful.%0ABest%20regards,&bcc=%7Bemail_address%7D&cc=%7Bemail_address%7D) - [Share via email](mailto:?subject=Check%20out%20this%20project&body=Hello%2C%0AI'm%20reaching%20out%20to%20recommend%20my%20latest%20discovery.%0A%0AIt's%20over%20500%20%20open-source%20components%20for%20Tailwind%20CSS%20with%20excellent%20support%20and%20an%20awesome%20community%3A%0Ahttps%3A%2F%2Ftw-elements.com%2F%0A%0AI%20hope%20you%20will%20find%20it%20useful.%0ABest%20regards%2C) Thank you! --- ## Coming soon Check out the upcoming features - make sure to **join the waiting list** in order to **get early access**!
Design blocks Templates
Drag & drop builder Templates
--- ## Components A collection of stunning components made with attention to the smallest details. Forms, cards, buttons, and hundreds of others – in TW Elements you will find all the essential elements necessary for every project.
Datepicker Dropdown Modal
Datepicker Dropdown Modal
Charts Tooltips Carousel
Charts Tooltips Carousel
Accordion Tabs Stepper
Accordion Tabs Stepper
Tailwind CSS Time picker Tailwind CSS Tables Tailwind CSS Navbar
Timepicker Footer Navbar
Tailwind CSS Time picker Tailwind CSS Tables Tailwind CSS Navbar
Alerts Avatar Badges
Tailwind CSS Time picker Tailwind CSS Tables Tailwind CSS Navbar
Button group Buttons Cards
Tailwind CSS Time picker Tailwind CSS Tables Tailwind CSS Navbar
Chips Collapse Gallery
Tailwind CSS Time picker Tailwind CSS Tables Tailwind CSS Navbar
Jumbotron Link List group
Tailwind CSS Time picker Tailwind CSS Tables Tailwind CSS Navbar
Notifications Paragraphs Placeholders
Tailwind CSS Time picker Tailwind CSS Tables Tailwind CSS Navbar
Popover Progress Rating
Tailwind Component Tailwind Component Tailwind Component
Scroll to top Social buttons Spinners
Tailwind Component Tailwind Component Tailwind Component
Timeline Toast Tooltip
Tailwind Component Tailwind Component Tailwind Component
Video Video carousel Checkbox
Tailwind Component Tailwind Component Tailwind Component
File input Input group Login form
Tailwind Component Tailwind Component Tailwind Component
Radio Range Registration form
Tailwind Component Tailwind Component Tailwind Component
Search Select Switch
Tailwind Component Tailwind Component Tailwind Component
Textarea Tables Ripple
Tailwind Component Tailwind Component Tailwind Component
Animations Masks Shadows
Tailwind Component Tailwind Component Tailwind Component
Datatables Lightbox Rating
Tailwind Component Tailwind Component Logo Clouds
Scrollbar Popconfirm More coming soon
--- ## Design blocks Responsive Landing page blocks built with Tailwind CSS. Plenty of design blocks examples such as Teams, services, projects, faq, and many more.
Hero Pricing Call to action
Hero Pricing Call to action
Features Contact News/blog
Features Contact News/blog
Team Tabs Stepper
Team Stats Testimonials
Content Newsletter Projects
Content Newsletter Projects
Headers FAQ Logo Clouds
Headers FAQ Logo Clouds
Headers FAQ Logo Clouds
Banners Mega Menu More coming soon
--- ## Integrations TW Elements integrations with popular technologies. - [Django Integration](https://tw-elements.com/docs/standard/integrations/django-integration/) - [Angular Integration](https://tw-elements.com/docs/standard/integrations/angular-integration/) - [Express Integration](https://tw-elements.com/docs/standard/integrations/express-integration/) - [Laravel Integration](https://tw-elements.com/docs/standard/integrations/laravel-integration/) - [Next Integration](https://tw-elements.com/docs/standard/integrations/next-integration/) - [Nuxt Integration](https://tw-elements.com/docs/standard/integrations/nuxt-integration/) - [Django Integration](https://tw-elements.com/docs/standard/integrations/react-integration/) - [Remix Integration](https://tw-elements.com/docs/standard/integrations/remix-integration/) - [Solid Integration](https://tw-elements.com/docs/standard/integrations/solid-integration/) - [Svelte Integration](https://tw-elements.com/docs/standard/integrations/svelte-integration/) - [Sveltekit Integration](https://tw-elements.com/docs/standard/integrations/sveltekit-integration/) - [Vue Integration](https://tw-elements.com/docs/standard/integrations/vue-integration/) --- ## Installation ##### NPM 1. Before starting the project make sure to install [Node.js (LTS)](https://nodejs.org/en/ "Node.js (LTS)") and [TailwindCSS](https://tailwindcss.com/ "TailwindCSS"). 2. Run the following command to install the package via NPM: ``` npm install tw-elements ``` 3. TW Elements is a plugin and should be included inside the **tailwind.config.js** file. It is also recommended to extend the content array with a js file that loads dynamic component classes: ```javascript module.exports = { content: ["./src/**/*.{html,js}", "./node_modules/tw-elements/js/**/*.js"], plugins: [require("tw-elements/plugin.cjs")], darkMode: "class", }; ``` 4. Dynamic components will work after adding the js file: ``` ``` Alternatively, you can import it in the following way (bundler version): ``` import 'tw-elements'; ``` ##### MDB GO / CLI Create, deploy and host anything with a single command. 1. To start using MDB GO / CLI install it with one command: ``` npm install -g mdb-cli ``` 2. Log into the CLI using your MDB account: ``` mdb login ``` 3. Initialize a project and choose **Tailwind Elements** from the list: ``` mdb init tailwind-elements-free ``` 4. Install the dependencies (inside the project directory): ``` npm install ``` 5. Run the app: ``` npm start ``` 6. Publish when you're ready: ``` mdb publish ``` ##### CDN You can easily test TW Elements by adding CDN scripts to your classic HTML template without the need for installing any packages. Add the stylesheet files below in the _head_ section: ``` ``` Require the js bundled file right before the _body_ closing tag: ``` ``` ================================================ FILE: README.txt ================================================ TW Elements Standard Version: 2.0.0 Documentation: https://tw-elements.com/ Contact: tailwind@mdbootstrap.com ================================================ FILE: index.html ================================================ TW Elements
logo
Thank you for using our product. We're glad you're with us.

TW Elements Team

Start TWE tutorial
================================================ FILE: package.json ================================================ { "name": "tw-elements", "version": "2.0.0", "type": "module", "homepage": "https://tw-elements.com/", "repository": "https://github.com/mdbootstrap/TW-Elements", "author": "MDBootstrap", "license": "SEE LICENSE IN ", "style": "./css/tw-elements.min.css", "sass": "./src/css/tailwind.scss", "main": "./js/tw-elements.umd.min.js", "module": "./js/tw-elements.es.min.js", "types": "./types/tw-elements.d.ts" } ================================================ FILE: plugin.cjs ================================================ const plugin = require("tailwindcss/plugin"); const defaultTheme = require("tailwindcss/defaultTheme"); const { spacing, borderRadius } = defaultTheme; module.exports = plugin( ({ addBase, theme }) => { addBase({ [['input[type="range"]::-webkit-slider-thumb']]: { height: spacing[4], width: spacing[4], background: theme("colors.primary.DEFAULT"), "border-radius": borderRadius.full, border: 0, appearance: "none", "-moz-appearance": "none", "-webkit-appearance": "none", cursor: "pointer", }, [['.dark input[type="range"]::-webkit-slider-thumb']]: { background: theme("colors.primary.400"), }, [['input[type="range"]:disabled::-webkit-slider-thumb']]: { background: theme("colors.neutral.400"), }, [['input[type="range"]:disabled:focus::-webkit-slider-thumb']]: { background: theme("colors.neutral.400"), }, [['input[type="range"]:disabled:active::-webkit-slider-thumb']]: { background: theme("colors.neutral.400"), }, [['.dark input[type="range"]:disabled::-webkit-slider-thumb']]: { background: theme("colors.neutral.500"), }, [['.dark input[type="range"]:disabled:focus::-webkit-slider-thumb']]: { background: theme("colors.neutral.500"), }, [['.dark input[type="range"]:disabled:active::-webkit-slider-thumb']]: { background: theme("colors.neutral.500"), }, [['input[type="range"]::-moz-range-thumb']]: { height: spacing[4], width: spacing[4], background: theme("colors.primary.DEFAULT"), "border-radius": borderRadius.full, border: 0, appearance: "none", "-moz-appearance": "none", "-webkit-appearance": "none", cursor: "pointer", }, [['.dark input[type="range"]::-moz-range-thumb']]: { background: theme("colors.primary.400"), }, [['input[type="range"]:disabled::-moz-range-thumb']]: { background: theme("colors.neutral.400"), }, [['.dark input[type="range"]:disabled::-moz-range-thumb']]: { background: theme("colors.neutral.500"), }, [['input[type="range"]::-moz-range-progress']]: { background: theme("colors.primary.600"), }, [['input[type="range"]::-ms-fill-lower']]: { background: theme("colors.primary.600"), }, [['.dark input[type="range"]::-moz-range-progress']]: { background: theme("colors.primary.500"), }, [['.dark input[type="range"]::-ms-fill-lower']]: { background: theme("colors.primary.500"), }, [['input[type="range"]:focus']]: { outline: "none", }, [['input[type="range"]:focus::-webkit-slider-thumb']]: { background: theme("colors.primary.600"), }, [['input[type="range"]:active::-webkit-slider-thumb']]: { background: theme("colors.primary.700"), }, [['.dark input[type="range"]:focus::-webkit-slider-thumb']]: { background: theme("colors.primary.500"), }, [['.dark input[type="range"]:active::-webkit-slider-thumb']]: { background: theme("colors.primary.600"), }, }); }, { theme: { screens: { xs: "320px", ...defaultTheme.screens, }, extend: { fontFamily: { sans: ["Roboto", "sans-serif"], body: ["Roboto", "sans-serif"], mono: ["ui-monospace", "monospace"], }, boxShadow: { "twe-primary": "0 0 0 1px rgb(59, 113, 202)", 1: "0 0 2px 0 rgba(0,0,0,.07),0 1px 1px 0 rgba(0,0,0,.04)", "1-strong": "0 0 2px 0 rgba(0,0,0,.16),0 1px 1px 0 rgba(0,0,0,.1)", 2: "0 0 3px 0 rgba(0,0,0,.07),0 2px 2px 0 rgba(0,0,0,.04)", "2-strong": "0 0 3px 0 rgba(0,0,0,.16),0 2px 2px 0 rgba(0,0,0,.1)", 3: "0 2px 6px -1px rgba(0,0,0,.07),0 6px 18px -1px rgba(0,0,0,.04)", "3-strong": "0 2px 6px -1px rgba(0,0,0,.16),0 6px 18px -1px rgba(0,0,0,.1)", 4: "0 2px 15px -3px rgba(0,0,0,.07),0 10px 20px -2px rgba(0,0,0,.04)", "4-strong": "0 2px 15px -3px rgba(0,0,0,.16),0 10px 20px -2px rgba(0,0,0,.1)", 5: "0 2px 25px -5px rgba(0,0,0,.07),0 25px 21px -5px rgba(0,0,0,.04)", "5-strong": " 0 2px 25px -5px rgba(0,0,0,.16),0 25px 21px -5px rgba(0,0,0,.1)", "twe-inner": "inset 0 2px 4px 0 #0000000d", "primary-1": "0 8px 9px -4px rgba(59,113,202,0.2),0 4px 18px 0 rgba(59,113,202,0.1)", "primary-2": "0 8px 9px -4px rgba(59,113,202,0.3),0 4px 18px 0 rgba(59,113,202,0.2)", "primary-3": "0 4px 9px -4px #3b71ca", "success-1": "0 8px 9px -4px rgba(20,164,77,0.2),0 4px 18px 0 rgba(20,164,77,0.1)", "success-2": "0 8px 9px -4px rgba(20,164,77,0.3),0 4px 18px 0 rgba(20,164,77,0.2)", "success-3": "0 4px 9px -4px #14a44d", "danger-1": "0 8px 9px -4px rgba(220,76,100,0.1),0 4px 18px 0 rgba(220,76,100,0.2)", "danger-2": "0 8px 9px -4px rgba(220,76,100,0.2),0 4px 18px 0 rgba(220,76,100,0.3)", "danger-3": "0 4px 9px -4px #dc4c64", "warning-1": "0 8px 9px -4px rgba(228,161,27,0.1),0 4px 18px 0 rgba(228,161,27,0.2)", "warning-2": "0 8px 9px -4px rgba(228,161,27,0.2),0 4px 18px 0 rgba(228,161,27,0.3)", "warning-3": "0 4px 9px -4px #e4a11b", "info-1": "0 8px 9px -4px rgba(84,180,211,0.1),0 4px 18px 0 rgba(84,180,211,0.2)", "info-2": "0 8px 9px -4px rgba(84,180,211,0.2),0 4px 18px 0 rgba(84,180,211,0.3)", "info-3": "0 4px 9px -4px #54b4d3", "light-1": "0 8px 9px -4px rgba(251,251,251,0.05),0 4px 18px 0 rgba(251,251,251,0.1)", "light-2": "0 8px 9px -4px rgba(203,203,203,0.2),0 4px 18px 0 rgba(203,203,203,0.3)", "light-3": "0 4px 9px -4px #cbcbcb", "dark-1": "0 8px 9px -4px rgba( 0, 0, 0 , 0.15), 0 4px 18px 0 rgba( 0, 0, 0 , 0.1)", "dark-2": "0 8px 9px -4px rgba(51,45,45,0.1),0 4px 18px 0 rgba(51,45,45,0.2)", "dark-3": "0 4px 9px -4px rgba(51,45,45,0.7)", "dark-strong": "0 4px 18px -2px rgba(0,0,0,.7)", "dark-mild": "0 4px 12px 0 rgba(0,0,0,0.07),0 2px 4px rgba(0,0,0,0.05)", "secondary-1": "0 2px 15px -3px rgba(0,0,0,0.04),0 10px 20px -2px rgba(0,0,0,0.07)", "secondary-2": "0 8px 9px -4px rgba(227,235,247,0.2),0 4px 18px 0 rgba(227,235,247,0.3)", "secondary-3": "0 4px 9px -4px #e3ebf7", "primary-5": "0 4px 9px -4px rgba(59,113,202,0.5)", checkbox: "0 0 0 13px #3b71ca", inset: "inset 0 0 0 1px rgb(59,113,202)", select: "0 2px 5px 0 rgba(0,0,0,0.16), 0 2px 10px 0 rgba(0,0,0,0.12)", "switch-1": "0 3px 1px -2px rgba(0,0,0,0.2), 0 2px 2px 0 rgba(0,0,0,0.14), 0 1px 5px 0 rgba(0,0,0,0.12)", "switch-2": "0 0px 3px 0 rgba(0,0,0,0.07), 0 2px 2px 0 rgba(0,0,0,0.04)", "switch-3": "3px -1px 0px 13px #3b71ca", "notch-1": "-1px 0 0 #3b71ca, 0 1px 0 0 #3b71ca, 0 -1px 0 0 #3b71ca", "notch-2": "0 1px 0 0 #3b71ca", "notch-3": "1px 0 0 #3b71ca, 0 -1px 0 0 #3b71ca, 0 1px 0 0 #3b71ca", "border-b": "inset 0 -1px 0 rgba(229,231,235)", autofill: "inset 0 0 0px 1000px rgb(62,62,62)", }, keyframes: { "fade-in": { "0%": { opacity: 0 }, "100%": { opacity: 1 }, }, "fade-out": { "0%": { opacity: 1 }, "100%": { opacity: 0 }, }, "fade-in-down": { "0%": { opacity: 0, transform: "translate3d(0, -100%, 0)", }, "100%": { opacity: 1, transform: "translate3d(0, 0, 0)", }, }, "fade-in-left": { "0%": { opacity: 0, transform: "translate3d(-100%, 0, 0)", }, "100%": { opacity: 1, transform: "translate3d(0, 0, 0)", }, }, "fade-in-right": { "0%": { opacity: 0, transform: "translate3d(100%, 0, 0)", }, "100%": { opacity: 1, transform: "translate3d(0, 0, 0)", }, }, "fade-in-up": { "0%": { opacity: 0, transform: "translate3d(0, 100%, 0)", }, "100%": { opacity: 1, transform: "translate3d(0, 0, 0)", }, }, "fade-out-down": { "0%": { opacity: 1, }, "100%": { opacity: 0, transform: "translate3d(0, 100%, 0)", }, }, "fade-out-left": { "0%": { opacity: 1, }, "100%": { opacity: 0, transform: "translate3d(-100%, 0, 0)", }, }, "fade-out-right": { "0%": { opacity: 1, }, "100%": { opacity: 0, transform: "translate3d(100%, 0, 0)", }, }, "fade-out-up": { "0%": { opacity: 1, }, "100%": { opacity: 0, transform: "translate3d(0, -100%, 0)", }, }, "slide-in-down": { "0%": { visibility: "visible", transform: "translate3d(0, -100%, 0)", }, "100%": { transform: "translate3d(0, 0, 0)", }, }, "slide-in-left": { "0%": { visibility: "visible", transform: "translate3d(-100%, 0, 0)", }, "100%": { transform: "translate3d(0, 0, 0)", }, }, "slide-in-right": { "0%": { visibility: "visible", transform: "translate3d(100%, 0, 0)", }, "100%": { transform: "translate3d(0, 0, 0)", }, }, "slide-in-up": { "0%": { visibility: "visible", transform: "translate3d(0, 100%, 0)", }, "100%": { transform: "translate3d(0, 0, 0)", }, }, "slide-out-down": { "0%": { transform: "translate3d(0, 0, 0)", }, "100%": { visibility: "hidden", transform: "translate3d(0, 100%, 0)", }, }, "slide-out-left": { "0%": { transform: "translate3d(0, 0, 0)", }, "100%": { visibility: "hidden", transform: "translate3d(-100%, 0, 0)", }, }, "slide-out-right": { "0%": { transform: "translate3d(0, 0, 0)", }, "100%": { visibility: "hidden", transform: "translate3d(100%, 0, 0)", }, }, "slide-out-up": { "0%": { transform: "translate3d(0, 0, 0)", }, "100%": { visibility: "hidden", transform: "translate3d(0, -100%, 0)", }, }, "slide-down": { "0%": { transform: "translate3d(0, 0, 0)", }, "100%": { transform: "translate3d(0, 100%, 0)", }, }, "slide-left": { "0%": { transform: "translate3d(0, 0, 0)", }, "100%": { transform: "translate3d(-100%, 0, 0)", }, }, "slide-right": { "0%": { transform: "translate3d(0, 0, 0)", }, "100%": { transform: "translate3d(100%, 0, 0)", }, }, "slide-up": { "0%": { transform: "translate3d(0, 0, 0)", }, "100%": { transform: "translate3d(0, -100%, 0)", }, }, "zoom-in": { "0%": { opacity: 0, transform: "scale3d(0.3, 0.3, 0.3)", }, "50%": { opacity: 1, }, }, "zoom-out": { "0%": { opacity: 1, }, "50%": { opacity: 0, transform: "scale3d(0.3, 0.3, 0.3)", }, "100%": { opacity: 0, }, }, tada: { "0%": { transform: "scale3d(1, 1, 1)", }, "10%, 20%": { transform: "scale3d(0.9, 0.9, 0.9) rotate3d(0, 0, 1, -3deg)", }, "30%, 50%, 70%, 90%": { transform: "scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, 3deg)", }, "40%, 60%, 80%": { transform: "scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, -3deg)", }, "100%": { transform: "scale3d(1, 1, 1)", }, }, "spinner-grow": { "0%": { transform: "scale(0)", }, "50%": { transform: "none", opacity: "1", }, }, "placeholder-wave": { "100%": { maskPosition: "-200% 0%" }, }, "show-up-clock": { "0%": { opacity: "0", transform: "scale(0.7)", }, "100%": { opacity: "1", transform: "scale(1)", }, }, progress: { "0%": { transform: "translateX(-45%)" }, "100%": { transform: "translateX(100%)" }, }, "drop-in": { "0%": { opacity: "0", transform: "scale(0)", animationTimingFunction: "cubic-bezier(0.34, 1.61, 0.7, 1)", }, "100%": { opacity: "1", transform: "scale(1)", }, }, "drop-out": { "0%": { opacity: "1", transform: "scale(1)", animationTimingFunction: "cubic-bezier(0.34, 1.61, 0.7, 1)", }, "100%": { opacity: "0", transform: "scale(0)" }, }, "fly-in": { "0%": { opacity: "0", transform: "scale3d(0.3, 0.3, 0.3)", transitionTimingFunction: "cubic-bezier(0.215, 0.61, 0.355, 1)", }, "20%": { transform: "scale3d(1.1, 1.1, 1.1)" }, "40%": { transform: "scale3d(0.9, 0.9, 0.9)" }, "60%": { opacity: "1", transform: "scale3d(1.03, 1.03, 1.03)" }, "80%": { transform: "scale3d(0.97, 0.97, 0.97)" }, "100%": { opacity: "1", transform: "scale3d(1, 1, 1)" }, }, "fly-in-up": { "0%": { opacity: "0", transform: "translate3d(0, 1500px, 0)", transitionTimingFunction: "cubic-bezier(0.215, 0.61, 0.355, 1)", }, "60%": { opacity: "1", transform: "translate3d(0, -20px, 0)" }, "75%": { transform: "translate3d(0, 10px, 0)" }, "90%": { transform: "translate3d(0, -5px, 0)" }, "100%": { transform: "translate3d(0, 0, 0)" }, }, "fly-in-down": { "0%": { opacity: "0", transform: "translate3d(0, -1500px, 0)", transitionTimingFunction: "cubic-bezier(0.215, 0.61, 0.355, 1)", }, "60%": { opacity: "1", transform: "translate3d(0, 25px, 0)" }, "75%": { transform: "translate3d(0, -10px, 0)" }, "90%": { transform: "translate3d(0, 5px, 0)" }, "100%": { transform: "none" }, }, "fly-in-left": { "0%": { opacity: "0", transform: "translate3d(1500px, 0, 0)", transitionTimingFunction: "cubic-bezier(0.215, 0.61, 0.355, 1)", }, "60%": { opacity: "1", transform: "translate3d(-25px, 0, 0)" }, "75%": { transform: "translate3d(10px, 0, 0)" }, "90%": { transform: "translate3d(-5px, 0, 0)" }, "100%": { transform: "none" }, }, "fly-in-right": { "0%": { opacity: "0", transform: "translate3d(-1500px, 0, 0)", transitionTimingFunction: "cubic-bezier(0.215, 0.61, 0.355, 1)", }, "60%": { opacity: "1", transform: "translate3d(25px, 0, 0)" }, "75%": { transform: "translate3d(-10px, 0, 0)" }, "90%": { transform: "translate3d(5px, 0, 0)" }, "100%": { transform: "none" }, }, "fly-out": { "0%": { transitionTimingFunction: "cubic-bezier(0.215, 0.61, 0.355, 1)", }, "20%": { transform: "scale3d(0.9, 0.9, 0.9)", }, "50%, 55%": { opacity: "1", transform: "scale3d(1.1, 1.1, 1.1)", }, "100%": { opacity: "0", transform: "scale3d(0.3, 0.3, 0.3)", }, }, "fly-out-up": { "0%": { transitionTimingFunction: "cubic-bezier(0.215, 0.61, 0.355, 1)", }, "20%": { transform: "translate3d(0, 10px, 0)", }, "40%, 45%": { opacity: "1", transform: "translate3d(0, -20px, 0)", }, "100%": { opacity: "0", transform: "translate3d(0, 2000px, 0)", }, }, "fly-out-down": { "0%": { transitionTimingFunction: "cubic-bezier(0.215, 0.61, 0.355, 1)", }, "20%": { transform: "translate3d(0, -10px, 0)", }, "40%, 45%": { opacity: "1", transform: "translate3d(0, 20px, 0)", }, "100%": { opacity: "0", transform: "translate3d(0, -2000px, 0)", }, }, "fly-out-left": { "0%": { transitionTimingFunction: "cubic-bezier(0.215, 0.61, 0.355, 1)", }, "20%": { opacity: "1", transform: "translate3d(-20px, 0, 0)", }, "100%": { opacity: "0", transform: "translate3d(2000px, 0, 0)", }, }, "fly-out-right": { "0%": { transitionTimingFunction: "cubic-bezier(0.215, 0.61, 0.355, 1)", }, "20%": { opacity: "1", transform: "translate3d(20px, 0, 0)", }, "100%": { opacity: "0", transform: "translate3d(-2000px, 0, 0)", }, }, "browse-in": { "0%": { transform: "scale(0.8) translateZ(0px)", zIndex: "-1" }, "10%": { transform: "scale(0.8) translateZ(0px)", zIndex: "-1", opacity: "0.7", }, "80%": { transform: "scale(1.05) translateZ(0px)", zIndex: "999", opacity: "1", }, "100%": { transform: "scale(1) translateZ(0px)", zIndex: "999" }, }, "browse-out": { "0%": { transform: "translateX(0%) rotateY(0deg) rotateX(0deg)", zIndex: "999", }, "50%": { transform: "translateX(-105%) rotateY(35deg) rotateX(10deg) translateZ(-10px)", zIndex: "-1", }, "80%": { opacity: "1" }, "100%": { zIndex: "-1", opacity: "0", transform: "translateX(0%) rotateY(0deg) rotateX(0deg) translateZ(-10px)", }, }, "browse-out-left": { "0%": { transform: "translateX(0%) rotateY(0deg) rotateX(0deg)", zIndex: "999", }, "50%": { transform: "translateX(-105%) rotateY(35deg) rotateX(10deg) translateZ(-10px)", zIndex: "-1", }, "80%": { opacity: "1" }, "100%": { zIndex: "-1", opacity: "0", transform: "translateX(0%) rotateY(0deg) rotateX(0deg) translateZ(-10px)", }, }, "browse-out-right": { "0%": { transform: "translateX(0%) rotateY(0deg) rotateX(0deg)", zIndex: "999", }, "50%": { transform: "translateX(105%) rotateY(35deg) rotateX(10deg) translateZ(-10px)", zIndex: "1", }, "80%": { opacity: "1" }, "100%": { zIndex: "1", opacity: "0", transform: "translateX(0%) rotateY(0deg) rotateX(0deg) translateZ(-10px)", }, }, jiggle: { "0%": { transform: "scale3d(1, 1, 1)" }, "30%": { transform: "scale3d(1.25, 0.75, 1)" }, "40%": { transform: "scale3d(0.75, 1.25, 1)" }, "50%": { transform: "scale3d(1.15, 0.85, 1)" }, "65%": { transform: "scale3d(0.95, 1.05, 1)" }, "75%": { transform: "scale3d(1.05, 0.95, 1)" }, "100%": { transform: "scale3d(1, 1, 1)" }, }, flash: { "0%, 50%, 100%": { opacity: "1" }, "25%, 75%": { opacity: "0" }, }, shake: { "0%, 100%": { transform: "translateX(0)", }, "10%, 30%, 50%, 70%, 90%": { transform: "translateX(-10px)", }, "20%, 40%, 60%, 80%": { transform: "translateX(10px)", }, }, glow: { "0%": { backgroundColor: "#fcfcfd" }, "30%": { backgroundColor: "#fff6cd" }, "100%": { backgroundColor: "#fcfcfd" }, }, }, colors: { primary: { DEFAULT: "#3B71CA", 50: "#F1F5FB", 100: "#E3EBF7", 200: "#C7D7F0", 300: "#ABC2E8", 400: "#8FAEE0", 500: "#6590D5", 600: "#3061AF", 700: "#285192", 800: "#204075", 900: "#183058", "accent-100": "#d9e4f3", "accent-200": "#cedbee", "accent-300": "#386bc0", }, secondary: { DEFAULT: "#9FA6B2", 50: "#F8F9F9", 100: "#F1F2F4", 200: "#E4E6E9", 300: "#D6D9DE", 400: "#C8CCD3", 500: "#B3B9C2", 600: "#848D9C", 700: "#6B7585", 800: "#565D6B", 900: "#404650", "accent-300": "#979ea9", }, success: { DEFAULT: "#14A44D", 50: "#EAFCF2", 100: "#D6FAE4", 200: "#ACF5C9", 300: "#83F0AE", 400: "#59EA93", 500: "#1CE26B", 600: "#118C42", 700: "#0E7537", 800: "#0C5D2C", 900: "#094621", "accent-300": "#139c49", }, danger: { DEFAULT: "#DC4C64", 50: "#FCF2F4", 100: "#FAE5E9", 200: "#F5CCD3", 300: "#F0B2BD", 400: "#EB99A6", 500: "#E37285", 600: "#D42A46", 700: "#B0233A", 800: "#8D1C2F", 900: "#6A1523", "accent-300": "#d1485f", }, warning: { DEFAULT: "#E4A11B", 50: "#FDF8EF", 100: "#FBF2DE", 200: "#F7E4BE", 300: "#F4D79D", 400: "#F0C97D", 500: "#EAB54C", 600: "#C48A17", 700: "#A37313", 800: "#825C0F", 900: "#62450B", "accent-300": "#d9991a", }, info: { DEFAULT: "#54B4D3", 50: "#F3FAFC", 100: "#E7F4F9", 200: "#CEE9F2", 300: "#B6DFEC", 400: "#9ED4E6", 500: "#79C4DC", 600: "#34A4CA", 700: "#2B89A8", 800: "#236D86", 900: "#1A5265", "accent-300": "#50abc8", }, surface: { DEFAULT: "#4f4f4f", dark: "#424242", }, body: { DEFAULT: "#fff", dark: "#303030", }, }, }, }, } ); ================================================ FILE: src/css/tailwind.scss ================================================ @tailwind base; @layer base { html { @apply text-surface; @apply bg-white; } html.dark { @apply text-neutral-50; @apply bg-body-dark; } } @tailwind components; @tailwind utilities; p { @apply leading-[1.6]; } ================================================ FILE: src/js/autoinit/Register.js ================================================ class InitRegister { constructor() { this.inits = []; } get initialized() { return this.inits; } isInited(componentName) { return this.inits.includes(componentName); } add(componentName) { if (!this.isInited(componentName)) { this.inits.push(componentName); } } } export default InitRegister; ================================================ FILE: src/js/autoinit/callbacks/free.js ================================================ import EventHandler from "../../dom/event-handler"; import SelectorEngine from "../../dom/selector-engine"; import { isDisabled, getElementFromSelector, isVisible, getSelectorFromElement, } from "../../util"; const dropdownCallback = (component, initSelector) => { EventHandler.on( document, `click.twe.${component.NAME}`, initSelector, function (event) { event.preventDefault(); component.getOrCreateInstance(this).toggle(); } ); }; const tabCallback = (component, initSelector) => { EventHandler.on( document, `click.twe.${component.NAME}.data-api`, initSelector, function (event) { if (["A", "AREA"].includes(this.tagName)) { event.preventDefault(); } if (isDisabled(this)) { return; } const data = component.getOrCreateInstance(this); data.show(); } ); }; const offcanvasCallback = (component, initSelector) => { EventHandler.on( document, `click.twe.${component.NAME}.data-api`, initSelector, function (event) { const target = getElementFromSelector(this); if (["A", "AREA"].includes(this.tagName)) { event.preventDefault(); } if (isDisabled(this)) { return; } EventHandler.one(target, component.EVENT_HIDDEN, () => { // focus on trigger when it is closed if (isVisible(this)) { this.focus(); } }); // avoid conflict when clicking a toggler of an offcanvas, while another is open const allReadyOpen = SelectorEngine.findOne(component.OPEN_SELECTOR); if (allReadyOpen && allReadyOpen !== target) { component.getInstance(allReadyOpen).hide(); } const data = component.getOrCreateInstance(target); data.toggle(this); } ); }; const buttonCallback = (component, initSelector) => { EventHandler.on( document, `click.twe.${component.NAME}`, initSelector, (event) => { event.preventDefault(); const button = event.target.closest(initSelector); const data = component.getOrCreateInstance(button); data.toggle(); } ); }; const rippleCallback = (component, initSelector) => { EventHandler.one( document, "mousedown", initSelector, component.autoInitial(new component()) ); }; const collapseCallback = (component, initSelector) => { EventHandler.on( document, `click.twe.${component.NAME}.data-api`, initSelector, function (event) { // preventDefault only for elements (which change the URL) not inside the collapsible element if ( event.target.tagName === "A" || (event.delegateTarget && event.delegateTarget.tagName === "A") ) { event.preventDefault(); } const selector = getSelectorFromElement(this); const selectorElements = SelectorEngine.find(selector); selectorElements.forEach((element) => { component.getOrCreateInstance(element, { toggle: false }).toggle(); }); } ); }; const tooltipsCallback = (component, initSelector) => { const tooltipTriggerList = [].slice.call( document.querySelectorAll(initSelector) ); tooltipTriggerList.map(function (tooltipTriggerEl) { return new component(tooltipTriggerEl); }); }; const popoverCallback = (component, initSelector) => { const popoverTriggerList = [].slice.call( document.querySelectorAll(initSelector) ); popoverTriggerList.map(function (popoverTriggerEl) { return new component(popoverTriggerEl); }); }; const modalCallback = (component, initSelector) => { EventHandler.on( document, `click.twe.${component.NAME}`, initSelector, function (event) { const target = getElementFromSelector(this); if (["A", "AREA"].includes(this.tagName)) { event.preventDefault(); } EventHandler.one(target, component.EVENT_SHOW, (showEvent) => { if (showEvent.defaultPrevented) { // only register focus restorer if modal will actually get shown return; } EventHandler.one(target, component.EVENT_HIDDEN, () => { if (isVisible(this)) { this.focus(); } }); }); // avoid conflict when clicking moddal toggler while another one is open const allReadyOpen = SelectorEngine.findOne( `[${component.OPEN_SELECTOR}="true"]` ); if (allReadyOpen) { component.getInstance(allReadyOpen).hide(); } const data = component.getOrCreateInstance(target); data.toggle(this); } ); }; export { dropdownCallback, tabCallback, offcanvasCallback, buttonCallback, rippleCallback, collapseCallback, tooltipsCallback, popoverCallback, modalCallback, }; ================================================ FILE: src/js/autoinit/index.free.js ================================================ import defaultInitSelectors from "./initSelectors/free"; import { InitTWE } from "./index"; const initTWEInstance = new InitTWE(defaultInitSelectors); const initTWE = initTWEInstance.initTWE; export default initTWE; ================================================ FILE: src/js/autoinit/index.js ================================================ import SelectorEngine from "../dom/selector-engine"; import jqueryInit from "./jqueryInit"; // key => component NAME constant // name => component exported by name import InitRegister from "./Register"; const register = new InitRegister(); let _defaultInitSelectors; const getComponentData = (component) => { return _defaultInitSelectors[component.NAME] || null; }; const initComponent = (component, options) => { if ( !component || (!options.allowReinits && register.isInited(component.NAME)) ) { return; } register.add(component.NAME); const thisComponent = getComponentData(component); const isToggler = thisComponent?.isToggler || false; jqueryInit(component); if (thisComponent?.advanced) { thisComponent?.advanced(component, thisComponent?.selector); return; } if (isToggler) { thisComponent?.callback(component, thisComponent?.selector); return; } SelectorEngine.find(thisComponent?.selector).forEach((element) => { let instance = component.getInstance(element); if (!instance) { instance = new component(element); if (thisComponent?.onInit) { instance[thisComponent.onInit](); } } }); }; // const init = (components, options) => { // components.forEach((component) => initComponent(component, options)); // }; const defaultOptions = { allowReinits: false, checkOtherImports: false, }; export class InitTWE { constructor(defaultInitSelectors) { _defaultInitSelectors = defaultInitSelectors; } init = (components, options) => { components.forEach((component) => initComponent(component, options)); }; initTWE = (components, options) => { const initOptions = { ...defaultOptions, ...options }; const componentList = Object.keys(_defaultInitSelectors).map((element) => { const requireAutoinit = Boolean( document.querySelector(_defaultInitSelectors[element].selector) ); if (requireAutoinit) { const component = components[_defaultInitSelectors[element].name]; if ( !component && !register.isInited(element) && initOptions.checkOtherImports ) { console.warn( `Please import ${_defaultInitSelectors[element].name} from "tw-elements" package and add it to a object parameter inside "initTWE" function` ); } return component; } }); this.init(componentList, initOptions); }; } export default InitTWE; ================================================ FILE: src/js/autoinit/initSelectors/free.js ================================================ import { dropdownCallback, offcanvasCallback, tabCallback, buttonCallback, rippleCallback, collapseCallback, tooltipsCallback, popoverCallback, modalCallback, } from "../callbacks/free"; const defaultInitSelectors = { carousel: { name: "Carousel", selector: "[data-twe-carousel-init]", isToggler: false, }, input: { name: "Input", selector: "[data-twe-input-wrapper-init]", isToggler: false, }, scrollspy: { name: "ScrollSpy", selector: "[data-twe-spy='scroll']", isToggler: false, }, // togglers button: { name: "Button", selector: "[data-twe-toggle='button']", isToggler: true, callback: buttonCallback, }, collapse: { name: "Collapse", selector: "[data-twe-collapse-init]", isToggler: true, callback: collapseCallback, }, dropdown: { name: "Dropdown", selector: "[data-twe-dropdown-toggle-ref]", isToggler: true, callback: dropdownCallback, }, ripple: { name: "Ripple", selector: "[data-twe-ripple-init]", isToggler: true, callback: rippleCallback, }, offcanvas: { name: "Offcanvas", selector: "[data-twe-offcanvas-toggle]", isToggler: true, callback: offcanvasCallback, }, tab: { name: "Tab", selector: "[data-twe-toggle='tab'], [data-twe-toggle='pill'], [data-twe-toggle='list']", isToggler: true, callback: tabCallback, }, tooltip: { name: "Tooltip", selector: "[data-twe-toggle='tooltip']", isToggler: false, callback: tooltipsCallback, }, popover: { name: "Popover", selector: "[data-twe-toggle='popover']", isToggler: true, callback: popoverCallback, }, modal: { name: "Modal", selector: "[data-twe-toggle='modal']", isToggler: true, callback: modalCallback, }, }; export default defaultInitSelectors; ================================================ FILE: src/js/autoinit/jqueryInit.js ================================================ import { getjQuery, onDOMContentLoaded } from "../util/index"; const jqueryInit = (plugin) => { onDOMContentLoaded(() => { const $ = getjQuery(); if ($) { const name = plugin.NAME; const JQUERY_NO_CONFLICT = $.fn[name]; $.fn[name] = plugin.jQueryInterface; $.fn[name].Constructor = plugin; $.fn[name].noConflict = () => { $.fn[name] = JQUERY_NO_CONFLICT; return plugin.jQueryInterface; }; } }); }; export default jqueryInit; ================================================ FILE: src/js/base-component.js ================================================ import Data from "./dom/data"; import { executeAfterTransition, getElement } from "./util/index"; import EventHandler from "./dom/event-handler"; /* ------------------------------------------------------------------------ Constants ------------------------------------------------------------------------ */ const VERSION = "5.1.3"; class BaseComponent { constructor(element) { element = getElement(element); if (!element) { return; } this._element = element; Data.setData(this._element, this.constructor.DATA_KEY, this); } dispose() { Data.removeData(this._element, this.constructor.DATA_KEY); EventHandler.off(this._element, this.constructor.EVENT_KEY); Object.getOwnPropertyNames(this).forEach((propertyName) => { this[propertyName] = null; }); } _queueCallback(callback, element, isAnimated = true) { executeAfterTransition(callback, element, isAnimated); } /** Static */ static getInstance(element) { return Data.getData(getElement(element), this.DATA_KEY); } static getOrCreateInstance(element, config = {}) { return ( this.getInstance(element) || new this(element, typeof config === "object" ? config : null) ); } static get VERSION() { return VERSION; } static get NAME() { throw new Error( 'You have to implement the static method "NAME", for each component!' ); } static get DATA_KEY() { return `twe.${this.NAME}`; } static get EVENT_KEY() { return `.${this.DATA_KEY}`; } } export default BaseComponent; ================================================ FILE: src/js/dom/data.js ================================================ /* ------------------------------------------------------------------------ Constants ------------------------------------------------------------------------ */ const mapData = (() => { const storeData = {}; let id = 1; return { set(element, key, data) { if (typeof element[key] === "undefined") { element[key] = { key, id, }; id++; } storeData[element[key].id] = data; }, get(element, key) { if (!element || typeof element[key] === "undefined") { return null; } const keyProperties = element[key]; if (keyProperties.key === key) { return storeData[keyProperties.id]; } return null; }, delete(element, key) { if (typeof element[key] === "undefined") { return; } const keyProperties = element[key]; if (keyProperties.key === key) { delete storeData[keyProperties.id]; delete element[key]; } }, }; })(); const Data = { setData(instance, key, data) { mapData.set(instance, key, data); }, getData(instance, key) { return mapData.get(instance, key); }, removeData(instance, key) { mapData.delete(instance, key); }, }; export default Data; ================================================ FILE: src/js/dom/event-handler.js ================================================ import { getjQuery } from "../util/index"; /* ------------------------------------------------------------------------ Constants ------------------------------------------------------------------------ */ const namespaceRegex = /[^.]*(?=\..*)\.|.*/; const stripNameRegex = /\..*/; const stripUidRegex = /::\d+$/; const eventRegistry = {}; // Events storage let uidEvent = 1; const customEvents = { mouseenter: "mouseover", mouseleave: "mouseout", }; const customEventsRegex = /^(mouseenter|mouseleave)/i; const nativeEvents = new Set([ "click", "dblclick", "mouseup", "mousedown", "contextmenu", "mousewheel", "DOMMouseScroll", "mouseover", "mouseout", "mousemove", "selectstart", "selectend", "keydown", "keypress", "keyup", "orientationchange", "touchstart", "touchmove", "touchend", "touchcancel", "pointerdown", "pointermove", "pointerup", "pointerleave", "pointercancel", "gesturestart", "gesturechange", "gestureend", "focus", "blur", "change", "reset", "select", "submit", "focusin", "focusout", "load", "unload", "beforeunload", "resize", "move", "DOMContentLoaded", "readystatechange", "error", "abort", "scroll", ]); /** * ------------------------------------------------------------------------ * Private methods * ------------------------------------------------------------------------ */ function getUidEvent(element, uid) { return (uid && `${uid}::${uidEvent++}`) || element.uidEvent || uidEvent++; } function getEvent(element) { const uid = getUidEvent(element); element.uidEvent = uid; eventRegistry[uid] = eventRegistry[uid] || {}; return eventRegistry[uid]; } function bootstrapHandler(element, fn) { return function handler(event) { event.delegateTarget = element; if (handler.oneOff) { EventHandler.off(element, event.type, fn); } return fn.apply(element, [event]); }; } function bootstrapDelegationHandler(element, selector, fn) { return function handler(event) { const domElements = element.querySelectorAll(selector); for ( let { target } = event; target && target !== this; target = target.parentNode ) { for (let i = domElements.length; i--; "") { if (domElements[i] === target) { event.delegateTarget = target; if (handler.oneOff) { EventHandler.off(element, event.type, fn); } return fn.apply(target, [event]); } } } // To please ESLint return null; }; } function findHandler(events, handler, delegationSelector = null) { const uidEventList = Object.keys(events); for (let i = 0, len = uidEventList.length; i < len; i++) { const event = events[uidEventList[i]]; if ( event.originalHandler === handler && event.delegationSelector === delegationSelector ) { return event; } } return null; } function normalizeParams(originalTypeEvent, handler, delegationFn) { const delegation = typeof handler === "string"; const originalHandler = delegation ? delegationFn : handler; let typeEvent = getTypeEvent(originalTypeEvent); const isNative = nativeEvents.has(typeEvent); if (!isNative) { typeEvent = originalTypeEvent; } return [delegation, originalHandler, typeEvent]; } function addHandler(element, originalTypeEvent, handler, delegationFn, oneOff) { if (typeof originalTypeEvent !== "string" || !element) { return; } if (!handler) { handler = delegationFn; delegationFn = null; } // in case of mouseenter or mouseleave wrap the handler within a function that checks for its DOM position // this prevents the handler from being dispatched the same way as mouseover or mouseout does if (customEventsRegex.test(originalTypeEvent)) { const wrapFn = (fn) => { return function (event) { if ( !event.relatedTarget || (event.relatedTarget !== event.delegateTarget && !event.delegateTarget.contains(event.relatedTarget)) ) { return fn.call(this, event); } }; }; if (delegationFn) { delegationFn = wrapFn(delegationFn); } else { handler = wrapFn(handler); } } const [delegation, originalHandler, typeEvent] = normalizeParams( originalTypeEvent, handler, delegationFn ); const events = getEvent(element); const handlers = events[typeEvent] || (events[typeEvent] = {}); const previousFn = findHandler( handlers, originalHandler, delegation ? handler : null ); if (previousFn) { previousFn.oneOff = previousFn.oneOff && oneOff; return; } const uid = getUidEvent( originalHandler, originalTypeEvent.replace(namespaceRegex, "") ); const fn = delegation ? bootstrapDelegationHandler(element, handler, delegationFn) : bootstrapHandler(element, handler); fn.delegationSelector = delegation ? handler : null; fn.originalHandler = originalHandler; fn.oneOff = oneOff; fn.uidEvent = uid; handlers[uid] = fn; element.addEventListener(typeEvent, fn, delegation); } function removeHandler( element, events, typeEvent, handler, delegationSelector ) { const fn = findHandler(events[typeEvent], handler, delegationSelector); if (!fn) { return; } element.removeEventListener(typeEvent, fn, Boolean(delegationSelector)); delete events[typeEvent][fn.uidEvent]; } function removeNamespacedHandlers(element, events, typeEvent, namespace) { const storeElementEvent = events[typeEvent] || {}; Object.keys(storeElementEvent).forEach((handlerKey) => { if (handlerKey.includes(namespace)) { const event = storeElementEvent[handlerKey]; removeHandler( element, events, typeEvent, event.originalHandler, event.delegationSelector ); } }); } function getTypeEvent(event) { // allow to get the native events from namespaced events ('click.twe.button' --> 'click') event = event.replace(stripNameRegex, ""); return customEvents[event] || event; } const EventHandler = { on(element, event, handler, delegationFn) { addHandler(element, event, handler, delegationFn, false); }, one(element, event, handler, delegationFn) { addHandler(element, event, handler, delegationFn, true); }, off(element, originalTypeEvent, handler, delegationFn) { if (typeof originalTypeEvent !== "string" || !element) { return; } const [delegation, originalHandler, typeEvent] = normalizeParams( originalTypeEvent, handler, delegationFn ); const inNamespace = typeEvent !== originalTypeEvent; const events = getEvent(element); const isNamespace = originalTypeEvent.startsWith("."); if (typeof originalHandler !== "undefined") { // Simplest case: handler is passed, remove that listener ONLY. if (!events || !events[typeEvent]) { return; } removeHandler( element, events, typeEvent, originalHandler, delegation ? handler : null ); return; } if (isNamespace) { Object.keys(events).forEach((elementEvent) => { removeNamespacedHandlers( element, events, elementEvent, originalTypeEvent.slice(1) ); }); } const storeElementEvent = events[typeEvent] || {}; Object.keys(storeElementEvent).forEach((keyHandlers) => { const handlerKey = keyHandlers.replace(stripUidRegex, ""); if (!inNamespace || originalTypeEvent.includes(handlerKey)) { const event = storeElementEvent[keyHandlers]; removeHandler( element, events, typeEvent, event.originalHandler, event.delegationSelector ); } }); }, trigger(element, event, args) { if (typeof event !== "string" || !element) { return null; } const $ = getjQuery(); const typeEvent = getTypeEvent(event); const inNamespace = event !== typeEvent; const isNative = nativeEvents.has(typeEvent); let jQueryEvent; let bubbles = true; let nativeDispatch = true; let defaultPrevented = false; let evt = null; if (inNamespace && $) { jQueryEvent = $.Event(event, args); $(element).trigger(jQueryEvent); bubbles = !jQueryEvent.isPropagationStopped(); nativeDispatch = !jQueryEvent.isImmediatePropagationStopped(); defaultPrevented = jQueryEvent.isDefaultPrevented(); } if (isNative) { evt = document.createEvent("HTMLEvents"); evt.initEvent(typeEvent, bubbles, true); } else { evt = new CustomEvent(event, { bubbles, cancelable: true, }); } // merge custom information in our event if (typeof args !== "undefined") { Object.keys(args).forEach((key) => { Object.defineProperty(evt, key, { get() { return args[key]; }, }); }); } if (defaultPrevented) { evt.preventDefault(); } if (nativeDispatch) { element.dispatchEvent(evt); } if (evt.defaultPrevented && typeof jQueryEvent !== "undefined") { jQueryEvent.preventDefault(); } return evt; }, }; export const EventHandlerMulti = { on(element, eventsName, handler, delegationFn) { const events = eventsName.split(" "); for (let i = 0; i < events.length; i++) { EventHandler.on(element, events[i], handler, delegationFn); } }, off(element, originalTypeEvent, handler, delegationFn) { const events = originalTypeEvent.split(" "); for (let i = 0; i < events.length; i++) { EventHandler.off(element, events[i], handler, delegationFn); } }, }; export default EventHandler; ================================================ FILE: src/js/dom/manipulator.js ================================================ function normalizeData(val) { if (val === "true") { return true; } if (val === "false") { return false; } if (val === Number(val).toString()) { return Number(val); } if (val === "" || val === "null") { return null; } return val; } function normalizeDataKey(key) { return key.replace(/[A-Z]/g, (chr) => `-${chr.toLowerCase()}`); } const Manipulator = { setDataAttribute(element, key, value) { element.setAttribute(`data-twe-${normalizeDataKey(key)}`, value); }, removeDataAttribute(element, key) { element.removeAttribute(`data-twe-${normalizeDataKey(key)}`); }, getDataAttributes(element) { if (!element) { return {}; } const attributes = {}; Object.keys(element.dataset) .filter((key) => key.startsWith("twe")) .forEach((key) => { if (key.startsWith("tweClass")) { return; } let pureKey = key.replace(/^twe/, ""); pureKey = pureKey.charAt(0).toLowerCase() + pureKey.slice(1, pureKey.length); attributes[pureKey] = normalizeData(element.dataset[key]); }); return attributes; }, getDataClassAttributes(element) { if (!element) { return {}; } const attributes = { ...element.dataset, }; Object.keys(attributes) .filter((key) => key.startsWith("tweClass")) .forEach((key) => { let pureKey = key.replace(/^tweClass/, ""); pureKey = pureKey.charAt(0).toLowerCase() + pureKey.slice(1, pureKey.length); attributes[pureKey] = normalizeData(attributes[key]); }); return attributes; }, getDataAttribute(element, key) { return normalizeData( element.getAttribute(`data-twe-${normalizeDataKey(key)}`) ); }, offset(element) { const rect = element.getBoundingClientRect(); return { top: rect.top + document.body.scrollTop, left: rect.left + document.body.scrollLeft, }; }, position(element) { return { top: element.offsetTop, left: element.offsetLeft, }; }, style(element, style) { Object.assign(element.style, style); }, toggleClass(element, classNameOrList) { if (!element) { return; } _classNameOrListToArray(classNameOrList).forEach((className) => { if (element.classList.contains(className)) { element.classList.remove(className); } else { element.classList.add(className); } }); }, addClass(element, classNameOrList) { _classNameOrListToArray(classNameOrList).forEach( (className) => !element.classList.contains(className) && element.classList.add(className) ); }, addStyle(element, style) { Object.keys(style).forEach((property) => { element.style[property] = style[property]; }); }, removeClass(element, classNameOrList) { _classNameOrListToArray(classNameOrList).forEach( (className) => element.classList.contains(className) && element.classList.remove(className) ); }, hasClass(element, className) { return element.classList.contains(className); }, maxOffset(element) { const rect = element.getBoundingClientRect(); return { top: rect.top + Math.max( document.body.scrollTop, document.documentElement.scrollTop, window.scrollY ), left: rect.left + Math.max( document.body.scrollLeft, document.documentElement.scrollLeft, window.scrollX ), }; }, }; function _classNameOrListToArray(classNameOrList) { if (typeof classNameOrList === "string") { return classNameOrList.split(" "); } else if (Array.isArray(classNameOrList)) { return classNameOrList; } return false; } export default Manipulator; ================================================ FILE: src/js/dom/selector-engine.js ================================================ /* ------------------------------------------------------------------------ Constants ------------------------------------------------------------------------ */ import { isDisabled, isVisible } from "../util/index"; const NODE_TEXT = 3; const SelectorEngine = { closest(element, selector) { return element.closest(selector); }, matches(element, selector) { return element.matches(selector); }, find(selector, element = document.documentElement) { return [].concat( ...Element.prototype.querySelectorAll.call(element, selector) ); }, findOne(selector, element = document.documentElement) { return Element.prototype.querySelector.call(element, selector); }, children(element, selector) { const children = [].concat(...element.children); return children.filter((child) => child.matches(selector)); }, parents(element, selector) { const parents = []; let ancestor = element.parentNode; while ( ancestor && ancestor.nodeType === Node.ELEMENT_NODE && ancestor.nodeType !== NODE_TEXT ) { if (this.matches(ancestor, selector)) { parents.push(ancestor); } ancestor = ancestor.parentNode; } return parents; }, prev(element, selector) { let previous = element.previousElementSibling; while (previous) { if (previous.matches(selector)) { return [previous]; } previous = previous.previousElementSibling; } return []; }, next(element, selector) { let next = element.nextElementSibling; while (next) { if (this.matches(next, selector)) { return [next]; } next = next.nextElementSibling; } return []; }, focusableChildren(element) { const focusables = [ "a", "button", "input", "textarea", "select", "details", "[tabindex]", '[contenteditable="true"]', ] .map((selector) => `${selector}:not([tabindex^="-"])`) .join(", "); return this.find(focusables, element).filter( (el) => !isDisabled(el) && isVisible(el) ); }, }; export default SelectorEngine; ================================================ FILE: src/js/free/components/button.js ================================================ import BaseComponent from "../../base-component"; /* ------------------------------------------------------------------------ Constants ------------------------------------------------------------------------ */ const NAME = "button"; const CLASS_NAME_ACTIVE = "active"; /* ------------------------------------------------------------------------ Class Definition ------------------------------------------------------------------------ */ class Button extends BaseComponent { // Getters static get NAME() { return NAME; } // Public toggle() { // Toggle class and sync the `aria-pressed` attribute with the return value of the `.toggle()` method this._element.setAttribute( "aria-pressed", this._element.classList.toggle(CLASS_NAME_ACTIVE) ); } // Static static jQueryInterface(config) { return this.each(function () { const data = Button.getOrCreateInstance(this); if (config === "toggle") { data[config](); } }); } } export default Button; ================================================ FILE: src/js/free/components/carousel.js ================================================ import { getElementFromSelector, isRTL, isVisible, getNextActiveElement, reflow, triggerTransitionEnd, typeCheckConfig, } from "../../util/index"; import EventHandler from "../../dom/event-handler"; import Manipulator from "../../dom/manipulator"; import SelectorEngine from "../../dom/selector-engine"; import BaseComponent from "../../base-component"; /* ------------------------------------------------------------------------ Constants ------------------------------------------------------------------------ */ const NAME = "carousel"; const DATA_KEY = "twe.carousel"; const EVENT_KEY = `.${DATA_KEY}`; const DATA_API_KEY = ".data-api"; const ARROW_LEFT_KEY = "ArrowLeft"; const ARROW_RIGHT_KEY = "ArrowRight"; const TOUCHEVENT_COMPAT_WAIT = 500; // Time for mouse compat events to fire after touch const SWIPE_THRESHOLD = 40; const Default = { interval: 5000, keyboard: true, ride: false, pause: "hover", wrap: true, touch: true, }; const DefaultType = { interval: "(number|boolean)", keyboard: "boolean", ride: "(boolean|string)", pause: "(string|boolean)", wrap: "boolean", touch: "boolean", }; const DefaultClasses = { pointer: "touch-pan-y", block: "!block", visible: "data-[twe-carousel-fade]:opacity-100 data-[twe-carousel-fade]:z-[1]", invisible: "data-[twe-carousel-fade]:z-0 data-[twe-carousel-fade]:opacity-0 data-[twe-carousel-fade]:duration-[600ms] data-[twe-carousel-fade]:delay-600", slideRight: "translate-x-full", slideLeft: "-translate-x-full", }; const DefaultClassesType = { pointer: "string", block: "string", visible: "string", invisible: "string", slideRight: "string", slideLeft: "string", }; const ORDER_NEXT = "next"; const ORDER_PREV = "prev"; const DIRECTION_LEFT = "left"; const DIRECTION_RIGHT = "right"; const KEY_TO_DIRECTION = { [ARROW_LEFT_KEY]: DIRECTION_RIGHT, [ARROW_RIGHT_KEY]: DIRECTION_LEFT, }; const EVENT_SLIDE = `slide${EVENT_KEY}`; const EVENT_SLID = `slid${EVENT_KEY}`; const EVENT_KEYDOWN = `keydown${EVENT_KEY}`; const EVENT_MOUSEENTER = `mouseenter${EVENT_KEY}`; const EVENT_MOUSELEAVE = `mouseleave${EVENT_KEY}`; const EVENT_TOUCHSTART = `touchstart${EVENT_KEY}`; const EVENT_TOUCHMOVE = `touchmove${EVENT_KEY}`; const EVENT_TOUCHEND = `touchend${EVENT_KEY}`; const EVENT_POINTERDOWN = `pointerdown${EVENT_KEY}`; const EVENT_POINTERUP = `pointerup${EVENT_KEY}`; const EVENT_DRAG_START = `dragstart${EVENT_KEY}`; const EVENT_LOAD_DATA_API = `load${EVENT_KEY}${DATA_API_KEY}`; const EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}`; const ATTR_ACTIVE = "data-twe-carousel-active"; const ATTR_END = "data-twe-carousel-item-end"; const ATTR_START = "data-twe-carousel-item-start"; const ATTR_NEXT = "data-twe-carousel-item-next"; const ATTR_PREV = "data-twe-carousel-item-prev"; const ATTR_POINTER_EVENT = "data-twe-carousel-pointer-event"; const SELECTOR_DATA_CAROUSEL_INIT = "[data-twe-carousel-init]"; const SELECTOR_DATA_ACTIVE = "[data-twe-carousel-active]"; const SELECTOR_DATA_ITEM = "[data-twe-carousel-item]"; const SELECTOR_DATA_ACTIVE_ITEM = `${SELECTOR_DATA_ACTIVE}${SELECTOR_DATA_ITEM}`; const SELECTOR_DATA_ITEM_IMG = `${SELECTOR_DATA_ITEM} img`; const SELECTOR_DATA_NEXT_PREV = "[data-twe-carousel-item-next], [data-twe-carousel-item-prev]"; const SELECTOR_DATA_INDICATORS = "[data-twe-carousel-indicators]"; const SELECTOR_INDICATOR = "[data-twe-target]"; const SELECTOR_DATA_SLIDE = "[data-twe-slide], [data-twe-slide-to]"; const POINTER_TYPE_TOUCH = "touch"; const POINTER_TYPE_PEN = "pen"; /* ------------------------------------------------------------------------ Class Definition ------------------------------------------------------------------------ */ class Carousel extends BaseComponent { constructor(element, config, classes) { super(element); this._items = null; this._interval = null; this._activeElement = null; this._isPaused = false; this._isSliding = false; this.touchTimeout = null; this.touchStartX = 0; this.touchDeltaX = 0; this._config = this._getConfig(config); this._classes = this._getClasses(classes); this._indicatorsElement = SelectorEngine.findOne( SELECTOR_DATA_INDICATORS, this._element ); this._touchSupported = "ontouchstart" in document.documentElement || navigator.maxTouchPoints > 0; this._pointerEvent = Boolean(window.PointerEvent); this._setActiveElementClass(); this._addEventListeners(); this._didInit = false; this._init(); if (this._config.ride === "carousel") { this.cycle(); } } // Getters static get Default() { return Default; } static get NAME() { return NAME; } // Public next() { this._slide(ORDER_NEXT); } nextWhenVisible() { // Don't call next when the page isn't visible // or the carousel or its parent isn't visible if (!document.hidden && isVisible(this._element)) { this.next(); } } prev() { this._slide(ORDER_PREV); } pause(event) { if (!event) { this._isPaused = true; } if (SelectorEngine.findOne(SELECTOR_DATA_NEXT_PREV, this._element)) { triggerTransitionEnd(this._element); this.cycle(true); } clearInterval(this._interval); this._interval = null; } cycle(event) { if (!event) { this._isPaused = false; } if (this._interval) { clearInterval(this._interval); this._interval = null; } if (this._config && this._config.interval && !this._isPaused) { this._updateInterval(); this._interval = setInterval( (document.visibilityState ? this.nextWhenVisible : this.next).bind( this ), this._config.interval ); } } to(index) { this._activeElement = SelectorEngine.findOne( SELECTOR_DATA_ACTIVE_ITEM, this._element ); const activeIndex = this._getItemIndex(this._activeElement); if (index > this._items.length - 1 || index < 0) { return; } if (this._isSliding) { EventHandler.one(this._element, EVENT_SLID, () => this.to(index)); return; } if (activeIndex === index) { this.pause(); this.cycle(); return; } const order = index > activeIndex ? ORDER_NEXT : ORDER_PREV; this._slide(order, this._items[index]); } dispose() { EventHandler.off( document, EVENT_CLICK_DATA_API, SELECTOR_DATA_SLIDE, Carousel.dataApiClickHandler ); EventHandler.off(window, EVENT_LOAD_DATA_API); super.dispose(); } // Private _init() { if (this._didInit) { return; } EventHandler.on( document, EVENT_CLICK_DATA_API, SELECTOR_DATA_SLIDE, Carousel.dataApiClickHandler ); EventHandler.on(window, EVENT_LOAD_DATA_API, () => { const carousels = SelectorEngine.find(SELECTOR_DATA_CAROUSEL_INIT); for (let i = 0, len = carousels.length; i < len; i++) { Carousel.carouselInterface( carousels[i], Carousel.getInstance(carousels[i]) ); } }); this._didInit = true; } _getConfig(config) { config = { ...Default, ...Manipulator.getDataAttributes(this._element), ...(typeof config === "object" ? config : {}), }; typeCheckConfig(NAME, config, DefaultType); return config; } _getClasses(classes) { const dataAttributes = Manipulator.getDataClassAttributes(this._element); classes = { ...DefaultClasses, ...dataAttributes, ...classes, }; typeCheckConfig(NAME, classes, DefaultClassesType); return classes; } _enableCycle() { if (!this._config.ride) { return; } if (this._isSliding) { EventHandler.one(this._element, EVENT_SLID, () => this.cycle()); return; } this.cycle(); } _applyInitialClasses() { const activeElement = SelectorEngine.findOne( SELECTOR_DATA_ACTIVE_ITEM, this._element ); activeElement.classList.add( this._classes.block, ...this._classes.visible.split(" ") ); this._setActiveIndicatorElement(activeElement); } _handleSwipe() { const absDeltax = Math.abs(this.touchDeltaX); if (absDeltax <= SWIPE_THRESHOLD) { return; } const direction = absDeltax / this.touchDeltaX; this.touchDeltaX = 0; if (!direction) { return; } this._slide(direction > 0 ? DIRECTION_RIGHT : DIRECTION_LEFT); } _setActiveElementClass() { this._activeElement = SelectorEngine.findOne( SELECTOR_DATA_ACTIVE_ITEM, this._element ); Manipulator.addClass(this._activeElement, "hidden"); } _addEventListeners() { if (this._config.keyboard) { EventHandler.on(this._element, EVENT_KEYDOWN, (event) => this._keydown(event) ); } if (this._config.pause === "hover") { EventHandler.on(this._element, EVENT_MOUSEENTER, (event) => this.pause(event) ); EventHandler.on(this._element, EVENT_MOUSELEAVE, (event) => this._enableCycle(event) ); } if (this._config.touch && this._touchSupported) { this._addTouchEventListeners(); } this._applyInitialClasses(); } _addTouchEventListeners() { const hasPointerPenTouch = (event) => { return ( this._pointerEvent && (event.pointerType === POINTER_TYPE_PEN || event.pointerType === POINTER_TYPE_TOUCH) ); }; const start = (event) => { if (hasPointerPenTouch(event)) { this.touchStartX = event.clientX; } else if (!this._pointerEvent) { this.touchStartX = event.touches[0].clientX; } }; const move = (event) => { // ensure swiping with one touch and not pinching this.touchDeltaX = event.touches && event.touches.length > 1 ? 0 : event.touches[0].clientX - this.touchStartX; }; const end = (event) => { if (hasPointerPenTouch(event)) { this.touchDeltaX = event.clientX - this.touchStartX; } this._handleSwipe(); if (this._config.pause === "hover") { // If it's a touch-enabled device, mouseenter/leave are fired as // part of the mouse compatibility events on first tap - the carousel // would stop cycling until user tapped out of it; // here, we listen for touchend, explicitly pause the carousel // (as if it's the second time we tap on it, mouseenter compat event // is NOT fired) and after a timeout (to allow for mouse compatibility // events to fire) we explicitly restart cycling this.pause(); if (this.touchTimeout) { clearTimeout(this.touchTimeout); } this.touchTimeout = setTimeout( (event) => this._enableCycle(event), TOUCHEVENT_COMPAT_WAIT + this._config.interval ); } }; SelectorEngine.find(SELECTOR_DATA_ITEM_IMG, this._element).forEach( (itemImg) => { EventHandler.on(itemImg, EVENT_DRAG_START, (event) => event.preventDefault() ); } ); if (this._pointerEvent) { EventHandler.on(this._element, EVENT_POINTERDOWN, (event) => start(event) ); EventHandler.on(this._element, EVENT_POINTERUP, (event) => end(event)); this._element.classList.add(this._classes.pointer); this._element.setAttribute(`${ATTR_POINTER_EVENT}`, ""); } else { EventHandler.on(this._element, EVENT_TOUCHSTART, (event) => start(event)); EventHandler.on(this._element, EVENT_TOUCHMOVE, (event) => move(event)); EventHandler.on(this._element, EVENT_TOUCHEND, (event) => end(event)); } } _keydown(event) { if (/input|textarea/i.test(event.target.tagName)) { return; } const direction = KEY_TO_DIRECTION[event.key]; if (direction) { event.preventDefault(); this._slide(direction); } } _getItemIndex(element) { this._items = element && element.parentNode ? SelectorEngine.find(SELECTOR_DATA_ITEM, element.parentNode) : []; return this._items.indexOf(element); } _getItemByOrder(order, activeElement) { const isNext = order === ORDER_NEXT; return getNextActiveElement( this._items, activeElement, isNext, this._config.wrap ); } _triggerSlideEvent(relatedTarget, eventDirectionName) { const targetIndex = this._getItemIndex(relatedTarget); const fromIndex = this._getItemIndex( SelectorEngine.findOne(SELECTOR_DATA_ACTIVE_ITEM, this._element) ); return EventHandler.trigger(this._element, EVENT_SLIDE, { relatedTarget, direction: eventDirectionName, from: fromIndex, to: targetIndex, }); } _setActiveIndicatorElement(element) { if (this._indicatorsElement) { const activeIndicator = SelectorEngine.findOne( SELECTOR_DATA_ACTIVE, this._indicatorsElement ); activeIndicator.removeAttribute(ATTR_ACTIVE); activeIndicator.removeAttribute("aria-current"); activeIndicator.classList.remove("!opacity-100"); const indicators = SelectorEngine.find( SELECTOR_INDICATOR, this._indicatorsElement ); for (let i = 0; i < indicators.length; i++) { if ( Number.parseInt( indicators[i].getAttribute("data-twe-slide-to"), 10 ) === this._getItemIndex(element) ) { indicators[i].setAttribute(`${ATTR_ACTIVE}`, ""); indicators[i].setAttribute("aria-current", "true"); indicators[i].classList.add("!opacity-100"); break; } } } } _updateInterval() { const element = this._activeElement || SelectorEngine.findOne(SELECTOR_DATA_ACTIVE_ITEM, this._element); if (!element) { return; } const elementInterval = Number.parseInt( element.getAttribute("data-twe-interval"), 10 ); if (elementInterval) { this._config.defaultInterval = this._config.defaultInterval || this._config.interval; this._config.interval = elementInterval; } else { this._config.interval = this._config.defaultInterval || this._config.interval; } } _slide(directionOrOrder, element) { const order = this._directionToOrder(directionOrOrder); const activeElement = SelectorEngine.findOne( SELECTOR_DATA_ACTIVE_ITEM, this._element ); const activeElementIndex = this._getItemIndex(activeElement); const nextElement = element || this._getItemByOrder(order, activeElement); const nextElementIndex = this._getItemIndex(nextElement); const isCycling = Boolean(this._interval); const isNext = order === ORDER_NEXT; const directionalAttr = isNext ? ATTR_START : ATTR_END; const orderAttr = isNext ? ATTR_NEXT : ATTR_PREV; const eventDirectionName = this._orderToDirection(order); const activeClass = directionalAttr === ATTR_START ? this._classes.slideLeft : this._classes.slideRight; const nextClass = directionalAttr !== ATTR_START ? this._classes.slideLeft : this._classes.slideRight; if (nextElement && nextElement.hasAttribute(ATTR_ACTIVE)) { this._isSliding = false; return; } if (this._isSliding) { return; } const slideEvent = this._triggerSlideEvent(nextElement, eventDirectionName); if (slideEvent.defaultPrevented) { return; } if (!activeElement || !nextElement) { // Some weirdness is happening, so we bail return; } this._isSliding = true; if (isCycling) { this.pause(); } this._setActiveIndicatorElement(nextElement); this._activeElement = nextElement; const triggerSlidEvent = () => { EventHandler.trigger(this._element, EVENT_SLID, { relatedTarget: nextElement, direction: eventDirectionName, from: activeElementIndex, to: nextElementIndex, }); }; nextElement.setAttribute(`${orderAttr}`, ""); nextElement.classList.add(this._classes.block, nextClass); reflow(nextElement); activeElement.setAttribute(`${directionalAttr}`, ""); activeElement.classList.add( activeClass, ...this._classes.invisible.split(" ") ); activeElement.classList.remove(...this._classes.visible.split(" ")); nextElement.setAttribute(`${directionalAttr}`, ""); nextElement.classList.add(...this._classes.visible.split(" ")); nextElement.classList.remove( this._classes.slideRight, this._classes.slideLeft ); const completeCallBack = () => { nextElement.removeAttribute(directionalAttr); nextElement.removeAttribute(orderAttr); nextElement.setAttribute(`${ATTR_ACTIVE}`, ""); activeElement.removeAttribute(ATTR_ACTIVE); activeElement.classList.remove( activeClass, ...this._classes.invisible.split(" "), this._classes.block ); activeElement.removeAttribute(orderAttr); activeElement.removeAttribute(directionalAttr); this._isSliding = false; setTimeout(triggerSlidEvent, 0); }; this._queueCallback(completeCallBack, activeElement, true); if (isCycling || this._config.ride === true) { this.cycle(); } } _directionToOrder(direction) { if (![DIRECTION_RIGHT, DIRECTION_LEFT].includes(direction)) { return direction; } if (isRTL()) { return direction === DIRECTION_LEFT ? ORDER_PREV : ORDER_NEXT; } return direction === DIRECTION_LEFT ? ORDER_NEXT : ORDER_PREV; } _orderToDirection(order) { if (![ORDER_NEXT, ORDER_PREV].includes(order)) { return order; } if (isRTL()) { return order === ORDER_PREV ? DIRECTION_LEFT : DIRECTION_RIGHT; } return order === ORDER_PREV ? DIRECTION_RIGHT : DIRECTION_LEFT; } // Static static carouselInterface(element, config) { const data = Carousel.getOrCreateInstance(element, config); let { _config } = data; if (typeof config === "object") { _config = { ..._config, ...config, }; } const action = typeof config === "string" ? config : config.slide; if (typeof config === "number") { data.to(config); return; } if (typeof action === "string") { if (typeof data[action] === "undefined") { throw new TypeError(`No method named "${action}"`); } data[action](); } else if (_config.interval && _config.ride === true) { data.pause(); } } static jQueryInterface(config) { return this.each(function () { let data = Carousel.getOrCreateInstance(this); if (typeof config === "number") { data.to(config); return; } if (typeof config === "string") { if (typeof data[config] === "undefined") { throw new TypeError(`No method named "${config}"`); } data[config](); } }); } static dataApiClickHandler(event) { const target = getElementFromSelector(this); if (!target) { return; } const config = { ...Manipulator.getDataAttributes(target), ...Manipulator.getDataAttributes(this), }; const slideIndex = this.getAttribute("data-twe-slide-to"); if (slideIndex) { config.interval = false; } Carousel.carouselInterface(target, config); if (slideIndex) { Carousel.getInstance(target).to(slideIndex); } event.preventDefault(); } } export default Carousel; ================================================ FILE: src/js/free/components/collapse.js ================================================ import { getElement, getSelectorFromElement, getElementFromSelector, reflow, typeCheckConfig, } from "../../util/index"; import Data from "../../dom/data"; import EventHandler from "../../dom/event-handler"; import Manipulator from "../../dom/manipulator"; import SelectorEngine from "../../dom/selector-engine"; import BaseComponent from "../../base-component"; /* ------------------------------------------------------------------------ Constants ------------------------------------------------------------------------ */ const NAME = "collapse"; const DATA_KEY = "twe.collapse"; const EVENT_KEY = `.${DATA_KEY}`; const Default = { toggle: true, parent: null, }; const DefaultType = { toggle: "boolean", parent: "(null|element)", }; const EVENT_SHOW = `show${EVENT_KEY}`; const EVENT_SHOWN = `shown${EVENT_KEY}`; const EVENT_HIDE = `hide${EVENT_KEY}`; const EVENT_HIDDEN = `hidden${EVENT_KEY}`; const ATTR_SHOW = "data-twe-collapse-show"; const ATTR_COLLAPSED = "data-twe-collapse-collapsed"; const ATTR_COLLAPSING = "data-twe-collapse-collapsing"; const ATTR_HORIZONTAL = "data-twe-collapse-horizontal"; const ATTR_COLLAPSE_ITEM = "data-twe-collapse-item"; const ATTR_COLLAPSE_DEEPER_CHILDREN = `:scope [${ATTR_COLLAPSE_ITEM}] [${ATTR_COLLAPSE_ITEM}]`; const WIDTH = "width"; const HEIGHT = "height"; const SELECTOR_DATA_ACTIVES = "[data-twe-collapse-item][data-twe-collapse-show], [data-twe-collapse-item][data-twe-collapse-collapsing]"; const SELECTOR_DATA_COLLAPSE_INIT = "[data-twe-collapse-init]"; const DefaultClasses = { visible: "!visible", hidden: "hidden", baseTransition: "overflow-hidden duration-[350ms] ease-[cubic-bezier(0.25,0.1,0.25,1.0)] motion-reduce:transition-none", collapsing: "h-0 transition-[height] overflow-hidden duration-[350ms] ease-[cubic-bezier(0.25,0.1,0.25,1.0)] motion-reduce:transition-none", collapsingHorizontal: "w-0 h-auto transition-[width] overflow-hidden duration-[350ms] ease-[cubic-bezier(0.25,0.1,0.25,1.0)] motion-reduce:transition-none", }; const DefaultClassesType = { visible: "string", hidden: "string", baseTransition: "string", collapsing: "string", collapsingHorizontal: "string", }; /* ------------------------------------------------------------------------ Class Definition ------------------------------------------------------------------------ */ class Collapse extends BaseComponent { constructor(element, config, classes) { super(element); this._isTransitioning = false; this._config = this._getConfig(config); this._classes = this._getClasses(classes); this._triggerArray = []; const toggleList = SelectorEngine.find(SELECTOR_DATA_COLLAPSE_INIT); for (let i = 0, len = toggleList.length; i < len; i++) { const elem = toggleList[i]; const selector = getSelectorFromElement(elem); const filterElement = SelectorEngine.find(selector).filter( (foundElem) => foundElem === this._element ); if (selector !== null && filterElement.length) { this._selector = selector; this._triggerArray.push(elem); } } this._initializeChildren(); if (!this._config.parent) { this._addAriaAndCollapsedClass(this._triggerArray, this._isShown()); } if (this._config.toggle) { this.toggle(); } } // Getters static get Default() { return Default; } static get NAME() { return NAME; } // Public toggle() { if (this._isShown()) { this.hide(); } else { this.show(); } } show() { if (this._isTransitioning || this._isShown()) { return; } let actives = []; let activesData; if (this._config.parent) { const children = SelectorEngine.find( ATTR_COLLAPSE_DEEPER_CHILDREN, this._config.parent ); actives = SelectorEngine.find( SELECTOR_DATA_ACTIVES, this._config.parent ).filter((elem) => !children.includes(elem)); // remove children if greater depth } const container = SelectorEngine.findOne(this._selector); if (actives.length) { const tempActiveData = actives.find((elem) => container !== elem); activesData = tempActiveData ? Collapse.getInstance(tempActiveData) : null; if (activesData && activesData._isTransitioning) { return; } } const startEvent = EventHandler.trigger(this._element, EVENT_SHOW); if (startEvent.defaultPrevented) { return; } actives.forEach((elemActive) => { if (container !== elemActive) { Collapse.getOrCreateInstance(elemActive, { toggle: false }).hide(); } if (!activesData) { Data.setData(elemActive, DATA_KEY, null); } }); const dimension = this._getDimension(); const CLASS_NAME_TRANSITION = dimension === "height" ? this._classes.collapsing : this._classes.collapsingHorizontal; Manipulator.removeClass(this._element, this._classes.visible); Manipulator.removeClass(this._element, this._classes.hidden); Manipulator.addClass(this._element, CLASS_NAME_TRANSITION); this._element.removeAttribute(ATTR_COLLAPSE_ITEM); this._element.setAttribute(ATTR_COLLAPSING, ""); this._element.style[dimension] = 0; this._addAriaAndCollapsedClass(this._triggerArray, true); this._isTransitioning = true; const complete = () => { this._isTransitioning = false; Manipulator.removeClass(this._element, this._classes.hidden); Manipulator.removeClass(this._element, CLASS_NAME_TRANSITION); Manipulator.addClass(this._element, this._classes.visible); this._element.removeAttribute(ATTR_COLLAPSING); this._element.setAttribute(ATTR_COLLAPSE_ITEM, ""); this._element.setAttribute(ATTR_SHOW, ""); this._element.style[dimension] = ""; EventHandler.trigger(this._element, EVENT_SHOWN); }; const capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1); const scrollSize = `scroll${capitalizedDimension}`; this._queueCallback(complete, this._element, true); this._element.style[dimension] = `${this._element[scrollSize]}px`; } hide() { if (this._isTransitioning || !this._isShown()) { return; } const startEvent = EventHandler.trigger(this._element, EVENT_HIDE); if (startEvent.defaultPrevented) { return; } const dimension = this._getDimension(); const CLASS_NAME_TRANSITION = dimension === "height" ? this._classes.collapsing : this._classes.collapsingHorizontal; this._element.style[dimension] = `${ this._element.getBoundingClientRect()[dimension] }px`; reflow(this._element); Manipulator.addClass(this._element, CLASS_NAME_TRANSITION); Manipulator.removeClass(this._element, this._classes.visible); Manipulator.removeClass(this._element, this._classes.hidden); this._element.setAttribute(ATTR_COLLAPSING, ""); this._element.removeAttribute(ATTR_COLLAPSE_ITEM); this._element.removeAttribute(ATTR_SHOW); const triggerArrayLength = this._triggerArray.length; for (let i = 0; i < triggerArrayLength; i++) { const trigger = this._triggerArray[i]; const elem = getElementFromSelector(trigger); if (elem && !this._isShown(elem)) { this._addAriaAndCollapsedClass([trigger], false); } } this._isTransitioning = true; const complete = () => { this._isTransitioning = false; Manipulator.removeClass(this._element, CLASS_NAME_TRANSITION); Manipulator.addClass(this._element, this._classes.visible); Manipulator.addClass(this._element, this._classes.hidden); this._element.removeAttribute(ATTR_COLLAPSING); this._element.setAttribute(ATTR_COLLAPSE_ITEM, ""); EventHandler.trigger(this._element, EVENT_HIDDEN); }; this._element.style[dimension] = ""; this._queueCallback(complete, this._element, true); } _isShown(element = this._element) { return element.hasAttribute(ATTR_SHOW); } // Private _getConfig(config) { config = { ...Default, ...Manipulator.getDataAttributes(this._element), ...config, }; config.toggle = Boolean(config.toggle); // Coerce string values config.parent = getElement(config.parent); typeCheckConfig(NAME, config, DefaultType); return config; } _getClasses(classes) { const dataAttributes = Manipulator.getDataClassAttributes(this._element); classes = { ...DefaultClasses, ...dataAttributes, ...classes, }; typeCheckConfig(NAME, classes, DefaultClassesType); return classes; } _getDimension() { return this._element.hasAttribute(ATTR_HORIZONTAL) ? WIDTH : HEIGHT; } _initializeChildren() { if (!this._config.parent) { return; } const children = SelectorEngine.find( ATTR_COLLAPSE_DEEPER_CHILDREN, this._config.parent ); SelectorEngine.find(SELECTOR_DATA_COLLAPSE_INIT, this._config.parent) .filter((elem) => !children.includes(elem)) .forEach((element) => { const selected = getElementFromSelector(element); if (selected) { this._addAriaAndCollapsedClass([element], this._isShown(selected)); } }); } _addAriaAndCollapsedClass(triggerArray, isOpen) { if (!triggerArray.length) { return; } triggerArray.forEach((elem) => { if (isOpen) { elem.removeAttribute(ATTR_COLLAPSED); } else { elem.setAttribute(`${ATTR_COLLAPSED}`, ""); } elem.setAttribute("aria-expanded", isOpen); }); } // Static static jQueryInterface(config) { return this.each(function () { const _config = {}; if (typeof config === "string" && /show|hide/.test(config)) { _config.toggle = false; } const data = Collapse.getOrCreateInstance(this, _config); if (typeof config === "string") { if (typeof data[config] === "undefined") { throw new TypeError(`No method named "${config}"`); } data[config](); } }); } } export default Collapse; ================================================ FILE: src/js/free/components/dropdown.js ================================================ import * as Popper from "@popperjs/core"; import { getElement, getElementFromSelector, getNextActiveElement, isDisabled, isElement, isRTL, isVisible, noop, typeCheckConfig, } from "../../util/index"; import EventHandler from "../../dom/event-handler"; import Manipulator from "../../dom/manipulator"; import SelectorEngine from "../../dom/selector-engine"; import BaseComponent from "../../base-component"; /* ------------------------------------------------------------------------ Constants ------------------------------------------------------------------------ */ const NAME = "dropdown"; const DATA_KEY = "twe.dropdown"; const EVENT_KEY = `.${DATA_KEY}`; const DATA_API_KEY = ".data-api"; const ESCAPE_KEY = "Escape"; const SPACE_KEY = "Space"; const TAB_KEY = "Tab"; const ARROW_UP_KEY = "ArrowUp"; const ARROW_DOWN_KEY = "ArrowDown"; const RIGHT_MOUSE_BUTTON = 2; // MouseEvent.button value for the secondary button, usually the right button const REGEXP_KEYDOWN = new RegExp( `${ARROW_UP_KEY}|${ARROW_DOWN_KEY}|${ESCAPE_KEY}` ); const EVENT_HIDE = `hide${EVENT_KEY}`; const EVENT_HIDDEN = `hidden${EVENT_KEY}`; const EVENT_SHOW = `show${EVENT_KEY}`; const EVENT_SHOWN = `shown${EVENT_KEY}`; const EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}`; const EVENT_KEYDOWN_DATA_API = `keydown${EVENT_KEY}${DATA_API_KEY}`; const EVENT_KEYUP_DATA_API = `keyup${EVENT_KEY}${DATA_API_KEY}`; const CLASS_NAME_SHOW = "show"; const CLASS_NAME_DROPUP = "dropup"; const CLASS_NAME_DROPEND = "dropend"; const CLASS_NAME_DROPSTART = "dropstart"; const SELECTOR_NAVBAR = "[data-twe-navbar-ref]"; const SELECTOR_DATA_TOGGLE = "[data-twe-dropdown-toggle-ref]"; const SELECTOR_MENU = "[data-twe-dropdown-menu-ref]"; const SELECTOR_NAVBAR_NAV = "[data-twe-navbar-nav-ref]"; const SELECTOR_VISIBLE_ITEMS = "[data-twe-dropdown-menu-ref] [data-twe-dropdown-item-ref]:not(.disabled):not(:disabled)"; const PLACEMENT_TOP = isRTL() ? "top-end" : "top-start"; const PLACEMENT_TOPEND = isRTL() ? "top-start" : "top-end"; const PLACEMENT_BOTTOM = isRTL() ? "bottom-end" : "bottom-start"; const PLACEMENT_BOTTOMEND = isRTL() ? "bottom-start" : "bottom-end"; const PLACEMENT_RIGHT = isRTL() ? "left-start" : "right-start"; const PLACEMENT_LEFT = isRTL() ? "right-start" : "left-start"; const ANIMATION_FADE_IN = [{ opacity: "0" }, { opacity: "1" }]; const ANIMATION_FADE_OUT = [{ opacity: "1" }, { opacity: "0" }]; const ANIMATION_TIMING = { iterations: 1, easing: "ease", fill: "both", }; const Default = { offset: [0, 2], boundary: "clippingParents", reference: "toggle", display: "dynamic", popperConfig: null, autoClose: true, dropdownAnimation: "on", animationDuration: 550, }; const DefaultType = { offset: "(array|string|function)", boundary: "(string|element)", reference: "(string|element|object)", display: "string", popperConfig: "(null|object|function)", autoClose: "(boolean|string)", dropdownAnimation: "string", animationDuration: "number", }; /* ------------------------------------------------------------------------ Class Definition ------------------------------------------------------------------------ */ class Dropdown extends BaseComponent { constructor(element, config) { super(element); this._popper = null; this._config = this._getConfig(config); this._menu = this._getMenuElement(); this._inNavbar = this._detectNavbar(); this._fadeOutAnimate = null; //* prevents dropdown close issue when system animation is turned off const isPrefersReducedMotionSet = window.matchMedia( "(prefers-reduced-motion: reduce)" ).matches; this._animationCanPlay = this._config.dropdownAnimation === "on" && !isPrefersReducedMotionSet; this._didInit = false; this._init(); } // Getters static get Default() { return Default; } static get DefaultType() { return DefaultType; } static get NAME() { return NAME; } // Public toggle() { return this._isShown() ? this.hide() : this.show(); } show() { if (isDisabled(this._element) || this._isShown(this._menu)) { return; } const relatedTarget = { relatedTarget: this._element, }; const showEvent = EventHandler.trigger( this._element, EVENT_SHOW, relatedTarget ); if (showEvent.defaultPrevented) { return; } const parent = Dropdown.getParentFromElement(this._element); // Totally disable Popper for Dropdowns in Navbar if (this._inNavbar) { Manipulator.setDataAttribute(this._menu, "popper", "none"); } else { this._createPopper(parent); } // If this is a touch-enabled device we add extra // empty mouseover listeners to the body's immediate children; // only needed because of broken event delegation on iOS // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html if ( "ontouchstart" in document.documentElement && !parent.closest(SELECTOR_NAVBAR_NAV) ) { [] .concat(...document.body.children) .forEach((elem) => EventHandler.on(elem, "mouseover", noop)); } this._element.focus(); this._element.setAttribute("aria-expanded", true); this._menu.setAttribute(`data-twe-dropdown-${CLASS_NAME_SHOW}`, ""); this._animationCanPlay && this._menu.animate(ANIMATION_FADE_IN, { ...ANIMATION_TIMING, duration: this._config.animationDuration, }); this._element.setAttribute(`data-twe-dropdown-${CLASS_NAME_SHOW}`, ""); setTimeout( () => { EventHandler.trigger(this._element, EVENT_SHOWN, relatedTarget); }, this._animationCanPlay ? this._config.animationDuration : 0 ); } hide() { if (isDisabled(this._element) || !this._isShown(this._menu)) { return; } const relatedTarget = { relatedTarget: this._element, }; this._completeHide(relatedTarget); } dispose() { if (this._popper) { this._popper.destroy(); } super.dispose(); } update() { this._inNavbar = this._detectNavbar(); if (this._popper) { this._popper.update(); } } // Private _init() { if (this._didInit) { return; } EventHandler.on( document, EVENT_KEYDOWN_DATA_API, SELECTOR_DATA_TOGGLE, Dropdown.dataApiKeydownHandler ); EventHandler.on( document, EVENT_KEYDOWN_DATA_API, SELECTOR_MENU, Dropdown.dataApiKeydownHandler ); EventHandler.on(document, EVENT_CLICK_DATA_API, Dropdown.clearMenus); EventHandler.on(document, EVENT_KEYUP_DATA_API, Dropdown.clearMenus); this._didInit = true; } _completeHide(relatedTarget) { if (this._fadeOutAnimate && this._fadeOutAnimate.playState === "running") { return; } const hideEvent = EventHandler.trigger( this._element, EVENT_HIDE, relatedTarget ); if (hideEvent.defaultPrevented) { return; } // If this is a touch-enabled device we remove the extra // empty mouseover listeners we added for iOS support if ("ontouchstart" in document.documentElement) { [] .concat(...document.body.children) .forEach((elem) => EventHandler.off(elem, "mouseover", noop)); } if (this._animationCanPlay) { this._fadeOutAnimate = this._menu.animate(ANIMATION_FADE_OUT, { ...ANIMATION_TIMING, duration: this._config.animationDuration, }); } setTimeout( () => { if (this._popper) { this._popper.destroy(); } this._menu.removeAttribute(`data-twe-dropdown-${CLASS_NAME_SHOW}`); this._element.removeAttribute(`data-twe-dropdown-${CLASS_NAME_SHOW}`); this._element.setAttribute("aria-expanded", "false"); Manipulator.removeDataAttribute(this._menu, "popper"); EventHandler.trigger(this._element, EVENT_HIDDEN, relatedTarget); }, this._animationCanPlay ? this._config.animationDuration : 0 ); } _getConfig(config) { config = { ...this.constructor.Default, ...Manipulator.getDataAttributes(this._element), ...config, }; typeCheckConfig(NAME, config, this.constructor.DefaultType); if ( typeof config.reference === "object" && !isElement(config.reference) && typeof config.reference.getBoundingClientRect !== "function" ) { // Popper virtual elements require a getBoundingClientRect method throw new TypeError( `${NAME.toUpperCase()}: Option "reference" provided type "object" without a required "getBoundingClientRect" method.` ); } return config; } _createPopper(parent) { if (typeof Popper === "undefined") { throw new TypeError( "Bootstrap's dropdowns require Popper (https://popper.js.org)" ); } let referenceElement = this._element; if (this._config.reference === "parent") { referenceElement = parent; } else if (isElement(this._config.reference)) { referenceElement = getElement(this._config.reference); } else if (typeof this._config.reference === "object") { referenceElement = this._config.reference; } const popperConfig = this._getPopperConfig(); const isDisplayStatic = popperConfig.modifiers.find( (modifier) => modifier.name === "applyStyles" && modifier.enabled === false ); this._popper = Popper.createPopper( referenceElement, this._menu, popperConfig ); if (isDisplayStatic) { Manipulator.setDataAttribute(this._menu, "popper", "static"); } } _isShown(element = this._element) { return ( element.dataset[ `tweDropdown${ CLASS_NAME_SHOW.charAt(0).toUpperCase() + CLASS_NAME_SHOW.slice(1) }` ] === "" ); } _getMenuElement() { return SelectorEngine.next(this._element, SELECTOR_MENU)[0]; } _getPlacement() { const parentDropdown = this._element.parentNode; if (parentDropdown.dataset.tweDropdownPosition === CLASS_NAME_DROPEND) { return PLACEMENT_RIGHT; } if (parentDropdown.dataset.tweDropdownPosition === CLASS_NAME_DROPSTART) { return PLACEMENT_LEFT; } // We need to trim the value because custom properties can also include spaces const isEnd = parentDropdown.dataset.tweDropdownAlignment === "end"; if (parentDropdown.dataset.tweDropdownPosition === CLASS_NAME_DROPUP) { return isEnd ? PLACEMENT_TOPEND : PLACEMENT_TOP; } return isEnd ? PLACEMENT_BOTTOMEND : PLACEMENT_BOTTOM; } _detectNavbar() { return this._element.closest(SELECTOR_NAVBAR) !== null; } _getOffset() { const { offset } = this._config; if (typeof offset === "string") { return offset.split(",").map((val) => Number.parseInt(val, 10)); } if (typeof offset === "function") { return (popperData) => offset(popperData, this._element); } return offset; } _getPopperConfig() { const defaultBsPopperConfig = { placement: this._getPlacement(), modifiers: [ { name: "preventOverflow", options: { boundary: this._config.boundary, }, }, { name: "offset", options: { offset: this._getOffset(), }, }, ], }; // Disable Popper if we have a static display if (this._config.display === "static") { defaultBsPopperConfig.modifiers = [ { name: "applyStyles", enabled: false, }, ]; } return { ...defaultBsPopperConfig, ...(typeof this._config.popperConfig === "function" ? this._config.popperConfig(defaultBsPopperConfig) : this._config.popperConfig), }; } _selectMenuItem({ key, target }) { const items = SelectorEngine.find( SELECTOR_VISIBLE_ITEMS, this._menu ).filter(isVisible); if (!items.length) { return; } // if target isn't included in items (e.g. when expanding the dropdown) // allow cycling to get the last item in case key equals ARROW_UP_KEY getNextActiveElement( items, target, key === ARROW_DOWN_KEY, !items.includes(target) ).focus(); } // Static static jQueryInterface(config) { return this.each(function () { const data = Dropdown.getOrCreateInstance(this, config); if (typeof config !== "string") { return; } if (typeof data[config] === "undefined") { throw new TypeError(`No method named "${config}"`); } data[config](); }); } static clearMenus(event) { if ( event && (event.button === RIGHT_MOUSE_BUTTON || (event.type === "keyup" && event.key !== TAB_KEY)) ) { return; } const toggles = SelectorEngine.find(SELECTOR_DATA_TOGGLE); for (let i = 0, len = toggles.length; i < len; i++) { const context = Dropdown.getInstance(toggles[i]); if (!context || context._config.autoClose === false) { continue; } if (!context._isShown()) { continue; } const relatedTarget = { relatedTarget: context._element, }; if (event) { const composedPath = event.composedPath(); const isMenuTarget = composedPath.includes(context._menu); if ( composedPath.includes(context._element) || (context._config.autoClose === "inside" && !isMenuTarget) || (context._config.autoClose === "outside" && isMenuTarget) ) { continue; } // Tab navigation through the dropdown menu or events from contained inputs shouldn't close the menu if ( context._menu.contains(event.target) && ((event.type === "keyup" && event.key === TAB_KEY) || /input|select|option|textarea|form/i.test(event.target.tagName)) ) { continue; } if (event.type === "click") { relatedTarget.clickEvent = event; } } context._completeHide(relatedTarget); } } static getParentFromElement(element) { return getElementFromSelector(element) || element.parentNode; } static dataApiKeydownHandler(event) { // If not input/textarea: // - And not a key in REGEXP_KEYDOWN => not a dropdown command // If input/textarea: // - If space key => not a dropdown command // - If key is other than escape // - If key is not up or down => not a dropdown command // - If trigger inside the menu => not a dropdown command if ( /input|textarea/i.test(event.target.tagName) ? event.key === SPACE_KEY || (event.key !== ESCAPE_KEY && ((event.key !== ARROW_DOWN_KEY && event.key !== ARROW_UP_KEY) || event.target.closest(SELECTOR_MENU))) : !REGEXP_KEYDOWN.test(event.key) ) { return; } const isActive = this.dataset[ `tweDropdown${ CLASS_NAME_SHOW.charAt(0).toUpperCase() + CLASS_NAME_SHOW.slice(1) }` ] === ""; if (!isActive && event.key === ESCAPE_KEY) { return; } event.preventDefault(); event.stopPropagation(); if (isDisabled(this)) { return; } const getToggleButton = this.matches(SELECTOR_DATA_TOGGLE) ? this : SelectorEngine.prev(this, SELECTOR_DATA_TOGGLE)[0]; const instance = Dropdown.getOrCreateInstance(getToggleButton); if (event.key === ESCAPE_KEY) { instance.hide(); return; } if (event.key === ARROW_UP_KEY || event.key === ARROW_DOWN_KEY) { if (!isActive) { instance.show(); } instance._selectMenuItem(event); return; } if (!isActive || event.key === SPACE_KEY) { Dropdown.clearMenus(); } } } export default Dropdown; ================================================ FILE: src/js/free/components/modal.js ================================================ import { isRTL, reflow, typeCheckConfig } from "../../util/index"; import EventHandler from "../../dom/event-handler"; import Manipulator from "../../dom/manipulator"; import SelectorEngine from "../../dom/selector-engine"; import ScrollBarHelper from "../../util/scrollbar"; import BaseComponent from "../../base-component"; import Backdrop from "../../util/backdrop"; import FocusTrap from "../../util/focusTrap"; import { enableDismissTrigger } from "../../util/component-functions"; import { getTransitionDurationFromElement } from "../../util/index"; /* ------------------------------------------------------------------------ Constants ------------------------------------------------------------------------ */ const NAME = "modal"; const DATA_KEY = "twe.modal"; const EVENT_KEY = `.${DATA_KEY}`; const ESCAPE_KEY = "Escape"; const Default = { backdrop: true, keyboard: true, focus: true, }; const DefaultType = { backdrop: "(boolean|string)", keyboard: "boolean", focus: "boolean", }; const DefaultClasses = { show: "transform-none", static: "scale-[1.02]", staticProperties: "transition-scale duration-300 ease-in-out", backdrop: "opacity-50 transition-all duration-300 ease-in-out fixed top-0 left-0 z-[1040] bg-black w-screen h-screen", }; const DefaultClassesType = { show: "string", static: "string", staticProperties: "string", backdrop: "string", }; const EVENT_HIDE = `hide${EVENT_KEY}`; const EVENT_HIDE_PREVENTED = `hidePrevented${EVENT_KEY}`; const EVENT_HIDDEN = `hidden${EVENT_KEY}`; const EVENT_SHOW = `show${EVENT_KEY}`; const EVENT_SHOWN = `shown${EVENT_KEY}`; const EVENT_RESIZE = `resize${EVENT_KEY}`; const EVENT_CLICK_DISMISS = `click.dismiss${EVENT_KEY}`; const EVENT_KEYDOWN_DISMISS = `keydown.dismiss${EVENT_KEY}`; const EVENT_MOUSEUP_DISMISS = `mouseup.dismiss${EVENT_KEY}`; const EVENT_MOUSEDOWN_DISMISS = `mousedown.dismiss${EVENT_KEY}`; const OPEN_SELECTOR_BODY = "data-twe-modal-open"; const OPEN_SELECTOR = "data-twe-open"; const SELECTOR_DIALOG = "[data-twe-modal-dialog-ref]"; const SELECTOR_MODAL_BODY = "[data-twe-modal-body-ref]"; /* ------------------------------------------------------------------------ Class Definition ------------------------------------------------------------------------ */ class Modal extends BaseComponent { constructor(element, config, classes) { super(element); this._config = this._getConfig(config); this._classes = this._getClasses(classes); this._backdrop = this._initializeBackDrop(); this._focustrap = this._initializeFocusTrap(); this._scrollBar = new ScrollBarHelper(); this._dialog = SelectorEngine.findOne(SELECTOR_DIALOG, this._element); this._isShown = false; this._ignoreBackdropClick = false; this._isTransitioning = false; this._didInit = false; this._init(); } // Getters static get NAME() { return NAME; } static get Default() { return Default; } static get getDefaultType() { return DefaultType; } // Public toggle(relatedTarget) { return this._isShown ? this.hide() : this.show(relatedTarget); } show(relatedTarget) { if (this._isShown || this._isTransitioning) { return; } const showEvent = EventHandler.trigger(this._element, EVENT_SHOW, { relatedTarget, }); if (showEvent.defaultPrevented) { return; } this._isShown = true; if (this._isAnimated()) { this._isTransitioning = true; } this._scrollBar.hide(); document.body.setAttribute(OPEN_SELECTOR_BODY, "true"); this._adjustDialog(); this._setEscapeEvent(); this._setResizeEvent(); EventHandler.on(this._dialog, EVENT_MOUSEDOWN_DISMISS, () => { EventHandler.one(this._element, EVENT_MOUSEUP_DISMISS, (event) => { if (event.target === this._element) { this._ignoreBackdropClick = true; } }); }); this._showElement(relatedTarget); this._showBackdrop(); } hide() { if (!this._isShown || this._isTransitioning) { return; } const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE); if (hideEvent.defaultPrevented) { return; } this._isShown = false; const isAnimated = this._isAnimated(); if (isAnimated) { this._isTransitioning = true; } this._setEscapeEvent(); this._setResizeEvent(); this._focustrap.disable(); const modalDialog = SelectorEngine.findOne(SELECTOR_DIALOG, this._element); modalDialog.classList.remove(this._classes.show); EventHandler.off(this._element, EVENT_CLICK_DISMISS); EventHandler.off(this._dialog, EVENT_MOUSEDOWN_DISMISS); this._queueCallback(() => this._hideModal(), this._element, isAnimated); this._element.removeAttribute(OPEN_SELECTOR); } dispose() { [window, document, this._dialog].forEach((htmlElement) => EventHandler.off(htmlElement, EVENT_KEY) ); this._backdrop.dispose(); this._focustrap.disable(); super.dispose(); } handleUpdate() { this._adjustDialog(); } // Private _init() { if (this._didInit) { return; } enableDismissTrigger(Modal); this._didInit = true; } _initializeBackDrop() { return new Backdrop({ isVisible: Boolean(this._config.backdrop), // 'static' option will be translated to true, and booleans will keep their value isAnimated: this._isAnimated(), backdropClasses: this._classes.backdrop, }); } _initializeFocusTrap() { return new FocusTrap(this._element, { event: "keydown", condition: (event) => event.key === "Tab", }); } _showElement(relatedTarget) { const isAnimated = this._isAnimated(); const modalBody = SelectorEngine.findOne(SELECTOR_MODAL_BODY, this._dialog); if ( !this._element.parentNode || this._element.parentNode.nodeType !== Node.ELEMENT_NODE ) { // Don't move modal's DOM position document.body.append(this._element); } this._element.style.display = "block"; this._element.classList.remove("hidden"); this._element.removeAttribute("aria-hidden"); this._element.setAttribute("aria-modal", true); this._element.setAttribute("role", "dialog"); this._element.setAttribute(`${OPEN_SELECTOR}`, "true"); this._element.scrollTop = 0; const modalDialog = SelectorEngine.findOne(SELECTOR_DIALOG, this._element); modalDialog.classList.add(this._classes.show); modalDialog.classList.remove("opacity-0"); modalDialog.classList.add("opacity-100"); if (modalBody) { modalBody.scrollTop = 0; } if (isAnimated) { reflow(this._element); } const transitionComplete = () => { if (this._config.focus) { this._focustrap.trap(); } this._isTransitioning = false; EventHandler.trigger(this._element, EVENT_SHOWN, { relatedTarget, }); }; this._queueCallback(transitionComplete, this._dialog, isAnimated); } _setEscapeEvent() { if (this._isShown) { EventHandler.on(document, EVENT_KEYDOWN_DISMISS, (event) => { if (this._config.keyboard && event.key === ESCAPE_KEY) { event.preventDefault(); this.hide(); } else if (!this._config.keyboard && event.key === ESCAPE_KEY) { this._triggerBackdropTransition(); } }); } else { EventHandler.off(this._element, EVENT_KEYDOWN_DISMISS); } } _setResizeEvent() { if (this._isShown) { EventHandler.on(window, EVENT_RESIZE, () => this._adjustDialog()); } else { EventHandler.off(window, EVENT_RESIZE); } } _hideModal() { const modalDialog = SelectorEngine.findOne(SELECTOR_DIALOG, this._element); modalDialog.classList.remove(this._classes.show); modalDialog.classList.remove("opacity-100"); modalDialog.classList.add("opacity-0"); const transitionTime = getTransitionDurationFromElement(modalDialog); setTimeout(() => { this._element.style.display = "none"; }, transitionTime); this._element.setAttribute("aria-hidden", true); this._element.removeAttribute("aria-modal"); this._element.removeAttribute("role"); this._isTransitioning = false; this._backdrop.hide(() => { document.body.removeAttribute(OPEN_SELECTOR_BODY); this._resetAdjustments(); this._scrollBar.reset(); EventHandler.trigger(this._element, EVENT_HIDDEN); }); } _showBackdrop(callback) { EventHandler.on(this._element, EVENT_CLICK_DISMISS, (event) => { if (this._ignoreBackdropClick) { this._ignoreBackdropClick = false; return; } if (event.target !== event.currentTarget) { return; } if (this._config.backdrop === true) { this.hide(); } else if (this._config.backdrop === "static") { this._triggerBackdropTransition(); } }); this._backdrop.show(callback); } _isAnimated() { const animate = SelectorEngine.findOne(SELECTOR_DIALOG, this._element); return !!animate; } _triggerBackdropTransition() { const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED); if (hideEvent.defaultPrevented) { return; } const { classList, scrollHeight, style } = this._element; const isModalOverflowing = scrollHeight > document.documentElement.clientHeight; // return if the following background transition hasn't yet completed if ( (!isModalOverflowing && style.overflowY === "hidden") || classList.contains(this._classes.static) ) { return; } if (!isModalOverflowing) { style.overflowY = "hidden"; } classList.add(...this._classes.static.split(" ")); classList.add(...this._classes.staticProperties.split(" ")); const transisitionTime = getTransitionDurationFromElement(this._element); this._queueCallback(() => { classList.remove(this._classes.static); setTimeout(() => { classList.remove(...this._classes.staticProperties.split(" ")); }, transisitionTime); if (!isModalOverflowing) { this._queueCallback(() => { style.overflowY = ""; }, this._dialog); } }, this._dialog); this._element.focus(); } _getConfig(config) { config = { ...Default, ...Manipulator.getDataAttributes(this._element), ...(typeof config === "object" ? config : {}), }; typeCheckConfig(NAME, config, DefaultType); return config; } _getClasses(classes) { const dataAttributes = Manipulator.getDataClassAttributes(this._element); classes = { ...DefaultClasses, ...dataAttributes, ...classes, }; typeCheckConfig(NAME, classes, DefaultClassesType); return classes; } // ---------------------------------------------------------------------- // the following methods are used to handle overflowing modals // ---------------------------------------------------------------------- _adjustDialog() { const isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight; const scrollbarWidth = this._scrollBar.getWidth(); const isBodyOverflowing = scrollbarWidth > 0; if ( (!isBodyOverflowing && isModalOverflowing && !isRTL()) || (isBodyOverflowing && !isModalOverflowing && isRTL()) ) { this._element.style.paddingLeft = `${scrollbarWidth}px`; } if ( (isBodyOverflowing && !isModalOverflowing && !isRTL()) || (!isBodyOverflowing && isModalOverflowing && isRTL()) ) { this._element.style.paddingRight = `${scrollbarWidth}px`; } } _resetAdjustments() { this._element.style.paddingLeft = ""; this._element.style.paddingRight = ""; } // Static static jQueryInterface(config, relatedTarget) { return this.each(function () { const data = Modal.getOrCreateInstance(this, config); if (typeof config !== "string") { return; } if (typeof data[config] === "undefined") { throw new TypeError(`No method named "${config}"`); } data[config](relatedTarget); }); } } export default Modal; ================================================ FILE: src/js/free/components/offcanvas.js ================================================ import { typeCheckConfig } from "../../util/index"; import ScrollBarHelper from "../../util/scrollbar"; import EventHandler from "../../dom/event-handler"; import BaseComponent from "../../base-component"; import SelectorEngine from "../../dom/selector-engine"; import Manipulator from "../../dom/manipulator"; import Backdrop from "../../util/backdrop"; import FocusTrap from "../../util/focusTrap"; import { enableDismissTrigger } from "../../util/component-functions"; import { TAB } from "../../util/keycodes"; /* ------------------------------------------------------------------------ Constants ------------------------------------------------------------------------ */ const NAME = "offcanvas"; const DATA_KEY = "twe.offcanvas"; const EVENT_KEY = `.${DATA_KEY}`; const DATA_API_KEY = ".data-api"; const EVENT_LOAD_DATA_API = `load${EVENT_KEY}${DATA_API_KEY}`; const ESCAPE_KEY = "Escape"; const Default = { backdrop: true, keyboard: true, scroll: false, }; const DefaultType = { backdrop: "boolean", keyboard: "boolean", scroll: "boolean", }; const CLASS_NAME_SHOW = "show"; const OPEN_SELECTOR = "[data-twe-offcanvas-init][data-twe-offcanvas-show]"; const EVENT_SHOW = `show${EVENT_KEY}`; const EVENT_SHOWN = `shown${EVENT_KEY}`; const EVENT_HIDE = `hide${EVENT_KEY}`; const EVENT_HIDDEN = `hidden${EVENT_KEY}`; const EVENT_KEYDOWN_DISMISS = `keydown.dismiss${EVENT_KEY}`; /* ------------------------------------------------------------------------ Class Definition ------------------------------------------------------------------------ */ class Offcanvas extends BaseComponent { constructor(element, config) { super(element); this._config = this._getConfig(config); this._isShown = false; this._backdrop = this._initializeBackDrop(); this._focustrap = this._initializeFocusTrap(); this._addEventListeners(); this._didInit = false; this._init(); } // Getters static get NAME() { return NAME; } static get Default() { return Default; } // Public toggle(relatedTarget) { return this._isShown ? this.hide() : this.show(relatedTarget); } show(relatedTarget) { if (this._isShown) { return; } const showEvent = EventHandler.trigger(this._element, EVENT_SHOW, { relatedTarget, }); if (showEvent.defaultPrevented) { return; } this._isShown = true; this._element.style.visibility = "visible"; this._backdrop.show(); if (!this._config.scroll) { new ScrollBarHelper().hide(); } this._element.removeAttribute("aria-hidden"); this._element.setAttribute("aria-modal", true); this._element.setAttribute("role", "dialog"); this._element.setAttribute(`data-twe-offcanvas-${CLASS_NAME_SHOW}`, ""); const completeCallBack = () => { if (!this._config.scroll) { this._focustrap.trap(); } EventHandler.trigger(this._element, EVENT_SHOWN, { relatedTarget }); }; this._queueCallback(completeCallBack, this._element, true); } hide() { if (!this._isShown) { return; } const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE); if (hideEvent.defaultPrevented) { return; } this._focustrap.disable(); this._element.blur(); this._isShown = false; this._element.removeAttribute(`data-twe-offcanvas-${CLASS_NAME_SHOW}`); this._backdrop.hide(); const completeCallback = () => { this._element.setAttribute("aria-hidden", true); this._element.removeAttribute("aria-modal"); this._element.removeAttribute("role"); this._element.style.visibility = "hidden"; if (!this._config.scroll) { new ScrollBarHelper().reset(); } EventHandler.trigger(this._element, EVENT_HIDDEN); }; this._queueCallback(completeCallback, this._element, true); } dispose() { this._backdrop.dispose(); this._focustrap.disable(); super.dispose(); } // Private _init() { if (this._didInit) { return; } EventHandler.on(window, EVENT_LOAD_DATA_API, () => SelectorEngine.find(OPEN_SELECTOR).forEach((el) => Offcanvas.getOrCreateInstance(el).show() ) ); this._didInit = true; enableDismissTrigger(Offcanvas); } _getConfig(config) { config = { ...Default, ...Manipulator.getDataAttributes(this._element), ...(typeof config === "object" ? config : {}), }; typeCheckConfig(NAME, config, DefaultType); return config; } _initializeBackDrop() { return new Backdrop({ isVisible: this._config.backdrop, isAnimated: true, rootElement: this._element.parentNode, clickCallback: () => this.hide(), }); } _initializeFocusTrap() { return new FocusTrap(this._element, { event: "keydown", condition: (e) => e.keyCode === TAB, onlyVisible: true, }); } _addEventListeners() { EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS, (event) => { if (this._config.keyboard && event.key === ESCAPE_KEY) { this.hide(); } }); } // Static static jQueryInterface(config) { return this.each(function () { const data = Offcanvas.getOrCreateInstance(this, config); if (typeof config !== "string") { return; } if ( data[config] === undefined || config.startsWith("_") || config === "constructor" ) { throw new TypeError(`No method named "${config}"`); } data[config](this); }); } } export default Offcanvas; ================================================ FILE: src/js/free/components/popover.js ================================================ import Tooltip from "./tooltip"; /* ------------------------------------------------------------------------ Constants ------------------------------------------------------------------------ */ const NAME = "popover"; const DATA_KEY = "twe.popover"; const EVENT_KEY = `.${DATA_KEY}`; const CLASS_PREFIX = "te-popover"; const Default = { ...Tooltip.Default, placement: "right", offset: [0, 8], trigger: "click", content: "", template: ` `, }; const DefaultType = { ...Tooltip.DefaultType, content: "(string|element|function)", }; const Event = { HIDE: `hide${EVENT_KEY}`, HIDDEN: `hidden${EVENT_KEY}`, SHOW: `show${EVENT_KEY}`, SHOWN: `shown${EVENT_KEY}`, INSERTED: `inserted${EVENT_KEY}`, CLICK: `click${EVENT_KEY}`, FOCUSIN: `focusin${EVENT_KEY}`, FOCUSOUT: `focusout${EVENT_KEY}`, MOUSEENTER: `mouseenter${EVENT_KEY}`, MOUSELEAVE: `mouseleave${EVENT_KEY}`, }; const SELECTOR_TITLE = "[data-twe-popover-header-ref]"; const SELECTOR_CONTENT = "[data-twe-popover-body-ref]"; /* ------------------------------------------------------------------------ Class Definition ------------------------------------------------------------------------ */ class Popover extends Tooltip { // Getters static get Default() { return Default; } static get NAME() { return NAME; } static get Event() { return Event; } static get DefaultType() { return DefaultType; } // Overrides isWithContent() { return this.getTitle() || this._getContent(); } setContent(tip) { this._sanitizeAndSetContent(tip, this.getTitle(), SELECTOR_TITLE); this._sanitizeAndSetContent(tip, this._getContent(), SELECTOR_CONTENT); } // Private _getContent() { return this._resolvePossibleFunction(this._config.content); } _getBasicClassPrefix() { return CLASS_PREFIX; } // Static static jQueryInterface(config) { return this.each(function () { const data = Popover.getOrCreateInstance(this, config); if (typeof config === "string") { if (typeof data[config] === "undefined") { throw new TypeError(`No method named "${config}"`); } data[config](); } }); } } export default Popover; ================================================ FILE: src/js/free/components/tooltip.js ================================================ import * as Popper from "@popperjs/core"; import { findShadowRoot, getElement, getUID, isElement, isRTL, noop, typeCheckConfig, } from "../../util/index"; import { DefaultAllowlist, sanitizeHtml } from "../../util/sanitizer"; import Data from "../../dom/data"; import EventHandler from "../../dom/event-handler"; import Manipulator from "../../dom/manipulator"; import SelectorEngine from "../../dom/selector-engine"; import BaseComponent from "../../base-component"; /* ------------------------------------------------------------------------ Constants ------------------------------------------------------------------------ */ const NAME = "tooltip"; const DATA_KEY = "twe.tooltip"; const EVENT_KEY = `.${DATA_KEY}`; const CLASS_PREFIX = "te-tooltip"; const DISALLOWED_ATTRIBUTES = new Set(["sanitize", "allowList", "sanitizeFn"]); const DefaultType = { animation: "boolean", template: "string", title: "(string|element|function)", trigger: "string", delay: "(number|object)", html: "boolean", selector: "(string|boolean)", placement: "(string|function)", offset: "(array|string|function)", container: "(string|element|boolean)", fallbackPlacements: "array", boundary: "(string|element)", customClass: "(string|function)", sanitize: "boolean", sanitizeFn: "(null|function)", allowList: "object", popperConfig: "(null|object|function)", }; const AttachmentMap = { AUTO: "auto", TOP: "top", RIGHT: isRTL() ? "left" : "right", BOTTOM: "bottom", LEFT: isRTL() ? "right" : "left", }; const Default = { animation: true, template: ` `, trigger: "hover focus", title: "", delay: 0, html: false, selector: false, placement: "top", offset: [0, 0], container: false, fallbackPlacements: ["top", "right", "bottom", "left"], boundary: "clippingParents", customClass: "", sanitize: true, sanitizeFn: null, allowList: DefaultAllowlist, popperConfig: { hide: true }, }; const Event = { HIDE: `hide${EVENT_KEY}`, HIDDEN: `hidden${EVENT_KEY}`, SHOW: `show${EVENT_KEY}`, SHOWN: `shown${EVENT_KEY}`, INSERTED: `inserted${EVENT_KEY}`, CLICK: `click${EVENT_KEY}`, FOCUSIN: `focusin${EVENT_KEY}`, FOCUSOUT: `focusout${EVENT_KEY}`, MOUSEENTER: `mouseenter${EVENT_KEY}`, MOUSELEAVE: `mouseleave${EVENT_KEY}`, }; const CLASS_NAME_FADE = "fade"; const CLASS_NAME_MODAL = "modal"; const CLASS_NAME_SHOW = "show"; const HOVER_STATE_SHOW = "show"; const HOVER_STATE_OUT = "out"; const SELECTOR_TOOLTIP_INNER = "[data-twe-tooltip-inner-ref]"; const SELECTOR_MODAL = `.${CLASS_NAME_MODAL}`; const EVENT_MODAL_HIDE = "hide.twe.modal"; const TRIGGER_HOVER = "hover"; const TRIGGER_FOCUS = "focus"; const TRIGGER_CLICK = "click"; const TRIGGER_MANUAL = "manual"; /* ------------------------------------------------------------------------ Class Definition ------------------------------------------------------------------------ */ class Tooltip extends BaseComponent { constructor(element, config) { if (typeof Popper === "undefined") { throw new TypeError( "Bootstrap's tooltips require Popper (https://popper.js.org)" ); } super(element); // private this._isEnabled = true; this._timeout = 0; this._hoverState = ""; this._activeTrigger = {}; this._popper = null; // Protected this._config = this._getConfig(config); this.tip = null; this._setListeners(); } // Getters static get Default() { return Default; } static get NAME() { return NAME; } static get Event() { return Event; } static get DefaultType() { return DefaultType; } // Public enable() { this._isEnabled = true; } disable() { this._isEnabled = false; } toggleEnabled() { this._isEnabled = !this._isEnabled; } toggle(event) { if (!this._isEnabled) { return; } if (event) { const context = this._initializeOnDelegatedTarget(event); context._activeTrigger.click = !context._activeTrigger.click; if (context._isWithActiveTrigger()) { context._enter(null, context); } else { context._leave(null, context); } } else { if (this.getTipElement().classList.contains(CLASS_NAME_SHOW)) { this._leave(null, this); return; } this._enter(null, this); } } dispose() { clearTimeout(this._timeout); EventHandler.off( this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler ); if (this.tip) { this.tip.remove(); } this._disposePopper(); super.dispose(); } show() { if (this._element.style.display === "none") { throw new Error("Please use show on visible elements"); } if (!(this.isWithContent() && this._isEnabled)) { return; } const showEvent = EventHandler.trigger( this._element, this.constructor.Event.SHOW ); const shadowRoot = findShadowRoot(this._element); const isInTheDom = shadowRoot === null ? this._element.ownerDocument.documentElement.contains(this._element) : shadowRoot.contains(this._element); if (showEvent.defaultPrevented || !isInTheDom) { return; } // A trick to recreate a tooltip in case a new title is given by using the NOT documented `data-twe-original-title` // This will be removed later in favor of a `setContent` method if ( this.constructor.NAME === "tooltip" && this.tip && this.getTitle() !== this.tip.querySelector(SELECTOR_TOOLTIP_INNER).innerHTML ) { this._disposePopper(); this.tip.remove(); this.tip = null; } const tip = this.getTipElement(); const tipId = getUID(this.constructor.NAME); tip.setAttribute("id", tipId); this._element.setAttribute("aria-describedby", tipId); if (this._config.animation) { setTimeout(() => { this.tip.classList.add("opacity-100"); this.tip.classList.remove("opacity-0"); }, 100); } const placement = typeof this._config.placement === "function" ? this._config.placement.call(this, tip, this._element) : this._config.placement; const attachment = this._getAttachment(placement); this._addAttachmentClass(attachment); const { container } = this._config; Data.setData(tip, this.constructor.DATA_KEY, this); if (!this._element.ownerDocument.documentElement.contains(this.tip)) { container.append(tip); EventHandler.trigger(this._element, this.constructor.Event.INSERTED); } if (this._popper) { this._popper.update(); } else { this._popper = Popper.createPopper( this._element, tip, this._getPopperConfig(attachment) ); } const notPopover = tip.getAttribute("id").includes("tooltip"); if (notPopover) { switch (placement) { case "bottom": tip.classList.add("py-[0.4rem]"); break; case "left": tip.classList.add("px-[0.4rem]"); break; case "right": tip.classList.add("px-[0.4rem]"); break; default: tip.classList.add("py-[0.4rem]"); break; } } const customClass = this._resolvePossibleFunction(this._config.customClass); if (customClass) { tip.classList.add(...customClass.split(" ")); } // If this is a touch-enabled device we add extra // empty mouseover listeners to the body's immediate children; // only needed because of broken event delegation on iOS // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html if ("ontouchstart" in document.documentElement) { [].concat(...document.body.children).forEach((element) => { EventHandler.on(element, "mouseover", noop); }); } const complete = () => { const prevHoverState = this._hoverState; this._hoverState = null; EventHandler.trigger(this._element, this.constructor.Event.SHOWN); if (prevHoverState === HOVER_STATE_OUT) { this._leave(null, this); } }; const isAnimated = this.tip.classList.contains("transition-opacity"); this._queueCallback(complete, this.tip, isAnimated); } hide() { if (!this._popper) { return; } const tip = this.getTipElement(); const complete = () => { if (this._isWithActiveTrigger()) { return; } if (this._hoverState !== HOVER_STATE_SHOW) { tip.remove(); } this._cleanTipClass(); this._element.removeAttribute("aria-describedby"); EventHandler.trigger(this._element, this.constructor.Event.HIDDEN); this._disposePopper(); }; const hideEvent = EventHandler.trigger( this._element, this.constructor.Event.HIDE ); if (hideEvent.defaultPrevented) { return; } tip.classList.add("opacity-0"); tip.classList.remove("opacity-100"); // If this is a touch-enabled device we remove the extra // empty mouseover listeners we added for iOS support if ("ontouchstart" in document.documentElement) { [] .concat(...document.body.children) .forEach((element) => EventHandler.off(element, "mouseover", noop)); } this._activeTrigger[TRIGGER_CLICK] = false; this._activeTrigger[TRIGGER_FOCUS] = false; this._activeTrigger[TRIGGER_HOVER] = false; const isAnimated = this.tip.classList.contains("opacity-0"); this._queueCallback(complete, this.tip, isAnimated); this._hoverState = ""; } update() { if (this._popper !== null) { this._popper.update(); } } // Protected isWithContent() { return Boolean(this.getTitle()); } getTipElement() { if (this.tip) { return this.tip; } const element = document.createElement("div"); element.innerHTML = this._config.template; const tip = element.children[0]; this.setContent(tip); tip.classList.remove(CLASS_NAME_FADE, CLASS_NAME_SHOW); this.tip = tip; return this.tip; } setContent(tip) { this._sanitizeAndSetContent(tip, this.getTitle(), SELECTOR_TOOLTIP_INNER); } _sanitizeAndSetContent(template, content, selector) { const templateElement = SelectorEngine.findOne(selector, template); if (!content && templateElement) { templateElement.remove(); return; } // we use append for html objects to maintain js events this.setElementContent(templateElement, content); } setElementContent(element, content) { if (element === null) { return; } if (isElement(content)) { content = getElement(content); // content is a DOM node or a jQuery if (this._config.html) { if (content.parentNode !== element) { element.innerHTML = ""; element.append(content); } } else { element.textContent = content.textContent; } return; } if (this._config.html) { if (this._config.sanitize) { content = sanitizeHtml( content, this._config.allowList, this._config.sanitizeFn ); } element.innerHTML = content; } else { element.textContent = content; } } getTitle() { const title = this._element.getAttribute("data-twe-original-title") || this._config.title; return this._resolvePossibleFunction(title); } updateAttachment(attachment) { if (attachment === "right") { return "end"; } if (attachment === "left") { return "start"; } return attachment; } // Private _initializeOnDelegatedTarget(event, context) { return ( context || this.constructor.getOrCreateInstance( event.delegateTarget, this._getDelegateConfig() ) ); } _getOffset() { const { offset } = this._config; if (typeof offset === "string") { return offset.split(",").map((val) => Number.parseInt(val, 10)); } if (typeof offset === "function") { return (popperData) => offset(popperData, this._element); } return offset; } _resolvePossibleFunction(content) { return typeof content === "function" ? content.call(this._element) : content; } _getPopperConfig(attachment) { const defaultBsPopperConfig = { placement: attachment, modifiers: [ { name: "flip", options: { fallbackPlacements: this._config.fallbackPlacements, }, }, { name: "offset", options: { offset: this._getOffset(), }, }, { name: "preventOverflow", options: { boundary: this._config.boundary, }, }, { name: "arrow", options: { element: `.${this.constructor.NAME}-arrow`, }, }, { name: "onChange", enabled: true, phase: "afterWrite", fn: (data) => this._handlePopperPlacementChange(data), }, ], onFirstUpdate: (data) => { if (data.options.placement !== data.placement) { this._handlePopperPlacementChange(data); } }, }; return { ...defaultBsPopperConfig, ...(typeof this._config.popperConfig === "function" ? this._config.popperConfig(defaultBsPopperConfig) : this._config.popperConfig), }; } _addAttachmentClass(attachment) { this.getTipElement().classList.add( `${this._getBasicClassPrefix()}-${this.updateAttachment(attachment)}` ); } _getAttachment(placement) { return AttachmentMap[placement.toUpperCase()]; } _setListeners() { const triggers = this._config.trigger.split(" "); triggers.forEach((trigger) => { if (trigger === "click") { EventHandler.on( this._element, this.constructor.Event.CLICK, this._config.selector, (event) => this.toggle(event) ); } else if (trigger !== TRIGGER_MANUAL) { const eventIn = trigger === TRIGGER_HOVER ? this.constructor.Event.MOUSEENTER : this.constructor.Event.FOCUSIN; const eventOut = trigger === TRIGGER_HOVER ? this.constructor.Event.MOUSELEAVE : this.constructor.Event.FOCUSOUT; EventHandler.on( this._element, eventIn, this._config.selector, (event) => this._enter(event) ); EventHandler.on( this._element, eventOut, this._config.selector, (event) => this._leave(event) ); } }); this._hideModalHandler = () => { if (this._element) { this.hide(); } }; EventHandler.on( this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler ); if (this._config.selector) { this._config = { ...this._config, trigger: "manual", selector: "", }; } else { this._fixTitle(); } } _fixTitle() { const title = this._element.getAttribute("title"); const originalTitleType = typeof this._element.getAttribute( "data-twe-original-title" ); if (title || originalTitleType !== "string") { this._element.setAttribute("data-twe-original-title", title || ""); if ( title && !this._element.getAttribute("aria-label") && !this._element.textContent ) { this._element.setAttribute("aria-label", title); } this._element.setAttribute("title", ""); } } _enter(event, context) { context = this._initializeOnDelegatedTarget(event, context); if (event) { context._activeTrigger[ event.type === "focusin" ? TRIGGER_FOCUS : TRIGGER_HOVER ] = true; } if ( context.getTipElement().classList.contains(CLASS_NAME_SHOW) || context._hoverState === HOVER_STATE_SHOW ) { context._hoverState = HOVER_STATE_SHOW; return; } clearTimeout(context._timeout); context._hoverState = HOVER_STATE_SHOW; if (!context._config.delay || !context._config.delay.show) { context.show(); return; } context._timeout = setTimeout(() => { if (context._hoverState === HOVER_STATE_SHOW) { context.show(); } }, context._config.delay.show); } _leave(event, context) { context = this._initializeOnDelegatedTarget(event, context); if (event) { context._activeTrigger[ event.type === "focusout" ? TRIGGER_FOCUS : TRIGGER_HOVER ] = context._element.contains(event.relatedTarget); } if (context._isWithActiveTrigger()) { return; } clearTimeout(context._timeout); context._hoverState = HOVER_STATE_OUT; if (!context._config.delay || !context._config.delay.hide) { context.hide(); return; } context._timeout = setTimeout(() => { if (context._hoverState === HOVER_STATE_OUT) { context.hide(); } }, context._config.delay.hide); } _isWithActiveTrigger() { for (const trigger in this._activeTrigger) { if (this._activeTrigger[trigger]) { return true; } } return false; } _getConfig(config) { const dataAttributes = Manipulator.getDataAttributes(this._element); Object.keys(dataAttributes).forEach((dataAttr) => { if (DISALLOWED_ATTRIBUTES.has(dataAttr)) { delete dataAttributes[dataAttr]; } }); config = { ...this.constructor.Default, ...dataAttributes, ...(typeof config === "object" && config ? config : {}), }; config.container = config.container === false ? document.body : getElement(config.container); if (typeof config.delay === "number") { config.delay = { show: config.delay, hide: config.delay, }; } if (typeof config.title === "number") { config.title = config.title.toString(); } if (typeof config.content === "number") { config.content = config.content.toString(); } typeCheckConfig(NAME, config, this.constructor.DefaultType); if (config.sanitize) { config.template = sanitizeHtml( config.template, config.allowList, config.sanitizeFn ); } return config; } _getDelegateConfig() { const config = {}; for (const key in this._config) { if (this.constructor.Default[key] !== this._config[key]) { config[key] = this._config[key]; } } // In the future can be replaced with: // const keysWithDifferentValues = Object.entries(this._config).filter(entry => this.constructor.Default[entry[0]] !== this._config[entry[0]]) // `Object.fromEntries(keysWithDifferentValues)` return config; } _cleanTipClass() { const tip = this.getTipElement(); const basicClassPrefixRegex = new RegExp( `(^|\\s)${this._getBasicClassPrefix()}\\S+`, "g" ); const tabClass = tip.getAttribute("class").match(basicClassPrefixRegex); if (tabClass !== null && tabClass.length > 0) { tabClass .map((token) => token.trim()) .forEach((tClass) => tip.classList.remove(tClass)); } } _getBasicClassPrefix() { return CLASS_PREFIX; } _handlePopperPlacementChange(popperData) { const { state } = popperData; if (!state) { return; } this.tip = state.elements.popper; this._cleanTipClass(); this._addAttachmentClass(this._getAttachment(state.placement)); } _disposePopper() { if (this._popper) { this._popper.destroy(); this._popper = null; } } // Static static jQueryInterface(config) { return this.each(function () { const data = Tooltip.getOrCreateInstance(this, config); if (typeof config === "string") { if (typeof data[config] === "undefined") { throw new TypeError(`No method named "${config}"`); } data[config](); } }); } } export default Tooltip; ================================================ FILE: src/js/free/forms/input.js ================================================ import { element, onDOMContentLoaded, typeCheckConfig } from "../../util/index"; import Data from "../../dom/data"; import EventHandler from "../../dom/event-handler"; import Manipulator from "../../dom/manipulator"; import SelectorEngine from "../../dom/selector-engine"; import "detect-autofill"; /* ------------------------------------------------------------------------ Constants ------------------------------------------------------------------------ */ const NAME = "input"; const DATA_KEY = "twe.input"; const DATA_WRAPPER = "data-twe-input-wrapper-init"; const DATA_NOTCH = "data-twe-input-notch-ref"; const DATA_NOTCH_LEADING = "data-twe-input-notch-leading-ref"; const DATA_NOTCH_MIDDLE = "data-twe-input-notch-middle-ref"; const DATA_NOTCH_TRAILING = "data-twe-input-notch-trailing-ref"; const DATA_HELPER = "data-twe-input-helper-ref"; const DATA_PLACEHOLDER_ACTIVE = "data-twe-input-placeholder-active"; const DATA_ACTIVE = "data-twe-input-state-active"; const DATA_FOCUSED = "data-twe-input-focused"; const DATA_FORM_COUNTER = "data-twe-input-form-counter"; const SELECTOR_OUTLINE_INPUT = `[${DATA_WRAPPER}] input`; const SELECTOR_OUTLINE_TEXTAREA = `[${DATA_WRAPPER}] textarea`; const SELECTOR_NOTCH = `[${DATA_NOTCH}]`; const SELECTOR_NOTCH_LEADING = `[${DATA_NOTCH_LEADING}]`; const SELECTOR_NOTCH_MIDDLE = `[${DATA_NOTCH_MIDDLE}]`; const SELECTOR_HELPER = `[${DATA_HELPER}]`; const Default = { inputFormWhite: false, }; const DefaultType = { inputFormWhite: "(boolean)", }; export const DefaultClasses = { notch: "group flex absolute left-0 top-0 w-full max-w-full h-full text-left pointer-events-none", notchLeading: "pointer-events-none border border-solid box-border bg-transparent transition-all duration-200 ease-linear motion-reduce:transition-none left-0 top-0 h-full w-2 border-e-0 rounded-s-[0.25rem] group-data-[twe-input-focused]:border-e-0 group-data-[twe-input-state-active]:border-e-0", notchLeadingNormal: "border-secondary-500 dark:border-neutral-400 group-data-[twe-input-focused]:shadow-notch-1 group-data-[twe-input-focused]:border-primary", notchLeadingWhite: "border-neutral-200 group-data-[twe-input-focused]:shadow-notch-1 group-data-[twe-input-focused]:shadow-white group-data-[twe-input-focused]:border-white", notchMiddle: "pointer-events-none border border-solid box-border bg-transparent transition-all duration-200 ease-linear motion-reduce:transition-none grow-0 shrink-0 basis-auto w-auto max-w-[calc(100%-1rem)] h-full border-e-0 border-s-0 group-data-[twe-input-focused]:border-x-0 group-data-[twe-input-state-active]:border-x-0 group-data-[twe-input-focused]:border-t group-data-[twe-input-state-active]:border-t group-data-[twe-input-focused]:border-solid group-data-[twe-input-state-active]:border-solid group-data-[twe-input-focused]:border-t-transparent group-data-[twe-input-state-active]:border-t-transparent", notchMiddleNormal: "border-secondary-500 dark:border-neutral-400 group-data-[twe-input-focused]:shadow-notch-2 group-data-[twe-input-focused]:border-primary", notchMiddleWhite: "border-neutral-200 group-data-[twe-input-focused]:shadow-notch-2 group-data-[twe-input-focused]:shadow-white group-data-[twe-input-focused]:border-white", notchTrailing: "pointer-events-none border border-solid box-border bg-transparent transition-all duration-200 ease-linear motion-reduce:transition-none grow h-full border-s-0 rounded-e-[0.25rem] group-data-[twe-input-focused]:border-s-0 group-data-[twe-input-state-active]:border-s-0", notchTrailingNormal: "border-secondary-500 dark:border-neutral-400 group-data-[twe-input-focused]:shadow-notch-3 group-data-[twe-input-focused]:border-primary", notchTrailingWhite: "border-neutral-200 group-data-[twe-input-focused]:shadow-notch-3 group-data-[twe-input-focused]:shadow-white group-data-[twe-input-focused]:border-white", counter: "text-right leading-[1.6]", }; const DefaultClassesType = { notch: "string", notchLeading: "string", notchLeadingNormal: "string", notchLeadingWhite: "string", notchMiddle: "string", notchMiddleNormal: "string", notchMiddleWhite: "string", notchTrailing: "string", notchTrailingNormal: "string", notchTrailingWhite: "string", counter: "string", }; /* ------------------------------------------------------------------------ Class Definition ------------------------------------------------------------------------ */ class Input { constructor(element, config, classes) { this._config = this._getConfig(config, element); this._element = element; this._classes = this._getClasses(classes); this._label = null; this._labelWidth = 0; this._labelMarginLeft = 0; this._notchLeading = null; this._notchMiddle = null; this._notchTrailing = null; this._initiated = false; this._helper = null; this._counter = false; this._counterElement = null; this._maxLength = 0; this._leadingIcon = null; if (this._element) { Data.setData(element, DATA_KEY, this); this.init(); } } // Getters static get NAME() { return NAME; } get input() { const inputElement = SelectorEngine.findOne("input", this._element) || SelectorEngine.findOne("textarea", this._element); return inputElement; } // Public init() { if (this._initiated) { return; } this._getLabelData(); this._applyDivs(); this._applyNotch(); this._activate(); this._getHelper(); this._getCounter(); this._getEvents(); this._initiated = true; } update() { this._getLabelData(); this._getNotchData(); this._applyNotch(); this._activate(); this._getHelper(); this._getCounter(); } forceActive() { this.input.setAttribute(DATA_ACTIVE, ""); SelectorEngine.findOne(SELECTOR_NOTCH, this.input.parentNode).setAttribute( DATA_ACTIVE, "" ); } forceInactive() { this.input.removeAttribute(DATA_ACTIVE); SelectorEngine.findOne( SELECTOR_NOTCH, this.input.parentNode ).removeAttribute(DATA_ACTIVE); } dispose() { this._removeBorder(); Data.removeData(this._element, DATA_KEY); this._element = null; } // Private _getConfig(config, element) { config = { ...Default, ...Manipulator.getDataAttributes(element), ...(typeof config === "object" ? config : {}), }; typeCheckConfig(NAME, config, DefaultType); return config; } _getClasses(classes) { const dataAttributes = Manipulator.getDataClassAttributes(this._element); classes = { ...DefaultClasses, ...dataAttributes, ...classes, }; typeCheckConfig(NAME, classes, DefaultClassesType); return classes; } _getLabelData() { this._label = SelectorEngine.findOne("label", this._element); if (this._label === null) { this._showPlaceholder(); } else { this._getLabelWidth(); this._getLabelPositionInInputGroup(); this._toggleDefaultDatePlaceholder(); } } _getHelper() { this._helper = SelectorEngine.findOne(SELECTOR_HELPER, this._element); } _getCounter() { this._counter = Manipulator.getDataAttribute( this.input, "inputShowcounter" ); if (this._counter) { this._maxLength = this.input.maxLength; this._showCounter(); } } _getEvents() { EventHandler.on( this._element, "focus", "input", Input.activate(new Input()) ); EventHandler.on( this._element, "input", "input", Input.activate(new Input()) ); EventHandler.on( this._element, "blur", "input", Input.deactivate(new Input()) ); EventHandler.on( this._element, "focus", "textarea", Input.activate(new Input()) ); EventHandler.on( this._element, "input", "textarea", Input.activate(new Input()) ); EventHandler.on( this._element, "blur", "textarea", Input.deactivate(new Input()) ); EventHandler.on(window, "shown.twe.modal", (e) => { SelectorEngine.find(SELECTOR_OUTLINE_INPUT, e.target).forEach( (element) => { const instance = Input.getInstance(element.parentNode); if (!instance) { return; } instance.update(); } ); SelectorEngine.find(SELECTOR_OUTLINE_TEXTAREA, e.target).forEach( (element) => { const instance = Input.getInstance(element.parentNode); if (!instance) { return; } instance.update(); } ); }); EventHandler.on(window, "shown.twe.dropdown", (e) => { const target = e.target.parentNode.querySelector( "[data-twe-dropdown-menu-ref]" ); if (target) { SelectorEngine.find(SELECTOR_OUTLINE_INPUT, target).forEach( (element) => { const instance = Input.getInstance(element.parentNode); if (!instance) { return; } instance.update(); } ); SelectorEngine.find(SELECTOR_OUTLINE_TEXTAREA, target).forEach( (element) => { const instance = Input.getInstance(element.parentNode); if (!instance) { return; } instance.update(); } ); } }); EventHandler.on(window, "shown.twe.tab", (e) => { let targetId; if (e.target.href) { targetId = e.target.href.split("#")[1]; } else { targetId = Manipulator.getDataAttribute(e.target, "target").split( "#" )[1]; } const target = SelectorEngine.findOne(`#${targetId}`); SelectorEngine.find(SELECTOR_OUTLINE_INPUT, target).forEach((element) => { const instance = Input.getInstance(element.parentNode); if (!instance) { return; } instance.update(); }); SelectorEngine.find(SELECTOR_OUTLINE_TEXTAREA, target).forEach( (element) => { const instance = Input.getInstance(element.parentNode); if (!instance) { return; } instance.update(); } ); }); // form reset handler EventHandler.on(window, "reset", (e) => { SelectorEngine.find(SELECTOR_OUTLINE_INPUT, e.target).forEach( (element) => { const instance = Input.getInstance(element.parentNode); if (!instance) { return; } instance.forceInactive(); } ); SelectorEngine.find(SELECTOR_OUTLINE_TEXTAREA, e.target).forEach( (element) => { const instance = Input.getInstance(element.parentNode); if (!instance) { return; } instance.forceInactive(); } ); }); // auto-fill EventHandler.on(window, "onautocomplete", (e) => { const instance = Input.getInstance(e.target.parentNode); if (!instance || !e.cancelable) { return; } instance.forceActive(); }); } _showCounter() { const counters = SelectorEngine.find( `[${DATA_FORM_COUNTER}]`, this._element ); if (counters.length > 0) { return; } this._counterElement = document.createElement("div"); Manipulator.addClass(this._counterElement, this._classes.counter); this._counterElement.setAttribute(DATA_FORM_COUNTER, ""); const actualLength = this.input.value.length; this._counterElement.innerHTML = `${actualLength} / ${this._maxLength}`; this._helper.appendChild(this._counterElement); this._bindCounter(); } _bindCounter() { EventHandler.on(this.input, "input", () => { const actualLength = this.input.value.length; this._counterElement.innerHTML = `${actualLength} / ${this._maxLength}`; }); } _toggleDefaultDatePlaceholder(input = this.input) { const isTypeDate = input.getAttribute("type") === "date"; if (!isTypeDate) { return; } const isInputFocused = document.activeElement === input; if (!isInputFocused && !input.value) { input.style.opacity = 0; } else { input.style.opacity = 1; } } _showPlaceholder() { this.input.setAttribute(DATA_PLACEHOLDER_ACTIVE, ""); } _getNotchData() { this._notchMiddle = SelectorEngine.findOne( SELECTOR_NOTCH_MIDDLE, this._element ); this._notchLeading = SelectorEngine.findOne( SELECTOR_NOTCH_LEADING, this._element ); } _getLabelWidth() { this._labelWidth = this._label.clientWidth * 0.8 + 8; } _getLabelPositionInInputGroup() { this._labelMarginLeft = 0; if (!this._element.hasAttribute("data-twe-input-group-ref")) return; const input = this.input; const prefix = SelectorEngine.prev( input, "[data-twe-input-group-text-ref]" )[0]; if (prefix === undefined) { this._labelMarginLeft = 0; } else { this._labelMarginLeft = prefix.offsetWidth - 1; } } _applyDivs() { const shadowLeading = this._config.inputFormWhite ? this._classes.notchLeadingWhite : this._classes.notchLeadingNormal; const shadowMiddle = this._config.inputFormWhite ? this._classes.notchMiddleWhite : this._classes.notchMiddleNormal; const shadowTrailing = this._config.inputFormWhite ? this._classes.notchTrailingWhite : this._classes.notchTrailingNormal; const allNotchWrappers = SelectorEngine.find(SELECTOR_NOTCH, this._element); const notchWrapper = element("div"); Manipulator.addClass(notchWrapper, this._classes.notch); notchWrapper.setAttribute(DATA_NOTCH, ""); this._notchLeading = element("div"); Manipulator.addClass( this._notchLeading, `${this._classes.notchLeading} ${shadowLeading}` ); this._notchLeading.setAttribute(DATA_NOTCH_LEADING, ""); this._notchMiddle = element("div"); Manipulator.addClass( this._notchMiddle, `${this._classes.notchMiddle} ${shadowMiddle}` ); this._notchMiddle.setAttribute(DATA_NOTCH_MIDDLE, ""); this._notchTrailing = element("div"); Manipulator.addClass( this._notchTrailing, `${this._classes.notchTrailing} ${shadowTrailing}` ); this._notchTrailing.setAttribute(DATA_NOTCH_TRAILING, ""); if (allNotchWrappers.length >= 1) { return; } notchWrapper.append(this._notchLeading); notchWrapper.append(this._notchMiddle); notchWrapper.append(this._notchTrailing); this._element.append(notchWrapper); // for now, before we can fix the rtl for notches notchWrapper.dir = "ltr"; } _applyNotch() { this._notchMiddle.style.width = `${this._labelWidth}px`; this._notchLeading.style.width = `${this._labelMarginLeft + 9}px`; if (this._label === null) return; this._label.style.marginLeft = `${this._labelMarginLeft}px`; } _removeBorder() { const border = SelectorEngine.findOne(SELECTOR_NOTCH, this._element); if (border) border.remove(); } _activate(event) { onDOMContentLoaded(() => { this._getElements(event); const input = event ? event.target : this.input; const notchWrapper = SelectorEngine.findOne( SELECTOR_NOTCH, this._element ); if (event && event.type === "focus") { notchWrapper && notchWrapper.setAttribute(DATA_FOCUSED, ""); } if (input.value !== "") { input.setAttribute(DATA_ACTIVE, ""); notchWrapper && notchWrapper.setAttribute(DATA_ACTIVE, ""); } this._toggleDefaultDatePlaceholder(input); }); } _getElements(event) { if (event) { this._element = event.target.parentNode; this._label = SelectorEngine.findOne("label", this._element); } if (event && this._label) { const prevLabelWidth = this._labelWidth; this._getLabelData(); if (prevLabelWidth !== this._labelWidth) { this._notchMiddle = SelectorEngine.findOne( SELECTOR_NOTCH_MIDDLE, event.target.parentNode ); this._notchLeading = SelectorEngine.findOne( SELECTOR_NOTCH_LEADING, event.target.parentNode ); this._applyNotch(); } } } _deactivate(event) { const input = event ? event.target : this.input; if (input.getAttribute("aria-expanded") === "true") { return; } const notchWrapper = SelectorEngine.findOne( SELECTOR_NOTCH, input.parentNode ); notchWrapper.removeAttribute(DATA_FOCUSED); if (input.value === "") { input.removeAttribute(DATA_ACTIVE); notchWrapper.removeAttribute(DATA_ACTIVE); } this._toggleDefaultDatePlaceholder(input); } static activate(instance) { return function (event) { instance._activate(event); }; } static deactivate(instance) { return function (event) { instance._deactivate(event); }; } static jQueryInterface(config, options) { return this.each(function () { let data = Data.getData(this, DATA_KEY); const _config = typeof config === "object" && config; if (!data && /dispose/.test(config)) { return; } if (!data) { data = new Input(this, _config); } if (typeof config === "string") { if (typeof data[config] === "undefined") { throw new TypeError(`No method named "${config}"`); } data[config](options); } }); } static getInstance(element) { return Data.getData(element, DATA_KEY); } static getOrCreateInstance(element, config = {}) { return ( this.getInstance(element) || new this(element, typeof config === "object" ? config : null) ); } } export default Input; ================================================ FILE: src/js/free/methods/ripple.js ================================================ import { element, typeCheckConfig } from "../../util/index"; import Data from "../../dom/data"; import EventHandler from "../../dom/event-handler"; import Manipulator from "../../dom/manipulator"; import SelectorEngine from "../../dom/selector-engine"; import { getStyle } from "../../util/getStyle"; /* ------------------------------------------------------------------------ Constants ------------------------------------------------------------------------ */ const NAME = "ripple"; const DATA_KEY = "twe.ripple"; const GRADIENT = "rgba({{color}}, 0.2) 0, rgba({{color}}, 0.3) 40%, rgba({{color}}, 0.4) 50%, rgba({{color}}, 0.5) 60%, rgba({{color}}, 0) 70%"; const SELECTOR_COMPONENT = ["[data-twe-ripple-init]"]; const DEFAULT_RIPPLE_COLOR = [0, 0, 0]; // prettier-ignore const BOOTSTRAP_COLORS = [ { name: "primary", gradientColor: getStyle("text-primary", { defaultValue: "#3B71CA", inherit: false }), }, { name: "secondary", gradientColor: getStyle("text-primary-100", { defaultValue: "#9FA6B2", inherit: false }), }, { name: "success", gradientColor: getStyle("text-success", { defaultValue: "#14A44D", inherit: false }), }, { name: "danger", gradientColor: getStyle("text-danger", { defaultValue: "#DC4C64", inherit: false }), }, { name: "warning", gradientColor: getStyle("text-warning", { defaultValue: "#E4A11B", inherit: false }), }, { name: "info", gradientColor: getStyle("text-info", { defaultValue: "#54B4D3", inherit: false }), }, { name: "light", gradientColor: "#fbfbfb", }, { name: "dark", gradientColor: "#262626", }, ]; // Sets value when run opacity transition // Hide element after 50% (0.5) time of animation and finish on 100% const TRANSITION_BREAK_OPACITY = 0.5; const Default = { rippleCentered: false, rippleColor: "", rippleColorDark: "", rippleDuration: "500ms", rippleRadius: 0, rippleUnbound: false, }; const DefaultType = { rippleCentered: "boolean", rippleColor: "string", rippleColorDark: "string", rippleDuration: "string", rippleRadius: "number", rippleUnbound: "boolean", }; const DefaultClasses = { ripple: "relative overflow-hidden inline-block align-bottom", rippleWave: "rounded-[50%] opacity-50 pointer-events-none absolute touch-none scale-0 transition-[transform,_opacity] ease-[cubic-bezier(0,0,0.15,1),_cubic-bezier(0,0,0.15,1)] z-[999]", unbound: "overflow-visible", }; const DefaultClassesType = { ripple: "string", rippleWave: "string", unbound: "string", }; /* ------------------------------------------------------------------------ Class Definition ------------------------------------------------------------------------ */ class Ripple { constructor(element, options, classes) { this._element = element; this._options = this._getConfig(options); this._classes = this._getClasses(classes); this._currentColor = this._options.rippleColor; if (this._element) { Data.setData(element, DATA_KEY, this); Manipulator.addClass(this._element, this._classes.ripple); } this._clickHandler = this._createRipple.bind(this); this._rippleTimer = null; this._isMinWidthSet = false; this._initialClasses = null; this.init(); } // Getters static get NAME() { return NAME; } // Public init() { this._addClickEvent(this._element); } dispose() { Data.removeData(this._element, DATA_KEY); EventHandler.off(this._element, "mousedown", this._clickHandler); this._element = null; this._options = null; } // Private _autoInit(event) { SELECTOR_COMPONENT.forEach((selector) => { const target = SelectorEngine.closest(event.target, selector); if (target) { this._element = SelectorEngine.closest(event.target, selector); } }); if (!this._element.style.minWidth) { Manipulator.style(this._element, { "min-width": getComputedStyle(this._element).width, }); this._isMinWidthSet = true; } this._options = this._getConfig(); this._classes = this._getClasses(); this._initialClasses = [...this._element.classList]; Manipulator.addClass(this._element, this._classes.ripple); this._createRipple(event); } _addClickEvent(target) { EventHandler.on(target, "mousedown", this._clickHandler); } _createRipple(event) { if (this._element.className.indexOf(this._classes.ripple) < 0) { Manipulator.addClass(this._element, this._classes.ripple); } const { layerX, layerY } = event; const offsetX = event.offsetX || layerX; const offsetY = event.offsetY || layerY; const height = this._element.offsetHeight; const width = this._element.offsetWidth; const duration = this._durationToMsNumber(this._options.rippleDuration); const diameterOptions = { offsetX: this._options.rippleCentered ? height / 2 : offsetX, offsetY: this._options.rippleCentered ? width / 2 : offsetY, height, width, }; const diameter = this._getDiameter(diameterOptions); const radiusValue = this._options.rippleRadius || diameter / 2; const opacity = { delay: duration * TRANSITION_BREAK_OPACITY, duration: duration - duration * TRANSITION_BREAK_OPACITY, }; const styles = { left: this._options.rippleCentered ? `${width / 2 - radiusValue}px` : `${offsetX - radiusValue}px`, top: this._options.rippleCentered ? `${height / 2 - radiusValue}px` : `${offsetY - radiusValue}px`, height: `${this._options.rippleRadius * 2 || diameter}px`, width: `${this._options.rippleRadius * 2 || diameter}px`, transitionDelay: `0s, ${opacity.delay}ms`, transitionDuration: `${duration}ms, ${opacity.duration}ms`, }; const rippleHTML = element("div"); this._createHTMLRipple({ wrapper: this._element, ripple: rippleHTML, styles, }); this._removeHTMLRipple({ ripple: rippleHTML, duration }); } _createHTMLRipple({ wrapper, ripple, styles }) { Object.keys(styles).forEach( (property) => (ripple.style[property] = styles[property]) ); Manipulator.addClass(ripple, this._classes.rippleWave); ripple.setAttribute("data-twe-ripple-ref", ""); this._addColor(ripple, wrapper); this._toggleUnbound(wrapper); this._appendRipple(ripple, wrapper); } _removeHTMLRipple({ ripple, duration }) { if (this._rippleTimer) { clearTimeout(this._rippleTimer); this._rippleTimer = null; } if (ripple) { setTimeout(() => { ripple.classList.add("!opacity-0"); }, 10); } this._rippleTimer = setTimeout(() => { if (ripple) { ripple.remove(); if (this._element) { SelectorEngine.find("[data-twe-ripple-ref]", this._element).forEach( (rippleEl) => { rippleEl.remove(); } ); if (this._isMinWidthSet) { Manipulator.style(this._element, { "min-width": "" }); this._isMinWidthSet = false; } // check if added ripple classes wasn't there initialy const classesToRemove = this._initialClasses ? this._addedNewRippleClasses( this._classes.ripple, this._initialClasses ) : this._classes.ripple.split(" "); Manipulator.removeClass(this._element, classesToRemove); } } }, duration); } _addedNewRippleClasses(defaultRipple, initialClasses) { return defaultRipple .split(" ") .filter( (item) => initialClasses.findIndex((init) => item === init) === -1 ); } _durationToMsNumber(time) { return Number(time.replace("ms", "").replace("s", "000")); } _getConfig(config = {}) { const dataAttributes = Manipulator.getDataAttributes(this._element); config = { ...Default, ...dataAttributes, ...config, }; typeCheckConfig(NAME, config, DefaultType); return config; } _getClasses(classes = {}) { const dataAttributes = Manipulator.getDataClassAttributes(this._element); classes = { ...DefaultClasses, ...dataAttributes, ...classes, }; typeCheckConfig(NAME, classes, DefaultClassesType); return classes; } _getDiameter({ offsetX, offsetY, height, width }) { const top = offsetY <= height / 2; const left = offsetX <= width / 2; const pythagorean = (sideA, sideB) => Math.sqrt(sideA ** 2 + sideB ** 2); const positionCenter = offsetY === height / 2 && offsetX === width / 2; // mouse position on the quadrants of the coordinate system const quadrant = { first: top === true && left === false, second: top === true && left === true, third: top === false && left === true, fourth: top === false && left === false, }; const getCorner = { topLeft: pythagorean(offsetX, offsetY), topRight: pythagorean(width - offsetX, offsetY), bottomLeft: pythagorean(offsetX, height - offsetY), bottomRight: pythagorean(width - offsetX, height - offsetY), }; let diameter = 0; if (positionCenter || quadrant.fourth) { diameter = getCorner.topLeft; } else if (quadrant.third) { diameter = getCorner.topRight; } else if (quadrant.second) { diameter = getCorner.bottomRight; } else if (quadrant.first) { diameter = getCorner.bottomLeft; } return diameter * 2; } _appendRipple(target, parent) { const FIX_ADD_RIPPLE_EFFECT = 50; // delay for active animations parent.appendChild(target); setTimeout(() => { Manipulator.addClass(target, "opacity-0 scale-100"); }, FIX_ADD_RIPPLE_EFFECT); } _toggleUnbound(target) { if (this._options.rippleUnbound === true) { Manipulator.addClass(target, this._classes.unbound); } else { Manipulator.removeClass(target, this._classes.unbound); } } _addColor(target) { let rippleColor = this._options.rippleColor || "rgb(0,0,0)"; if ( localStorage.theme === "dark" || (!("theme" in localStorage) && window.matchMedia("(prefers-color-scheme: dark)").matches) ) { rippleColor = this._options.rippleColorDark || this._options.rippleColor; } const IS_BOOTSTRAP_COLOR = BOOTSTRAP_COLORS.find( (color) => color.name === rippleColor.toLowerCase() ); const rgbValue = IS_BOOTSTRAP_COLOR ? this._colorToRGB(IS_BOOTSTRAP_COLOR.gradientColor).join(",") : this._colorToRGB(rippleColor).join(","); const gradientImage = GRADIENT.split("{{color}}").join(`${rgbValue}`); target.style.backgroundImage = `radial-gradient(circle, ${gradientImage})`; } _colorToRGB(color) { function hexToRgb(color) { const HEX_COLOR_LENGTH = 7; const IS_SHORT_HEX = color.length < HEX_COLOR_LENGTH; if (IS_SHORT_HEX) { color = `#${color[1]}${color[1]}${color[2]}${color[2]}${color[3]}${color[3]}`; } return [ parseInt(color.substr(1, 2), 16), parseInt(color.substr(3, 2), 16), parseInt(color.substr(5, 2), 16), ]; } function namedColorsToRgba(color) { const tempElem = document.body.appendChild( document.createElement("fictum") ); const flag = "rgb(1, 2, 3)"; tempElem.style.color = flag; if (tempElem.style.color !== flag) { return DEFAULT_RIPPLE_COLOR; } tempElem.style.color = color; if (tempElem.style.color === flag || tempElem.style.color === "") { return DEFAULT_RIPPLE_COLOR; } // color parse failed color = getComputedStyle(tempElem).color; document.body.removeChild(tempElem); return color; } function rgbaToRgb(color) { color = color.match(/[.\d]+/g).map((a) => +Number(a)); color.length = 3; return color; } if (color.toLowerCase() === "transparent") { return DEFAULT_RIPPLE_COLOR; } if (color[0] === "#") { return hexToRgb(color); } if (color.indexOf("rgb") === -1) { color = namedColorsToRgba(color); } if (color.indexOf("rgb") === 0) { return rgbaToRgb(color); } return DEFAULT_RIPPLE_COLOR; } // Static static autoInitial(instance) { return function (event) { instance._autoInit(event); }; } static jQueryInterface(options) { return this.each(function () { const data = Data.getData(this, DATA_KEY); if (!data) { return new Ripple(this, options); } return null; }); } static getInstance(element) { return Data.getData(element, DATA_KEY); } static getOrCreateInstance(element, config = {}) { return ( this.getInstance(element) || new this(element, typeof config === "object" ? config : null) ); } } export default Ripple; ================================================ FILE: src/js/free/navigation/scrollspy.js ================================================ import { getElement, getSelectorFromElement, typeCheckConfig, } from "../../util/index"; import EventHandler from "../../dom/event-handler"; import Manipulator from "../../dom/manipulator"; import MDBManipulator from "../../dom/manipulator"; import SelectorEngine from "../../dom/selector-engine"; import BaseComponent from "../../base-component"; /* ------------------------------------------------------------------------ Constants ------------------------------------------------------------------------ */ const NAME = "scrollspy"; const DATA_KEY = "twe.scrollspy"; const EVENT_KEY = `.${DATA_KEY}`; const Default = { offset: 10, method: "auto", target: "", }; const DefaultType = { offset: "number", method: "string", target: "(string|element)", }; const DefaultClasses = { active: "!text-primary font-semibold border-s-[0.125rem] border-solid border-primary", }; const DefaultClassesType = { active: "string", }; const EVENT_ACTIVATE = `activate${EVENT_KEY}`; const EVENT_SCROLL = `scroll${EVENT_KEY}`; const LINK_ACTIVE = "data-twe-nav-link-active"; const LINK_COLLAPSIBLE = "data-twe-collapsible-scrollspy-ref"; const SELECTOR_DROPDOWN_ITEM = "[data-twe-dropdown-item-ref]"; const SELECTOR_NAV_LIST_GROUP = "[data-twe-nav-list-ref]"; const SELECTOR_NAV_LINKS = "[data-twe-nav-link-ref]"; const SELECTOR_NAV_ITEMS = "[data-twe-nav-item-ref]"; const SELECTOR_LIST_ITEMS = "[data-twe-list-group-item-ref]"; const SELECTOR_LINK_ITEMS = `${SELECTOR_NAV_LINKS}, ${SELECTOR_LIST_ITEMS}, ${SELECTOR_DROPDOWN_ITEM}`; const SELECTOR_DROPDOWN = "[data-twe-dropdown-ref]"; const SELECTOR_DROPDOWN_TOGGLE = "[data-twe-dropdown-toggle-ref]"; const SELECTOR_COLLAPSIBLE_SCROLLSPY = `[${LINK_COLLAPSIBLE}]`; const SELECTOR_ACTIVE = `[${LINK_ACTIVE}]`; const SELECTOR_LIST = "ul"; const METHOD_OFFSET = "maxOffset"; const METHOD_POSITION = "position"; /* ------------------------------------------------------------------------ Class Definition ------------------------------------------------------------------------ */ class ScrollSpy extends BaseComponent { constructor(element, config, classes) { super(element); this._scrollElement = this._element.tagName === "BODY" ? window : this._element; this._config = this._getConfig(config); this._classes = this._getClasses(classes); this._offsets = []; this._targets = []; this._collapsibles = []; this._activeTarget = null; this._scrollHeight = 0; EventHandler.on(this._scrollElement, EVENT_SCROLL, () => this._process()); this.refresh(); this._process(); this._bindActivateEvent(); this._getCollapsibles(); if (this._collapsibles.length === 0) { return; } this._showSubsection(); this._hideSubsection(); } // Getters static get Default() { return Default; } static get NAME() { return NAME; } // Public refresh() { const autoMethod = this._scrollElement === this._scrollElement.window ? METHOD_OFFSET : METHOD_POSITION; const offsetMethod = this._config.method === "auto" ? autoMethod : this._config.method; const offsetBase = offsetMethod === METHOD_POSITION ? this._getScrollTop() : 0; this._offsets = []; this._targets = []; this._scrollHeight = this._getScrollHeight(); const targets = SelectorEngine.find( SELECTOR_LINK_ITEMS, this._config.target ); targets .map((element) => { const targetSelector = getSelectorFromElement(element); const target = targetSelector ? SelectorEngine.findOne(targetSelector) : null; if (target) { const targetBCR = target.getBoundingClientRect(); if (targetBCR.width || targetBCR.height) { return [ Manipulator[offsetMethod](target).top + offsetBase, targetSelector, ]; } } return null; }) .filter((item) => item) .sort((a, b) => a[0] - b[0]) .forEach((item) => { this._offsets.push(item[0]); this._targets.push(item[1]); }); } dispose() { EventHandler.off(this._scrollElement, EVENT_KEY); EventHandler.off(this._scrollElement, EVENT_ACTIVATE); super.dispose(); } // Private _getConfig(config) { config = { ...Default, ...Manipulator.getDataAttributes(this._element), ...(typeof config === "object" && config ? config : {}), }; config.target = getElement(config.target) || document.documentElement; typeCheckConfig(NAME, config, DefaultType); return config; } _getClasses(classes) { const dataAttributes = MDBManipulator.getDataClassAttributes(this._element); classes = { ...DefaultClasses, ...dataAttributes, ...classes, }; typeCheckConfig(NAME, classes, DefaultClassesType); return classes; } _getScrollTop() { return this._scrollElement === window ? this._scrollElement.pageYOffset : this._scrollElement.scrollTop; } _getScrollHeight() { return ( this._scrollElement.scrollHeight || Math.max( document.body.scrollHeight, document.documentElement.scrollHeight ) ); } _getOffsetHeight() { return this._scrollElement === window ? window.innerHeight : this._scrollElement.getBoundingClientRect().height; } _process() { const scrollTop = this._getScrollTop() + this._config.offset; const scrollHeight = this._getScrollHeight(); const maxScroll = this._config.offset + scrollHeight - this._getOffsetHeight(); if (this._scrollHeight !== scrollHeight) { this.refresh(); } if (scrollTop >= maxScroll) { const target = this._targets[this._targets.length - 1]; if (this._activeTarget !== target) { this._activate(target); } return; } if ( this._activeTarget && scrollTop < this._offsets[0] && this._offsets[0] > 0 ) { this._activeTarget = null; this._clear(); return; } for (let i = this._offsets.length; i--; ) { const isActiveTarget = this._activeTarget !== this._targets[i] && scrollTop >= this._offsets[i] && (typeof this._offsets[i + 1] === "undefined" || scrollTop < this._offsets[i + 1]); if (isActiveTarget) { this._activate(this._targets[i]); } } } _activate(target) { this._activeTarget = target; this._clear(); const queries = SELECTOR_LINK_ITEMS.split(",").map( (selector) => `${selector}[data-twe-target="${target}"],${selector}[href="${target}"]` ); const link = SelectorEngine.findOne(queries.join(","), this._config.target); link.classList.add(...this._classes.active.split(" ")); link.setAttribute(LINK_ACTIVE, ""); if (link.getAttribute(SELECTOR_DROPDOWN_ITEM)) { SelectorEngine.findOne( SELECTOR_DROPDOWN_TOGGLE, link.closest(SELECTOR_DROPDOWN) ).classList.add(...this._classes.active.split(" ")); } else { SelectorEngine.parents(link, SELECTOR_NAV_LIST_GROUP).forEach( (listGroup) => { // Set triggered links parents as active // With both
    and